: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(provisioning): allow deep links to any in-app path (#60740)
Matt Brooker61af871eb1d9
diff --git a/ee/api/agentic_provisioning/test/test_deep_links.py b/ee/api/agentic_provisioning/test/test_deep_links.pyindex dba6f031511d..3605f031599f 100644--- a/ee/api/agentic_provisioning/test/test_deep_links.py+++ b/ee/api/agentic_provisioning/test/test_deep_links.py@@ -74,6 +74,45 @@ class TestDeepLinks(ProvisioningTestBase):assert res.status_code == 403assert res.json()["error"]["code"] == "deep_links_not_enabled"+ def test_deep_link_with_path_redirects_there(self):+ token = self._get_bearer_token()+ target = f"/project/{self.team.id}/replay/019e6d10-c3b0-7000-8000-000000000000"+ res = self._post_signed_with_bearer(+ "/api/agentic/provisioning/deep_links",+ data={"path": target},+ token=token,+ )+ assert res.status_code == 200++ login_token = res.json()["url"].split("token=")[1].split("&")[0]+ login_res = self.client.get(f"/agentic/login?token={login_token}")+ assert login_res.status_code == 302+ assert login_res["Location"] == target++ @parameterized.expand(+ [+ ("protocol_relative", "//evil.com"),+ ("absolute_url", "https://evil.com/steal"),+ ("backslash_host", "/\\evil.com"),+ ("javascript_scheme", "javascript:alert(1)"),+ ("not_rooted", "project/123/insights"),+ ("crlf_header_injection", "/project/1\r\nLocation: https://evil.com"),+ ("newline", "/project/1\nreplay"),+ ("tab", "/project/1\treplay"),+ ("space", "/project/1 replay"),+ ("null_byte", "/project/1\x00"),+ ]+ )+ def test_deep_link_rejects_unsafe_path(self, _name: str, path: str):+ token = self._get_bearer_token()+ res = self._post_signed_with_bearer(+ "/api/agentic/provisioning/deep_links",+ data={"path": path},+ token=token,+ )+ assert res.status_code == 400+ assert res.json()["error"]["code"] == "invalid_path"+def test_deep_link_requires_hmac_signature_for_hmac_partner(self):from posthog.models.oauth import OAuthApplication@@ -179,3 +218,26 @@ class TestAgenticLogin(ProvisioningTestBase):res = self.client.get(f"/agentic/login?token={token}")assert res.status_code == 302assert not res["Location"].startswith("http")++ def test_path_token_redirects_to_path(self):+ token = "test_path_token"+ target = f"/project/{self.team.id}/replay/abc123-DEF"+ cache.set(+ f"{DEEP_LINK_CACHE_PREFIX}{token}",+ {"user_id": self.user.id, "team_id": self.team.id, "path": target},+ timeout=600,+ )+ res = self.client.get(f"/agentic/login?token={token}")+ assert res.status_code == 302+ assert res["Location"] == target++ def test_unsafe_path_in_cache_falls_back_to_project(self):+ token = "test_unsafe_path_token"+ cache.set(+ f"{DEEP_LINK_CACHE_PREFIX}{token}",+ {"user_id": self.user.id, "team_id": self.team.id, "path": "//evil.com"},+ timeout=600,+ )+ res = self.client.get(f"/agentic/login?token={token}")+ assert res.status_code == 302+ assert res["Location"] == f"/project/{self.team.id}"diff --git a/ee/api/agentic_provisioning/views.py b/ee/api/agentic_provisioning/views.pyindex 651aae074954..218880cce762 100644--- a/ee/api/agentic_provisioning/views.py+++ b/ee/api/agentic_provisioning/views.py@@ -20,6 +20,7 @@ from django.db import IntegrityError, transactionfrom django.http import HttpResponseRedirectfrom django.http.response import HttpResponseBasefrom django.utils import timezone+from django.utils.http import url_has_allowed_host_and_schemeimport requestsimport structlog@@ -67,7 +68,10 @@ AUTH_CODE_TTL_SECONDS = 300PENDING_AUTH_TTL_SECONDS = 600DEEP_LINK_TTL_SECONDS = 600DEEP_LINK_CACHE_PREFIX = "provisioning_deep_link:"-SUPPORTED_DEEP_LINK_PURPOSES = {"dashboard"}+DEEP_LINK_MAX_PATH_LENGTH = 2000+# Control chars, whitespace, and backslashes never appear in a legitimate in-app path; they are the+# building blocks of header-injection and backslash-host open-redirect tricks, so reject them outright.+DEEP_LINK_DISALLOWED_PATH_CHARS = re.compile(r"[\x00-\x20\x7f-\x9f\\]")DEEP_LINK_RATE_LIMIT_PREFIX = "agentic_login_rate:"DEEP_LINK_RATE_LIMIT_MAX_ATTEMPTS = 10DEEP_LINK_RATE_LIMIT_WINDOW_SECONDS = 300@@ -2034,18 +2038,17 @@ def deep_links(request: Request) -> Response:status=403,)+ # `purpose` is a free-form label retained for analytics. `path` is the generic+ # destination: any in-app path the partner wants the user to land on after login.purpose = request.data.get("purpose", "dashboard")- if purpose not in SUPPORTED_DEEP_LINK_PURPOSES:+ path = request.data.get("path")+ if path and not _is_safe_deep_link_path(path):_capture_provisioning_event(- "deep_link_created", "unsupported_purpose", partner=access_token.application, purpose=purpose+ "deep_link_created", "invalid_path", partner=access_token.application, purpose=purpose)- return Response(- {- "error": {- "code": "unsupported_purpose",- "message": f"Unsupported purpose: {purpose}. Supported: {', '.join(sorted(SUPPORTED_DEEP_LINK_PURPOSES))}",- }- },+ return _error_response(+ "invalid_path",+ "path must be a relative in-app path beginning with a single '/'",status=400,)@@ -2063,6 +2066,7 @@ def deep_links(request: Request) -> Response:"user_id": access_token.user_id,"team_id": team_id,"purpose": purpose,+ "path": path or None,},timeout=DEEP_LINK_TTL_SECONDS,)@@ -2417,6 +2421,7 @@ def agentic_login(request: Any) -> HttpResponseBase:user_id = link_data.get("user_id")team_id = link_data.get("team_id")purpose = link_data.get("purpose", "dashboard")+ path = link_data.get("path")if not user_id:_capture_deep_link_event("invalid_token_data")@@ -2443,11 +2448,31 @@ def agentic_login(request: Any) -> HttpResponseBase:_capture_deep_link_event("success", user_id=user_id, team_id=team_id, purpose=purpose)logger.info("agentic_login.success", user_id=user_id, team_id=team_id, purpose=purpose)- redirect_path = _deep_link_redirect_path(purpose, team_id)+ redirect_path = _deep_link_redirect_path(purpose, team_id, path)return HttpResponseRedirect(redirect_path)-def _deep_link_redirect_path(purpose: str, team_id: int | None) -> str:+def _is_safe_deep_link_path(path: object) -> bool:+ """Allow only relative, same-origin in-app paths so a deep link can't become an open redirect."""+ return (+ isinstance(path, str)+ and 0 < len(path) <= DEEP_LINK_MAX_PATH_LENGTH+ # Reject control chars, whitespace, and backslashes (the `/\` backslash-host form included).+ and not DEEP_LINK_DISALLOWED_PATH_CHARS.search(path)+ and path.startswith("/")+ # Reject protocol-relative (`//`) forms; a single leading `/` keeps it same-origin.+ and not path.startswith("//")+ and url_has_allowed_host_and_scheme(path, allowed_hosts=None)+ )+++def _deep_link_redirect_path(purpose: str, team_id: int | None, path: str | None = None) -> str:+ if path and _is_safe_deep_link_path(path):+ return path+ if path:+ # Unreachable in normal operation (mint-time validation already ran); a hit here means+ # cache tampering or a mint-side regression.+ logger.warning("agentic_login.unsafe_path_in_cache", path=path)if team_id and Team.objects.filter(id=team_id).exists():return f"/project/{team_id}"return "/"