: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(security): log out-of-band interaction domains at the host guards (#117466)
Tom Piccirello3721e4600f6c
diff --git a/.agents/security.md b/.agents/security.mdindex 2d1007261062..7f33977ee4c1 100644--- a/.agents/security.md+++ b/.agents/security.md@@ -192,6 +192,26 @@ semgrep --test .semgrep/rules/security/docker run --rm -v "${PWD}:/src" semgrep/semgrep semgrep --test /src/.semgrep/rules/security/```+## Out-of-band interaction domains++`posthog/security/crosslang/oob_domains.json` lists the services that capture out-of-band+interactions, such as Interactsh and Burp Collaborator, and the DNS rebinding services.++Today the guards only log a match. Nothing is refused yet.++The warehouse guards emit the `oob_domain` stage of `data_imports.host_check`, which carries+`team_id`, and the `oob_domain_resolved` stage when the caller resolved the host first. The HTTP+adapter emits `security.oob_domain_seen` and takes its team from the activity's bound log context.+`posthog/security/url_validation.py` emits the same event with no team at all, because no team is+in scope there, so those lines are attributable to a host and not to a project.++The check runs on cloud only, and it runs before each guard's own DNS resolution, because the+lookup alone confirms the path to whoever runs the collaborator.++It stops the default scanner configuration. It does not stop a determined attacker, who points a+CNAME at the collaborator or runs their own server. The IP checks and the address pinning remain+the real controls.+## Content Security Policy`CSPMiddleware` in `posthog/csp_middleware.py` attaches a policy to every HTML response.diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex b177394778d4..0e68e44ffd2f 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -544,6 +544,10 @@ jobs:# (markdown is dropped outright, .semgrep is not listed), so a# change to either would skip repo-checks and report green while# leaving a tag pointing at a rule that no longer exists.+ # The out-of-band domain ratchet reads these trees, so a resolver added there must run it.+ - 'nodejs/src/**'+ - 'rust/**'+ - 'products/desktop/**'- 'AGENTS.md'- '.semgrep/**'- 'pyproject.toml'diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 6bffbd9c0949..d2eb2b825ad6 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -408,6 +408,10 @@ jobs:# (markdown is dropped outright, .semgrep is not listed), so a# change to either would skip repo-checks and report green while# leaving a tag pointing at a rule that no longer exists.+ # The out-of-band domain ratchet reads these trees, so a resolver added there must run it.+ - 'nodejs/src/**'+ - 'rust/**'+ - 'products/desktop/**'- 'AGENTS.md'- '.semgrep/**'- 'pyproject.toml'diff --git a/AGENTS.md b/AGENTS.mdindex e8791b2ab08a..87224c9c1c94 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -206,6 +206,8 @@ Each rule is tagged with what catches a violation.- **Any other third-party API that needs rate-limiting or egress telemetry belongs there too.** `[review]` Add a `<domain>/` incarnation (GitHub is the reference). No semgrep rule covers a new domain, so a raw client for one reaches master unless a reader catches it. `/routing-outbound-api-calls` decides the route and names the reference domain to copy.- **Object storage is SeaweedFS — do not add new MinIO dependencies.** `[review]` Both S3-compatible stores are SeaweedFS: `objectstorage` (`:19000`, `OBJECT_STORAGE_*`) for general storage, `seaweedfs` (`:8333`, `SESSION_RECORDING_V2_S3_*`) for session replay v2. MinIO survives only as one-off salvage tooling: `bin/migrate-storage-hobby` starts a temporary container to read an old hobby MinIO volume. Do not add compose services, scripts, tests or docs that stand up a `minio/minio` container. Talk to storage through the existing config and a standard S3 client, never a hardcoded endpoint. Note `objectstorage` registers credentials at runtime and returns `InvalidAccessKeyId` until that finishes, so wait for its readiness sentinel rather than the container start.+- **A new DNS-resolution or outbound-host entry point calls the shared out-of-band domain check.** `[lint: test_oob_denylist_coverage.py]` Every host guard here is IP-based, and an out-of-band interaction domain resolves to an ordinary public IP, so a resolver that skips the check restores the gap in silence. The list and the edit procedure live in `posthog/security/crosslang/`.+### Django admin- **A new `ForeignKey`/`OneToOneField` on an admin-exposed model needs explicit widget config.** `[review]` List the field in `autocomplete_fields`, `raw_id_fields`, or `readonly_fields` on **every** admin class that renders the model, including inlines attached to a related admin. Otherwise the default `<select>` loads the entire target table per row on each change-page render. Declare it on a shared base inline so per-parent variants inherit it.diff --git a/posthog/security/crosslang/README.md b/posthog/security/crosslang/README.mdnew file mode 100644index 000000000000..82afbc71341c--- /dev/null+++ b/posthog/security/crosslang/README.md@@ -0,0 +1,26 @@+# Out-of-band interaction domains++`oob_domains.json` lists the services that exist to capture out-of-band interactions, and the+DNS rebinding services. PostHog's host guards log a lookup of any of these names.++## What belongs on the list++A domain belongs here when its service exists to capture out-of-band interactions or to perform+DNS rebinding, and it has no legitimate production use.++These do not belong here:++- Wildcard-IP DNS, such as `nip.io` and `sslip.io`. Knative and OpenShift use them for real+ routes, and the IP checks already refuse the private targets.+- Request-inspection services, such as `webhook.site` and `ngrok`. Customers use them to test+ destinations.++## How to edit the list++1. Edit this file first.+2. Update each mirror. A parity test in that language fails until you do.+3. The matcher compares the canonical host, exactly or on a label boundary. Write the registrable+ domain only, lowercase, with no leading dot.++Python reads this file at runtime. Node and Rust hold mirrors, because the Rust image build+context is `rust/` and the Node build compiles from `nodejs/`.diff --git a/posthog/security/crosslang/oob_domains.json b/posthog/security/crosslang/oob_domains.jsonnew file mode 100644index 000000000000..ab2acd4f7404--- /dev/null+++ b/posthog/security/crosslang/oob_domains.json@@ -0,0 +1,17 @@+{+ "domains": [+ "1u.ms",+ "burpcollaborator.net",+ "ceye.io",+ "dnslog.cn",+ "interact.sh",+ "oast.fun",+ "oast.live",+ "oast.me",+ "oast.online",+ "oast.pro",+ "oast.site",+ "oastify.com",+ "rbndr.us"+ ]+}diff --git a/posthog/security/oob_domains.py b/posthog/security/oob_domains.pynew file mode 100644index 000000000000..e792c3789585--- /dev/null+++ b/posthog/security/oob_domains.py@@ -0,0 +1,39 @@+import json+from functools import lru_cache+from pathlib import Path++import structlog++from posthog.security.url_validation import canonicalize_host++logger = structlog.get_logger(__name__)++_DOMAINS_PATH = Path(__file__).parent / "crosslang" / "oob_domains.json"+++@lru_cache(maxsize=1)+def oob_domains() -> frozenset[str]:+ """The out-of-band interaction domains, read once.++ Detection must never break traffic, so a missing or malformed file matches nothing. When this+ list starts refusing hosts, this read has to fail closed instead.+ """+ try:+ raw = json.loads(_DOMAINS_PATH.read_text())+ return frozenset(domain.lower() for domain in raw["domains"])+ except (OSError, ValueError, KeyError, TypeError) as error:+ logger.exception("security.oob_domains_unavailable", error=str(error))+ return frozenset()+++def matched_oob_domain(host: str) -> str | None:+ """The listed domain this host belongs to, or None."""+ if not host or "@" in host or "/" in host:+ # The guards hand us a parsed hostname. Anything else is a raw URL or a credential, and+ # matching it would put that string in the log line.+ return None+ canonical = canonicalize_host(host)+ for domain in oob_domains():+ if canonical == domain or canonical.endswith(f".{domain}"):+ return domain+ return Nonediff --git a/posthog/security/test/test_oob_domains.py b/posthog/security/test/test_oob_domains.pynew file mode 100644index 000000000000..86e34c56837e--- /dev/null+++ b/posthog/security/test/test_oob_domains.py@@ -0,0 +1,46 @@+import json+from pathlib import Path++import pytest++from posthog.security.oob_domains import matched_oob_domain, oob_domains+++ "host",+ ["oast.live", "x.oast.live", "a.b.oast.pro", "burpcollaborator.net", "sub.oastify.com", "OAST.ME", "oast.me."],+)+def test_matches_listed_domains(host: str) -> None:+ assert matched_oob_domain(host) is not None+++ "host",+ ["notoast.me", "oast.me.evil.example", "example.com", "", "myoast.live"],+)+def test_passes_other_hosts(host: str) -> None:+ assert matched_oob_domain(host) is None+++def test_matches_the_idna_form_of_a_listed_domain() -> None:+ assert matched_oob_domain("oast.me") == "oast.me"+++def test_returns_the_matched_domain() -> None:+ assert matched_oob_domain("abc.oast.live") == "oast.live"+++def test_file_and_loader_agree() -> None:+ raw = json.loads((Path(__file__).parents[1] / "crosslang" / "oob_domains.json").read_text())+ assert oob_domains() == frozenset(raw["domains"])+++def test_a_broken_file_matches_nothing_instead_of_raising(monkeypatch: pytest.MonkeyPatch) -> None:+ import posthog.security.oob_domains as module++ module.oob_domains.cache_clear()+ monkeypatch.setattr(module, "_DOMAINS_PATH", Path("/nonexistent/oob_domains.json"))+ try:+ assert matched_oob_domain("oast.live") is None+ finally:+ module.oob_domains.cache_clear()diff --git a/posthog/security/test/test_url_validation.py b/posthog/security/test/test_url_validation.pyindex 38ceb23bfe77..8203e95edba6 100644--- a/posthog/security/test/test_url_validation.py+++ b/posthog/security/test/test_url_validation.py@@ -573,3 +573,34 @@ class TestUrlValidation:)def test_rejects_non_teams_webhook_url(self, url):assert uv.is_microsoft_teams_webhook_url(url) is False+++class TestOOBDomainDetection:+ @pytest.fixture+ def seen(self, monkeypatch):+ events: list[tuple[str, dict]] = []+ monkeypatch.setattr(uv.logger, "info", lambda event, **fields: events.append((event, fields)))+ return events++ def test_logs_a_listed_host_and_still_allows_it(self, monkeypatch, seen):+ monkeypatch.setattr(uv, "is_cloud", lambda: True)++ assert uv._blocked_host_name("abc.oast.live") is None++ assert [event for event, _ in seen] == ["security.oob_domain_seen"]+ assert seen[0][1]["domain"] == "oast.live"+ assert seen[0][1]["guard"] == "url_validation"++ def test_does_not_log_an_unlisted_host(self, monkeypatch, seen):+ monkeypatch.setattr(uv, "is_cloud", lambda: True)++ assert uv._blocked_host_name("notoast.me") is None++ assert seen == []++ def test_does_not_log_off_cloud(self, monkeypatch, seen):+ monkeypatch.setattr(uv, "is_cloud", lambda: False)++ assert uv._blocked_host_name("abc.oast.live") is None++ assert seen == []diff --git a/posthog/security/url_validation.py b/posthog/security/url_validation.pyindex f9e89aeda8f5..2e4c0c9cb899 100644--- a/posthog/security/url_validation.py+++ b/posthog/security/url_validation.py@@ -11,7 +11,7 @@ import structlogimport dns.resolverimport dns.exception-from posthog.cloud_utils import is_dev_mode+from posthog.cloud_utils import is_cloud, is_dev_modefrom posthog.dataclasses import frozenlogger = structlog.get_logger(__name__)@@ -182,7 +182,7 @@ def _matches_hostname_pattern(host: str) -> bool:return len(host) <= _MAX_HOSTNAME_LENGTH and _BARE_HOSTNAME.fullmatch(host) is not None-def _canonicalize_host(host: str) -> str:+def canonicalize_host(host: str) -> str:"""The one form every host check runs on.We strip any trailing "." because an absolute FQDN carries the DNS root dot ("db.corp.").@@ -200,6 +200,9 @@ def _canonicalize_host(host: str) -> str:return host.lower().rstrip(".")+_canonicalize_host = canonicalize_host++def _host_shape_error(host: str) -> str | None:"""Reason to reject a host on its form alone, or None when the form is usable.@@ -281,6 +284,14 @@ def _blocked_host_name(host: str) -> BlockedName | None:return BlockedName(reason=f"Internal domain pattern blocked: {pattern}", pattern=pattern)if _is_internal_ip_literal(host):return BlockedName(reason="Private IP address not allowed")++ if is_cloud():+ # Detection only: these names resolve to ordinary public IPs, so every IP check passes+ # them, and the lookup alone confirms the path to whoever runs the collaborator.+ from posthog.security.oob_domains import matched_oob_domain # noqa: PLC0415 — breaks an import cycle++ if (oob_domain := matched_oob_domain(host)) is not None:+ logger.info("security.oob_domain_seen", host=host, domain=oob_domain, guard="url_validation")return Nonediff --git a/posthog/test/repo_invariants/oob_denylist_coverage_baseline.txt b/posthog/test/repo_invariants/oob_denylist_coverage_baseline.txtnew file mode 100644index 000000000000..a1127a33e4a5--- /dev/null+++ b/posthog/test/repo_invariants/oob_denylist_coverage_baseline.txt@@ -0,0 +1,19 @@+nodejs/src/cdp/services/messaging/email-validation.service.ts+nodejs/src/common/utils/request.ts+nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts+posthog/api/proxy_record_diagnostics.py+posthog/api/utils.py+posthog/dns_utils.py+posthog/domain_connect.py+posthog/models/organization_domain.py+posthog/psycopg_helpers.py+posthog/temporal/proxy_service/create.py+posthog/temporal/proxy_service/monitor.py+products/desktop/apps/code/src/main/bootstrap.ts+products/desktop/packages/workspace-server/src/serve.ts+products/tasks/backend/logic/services/agent_command.py+products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/destinations_load/writers/postgres.py+products/warehouse_sources/backend/temporal/data_imports/sources/salesforce/auth.py+products/workflows/backend/providers/ses.py+rust/common/dns/src/lib.rs+rust/cymbal/src/modes/processing/stages/resolution/remote/dns.rsdiff --git a/posthog/test/repo_invariants/test_oob_denylist_coverage.py b/posthog/test/repo_invariants/test_oob_denylist_coverage.pynew file mode 100644index 000000000000..a0222ee79839--- /dev/null+++ b/posthog/test/repo_invariants/test_oob_denylist_coverage.py@@ -0,0 +1,85 @@+"""Ratchet on files that resolve a hostname without the out-of-band domain check.++Every host guard in this repo is IP-based, and an out-of-band interaction domain resolves to an+ordinary public IP, so a new resolver that skips the check silently restores the gap.++The check proves a file references the matcher. It cannot prove the call runs before the resolve,+so placement stays a review matter.+"""++import sys+from pathlib import Path++REPO_ROOT = Path(__file__).parents[3]+BASELINE = Path(__file__).parent / "oob_denylist_coverage_baseline.txt"+REGENERATE = "python posthog/test/repo_invariants/test_oob_denylist_coverage.py"++SCANNED_ROOTS = ("posthog", "products", "ee", "common", "nodejs/src", "rust")+SCANNED_SUFFIXES = (".py", ".ts", ".rs")+RESOLUTION_MARKERS = (+ # Python+ "getaddrinfo(",+ "gethostbyname",+ "dns.resolver",+ "dns.asyncresolver",+ # TypeScript+ "dns.lookup",+ "dns/promises",+ "node:dns",+ "resolveMx(",+ "resolve4(",+ # Rust+ "to_socket_addrs(",+ "lookup_host(",+ "TokioAsyncResolver",+ "hickory",+ "trust_dns",+)++CHECK_MARKERS = ("matched_oob_domain", "note_oob_domain", "OOB_DOMAINS", "oob_domains")+SKIPPED_PARTS = ("node_modules", "__pycache__", "target", "dist", "migrations")+++def _is_test(path: Path) -> bool:+ name = path.name+ return name.startswith("test_") or name.endswith(("_test.py", ".test.ts", ".spec.ts")) or "tests" in path.parts+++def _resolves_hostnames(text: str) -> bool:+ """Whether the file resolves a hostname and never names the out-of-band check."""+ return any(marker in text for marker in RESOLUTION_MARKERS) and not any(marker in text for marker in CHECK_MARKERS)+++def collect() -> list[str]:+ found: set[str] = set()+ for root in SCANNED_ROOTS:+ for path in (REPO_ROOT / root).rglob("*"):+ if path.suffix not in SCANNED_SUFFIXES or not path.is_file():+ continue+ if any(part in SKIPPED_PARTS for part in path.parts) or _is_test(path):+ continue+ if _resolves_hostnames(path.read_text(errors="ignore")):+ found.add(str(path.relative_to(REPO_ROOT)))+ return sorted(found)+++def test_resolvers_match_the_baseline() -> None:+ scanned = collect()+ recorded = sorted(line for line in BASELINE.read_text().splitlines() if line.strip())+ if scanned == recorded:+ return+ added = [line for line in scanned if line not in recorded]+ removed = [line for line in recorded if line not in scanned]+ report = "\n".join([*(f" + {line}" for line in added), *(f" - {line}" for line in removed)])+ raise AssertionError(+ "oob_denylist_coverage_baseline.txt no longer matches the repo.\n"+ "A '+' line resolves a hostname and does not reference the out-of-band domain check. "+ "Call the check before the resolve. Do not add the line to the baseline: the list may only get shorter.\n"+ f"A '-' line means a file was fixed. The file must record that too. Run: {REGENERATE}\n"+ f"{report}"+ )+++if __name__ == "__main__":+ BASELINE.write_text("\n".join(collect()) + "\n")+ sys.stdout.write(f"{BASELINE.name} written\n")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/tests/test_transport.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/tests/test_transport.pyindex b2c9b39015b1..be463b9b6ce5 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/tests/test_transport.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/tests/test_transport.py@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, patchfrom django.test import override_settings+import requestsfrom parameterized import parameterizedfrom urllib3.exceptions import MaxRetryError, ReadTimeoutError@@ -105,3 +106,89 @@ class TestBoundedRetry:assert sum(call.args[0] for call in sleep.call_args_list) == expected_sleep# The adapter cannot know where the source is, so it never reaches a safe point by itself.safe_point.assert_not_called()+++class TestOOBDomainDetection:+ def _record(self, mocker):+ events: list[tuple[str, dict]] = []+ mocker.patch.object(transport, "is_cloud", return_value=True)+ mocker.patch.object(+ transport.logger, "info", side_effect=lambda event, **fields: events.append((event, fields))+ )+ mocker.patch("requests.adapters.HTTPAdapter.send", return_value=MagicMock())+ return events++ def test_logs_a_listed_host(self, mocker):+ events = self._record(mocker)+ adapter = transport.make_tracked_adapter()++ adapter.send(requests.Request("GET", "https://abc.oast.live/x").prepare())++ assert [event for event, _ in events] == ["security.oob_domain_seen"]+ assert events[0][1]["domain"] == "oast.live"+ assert events[0][1]["guard"] == "warehouse_http"++ def test_a_matcher_failure_logs_the_host_and_never_the_url(self, mocker):+ events: list[tuple[str, dict]] = []+ mocker.patch.object(transport, "is_cloud", return_value=True)+ mocker.patch.object(transport, "matched_oob_domain", side_effect=RuntimeError("boom"))+ mocker.patch.object(+ transport.logger, "exception", side_effect=lambda event, **fields: events.append((event, fields))+ )+ mocker.patch("requests.adapters.HTTPAdapter.send", return_value=MagicMock())+ adapter = transport.make_tracked_adapter()++ adapter.send(requests.Request("GET", "https://key:[email protected]/x?api_key=abc").prepare())++ assert [event for event, _ in events] == ["security.oob_domain_check_failed"]+ assert events[0][1] == {"host": "example.com"}++ def test_logs_a_redirect_hop_to_a_listed_host(self, mocker):+ events: list[tuple[str, dict]] = []+ mocker.patch.object(transport, "is_cloud", return_value=True)+ mocker.patch.object(+ transport.logger, "info", side_effect=lambda event, **fields: events.append((event, fields))+ )+ session = transport.make_tracked_session()+ start = session.prepare_request(requests.Request("GET", "https://example.com/start"))+ redirect = requests.Response()+ redirect.status_code = 302+ redirect.headers["Location"] = "https://abc.oast.live/hop"+ redirect.url = "https://example.com/start"+ redirect.request = start+ final = requests.Response()+ final.status_code = 200+ final.url = "https://abc.oast.live/hop"+ mocker.patch("requests.adapters.HTTPAdapter.send", side_effect=[redirect, final])++ session.send(start, allow_redirects=True)++ assert [fields["host"] for _, fields in events] == ["abc.oast.live"]++ def test_does_not_log_an_unlisted_host(self, mocker):+ events = self._record(mocker)+ adapter = transport.make_tracked_adapter()++ adapter.send(requests.Request("GET", "https://notoast.me/x").prepare())++ assert events == []++ def test_a_request_with_no_hostname_does_not_raise(self, mocker):+ events = self._record(mocker)+ adapter = transport.make_tracked_adapter()+ request = requests.Request("GET", "https://example.com/x").prepare()+ request.url = "/relative/path"++ adapter.send(request)++ assert events == []++ def test_a_malformed_ipv6_url_does_not_raise(self, mocker):+ events = self._record(mocker)+ adapter = transport.make_tracked_adapter()+ request = requests.Request("GET", "https://example.com/x").prepare()+ request.url = "https://[::1/x"++ adapter.send(request)++ assert events == []diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.pyindex 49e27e5ae043..2a6692e1cd10 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/http/transport.py@@ -20,21 +20,28 @@ from collections.abc import Iterator, Mappingfrom contextlib import contextmanagerfrom contextvars import ContextVarfrom typing import Any, cast+from urllib.parse import urlparsefrom django.conf import settingsimport requests+import structlogfrom requests import PreparedRequest, Responsefrom requests.adapters import HTTPAdapterfrom urllib3.exceptions import InvalidHeader, MaxRetryError, ResponseErrorfrom urllib3.util.retry import Retry+from posthog.cloud_utils import is_cloud+from posthog.security.oob_domains import matched_oob_domain+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.observer import record_requestfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.interruptible_wait import (interruptible_wait,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.retry_limits import retry_budget_seconds+logger = structlog.get_logger(__name__)+RequestTimeout = float | tuple[float, float] | tuple[float, None]# Pass this as `timeout` to send a request with no deadline. `None` does not do that: `requests`@@ -182,6 +189,38 @@ DEFAULT_RETRY = BoundedRetry()+def _note_oob_domain(request: PreparedRequest) -> None:+ """Record a request to an out-of-band interaction domain, without refusing it.++ `requests` re-enters the adapter on every redirect hop, so a hop to a listed host is recorded+ as well as the first request.+ """+ if not is_cloud():+ return++ try:+ host = urlparse(request.url or "").hostname+ except Exception as exc:+ # Detection never fails a request: a malformed URL is the connection's problem to report.+ # `requests` rejects a URL it cannot parse before `send()`, so reaching this means the two+ # parsers disagree. The URL stays out of the line because it carries the credential that+ # `record_request` scrubs; it logs the same request a moment later.+ logger.warning("security.oob_domain_url_unparsed", error=type(exc).__name__)+ return++ if host is None:+ return++ try:+ oob_domain = matched_oob_domain(host)+ except Exception:+ logger.exception("security.oob_domain_check_failed", host=host)+ return++ if oob_domain is not None:+ logger.info("security.oob_domain_seen", host=host, domain=oob_domain, guard="warehouse_http")++class TrackedHTTPAdapter(HTTPAdapter):"""`HTTPAdapter` that records every dispatched request via the observer.@@ -224,6 +263,7 @@ class TrackedHTTPAdapter(HTTPAdapter):cert: bytes | str | tuple[bytes | str, bytes | str] | None = None,proxies: Mapping[str, str] | None = None,) -> Response:+ _note_oob_domain(request)started = time.monotonic()response: Response | None = Noneexception: BaseException | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.pyindex 0546ef39e777..e888fc4d5896 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/mixins.py@@ -22,6 +22,7 @@ from posthog.psycopg_helpers import (prefer_routable_addresses,resolve_psycopg_hostaddr_with_timeout,)+from posthog.security.oob_domains import matched_oob_domainfrom posthog.temporal.common.errors import NonReportableErrorfrom posthog.utils import get_instance_region@@ -174,6 +175,8 @@ def resolve_safe_host(host: str, team_id: int | None) -> HostResolution:addresses in turn, resolves the host itself and passes the answer to`check_resolved_addresses` instead, so the set it validates is the set it dials."""+ note_oob_domain(host, team_id)+if is_cloud() and (guard_error := _single_host_error(host)) is not None:_log_host_check(host, team_id, "block", "malformed_host", guard_error)return HostResolution(connect_host=None, error=guard_error)@@ -233,6 +236,8 @@ def check_resolved_addresses(host: str, addresses: Sequence[str], team_id: int |exempt caller still dials what it resolved. An empty `addresses` is a failed lookup and isrefused, because letting the connection library resolve again would reopen the gap."""+ note_oob_domain(host, team_id, stage="oob_domain_resolved")+if is_cloud() and (guard_error := _single_host_error(host)) is not None:_log_host_check(host, team_id, "block", "malformed_host", guard_error)return HostResolution(connect_host=None, error=guard_error)@@ -263,6 +268,8 @@ def pinned_host_kwargs(host: str, *, port: int, connect_timeout: float, team_id:lookup to race and comes back unchanged. Dev and test connect to local or fake hosts, so thelookup is skipped there, as in `_get_sslmode`."""+ note_oob_domain(host, team_id)+if host_lookup_is_skipped():return {"host": host}@@ -383,6 +390,27 @@ def _host_check_exemption(host: str, team_id: int | None) -> str | None:return None+def note_oob_domain(host: str, team_id: int | None, stage: str = "oob_domain") -> None:+ """Record a lookup of an out-of-band interaction domain, without refusing it.++ Runs before the exemptions, so an allowlisted team is recorded too, and before the resolve,+ because the lookup alone confirms the path to whoever runs the collaborator. `stage` tells a+ reader which call site produced the line, so a count does not double on the pinned paths.+ """+ if not is_cloud():+ return++ try:+ oob_domain = matched_oob_domain(unbracket_host(host))+ except Exception:+ # Detection never refuses a connection, so a fault here stays invisible to the customer.+ logger.exception("data_imports.oob_domain_check_failed", host=host, team_id=team_id)+ return++ if oob_domain is not None:+ _log_host_check(host, team_id, "allow", stage, oob_domain)++def _check_resolved_ips(host: str, team_id: int | None, resolved_ips: list[str]) -> HostResolution:if not resolved_ips:_log_host_check(host, team_id, "block", "dns_failure", _DNS_FAILURE_ERROR)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.pyindex 65d5d4e5596b..71d43b5d2b62 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test_mixins.py@@ -35,6 +35,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixcheck_resolved_addresses,make_ssh_tunnel_factory,open_ssh_tunnel,+ pinned_host_kwargs,resolve_safe_host,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.tests.resolver import resolver@@ -934,3 +935,101 @@ class TestCheckResolvedAddresses(SimpleTestCase):assert resolution.error is Noneassert resolution.connect_host == hostassert resolution.addresses == ("10.0.0.5",)+++class TestOOBDomainDetection(SimpleTestCase):+ def test_logs_before_the_exemption_so_an_allowlisted_team_is_recorded(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=True),+ patch(f"{_MIXINS_MODULE}._host_check_exemption", return_value="team_allowlist"),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ resolution = resolve_safe_host("abc.oast.live", 2)++ stages = [call.args[3] for call in log_host_check.call_args_list]+ assert "oob_domain" in stages+ assert resolution.connect_host is not None++ def test_records_the_matched_domain_as_the_reason(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=True),+ patch(f"{_MIXINS_MODULE}._host_check_exemption", return_value="team_allowlist"),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ resolve_safe_host("abc.oast.live", 2)++ oob_calls = [call for call in log_host_check.call_args_list if call.args[3] == "oob_domain"]+ assert [call.args[4] for call in oob_calls] == ["oast.live"]++ def test_does_not_log_off_cloud(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=False),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ resolve_safe_host("abc.oast.live", 2)++ stages = [call.args[3] for call in log_host_check.call_args_list]+ assert "oob_domain" not in stages++ def test_does_not_log_an_unlisted_host(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=True),+ patch(f"{_MIXINS_MODULE}._host_check_exemption", return_value="team_allowlist"),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ resolve_safe_host("notoast.me", 2)++ stages = [call.args[3] for call in log_host_check.call_args_list]+ assert "oob_domain" not in stages+++class TestOOBDomainDetectionOnThePinnedPath(SimpleTestCase):+ def test_logs_before_it_resolves(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=True),+ patch(f"{_MIXINS_MODULE}.host_lookup_is_skipped", return_value=False),+ patch(f"{_MIXINS_MODULE}._resolve_hostaddr_with_timeout", side_effect=AssertionError("resolved first")),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ with pytest.raises(AssertionError):+ pinned_host_kwargs("abc.oast.live", port=5432, connect_timeout=1.0, team_id=2)++ stages = [call.args[3] for call in log_host_check.call_args_list]+ assert "oob_domain" in stages+++class TestOOBDomainDetectionDetail(SimpleTestCase):+ def test_the_two_call_sites_are_distinguishable(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=True),+ patch(f"{_MIXINS_MODULE}._host_check_exemption", return_value="team_allowlist"),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ resolve_safe_host("abc.oast.live", 2)+ check_resolved_addresses("abc.oast.live", ["93.184.216.34"], 2)++ stages = [call.args[3] for call in log_host_check.call_args_list if call.args[3].startswith("oob_domain")]+ assert stages == ["oob_domain", "oob_domain_resolved"]++ def test_a_host_with_userinfo_is_not_matched(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=True),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ resolve_safe_host("user:[email protected]", 2)++ stages = [call.args[3] for call in log_host_check.call_args_list]+ assert "oob_domain" not in stages++ def test_the_real_team_allowlist_does_not_swallow_the_detection(self):+ with (+ patch(f"{_MIXINS_MODULE}.is_cloud", return_value=True),+ patch(f"{_MIXINS_MODULE}.get_instance_region", return_value="US"),+ patch(f"{_MIXINS_MODULE}._log_host_check") as log_host_check,+ ):+ resolution = resolve_safe_host("abc.oast.live", 2)++ stages = [call.args[3] for call in log_host_check.call_args_list]+ assert stages[0] == "oob_domain"+ assert "team_allowlist" in stages+ assert resolution.connect_host is not Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.pyindex f03cd0402c18..89068d14323f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/mysql.py@@ -63,6 +63,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixHostNotAllowedError,check_resolved_addresses,host_lookup_is_skipped,+ note_oob_domain,open_ssh_tunnel,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager@@ -692,6 +693,8 @@ def _pinned_addresses(host: str, port: int, connect_timeout: int, team_id: int |or a resolver "try again" answer raises the error pymysql raises for its own failed lookup,so the transient-connect retry runs a fresh lookup on the next attempt."""+ note_oob_domain(host, team_id)+if host_lookup_is_skipped():return ()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.pyindex ee9266403d02..6f55f1decbdf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/mysql/tests/test_mysql.py@@ -61,6 +61,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysq_is_transient_vitess_dial_timeout,_is_transient_vitess_no_endpoints,_is_transient_vitess_reparent,+ _pinned_addresses,_reconnect_pinned,_release_streaming_cursor,_retry_on_transient_tablet_unavailable,@@ -3387,3 +3388,22 @@ class TestConnectCertificateVerification:else:connection._request_authentication()delegate.assert_called_once()+++class TestOOBDomainDetection:+ def test_the_pinned_path_logs_before_it_resolves(self, mocker):+ mysql_module = "products.warehouse_sources.backend.temporal.data_imports.sources.mysql.mysql"+ mixins_module = "products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins"+ mocker.patch(f"{mixins_module}.is_cloud", return_value=True)+ mocker.patch(f"{mysql_module}.host_lookup_is_skipped", return_value=False)+ mocker.patch(+ f"{mysql_module}.resolve_psycopg_hostaddr_with_timeout",+ side_effect=AssertionError("resolved before the detection log"),+ )+ log_host_check = mocker.patch(f"{mixins_module}._log_host_check")++ with pytest.raises(AssertionError):+ _pinned_addresses("abc.oast.live", 3306, 5, 2)++ stages = [call.args[3] for call in log_host_check.call_args_list]+ assert "oob_domain" in stagesdiff --git a/tools/snob_backend_test_selection_shadow.py b/tools/snob_backend_test_selection_shadow.pyindex 536218c893aa..4da6fd102a4f 100755--- a/tools/snob_backend_test_selection_shadow.py+++ b/tools/snob_backend_test_selection_shadow.py@@ -89,6 +89,8 @@ FULL_RUN_PATTERNS = ("bin/wait-for-docker","bin/ci-wait-for-docker",# Non-Python files that affect generated Python code or test behavior+ # A data file the host guards read at runtime, so a change to it is a behavior change+ "posthog/security/crosslang/","frontend/src/queries/schema.json","frontend/src/products.json","frontend/public/email/",