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.

chore(auth): return frozen dataclasses for credential tuples (#83151)

Arno Hillene3d05cb31942
diff --git a/ee/api/agentic_provisioning/authentication.py b/ee/api/agentic_provisioning/authentication.py
index 31d0cbc38b86..ec4f533647f2 100644
--- a/ee/api/agentic_provisioning/authentication.py
+++ b/ee/api/agentic_provisioning/authentication.py
@@ -16,8 +16,13 @@ from posthog.api.oauth.cimd import (
is_cimd_client_id,
is_cimd_url_blocked,
)
-from posthog.api.oauth.client_assertion import ClientAssertionError, extract_client_assertion, verify_client_assertion
-from posthog.api.oauth.client_auth import extract_client_credentials, verify_client_secret
+from posthog.api.oauth.client_assertion import (
+ ClientAssertionError,
+ ResolvedClientAssertion,
+ extract_client_assertion,
+ verify_client_assertion,
+)
+from posthog.api.oauth.client_auth import ClientCredentials, extract_client_credentials, verify_client_secret
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, find_oauth_access_token
from posthog.models.user import User
@@ -93,12 +98,12 @@ class ProvisioningAuthentication(BaseAuthentication):
# 1. A signed assertion identifies and proves a private_key_jwt partner at once.
assertion = extract_client_assertion(request)
if assertion is not None:
- return self._identify_assertion_partner(request, *assertion)
+ return self._identify_assertion_partner(request, assertion)
# 2. So do client credentials, for a partner registered with a secret.
credentials = extract_client_credentials(request)
if credentials is not None:
- return self._identify_client_secret_partner(request, *credentials)
+ return self._identify_client_secret_partner(request, credentials)
# 3. A bare client_id identifies a public client, which relies on PKCE.
client_id = request.data.get("client_id") or request.query_params.get("client_id")
@@ -124,30 +129,32 @@ class ProvisioningAuthentication(BaseAuthentication):
capture_auth_event(app, "verification_failed", endpoint=request.path)
raise AuthenticationFailed(reason)
- def _identify_assertion_partner(self, request: Request, assertion: str, client_id: str) -> OAuthApplication | None:
- app = self._resolve_partner(client_id)
+ def _identify_assertion_partner(
+ self, request: Request, assertion: ResolvedClientAssertion
+ ) -> OAuthApplication | None:
+ app = self._resolve_partner(assertion.client_id)
if app is None:
raise AuthenticationFailed(CLIENT_NOT_REGISTERED_MESSAGE)
if not app.uses_private_key_jwt_auth:
self._reject(request, app, "This client does not authenticate with a client assertion")
try:
- verify_client_assertion(app, assertion)
+ verify_client_assertion(app, assertion.client_assertion)
except ClientAssertionError as exc:
self._reject(request, app, str(exc))
return app
def _identify_client_secret_partner(
- self, request: Request, client_id: str, client_secret: str
+ self, request: Request, credentials: ClientCredentials
) -> OAuthApplication | None:
- app = self._resolve_partner(client_id)
+ app = self._resolve_partner(credentials.client_id)
if app is None:
return None
if not app.uses_client_secret_auth:
self._reject(request, app, "This client does not authenticate with a client secret")
- if not verify_client_secret(client_secret, app.client_secret or ""):
+ if not verify_client_secret(credentials.client_secret, app.client_secret or ""):
self._reject(request, app, "Invalid client credentials")
return app
diff --git a/ee/api/agentic_provisioning/throttling.py b/ee/api/agentic_provisioning/throttling.py
index dcb5717e98f2..126a8f020332 100644
--- a/ee/api/agentic_provisioning/throttling.py
+++ b/ee/api/agentic_provisioning/throttling.py
@@ -39,6 +39,7 @@ from rest_framework.throttling import BaseThrottle
from rest_framework.views import APIView
from posthog.api.oauth import cimd
+from posthog.dataclasses import frozen
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.rate_limit import IPThrottle
@@ -67,6 +68,12 @@ from ee.api.agentic_provisioning.exceptions import Envelope, ProvisioningError
logger = structlog.get_logger(__name__)
+@frozen
+class RateWindowUsage:
+ count: int
+ limit: int
+
+
def _fixed_window_count(cache_key: str, window_seconds: int) -> int:
try:
cache.add(cache_key, 0, timeout=window_seconds)
@@ -83,10 +90,10 @@ def _window_retry_after(window_seconds: int) -> int:
return window_seconds - (int(time.time()) % window_seconds)
-def _count_partner_request(partner: OAuthApplication, endpoint: str) -> tuple[int, int] | None:
+def _count_partner_request(partner: OAuthApplication, endpoint: str) -> RateWindowUsage | None:
"""Count one request against the partner's per-endpoint fixed window.
- Returns ``(count, limit)``, or None when rate limiting is disabled for the
+ Returns the window's usage, or None when rate limiting is disabled for the
endpoint (model override of 0). The model's override field takes precedence
over the conservative default; the window is keyed on partner id +
window-of-epoch.
@@ -102,7 +109,7 @@ def _count_partner_request(partner: OAuthApplication, endpoint: str) -> tuple[in
window_index = int(time.time()) // PARTNER_RATE_LIMIT_WINDOW_SECONDS
cache_key = f"{PARTNER_RATE_LIMIT_PREFIX}{endpoint}:{partner.id}:{window_index}"
- return _fixed_window_count(cache_key, PARTNER_RATE_LIMIT_WINDOW_SECONDS), limit
+ return RateWindowUsage(count=_fixed_window_count(cache_key, PARTNER_RATE_LIMIT_WINDOW_SECONDS), limit=limit)
def _capture_partner_rate_limited(partner: OAuthApplication, endpoint: str, limit: int, count: int) -> None:
@@ -124,13 +131,12 @@ def enforce_partner_rate_limit(
Raises a ``rate_limited`` :class:`ProvisioningError` when the limit is exceeded.
"""
- counted = _count_partner_request(partner, endpoint)
- if counted is None:
+ usage = _count_partner_request(partner, endpoint)
+ if usage is None:
return
- count, limit = counted
- if count > limit:
- _capture_partner_rate_limited(partner, endpoint, limit, count)
+ if usage.count > usage.limit:
+ _capture_partner_rate_limited(partner, endpoint, usage.limit, usage.count)
raise ProvisioningError(
"rate_limited",
message or f"Rate limit exceeded for this partner ({endpoint}). Try again later.",
@@ -159,12 +165,11 @@ class PartnerRateThrottle(BaseThrottle):
partner = self.get_partner(request)
if partner is None:
return True
- counted = _count_partner_request(partner, self.endpoint)
- if counted is None:
+ usage = _count_partner_request(partner, self.endpoint)
+ if usage is None:
return True
- count, limit = counted
- if count > limit:
- _capture_partner_rate_limited(partner, self.endpoint, limit, count)
+ if usage.count > usage.limit:
+ _capture_partner_rate_limited(partner, self.endpoint, usage.limit, usage.count)
return False
return True
diff --git a/ee/api/agentic_provisioning/views/oauth_token.py b/ee/api/agentic_provisioning/views/oauth_token.py
index 3ffe31228977..48a4f86dbed0 100644
--- a/ee/api/agentic_provisioning/views/oauth_token.py
+++ b/ee/api/agentic_provisioning/views/oauth_token.py
@@ -68,9 +68,8 @@ def _require_client_authentication(request: Request, oauth_app: OAuthApplication
)
raise ProvisioningError("invalid_client", "client_id and client_secret are required", status=401)
- client_id, client_secret = credentials
- if not constant_time_compare(client_id, oauth_app.effective_client_id) or not verify_client_secret(
- client_secret, oauth_app.client_secret or ""
+ if not constant_time_compare(credentials.client_id, oauth_app.effective_client_id) or not verify_client_secret(
+ credentials.client_secret, oauth_app.client_secret or ""
):
capture_provisioning_event(
"token_exchange", "invalid_client_credentials", partner=oauth_app, grant_type=grant_type
@@ -86,17 +85,16 @@ def _verify_assertion_or_fail(request: Request, oauth_app: OAuthApplication, gra
)
raise ProvisioningError("invalid_client", "A client_assertion is required", status=401)
- assertion_value, asserted_client_id = assertion
# The assertion is verified against the app the grant names, so an assertion validly
# signed by a different client cannot be used to redeem this one's grant.
- if not constant_time_compare(asserted_client_id, oauth_app.effective_client_id):
+ if not constant_time_compare(assertion.client_id, oauth_app.effective_client_id):
capture_provisioning_event(
"token_exchange", "client_assertion_mismatch", partner=oauth_app, grant_type=grant_type
)
raise ProvisioningError("invalid_client", "Client assertion does not match this grant", status=401)
try:
- verify_client_assertion(oauth_app, assertion_value)
+ verify_client_assertion(oauth_app, assertion.client_assertion)
except ClientAssertionError as exc:
capture_provisioning_event(
"token_exchange", "invalid_client_assertion", partner=oauth_app, grant_type=grant_type
diff --git a/posthog/api/oauth/cimd.py b/posthog/api/oauth/cimd.py
index 7ff17650ada1..4d5fb4ce0518 100644
--- a/posthog/api/oauth/cimd.py
+++ b/posthog/api/oauth/cimd.py
@@ -302,13 +302,13 @@ def fetch_client_json_document(
# the first lookup with a public address and the second with an internal one. Pinning
# the connection to the addresses we actually validated closes that rebinding window;
# PinnedIPAdapter keeps the original hostname for SNI and certificate verification.
- allowed, reason, pinned_ips = validate_url_and_pin_ips(url)
- if not allowed:
- raise CIMDValidationError(f"URL blocked: {reason}")
+ verdict = validate_url_and_pin_ips(url)
+ if not verdict.allowed:
+ raise CIMDValidationError(f"URL blocked: {verdict.reason}")
adapter = PinnedIPAdapter()
hostname = (urlparse(url).hostname or "").lower()
- chosen_ip = select_pinned_ip(pinned_ips)
+ chosen_ip = select_pinned_ip(verdict.pinned_ips)
if chosen_ip is not None:
adapter.pin(hostname, chosen_ip)
diff --git a/posthog/api/oauth/client_assertion.py b/posthog/api/oauth/client_assertion.py
index 9a1859c61fa7..1dcb49084182 100644
--- a/posthog/api/oauth/client_assertion.py
+++ b/posthog/api/oauth/client_assertion.py
@@ -13,6 +13,7 @@ authentic without any registration ceremony.
from __future__ import annotations
import time
+from dataclasses import field
from typing import Any
from django.conf import settings
@@ -23,10 +24,19 @@ import structlog
from jwt import PyJWK, PyJWKSet
from posthog.api.oauth.cimd import CIMDFetchError, CIMDValidationError, fetch_client_json_document
+from posthog.dataclasses import frozen
from posthog.models.oauth import OAuthApplication
logger = structlog.get_logger(__name__)
+
+@frozen
+class ResolvedClientAssertion:
+ # repr=False: the assertion is a signed credential, kept out of logs and tracebacks.
+ client_assertion: str = field(repr=False)
+ client_id: str
+
+
CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
# Asymmetric signatures only. Allowing an HMAC family here would be a key-confusion hole:
@@ -78,8 +88,8 @@ def _request_field(request: Any, name: str) -> str:
return str(request.query_params.get(name) or "") if hasattr(request, "query_params") else ""
-def extract_client_assertion(request: Any) -> tuple[str, str] | None:
- """Return the ``(client_assertion, client_id)`` a request presents, or None.
+def extract_client_assertion(request: Any) -> ResolvedClientAssertion | None:
+ """Return the client assertion and client_id a request presents, or None.
``client_id`` is optional on the wire for this method (RFC 7521 section 4.2 allows the
assertion to carry the identity), so it falls back to the assertion's own ``sub``.
@@ -91,8 +101,8 @@ def extract_client_assertion(request: Any) -> tuple[str, str] | None:
)
-def resolve_client_assertion(assertion: str, assertion_type: str, client_id: str) -> tuple[str, str] | None:
- """Return the ``(client_assertion, client_id)`` from raw field values, or None.
+def resolve_client_assertion(assertion: str, assertion_type: str, client_id: str) -> ResolvedClientAssertion | None:
+ """Return the client assertion and client_id from raw field values, or None.
Kept separate from ``extract_client_assertion`` so the oauthlib-backed token endpoint,
whose request object exposes these fields as plain attributes rather than through the DRF
@@ -105,7 +115,7 @@ def resolve_client_assertion(assertion: str, assertion_type: str, client_id: str
if not resolved_client_id:
return None
- return assertion, resolved_client_id
+ return ResolvedClientAssertion(client_assertion=assertion, client_id=resolved_client_id)
def _unverified_subject(assertion: str) -> str:
diff --git a/posthog/api/oauth/client_auth.py b/posthog/api/oauth/client_auth.py
index ac27a39127ff..ee69b991f4a4 100644
--- a/posthog/api/oauth/client_auth.py
+++ b/posthog/api/oauth/client_auth.py
@@ -9,15 +9,25 @@ from __future__ import annotations
import base64
import binascii
+from dataclasses import field
from typing import Any
from urllib.parse import unquote_plus
from django.contrib.auth.hashers import check_password, identify_hasher
from django.utils.crypto import constant_time_compare
+from posthog.dataclasses import frozen
+
BASIC_PREFIX = "Basic "
+@frozen
+class ClientCredentials:
+ client_id: str
+ # repr=False keeps the secret out of logs and tracebacks.
+ client_secret: str = field(repr=False)
+
+
def verify_client_secret(provided_secret: str, stored_secret: str) -> bool:
"""Check a presented client secret against the stored one.
@@ -43,7 +53,7 @@ def verify_client_secret(provided_secret: str, stored_secret: str) -> bool:
return check_password(provided_secret, stored_secret)
-def client_credentials_from_basic_auth(request: Any) -> tuple[str, str] | None:
+def client_credentials_from_basic_auth(request: Any) -> ClientCredentials | None:
auth_header = request.headers.get("authorization", "")
if not auth_header.startswith(BASIC_PREFIX):
return None
@@ -59,11 +69,11 @@ def client_credentials_from_basic_auth(request: Any) -> tuple[str, str] | None:
# RFC 6749 section 2.3.1 requires both halves to be form-urlencoded before they are
# base64'd, so a secret containing ":" survives the split above.
- return unquote_plus(client_id), unquote_plus(client_secret)
+ return ClientCredentials(client_id=unquote_plus(client_id), client_secret=unquote_plus(client_secret))
-def extract_client_credentials(request: Any) -> tuple[str, str] | None:
- """Return the ``(client_id, client_secret)`` pair the request presents, or None.
+def extract_client_credentials(request: Any) -> ClientCredentials | None:
+ """Return the client_id and client_secret the request presents, or None.
Both RFC 6749 transports are accepted. Basic auth is read first because the GitHub
grant listing endpoint is a GET, which has no body to carry the pair.
@@ -75,6 +85,6 @@ def extract_client_credentials(request: Any) -> tuple[str, str] | None:
client_id = request.data.get("client_id") or ""
client_secret = request.data.get("client_secret") or ""
if client_id and client_secret:
- return client_id, client_secret
+ return ClientCredentials(client_id=client_id, client_secret=client_secret)
return None
diff --git a/posthog/api/oauth/test_client_assertion.py b/posthog/api/oauth/test_client_assertion.py
index 94afe4d11071..21c9123e29b2 100644
--- a/posthog/api/oauth/test_client_assertion.py
+++ b/posthog/api/oauth/test_client_assertion.py
@@ -20,6 +20,7 @@ from posthog.api.oauth.client_assertion import (
CLIENT_ASSERTION_TYPE_JWT_BEARER,
MAX_ASSERTION_LIFETIME_SECONDS,
ClientAssertionError,
+ ResolvedClientAssertion,
extract_client_assertion,
load_jwks,
verify_client_assertion,
@@ -267,4 +268,6 @@ class TestClientAssertion(BaseTest):
request = _drf_request(
{"client_assertion": assertion, "client_assertion_type": CLIENT_ASSERTION_TYPE_JWT_BEARER}
)
- assert extract_client_assertion(request) == (assertion, CLIENT_ID)
+ assert extract_client_assertion(request) == ResolvedClientAssertion(
+ client_assertion=assertion, client_id=CLIENT_ID
+ )
diff --git a/posthog/api/oauth/test_client_auth.py b/posthog/api/oauth/test_client_auth.py
index 81ec4717bf4a..1307f7b14830 100644
--- a/posthog/api/oauth/test_client_auth.py
+++ b/posthog/api/oauth/test_client_auth.py
@@ -3,7 +3,8 @@ from django.test import SimpleTestCase
from parameterized import parameterized
-from posthog.api.oauth.client_auth import verify_client_secret
+from posthog.api.oauth.client_assertion import ResolvedClientAssertion
+from posthog.api.oauth.client_auth import ClientCredentials, verify_client_secret
from posthog.api.oauth.views import OAuthValidator
@@ -31,3 +32,16 @@ class TestVerifyClientSecret(SimpleTestCase):
# a credential-less request and every confidential app that holds no secret.
assert OAuthValidator()._check_secret("", make_password("")) is False
assert OAuthValidator()._check_secret("s3cret", make_password("s3cret")) is True
+
+
+class TestCredentialRepr(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("client_credentials", ClientCredentials(client_id="client-id", client_secret="s3cret-value")),
+ ("client_assertion", ResolvedClientAssertion(client_assertion="s3cret-value", client_id="client-id")),
+ ]
+ )
+ def test_secret_is_absent_from_repr(self, _name, credential):
+ # These objects end up in logs and tracebacks; the credential must never ride along.
+ assert "s3cret-value" not in repr(credential)
+ assert "client-id" in repr(credential)
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 41518ca49a8a..17f87e643bb4 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -52,6 +52,7 @@ from posthog.api.oauth.cimd import (
)
from posthog.api.oauth.client_assertion import (
ClientAssertionError,
+ ResolvedClientAssertion,
expected_assertion_audiences,
resolve_client_assertion,
verify_client_assertion,
@@ -508,7 +509,7 @@ class OAuthValidator(OAuth2Validator):
)
@staticmethod
- def _resolve_request_assertion(request) -> tuple[str, str] | None:
+ def _resolve_request_assertion(request) -> ResolvedClientAssertion | None:
return resolve_client_assertion(
getattr(request, "client_assertion", None) or "",
getattr(request, "client_assertion_type", None) or "",
@@ -520,8 +521,7 @@ class OAuthValidator(OAuth2Validator):
if assertion is None:
return False
- assertion_value, client_id = assertion
- app = self._load_application(client_id, request)
+ app = self._load_application(assertion.client_id, request)
# jwks_uri alone gates this, not client_type: a public CIMD client may publish keys
# and start signing before any partner registration. What's REQUIRED is a separate
# question, decided by client_type via client_authentication_required.
@@ -529,16 +529,16 @@ class OAuthValidator(OAuth2Validator):
return False
if app.is_cimd_client and app.cimd_metadata_url:
- self._enqueue_cimd_metadata_refresh(app.cimd_metadata_url, client_id)
+ self._enqueue_cimd_metadata_refresh(app.cimd_metadata_url, assertion.client_id)
try:
verify_client_assertion(
app,
- assertion_value,
+ assertion.client_assertion,
audiences=expected_assertion_audiences(*STANDARD_TOKEN_ENDPOINT_PATHS),
)
except ClientAssertionError as e:
- logger.warning("oauth_client_assertion_rejected", client_id=client_id, error=str(e))
+ logger.warning("oauth_client_assertion_rejected", client_id=assertion.client_id, error=str(e))
return False
request.client = app
@@ -1987,7 +1987,7 @@ class OAuthIntrospectTokenView(ClientProtectedScopedResourceView):
credentials = client_credentials_from_basic_auth(request)
if credentials is not None:
- return credentials[0]
+ return credentials.client_id
return request.POST.get("client_id") or None
def get_token_response(self, request, token_value=None):
diff --git a/posthog/api/proxy_record_diagnostics.py b/posthog/api/proxy_record_diagnostics.py
index 1faf123d3fb8..42c0e2e4b6b7 100644
--- a/posthog/api/proxy_record_diagnostics.py
+++ b/posthog/api/proxy_record_diagnostics.py
@@ -688,15 +688,15 @@ def _check_cert_expiry(record: ProxyRecord, *, is_cloudflare: bool) -> CheckResu
# points at. This resolution is its own, separate from the one the live probe pinned, so
# it has to be validated and pinned here too. SNI stays on the hostname so certificate
# verification still checks the name the customer configured.
- allowed, _reason, pinned_ips = validate_url_and_pin_ips(_probe_url(record.domain, "/"))
- if not allowed:
+ verdict = validate_url_and_pin_ips(_probe_url(record.domain, "/"))
+ if not verdict.allowed:
return CheckResult(
id="cert_expiry",
name="Certificate expiry",
status="warned",
detail=f"Couldn't check the certificate because `{record.domain}` doesn't resolve to a public address.",
)
- chosen_ip = select_pinned_ip(pinned_ips)
+ chosen_ip = select_pinned_ip(verdict.pinned_ips)
# An empty set means validation was bypassed (dev mode), so fall back to the hostname.
connect_host = str(chosen_ip) if chosen_ip is not None else record.domain
diff --git a/posthog/api/test/test_proxy_record_diagnostics.py b/posthog/api/test/test_proxy_record_diagnostics.py
index a14aed4fc44b..de4cd91a8c16 100644
--- a/posthog/api/test/test_proxy_record_diagnostics.py
+++ b/posthog/api/test/test_proxy_record_diagnostics.py
@@ -11,6 +11,7 @@ from parameterized import parameterized
from posthog.api import proxy_record_diagnostics as diagnostics
from posthog.models.proxy_record import is_valid_proxy_domain
from posthog.security.pinned_requests import SSRFBlockedError
+from posthog.security.url_validation import PinnedUrlVerdict
from posthog.temporal.proxy_service.cloudflare import (
CloudflareAPIError,
CustomHostname,
@@ -280,7 +281,7 @@ PUBLIC_IP = ipaddress.ip_address("203.0.113.10")
@patch(
"posthog.api.proxy_record_diagnostics.validate_url_and_pin_ips",
- return_value=(True, None, {PUBLIC_IP}),
+ return_value=PinnedUrlVerdict(allowed=True, reason=None, pinned_ips={PUBLIC_IP}),
)
class TestCheckCertExpiry(TestCase):
@parameterized.expand(
@@ -325,7 +326,9 @@ class TestCheckCertExpiry(TestCase):
@patch("posthog.api.proxy_record_diagnostics.socket.create_connection")
def test_warns_without_connecting_when_the_host_is_not_public(self, create_conn_mock, validate_mock):
- validate_mock.return_value = (False, "Private IP address not allowed", set())
+ validate_mock.return_value = PinnedUrlVerdict(
+ allowed=False, reason="Private IP address not allowed", pinned_ips=set()
+ )
result = diagnostics._check_cert_expiry(_record(), is_cloudflare=True)
diff --git a/posthog/security/pinned_requests.py b/posthog/security/pinned_requests.py
index e2b2f6ae4832..84d6e0ca571c 100644
--- a/posthog/security/pinned_requests.py
+++ b/posthog/security/pinned_requests.py
@@ -160,13 +160,13 @@ def pinned_session(url: str) -> Iterator[requests.Session]:
``pinned_request`` unless you need to stream the response, which requires the
session to outlive the call.
"""
- allowed, reason, pinned_ips = validate_url_and_pin_ips(url)
- if not allowed:
- raise SSRFBlockedError(reason or "URL blocked by SSRF protection")
+ verdict = validate_url_and_pin_ips(url)
+ if not verdict.allowed:
+ raise SSRFBlockedError(verdict.reason or "URL blocked by SSRF protection")
adapter = PinnedIPAdapter()
hostname = (urlparse.urlparse(url).hostname or "").lower()
- chosen_ip = select_pinned_ip(pinned_ips)
+ chosen_ip = select_pinned_ip(verdict.pinned_ips)
if chosen_ip is not None:
adapter.pin(hostname, chosen_ip)
diff --git a/posthog/security/test/test_pinned_requests.py b/posthog/security/test/test_pinned_requests.py
index cd23b5eec557..d2cd90280626 100644
--- a/posthog/security/test/test_pinned_requests.py
+++ b/posthog/security/test/test_pinned_requests.py
@@ -7,12 +7,17 @@ import requests
from requests.adapters import HTTPAdapter
from posthog.security import pinned_requests as pr
+from posthog.security.url_validation import PinnedUrlVerdict
class TestPinnedRequest:
def test_blocked_url_raises_before_any_connection(self):
with (
- patch.object(pr, "validate_url_and_pin_ips", return_value=(False, "Loopback host", set())),
+ patch.object(
+ pr,
+ "validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=False, reason="Loopback host", pinned_ips=set()),
+ ),
patch.object(pr.requests, "Session") as session_cls,
):
with pytest.raises(pr.SSRFBlockedError, match="Loopback host"):
diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.py
index c6f5e3f6f688..29a488acccbb 100644
--- a/posthog/security/url_validation.py
+++ b/posthog/security/url_validation.py
@@ -11,11 +11,20 @@ import dns.resolver
import dns.exception
from posthog.cloud_utils import is_dev_mode
+from posthog.dataclasses import frozen
logger = structlog.get_logger(__name__)
ResolvedIPs = set[ipaddress.IPv4Address | ipaddress.IPv6Address]
+
+@frozen
+class PinnedUrlVerdict:
+ allowed: bool
+ reason: str | None
+ pinned_ips: ResolvedIPs
+
+
DNS_RESOLUTION_LIFETIME_SECONDS = 2.0
DNS_RESOLUTION_BATCH_TIMEOUT_SECONDS = 2.5
DNS_RESOLUTION_MAX_WORKERS = 20
@@ -271,13 +280,11 @@ def is_url_allowed(
- Host must not be localhost, metadata service, or internal domain
- Resolved IPs must not be private/internal
"""
- allowed, reason, _ips = _validate_url_with_ips(raw_url, resolved_ips_by_host=resolved_ips_by_host)
- return allowed, reason
+ verdict = _validate_url_with_ips(raw_url, resolved_ips_by_host=resolved_ips_by_host)
+ return verdict.allowed, verdict.reason
-def validate_url_and_pin_ips(
- raw_url: str,
-) -> tuple[bool, str | None, set[ipaddress.IPv4Address | ipaddress.IPv6Address]]:
+def validate_url_and_pin_ips(raw_url: str) -> PinnedUrlVerdict:
"""
Like ``is_url_allowed`` but also returns the validated IP set.
@@ -292,17 +299,15 @@ def _validate_url_with_ips(
raw_url: str,
*,
resolved_ips_by_host: Mapping[str, ResolvedIPs] | None = None,
-) -> tuple[bool, str | None, set[ipaddress.IPv4Address | ipaddress.IPv6Address]]:
- empty: set[ipaddress.IPv4Address | ipaddress.IPv6Address] = set()
+) -> PinnedUrlVerdict:
+ empty: ResolvedIPs = set()
if _dev_bypass_enabled():
- return True, None, empty
+ return PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=empty)
- def _blocked(
- reason: str, **log_kwargs: object
- ) -> tuple[bool, str, set[ipaddress.IPv4Address | ipaddress.IPv6Address]]:
+ def _blocked(reason: str, **log_kwargs: object) -> PinnedUrlVerdict:
logger.warning("url_validation.blocked", reason=reason, **log_kwargs)
- return False, reason, empty
+ return PinnedUrlVerdict(allowed=False, reason=reason, pinned_ips=empty)
if has_authority_bypass_chars(raw_url):
return _blocked("Invalid URL: ambiguous authority")
@@ -335,7 +340,7 @@ def _validate_url_with_ips(
for ip in ips:
if _is_internal_ip(ip):
return _blocked(f"Disallowed target IP: {ip}", host=host, ip=str(ip))
- return True, None, ips
+ return PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=ips)
def should_block_url(u: str) -> bool:
diff --git a/posthog/temporal/proxy_service/monitor.py b/posthog/temporal/proxy_service/monitor.py
index fb87bdaaa32f..cb6b752d7574 100644
--- a/posthog/temporal/proxy_service/monitor.py
+++ b/posthog/temporal/proxy_service/monitor.py
@@ -340,13 +340,13 @@ def _probe_proxy(proxy_record: ProxyRecord) -> CheckActivityOutput:
# is its own, separate from whatever the POST resolved, so the domain can answer the first
# lookup correctly and point somewhere internal by this one. SNI stays on the hostname so
# certificate verification still checks the name the customer configured.
- allowed, _reason, pinned_ips = validate_url_and_pin_ips(f"{probe_base}/")
- if not allowed:
+ verdict = validate_url_and_pin_ips(f"{probe_base}/")
+ if not verdict.allowed:
return CheckActivityOutput(
errors=["Proxy domain does not resolve to a public address"],
warnings=[],
)
- chosen_ip = select_pinned_ip(pinned_ips)
+ chosen_ip = select_pinned_ip(verdict.pinned_ips)
# An empty set means validation was bypassed (dev mode), so fall back to the hostname.
connect_host = str(chosen_ip) if chosen_ip is not None else proxy_record.domain
diff --git a/posthog/temporal/proxy_service/test/monitor_test.py b/posthog/temporal/proxy_service/test/monitor_test.py
index 25a6c4ae2f06..e600e77c6d1c 100644
--- a/posthog/temporal/proxy_service/test/monitor_test.py
+++ b/posthog/temporal/proxy_service/test/monitor_test.py
@@ -11,6 +11,7 @@ import requests
from parameterized import parameterized
from posthog.models import Organization, ProxyRecord
+from posthog.security.url_validation import PinnedUrlVerdict
from posthog.temporal.proxy_service.monitor import PROXY_LIVE_CHECK_TIMEOUT_S, CheckActivityInput, check_proxy_is_live
@@ -158,7 +159,9 @@ class TestCheckProxyIsLive(TestCase):
):
mock_get_record.return_value = self.proxy_record
mock_post.return_value = Mock(status_code=200, raise_for_status=Mock(return_value=None))
- mock_validate.return_value = (True, None, {ipaddress.ip_address("203.0.113.7")})
+ mock_validate.return_value = PinnedUrlVerdict(
+ allowed=True, reason=None, pinned_ips={ipaddress.ip_address("203.0.113.7")}
+ )
mock_create_connection.return_value = MagicMock()
mock_socket = Mock()
@@ -188,7 +191,7 @@ class TestCheckProxyIsLive(TestCase):
):
mock_get_record.return_value = self.proxy_record
mock_post.return_value = Mock(status_code=200, raise_for_status=Mock(return_value=None))
- mock_validate.return_value = (False, "private address", set())
+ mock_validate.return_value = PinnedUrlVerdict(allowed=False, reason="private address", pinned_ips=set())
result = await check_proxy_is_live(self.input)
diff --git a/products/business_knowledge/backend/tests/test_url_ingest.py b/products/business_knowledge/backend/tests/test_url_ingest.py
index a48e42a6c8ff..e205a84ac60d 100644
--- a/products/business_knowledge/backend/tests/test_url_ingest.py
+++ b/products/business_knowledge/backend/tests/test_url_ingest.py
@@ -17,6 +17,8 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
from rest_framework import status
+from posthog.security.url_validation import PinnedUrlVerdict
+
from products.business_knowledge.backend import url_fetch
from products.business_knowledge.backend.html_parse import _bs4_fallback, parse_html
from products.business_knowledge.backend.logic import (
@@ -82,7 +84,10 @@ class TestNormalizeUrl(BaseTest):
class TestFetchUrl(BaseTest):
- @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips", return_value=(True, None, set()))
+ @patch(
+ "products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set()),
+ )
@patch("products.business_knowledge.backend.url_fetch.requests.Session")
def test_happy_path_returns_body(self, mock_session_cls: MagicMock, _ssrf: MagicMock) -> None:
session = mock_session_cls.return_value
@@ -92,7 +97,10 @@ class TestFetchUrl(BaseTest):
assert result.body == b"<html>hi</html>"
assert result.etag == '"abc"'
- @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips", return_value=(True, None, set()))
+ @patch(
+ "products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set()),
+ )
@patch("products.business_knowledge.backend.url_fetch.requests.Session")
def test_conditional_get_returns_304(self, mock_session_cls: MagicMock, _ssrf: MagicMock) -> None:
session = mock_session_cls.return_value
@@ -101,7 +109,10 @@ class TestFetchUrl(BaseTest):
assert result.status == 304
assert result.body is None
- @patch("products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips", return_value=(True, None, set()))
+ @patch(
+ "products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips",
+ return_value=PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set()),
+ )
@patch("products.business_knowledge.backend.url_fetch.requests.Session")
def test_size_cap_aborts(self, mock_session_cls: MagicMock, _ssrf: MagicMock) -> None:
session = mock_session_cls.return_value
@@ -118,7 +129,10 @@ class TestFetchUrl(BaseTest):
def test_redirect_revalidates_ssrf(self, mock_session_cls: MagicMock, mock_ssrf: MagicMock) -> None:
# First hop allowed (public), second hop blocked (internal). If the
# client blindly followed, the second Location would be fetched.
- mock_ssrf.side_effect = [(True, None, set()), (False, "Loopback", set())]
+ mock_ssrf.side_effect = [
+ PinnedUrlVerdict(allowed=True, reason=None, pinned_ips=set()),
+ PinnedUrlVerdict(allowed=False, reason="Loopback", pinned_ips=set()),
+ ]
session = mock_session_cls.return_value
session.get.return_value = _mock_response(status_code=302, body=b"", location="http://127.0.0.1/admin")
with self.assertRaises(url_fetch.UrlFetchError):
@@ -128,7 +142,7 @@ class TestFetchUrl(BaseTest):
@patch(
"products.business_knowledge.backend.url_fetch.validate_url_and_pin_ips",
- return_value=(False, "Loopback", set()),
+ return_value=PinnedUrlVerdict(allowed=False, reason="Loopback", pinned_ips=set()),
)
def test_ssrf_blocked_upfront(self, _ssrf: MagicMock) -> None:
with self.assertRaises(url_fetch.UrlFetchError):
diff --git a/products/business_knowledge/backend/url_fetch.py b/products/business_knowledge/backend/url_fetch.py
index 863215e56408..8ced59ace1e9 100644
--- a/products/business_knowledge/backend/url_fetch.py
+++ b/products/business_knowledge/backend/url_fetch.py
@@ -126,20 +126,20 @@ def _ssrf_safe_get(
session.mount("https://", adapter)
try:
for _hop in range(URL_MAX_REDIRECTS + 1):
- allowed, reason, pinned_ips = validate_url_and_pin_ips(current)
- if not allowed:
+ verdict = validate_url_and_pin_ips(current)
+ if not verdict.allowed:
logger.warning(
"business_knowledge.url_fetch.ssrf_blocked",
url=current,
- reason=reason,
+ reason=verdict.reason,
)
raise UrlFetchError("URL is not reachable from this environment.")
# Pin the first validated IP so requests connects to it directly
parsed = urlparse.urlparse(current)
hostname = (parsed.hostname or "").lower()
- if pinned_ips:
- adapter.pin(hostname, next(iter(pinned_ips)))
+ if verdict.pinned_ips:
+ adapter.pin(hostname, next(iter(verdict.pinned_ips)))
merged_headers = dict(headers)
if etag: