: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
chore(devex): close semgrep gaps in url naming, codegen and egress guards (#109791)
Julian Bezab6957336525
diff --git a/.semgrep/rules/devex/api-route-path-underscore-in-products.py b/.semgrep/rules/devex/api-route-path-underscore-in-products.pynew file mode 100644index 000000000000..8ef0c9b0c95c--- /dev/null+++ b/.semgrep/rules/devex/api-route-path-underscore-in-products.py@@ -0,0 +1,26 @@+# Test cases for the api-route-path-underscore-in-products rule.+# ruff: noqa+++api_urlpatterns = [+ # ruleid: api-route-path-underscore-in-products+ re_path(r"^v1/email/set-trusted-relay/?$", EmailSetTrustedRelayView.as_view(), name="email-set-trusted-relay"),+ # ruleid: api-route-path-underscore-in-products+ path("count-accounts/", csrf_exempt(CountAccountsView.as_view())),+ # ok: api-route-path-underscore-in-products+ re_path(r"^v1/email/set_trusted_relay/?$", EmailSetTrustedRelayView.as_view(), name="email-set-trusted-relay"),+ # ok: api-route-path-underscore-in-products+ path("external/ticket/<uuid:ticket_id>", ExternalTicketView.as_view(), name="external-ticket"),+]++webhook_urlpatterns = [+ # ok: api-route-path-underscore-in-products+ path("ses-events", SesEventsView.as_view()),+ # ok: api-route-path-underscore-in-products+ re_path(r"^vapi-webhook/?$", VapiWebhookView.as_view()),+]++webhook_urlpatterns: list[URLPattern] = [+ # ok: api-route-path-underscore-in-products+ path("annotated-events", SesEventsView.as_view()),+]diff --git a/.semgrep/rules/devex/api-route-path-underscore-in-products.yaml b/.semgrep/rules/devex/api-route-path-underscore-in-products.yamlnew file mode 100644index 000000000000..d03a9620dd15--- /dev/null+++ b/.semgrep/rules/devex/api-route-path-underscore-in-products.yaml@@ -0,0 +1,44 @@+rules:+ - id: api-route-path-underscore-in-products+ message: |+ This API route uses a hyphen in a path segment. API paths use underscores+ (`set_default`, not `set-default`), so that the URL, the view name and the JSON fields all+ read the same way. This covers a route passed to `path()`, `re_path()` or+ `opt_slash_path()` in a product `urls.py`, `routes.py` or `hub_api.py`. Product routes+ sit under an `api/` mount.++ Change the literal to use underscores. Route names (`name="..."`) and `<converter:param>`+ values are not checked.++ A hyphenated path that has already shipped keeps its name, because SDKs, MCP tools and+ customer scripts call it. It carries `# nosemgrep: api-route-path-underscore-in-products` on the line+ above. Use the same comment, with a reason, when a provider or an external contract+ dictates the path. Routes in `webhook_urlpatterns` are not checked.+ severity: WARNING+ languages: [python]+ paths:+ include:+ - 'products/**/backend/**/urls.py'+ - 'products/**/backend/**/routes.py'+ - 'products/**/backend/**/hub_api.py'+ exclude:+ - '**/test/**'+ - '**/tests/**'+ - '**/test_*.py'+ patterns:+ - pattern-either:+ - pattern: path("$PATH", ...)+ - pattern: re_path("$PATH", ...)+ - pattern: opt_slash_path("$PATH", ...)+ # A product mounts `webhook_urlpatterns` at `webhooks/<product>/`: not an API route.+ - pattern-not-inside: |+ webhook_urlpatterns = [...]+ - pattern-not-inside: |+ webhook_urlpatterns: $T = [...]+ # Same segment check as `api-path-underscore`. Product modules declare routes relative+ # to an API mount, so every route counts. `^` may start a `re_path` pattern.+ - metavariable-regex:+ metavariable: $PATH+ regex: '^(?:\^)?(?:.*/)?[A-Za-z0-9_]+-[A-Za-z0-9_-]*(?=/|\(|\?|\$|$)'+ metadata:+ category: best-practicediff --git a/.semgrep/rules/devex/github-api-calls-go-through-egress.py b/.semgrep/rules/devex/github-api-calls-go-through-egress.pyindex 74af9f8d9bba..671895fa48f9 100644--- a/.semgrep/rules/devex/github-api-calls-go-through-egress.py+++ b/.semgrep/rules/devex/github-api-calls-go-through-egress.py@@ -1,6 +1,10 @@# Test cases for github-api-calls-go-through-egress rule.# ruff: noqa: F841, E501+import httpx+import aiohttpimport requests+import urllib.request+from urllib.request import urlopenfrom posthog.egress.github.transport import github_request@@ -28,3 +32,127 @@ def ok_through_transport(token: str):def ok_other_host():# ok: github-api-calls-go-through-egressreturn requests.get("https://example.com/api")+++GITHUB_API = "https://api.github.com"+GITHUB_USER_URL = "https://api.github.com/user"+++def flagged_url_in_variable(token: str):+ url = "https://api.github.com/user"+ # ruleid: github-api-calls-go-through-egress-wide+ return requests.get(url, headers={"Authorization": f"Bearer {token}"})+++def flagged_module_constant():+ # ruleid: github-api-calls-go-through-egress-wide+ return requests.get(GITHUB_USER_URL)+++def flagged_concatenation(repo: str):+ # ruleid: github-api-calls-go-through-egress-wide+ return requests.get(GITHUB_API + "/repos/" + repo)+++def flagged_fstring_with_constant(repo: str):+ # ruleid: github-api-calls-go-through-egress-wide+ return requests.get(f"{GITHUB_API}/repos/{repo}")+++def flagged_session():+ # ruleid: github-api-calls-go-through-egress-wide+ return requests.Session().get("https://api.github.com/user")+++def flagged_session_variable():+ session = requests.Session()+ # ruleid: github-api-calls-go-through-egress-wide+ return session.post(GITHUB_USER_URL)+++def flagged_session_context_manager():+ with requests.Session() as session:+ # ruleid: github-api-calls-go-through-egress-wide+ return session.get(GITHUB_USER_URL)+++def flagged_httpx_module_call():+ # ruleid: github-api-calls-go-through-egress-wide+ return httpx.get("https://api.github.com/user")+++def flagged_httpx_client():+ # ruleid: github-api-calls-go-through-egress-wide+ return httpx.Client().get(GITHUB_USER_URL)+++async def flagged_httpx_async_client():+ async with httpx.AsyncClient() as client:+ # ruleid: github-api-calls-go-through-egress-wide+ return await client.get(GITHUB_USER_URL)+++async def flagged_aiohttp():+ async with aiohttp.ClientSession() as session:+ # ruleid: github-api-calls-go-through-egress-wide+ return await session.get(GITHUB_USER_URL)+++def flagged_urlopen():+ # ruleid: github-api-calls-go-through-egress-wide+ return urllib.request.urlopen("https://uploads.github.com/repos/o/r/releases/1/assets")+++def flagged_urlopen_request():+ # ruleid: github-api-calls-go-through-egress-wide+ return urlopen(urllib.request.Request(GITHUB_USER_URL))+++def flagged_requests_options():+ # ruleid: github-api-calls-go-through-egress+ return requests.options("https://api.github.com/user")+++def flagged_session_request_method_first():+ session = requests.Session()+ # ruleid: github-api-calls-go-through-egress-wide+ return session.request("POST", GITHUB_USER_URL)+++async def flagged_aiohttp_request_method_first():+ async with aiohttp.ClientSession() as session:+ # ruleid: github-api-calls-go-through-egress-wide+ return await session.request("POST", GITHUB_USER_URL)+++async def flagged_aiohttp_module_request():+ # ruleid: github-api-calls-go-through-egress-wide+ return aiohttp.request("GET", GITHUB_USER_URL)+++async def flagged_aiohttp_assigned_session():+ session = aiohttp.ClientSession()+ # ruleid: github-api-calls-go-through-egress-wide+ return await session.get(GITHUB_USER_URL)+++def ok_wide_url_helpers():+ # ok: github-api-calls-go-through-egress-wide+ httpx.URL(GITHUB_USER_URL)+ session = requests.Session()+ # ok: github-api-calls-go-through-egress-wide+ session.mount(GITHUB_USER_URL, adapter)++def ok_wide_other_host():+ url = "https://example.com/api"+ # ok: github-api-calls-go-through-egress-wide+ requests.get(url)+ # ok: github-api-calls-go-through-egress-wide+ httpx.get("https://example.com/api")+ # ok: github-api-calls-go-through-egress-wide+ return requests.Session().get("https://github.com/PostHog/posthog")+++def ok_wide_through_transport(token: str):+ # ok: github-api-calls-go-through-egress-wide+ return github_request("GET", GITHUB_USER_URL, source="integration", headers={})diff --git a/.semgrep/rules/devex/github-api-calls-go-through-egress.yaml b/.semgrep/rules/devex/github-api-calls-go-through-egress.yamlindex 9dbcab438251..584b910c6a3d 100644--- a/.semgrep/rules/devex/github-api-calls-go-through-egress.yaml+++ b/.semgrep/rules/devex/github-api-calls-go-through-egress.yaml@@ -18,7 +18,8 @@ rules:egress telemetry (request volume + `X-RateLimit-*` gauges), so it can burn acustomer's GitHub budget invisibly. See `posthog/egress/github/README.md`.- This rule only catches literal/f-string URLs; keep URLs inline at the call site.+ This rule only catches literal/f-string URLs passed to `requests`; the other shapes are+ caught by `github-api-calls-go-through-egress-wide`.Suppress a legitimate exception with`# nosemgrep: github-api-calls-go-through-egress -- <reason>`.languages: [python]@@ -29,7 +30,7 @@ rules:- pattern: requests.$METHOD($URL, ...)- metavariable-regex:metavariable: $METHOD- regex: ^(get|post|put|patch|delete|head)$+ regex: ^(get|post|put|patch|delete|head|options)$- pattern: requests.request($METHOD, $URL, ...)- metavariable-regex:metavariable: $URL@@ -42,3 +43,141 @@ rules:- /products/**/*.pyexclude:- /posthog/egress/**++ - id: github-api-calls-go-through-egress-wide+ message: |+ Outbound GitHub API calls must go through the gated, recorded egress transport. This rule+ catches the shapes that `github-api-calls-go-through-egress` misses: a URL bound to a+ variable or constant first, a URL built by concatenation or an f-string, a+ `requests.Session`, `httpx`, `aiohttp` or `urllib.request` call.++ Use one of:+ - `GitHubIntegrationBase.api_request(...)` when you hold a `GitHubIntegration` /+ `UserGitHubIntegration`. It owns token refresh, the 401 refresh-retry, rate-limit+ raising (`GitHubRateLimitError`), and telemetry attribution via the instance's `source`.+ - `posthog.egress.github.transport.github_request(...)` for token-agnostic calls (user+ OAuth tokens, PATs, App JWTs). Pass `installation_id` only when the call is metered+ against that installation's budget.++ Why: a raw call bypasses the shared per-installation rate-limit budget and the egress+ telemetry, so it can burn a customer's GitHub budget invisibly. See+ `posthog/egress/github/README.md`.++ Suppress a legitimate exception with+ `# nosemgrep: github-api-calls-go-through-egress-wide -- <reason>`.+ languages: [python]+ severity: ERROR+ patterns:+ - pattern-either:+ - patterns:+ - pattern-either:+ - pattern: requests.$METHOD($URL, ...)+ - pattern: requests.Session().$METHOD($URL, ...)+ - pattern: httpx.$METHOD($URL, ...)+ - pattern: httpx.Client(...).$METHOD($URL, ...)+ - pattern: httpx.AsyncClient(...).$METHOD($URL, ...)+ - pattern: aiohttp.ClientSession(...).$METHOD($URL, ...)+ - patterns:+ - pattern: $S.$METHOD($URL, ...)+ - pattern-either:+ - pattern-inside: |+ $S = requests.Session()+ ...+ - pattern-inside: |+ $S = httpx.Client(...)+ ...+ - pattern-inside: |+ $S = httpx.AsyncClient(...)+ ...+ - pattern-inside: |+ $S = aiohttp.ClientSession(...)+ ...+ - pattern-inside: |+ with requests.Session() as $S:+ ...+ - pattern-inside: |+ with httpx.Client(...) as $S:+ ...+ - pattern-inside: |+ async with httpx.AsyncClient(...) as $S:+ ...+ - pattern-inside: |+ async with aiohttp.ClientSession(...) as $S:+ ...+ # Only the HTTP verbs send a request. `httpx.URL(...)` and `Session().mount(...)`+ # take a URL and send nothing.+ - metavariable-regex:+ metavariable: $METHOD+ regex: ^(get|post|put|patch|delete|head|options)$+ - pattern: requests.request($M, $URL, ...)+ - pattern: requests.Session().request($M, $URL, ...)+ - pattern: httpx.request($M, $URL, ...)+ - pattern: httpx.Client(...).request($M, $URL, ...)+ - pattern: httpx.AsyncClient(...).request($M, $URL, ...)+ - pattern: aiohttp.request($M, $URL, ...)+ - pattern: aiohttp.ClientSession(...).request($M, $URL, ...)+ - patterns:+ - pattern: $S.request($M, $URL, ...)+ - pattern-either:+ - pattern-inside: |+ $S = requests.Session()+ ...+ - pattern-inside: |+ $S = httpx.Client(...)+ ...+ - pattern-inside: |+ $S = httpx.AsyncClient(...)+ ...+ - pattern-inside: |+ $S = aiohttp.ClientSession(...)+ ...+ - pattern-inside: |+ with requests.Session() as $S:+ ...+ - pattern-inside: |+ with httpx.Client(...) as $S:+ ...+ - pattern-inside: |+ async with httpx.AsyncClient(...) as $S:+ ...+ - pattern-inside: |+ async with aiohttp.ClientSession(...) as $S:+ ...+ - pattern: urllib.request.urlopen($URL, ...)+ - pattern: urlopen($URL, ...)+ # Skip what `github-api-calls-go-through-egress` already reports: a `requests` call whose argument text names the host.+ - pattern-not:+ patterns:+ - pattern: requests.$METHOD($URL, ...)+ - metavariable-regex:+ metavariable: $METHOD+ regex: ^(get|post|put|patch|delete|head|options)$+ - metavariable-regex:+ metavariable: $URL+ regex: .*(api|uploads)\.github\.com.*+ - pattern-not:+ patterns:+ - pattern: requests.request($M, $URL, ...)+ - metavariable-regex:+ metavariable: $URL+ regex: .*(api|uploads)\.github\.com.*+ # A URL bound to a variable or constant is matched through constant propagation, so the+ # string pattern sees the value. A call that has a literal GitHub URL inline is already+ # blocked by `github-api-calls-go-through-egress`.+ - metavariable-pattern:+ metavariable: $URL+ pattern-either:+ - pattern: |+ "=~/.*(api|uploads)\.github\.com.*/"+ - pattern: |+ "=~/.*(api|uploads)\.github\.com.*/" + ...+ - pattern: |+ f"=~/.*(api|uploads)\.github\.com.*/"+ paths:+ include:+ - /common/**/*.py+ - /ee/**/*.py+ - /posthog/**/*.py+ - /products/**/*.py+ exclude:+ - /posthog/egress/**diff --git a/.semgrep/rules/devex/no-raw-api-calls-outside-api-layer.test.ts b/.semgrep/rules/devex/no-raw-api-calls-outside-api-layer.test.tsnew file mode 100644index 000000000000..901365dce6b3--- /dev/null+++ b/.semgrep/rules/devex/no-raw-api-calls-outside-api-layer.test.ts@@ -0,0 +1,52 @@+// @ts-nocheck+// Test fixture for the no-raw-api-calls-outside-api-layer rules.+import { teamsList } from 'products/example/frontend/generated/api'++// ruleid: no-api-request-outside-api-layer+const a = await new ApiRequest().errorTrackingIssuesExists().get()++// ruleid: no-api-request-outside-api-layer+const b = await new ApiRequest().hogFlow(id).withAction('assets').withQueryString(params).get()++// ok: no-api-request-outside-api-layer+const c = await teamsList(projectId)++// ruleid: no-raw-fetch-to-api-outside-api-layer+const d = await fetch(`/api/projects/${teamId}/vision/observations/${id}/progress/`, { method: 'GET' })++// ruleid: no-raw-fetch-to-api-outside-api-layer+const e = await fetch('/api/vercel/connect/complete', { method: 'POST' })++// ruleid: no-raw-fetch-to-api-outside-api-layer+const f = await window.fetch(`${apiHost}/api/organizations/@current/`)++// ok: no-raw-fetch-to-api-outside-api-layer+const g = await fetch(assetUrl)++// A URL outside `/api/` is not checked.+// ok: no-raw-fetch-to-api-outside-api-layer+const h = await fetch('/static/example.json')++// ok: no-raw-fetch-to-api-outside-api-layer+const i = await fetch(`https://example.com/api/items`)++// A literal URL held in a local constant is still a raw call.+const apiUrl = '/api/projects/1/things/'+// ruleid: no-raw-fetch-to-api-outside-api-layer+const j = await fetch(apiUrl)++const staticUrl = '/static/example.json'+// ok: no-raw-fetch-to-api-outside-api-layer+const k = await fetch(staticUrl)++// ruleid: no-axios-in-frontend+import axios from 'axios'++// ruleid: no-axios-in-frontend+import { AxiosError } from 'axios'++// ruleid: no-axios-in-frontend+import * as axiosLib from 'axios'++// ok: no-axios-in-frontend+import { somethingElse } from 'other-http-client'diff --git a/.semgrep/rules/devex/no-raw-api-calls-outside-api-layer.yaml b/.semgrep/rules/devex/no-raw-api-calls-outside-api-layer.yamlnew file mode 100644index 000000000000..a7cdbda57a87--- /dev/null+++ b/.semgrep/rules/devex/no-raw-api-calls-outside-api-layer.yaml@@ -0,0 +1,130 @@+rules:+ - id: no-api-request-outside-api-layer+ message: |+ `new ApiRequest()` outside `frontend/src/lib/api.ts`. It puts a hand-written URL builder+ and an unchecked response type at the call site, so a backend change breaks it at runtime+ instead of at compile time. `prefer-codegen-api` blocks `api.get(...)` and its siblings,+ and this shape does the same job.++ Call the generated function instead: `products/<product>/frontend/generated/api.ts` for a+ product endpoint, `frontend/src/generated/core/api.ts` for a core endpoint. If no+ generated function covers the endpoint, add its OpenAPI schema (`/improving-drf-endpoints`)+ and run `hogli build:openapi`.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration workflow.++ Only a URL that the server returns (a pagination `next` link, an export download) or a+ route outside the API may stay raw. Mark it with+ `// nosemgrep: no-api-request-outside-api-layer -- <reason>` on the line above.+ severity: WARNING+ languages: [typescript, javascript]+ paths:+ include:+ - 'frontend/src/**'+ - 'products/*/frontend/**'+ exclude:+ - 'frontend/src/lib/api.ts'+ - 'frontend/src/toolbar/**'+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.spec.ts'+ - '**/*.spec.tsx'+ - '**/*.stories.ts'+ - '**/*.stories.tsx'+ - '**/mocks/**'+ - '**/__mocks__/**'+ pattern: new ApiRequest(...)+ metadata:+ category: best-practice++ - id: no-raw-fetch-to-api-outside-api-layer+ message: |+ Raw `fetch(...)` to a PostHog `/api/...` URL. It skips the shared request layer (CSRF+ header, error handling, region and project handling) and puts an unchecked URL and+ response type at the call site.++ Call the generated function instead: `products/<product>/frontend/generated/api.ts` for a+ product endpoint, `frontend/src/generated/core/api.ts` for a core endpoint. If no+ generated function covers the endpoint, add its OpenAPI schema (`/improving-drf-endpoints`)+ and run `hogli build:openapi`.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration workflow.++ A public page that cannot use the app request layer, or a route outside the API, may stay+ raw. Mark it with `// nosemgrep: no-raw-fetch-to-api-outside-api-layer -- <reason>` on+ the line above. Toolbar code has its own rule, `toolbar-no-raw-fetch`.+ severity: WARNING+ languages: [typescript, javascript]+ paths:+ include:+ - 'frontend/src/**'+ - 'products/*/frontend/**'+ exclude:+ - 'frontend/src/lib/api.ts'+ - 'frontend/src/toolbar/**'+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.spec.ts'+ - '**/*.spec.tsx'+ - '**/*.stories.ts'+ - '**/*.stories.tsx'+ - '**/mocks/**'+ - '**/__mocks__/**'+ patterns:+ - pattern-either:+ - pattern: fetch($URL, ...)+ - pattern: window.fetch($URL, ...)+ - pattern: globalThis.fetch($URL, ...)+ # A string or template literal that starts with `/api/`, optionally after a `${host}` part.+ # The URL is a literal at the call, or a local constant that holds a literal+ # (constant propagation).+ - metavariable-pattern:+ metavariable: $URL+ pattern-either:+ - pattern-regex: '^[`''"](?:\$\{[^}]*\})?/api/'+ - pattern: |+ "=~/^\/api\//"+ metadata:+ category: best-practice++ - id: no-axios-in-frontend+ message: |+ `axios` import in frontend code. The app talks to the PostHog API through the generated+ clients (`frontend/src/generated/core/`, `products/<product>/frontend/generated/`), which+ share one request layer for CSRF, errors and typing. A second HTTP client forks that+ layer.++ Call the generated function instead. If no generated function covers the endpoint, add+ its OpenAPI schema (`/improving-drf-endpoints`) and run `hogli build:openapi`.++ Agents: invoke the `adopting-generated-api-types` skill+ (`.agents/skills/adopting-generated-api-types/SKILL.md`) for the migration workflow.+ severity: WARNING+ languages: [typescript, javascript]+ paths:+ include:+ - 'frontend/src/**'+ - 'products/*/frontend/**'+ exclude:+ - 'frontend/src/lib/api.ts'+ - 'frontend/src/toolbar/**'+ - '**/generated/**'+ - '**/*.test.ts'+ - '**/*.test.tsx'+ - '**/*.spec.ts'+ - '**/*.spec.tsx'+ - '**/*.stories.ts'+ - '**/*.stories.tsx'+ - '**/mocks/**'+ - '**/__mocks__/**'+ pattern-either:+ - pattern: import $X from 'axios'+ - pattern: import * as $X from 'axios'+ - pattern: import {...} from 'axios'+ - pattern: require('axios')+ metadata:+ category: best-practicediff --git a/.semgrep/rules/devex/slack-api-calls-go-through-egress.py b/.semgrep/rules/devex/slack-api-calls-go-through-egress.pyindex b7a648dc8440..d21f1ee929a2 100644--- a/.semgrep/rules/devex/slack-api-calls-go-through-egress.py+++ b/.semgrep/rules/devex/slack-api-calls-go-through-egress.py@@ -1,6 +1,12 @@# ruff: noqa: F841+import aiohttp+import httpximport requests+import slack_sdk+import urllib.request+from slack_sdk import AsyncWebClientfrom slack_sdk import WebClient+from slack_sdk import WebClient as AliasedWebClientfrom posthog.egress.slack.client import SlackWebClientfrom posthog.egress.slack.transport import slack_request@@ -35,3 +41,105 @@ def ok_egress_client(token: str):def ok_webhook():# ok: slack-api-calls-go-through-egressreturn requests.post("https://hooks.slack.com/services/example")+++SLACK_POST_MESSAGE = "https://slack.com/api/chat.postMessage"+++def flagged_aliased_sdk_client(token: str):+ # ruleid: slack-api-calls-go-through-egress-wide+ return AliasedWebClient(token=token)+++def flagged_async_sdk_client(token: str):+ # ruleid: slack-api-calls-go-through-egress-wide+ return AsyncWebClient(token=token)+++def flagged_module_sdk_client(token: str):+ # ruleid: slack-api-calls-go-through-egress-wide+ return slack_sdk.WebClient(token=token)+++def flagged_variable_url(token: str):+ # ruleid: slack-api-calls-go-through-egress-wide+ return requests.post(SLACK_POST_MESSAGE, data={"token": token})+++def flagged_session():+ # ruleid: slack-api-calls-go-through-egress-wide+ return requests.Session().post("https://slack.com/api/chat.postMessage")+++def flagged_httpx():+ # ruleid: slack-api-calls-go-through-egress-wide+ return httpx.post(SLACK_POST_MESSAGE)+++async def flagged_httpx_async_client():+ async with httpx.AsyncClient() as client:+ # ruleid: slack-api-calls-go-through-egress-wide+ return await client.post(SLACK_POST_MESSAGE)+++async def flagged_aiohttp():+ async with aiohttp.ClientSession() as session:+ # ruleid: slack-api-calls-go-through-egress-wide+ return await session.post(SLACK_POST_MESSAGE)+++def flagged_urlopen():+ # ruleid: slack-api-calls-go-through-egress-wide+ return urllib.request.urlopen(SLACK_POST_MESSAGE)+++def flagged_requests_options():+ # ruleid: slack-api-calls-go-through-egress-wide+ return requests.options(SLACK_POST_MESSAGE)+++def flagged_session_request_method_first():+ session = requests.Session()+ # ruleid: slack-api-calls-go-through-egress-wide+ return session.request("POST", SLACK_POST_MESSAGE)+++async def flagged_aiohttp_request_method_first():+ async with aiohttp.ClientSession() as session:+ # ruleid: slack-api-calls-go-through-egress-wide+ return await session.request("POST", SLACK_POST_MESSAGE)+++async def flagged_aiohttp_module_request():+ # ruleid: slack-api-calls-go-through-egress-wide+ return aiohttp.request("GET", SLACK_POST_MESSAGE)+++async def flagged_aiohttp_assigned_session():+ session = aiohttp.ClientSession()+ # ruleid: slack-api-calls-go-through-egress-wide+ return await session.get(SLACK_POST_MESSAGE)+++def ok_wide_url_helpers():+ # ok: slack-api-calls-go-through-egress-wide+ httpx.URL(SLACK_POST_MESSAGE)+ session = requests.Session()+ # ok: slack-api-calls-go-through-egress-wide+ session.mount(SLACK_POST_MESSAGE, adapter)++def ok_wide_webhook():+ # ok: slack-api-calls-go-through-egress-wide+ httpx.post("https://hooks.slack.com/services/example")+ # ok: slack-api-calls-go-through-egress-wide+ return requests.Session().post("https://hooks.slack.com/services/example")+++def ok_wide_egress_client(token: str):+ # ok: slack-api-calls-go-through-egress-wide+ return SlackWebClient(token=token, source="test")+++def flagged_urlopen_request():+ # ruleid: slack-api-calls-go-through-egress-wide+ return urllib.request.urlopen(urllib.request.Request(SLACK_POST_MESSAGE))diff --git a/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml b/.semgrep/rules/devex/slack-api-calls-go-through-egress.yamlindex 8a830c555abe..63e0779d27c3 100644--- a/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml+++ b/.semgrep/rules/devex/slack-api-calls-go-through-egress.yaml@@ -8,9 +8,9 @@ rules:Incoming webhooks and interactivity response URLs are outside this rule because theirsecret URL, not a workspace ID, owns the budget. See `posthog/egress/slack/README.md`.- The direct-HTTP half only catches literal/f-string URLs on the `requests` module, so- keep URLs inline at the call site. Any `WebClient` / `AsyncWebClient` construction is- caught regardless of URL shape. Suppress a legitimate exception with+ The direct-HTTP half only catches literal/f-string URLs on the `requests` module, and the+ SDK half only a plain `WebClient` / `AsyncWebClient` import. The other shapes are caught by+ `slack-api-calls-go-through-egress-wide`. Suppress a legitimate exception with`# nosemgrep: slack-api-calls-go-through-egress -- <reason>`.languages: [python]severity: ERROR@@ -42,3 +42,195 @@ rules:- posthog/egress/**- '**/test/**'- '**/tests/**'++ - id: slack-api-calls-go-through-egress-wide+ message: |+ Outbound Slack Web API calls must go through the recorded egress clients. This rule catches+ the shapes that `slack-api-calls-go-through-egress` misses: a `WebClient` or+ `AsyncWebClient` that is aliased (`from slack_sdk import WebClient as X`), imported from+ another `slack_sdk` module or called through the module (`slack_sdk.WebClient(...)`), and a+ `slack.com/api` URL called through a variable, `requests.Session`, `httpx`, `aiohttp` or+ `urllib.request`.++ Use `posthog.egress.slack.client.SlackWebClient` (or `SlackAsyncWebClient`) for Slack SDK+ calls and `posthog.egress.slack.transport.slack_request` for direct HTTP. Incoming webhooks+ and interactivity response URLs are outside this rule because their secret URL, not a+ workspace ID, owns the budget. See `posthog/egress/slack/README.md`.++ Suppress a legitimate exception with+ `# nosemgrep: slack-api-calls-go-through-egress-wide -- <reason>`.+ languages: [python]+ severity: ERROR+ patterns:+ - pattern-either:+ # Semgrep resolves an imported name to its module path, so these patterns also match+ # a bare `WebClient(...)`. The `pattern-not` lines leave those to the ERROR rule.+ - patterns:+ - pattern-either:+ - pattern: slack_sdk.WebClient(...)+ - pattern: slack_sdk.AsyncWebClient(...)+ - pattern: slack_sdk.web.WebClient(...)+ - pattern: slack_sdk.web.AsyncWebClient(...)+ - pattern: slack_sdk.web.client.WebClient(...)+ - pattern: slack_sdk.web.async_client.AsyncWebClient(...)+ - pattern-not: WebClient(...)+ - pattern-not: AsyncWebClient(...)+ - patterns:+ - pattern: $CLIENT(...)+ - pattern-either:+ - pattern-inside: |+ from slack_sdk import WebClient as $CLIENT+ ...+ - pattern-inside: |+ from slack_sdk import AsyncWebClient as $CLIENT+ ...+ - pattern-inside: |+ from slack_sdk.web import WebClient as $CLIENT+ ...+ - pattern-inside: |+ from slack_sdk.web import AsyncWebClient as $CLIENT+ ...+ - pattern-inside: |+ from slack_sdk.web.client import WebClient as $CLIENT+ ...+ - pattern-inside: |+ from slack_sdk.web.async_client import AsyncWebClient as $CLIENT+ ...+ # An alias pattern also matches an import without `as`. The plain names are the+ # business of `slack-api-calls-go-through-egress`.+ - metavariable-regex:+ metavariable: $CLIENT+ regex: ^(?!WebClient$|AsyncWebClient$)+ - patterns:+ - pattern-either:+ - patterns:+ - pattern: AsyncWebClient(...)+ - pattern-either:+ - pattern-inside: |+ from slack_sdk import AsyncWebClient+ ...+ - pattern-inside: |+ from slack_sdk.web import AsyncWebClient+ ...+ - patterns:+ - pattern: WebClient(...)+ - pattern-either:+ - pattern-inside: |+ from slack_sdk.web import WebClient+ ...+ - pattern-inside: |+ from slack_sdk.web.client import WebClient+ ...+ - patterns:+ - pattern-either:+ - patterns:+ - pattern-either:+ - pattern: requests.$METHOD($URL, ...)+ - pattern: requests.Session().$METHOD($URL, ...)+ - pattern: httpx.$METHOD($URL, ...)+ - pattern: httpx.Client(...).$METHOD($URL, ...)+ - pattern: httpx.AsyncClient(...).$METHOD($URL, ...)+ - pattern: aiohttp.ClientSession(...).$METHOD($URL, ...)+ - patterns:+ - pattern: $S.$METHOD($URL, ...)+ - pattern-either:+ - pattern-inside: |+ $S = requests.Session()+ ...+ - pattern-inside: |+ $S = httpx.Client(...)+ ...+ - pattern-inside: |+ $S = httpx.AsyncClient(...)+ ...+ - pattern-inside: |+ $S = aiohttp.ClientSession(...)+ ...+ - pattern-inside: |+ with requests.Session() as $S:+ ...+ - pattern-inside: |+ with httpx.Client(...) as $S:+ ...+ - pattern-inside: |+ async with httpx.AsyncClient(...) as $S:+ ...+ - pattern-inside: |+ async with aiohttp.ClientSession(...) as $S:+ ...+ # Only the HTTP verbs send a request. `httpx.URL(...)` and `Session().mount(...)`+ # take a URL and send nothing.+ - metavariable-regex:+ metavariable: $METHOD+ regex: ^(get|post|put|patch|delete|head|options)$+ - pattern: requests.request($M, $URL, ...)+ - pattern: requests.Session().request($M, $URL, ...)+ - pattern: httpx.request($M, $URL, ...)+ - pattern: httpx.Client(...).request($M, $URL, ...)+ - pattern: httpx.AsyncClient(...).request($M, $URL, ...)+ - pattern: aiohttp.request($M, $URL, ...)+ - pattern: aiohttp.ClientSession(...).request($M, $URL, ...)+ - patterns:+ - pattern: $S.request($M, $URL, ...)+ - pattern-either:+ - pattern-inside: |+ $S = requests.Session()+ ...+ - pattern-inside: |+ $S = httpx.Client(...)+ ...+ - pattern-inside: |+ $S = httpx.AsyncClient(...)+ ...+ - pattern-inside: |+ $S = aiohttp.ClientSession(...)+ ...+ - pattern-inside: |+ with requests.Session() as $S:+ ...+ - pattern-inside: |+ with httpx.Client(...) as $S:+ ...+ - pattern-inside: |+ async with httpx.AsyncClient(...) as $S:+ ...+ - pattern-inside: |+ async with aiohttp.ClientSession(...) as $S:+ ...+ - pattern: urllib.request.urlopen($URL, ...)+ - pattern: urlopen($URL, ...)+ # Skip what `slack-api-calls-go-through-egress` already reports: a `requests` call whose argument text names the API.+ - pattern-not:+ patterns:+ - pattern: requests.$METHOD($URL, ...)+ - metavariable-regex:+ metavariable: $METHOD+ regex: ^(get|post|put|patch|delete|head|options)$+ - metavariable-regex:+ metavariable: $URL+ regex: .*slack\.com/api.*+ - pattern-not:+ patterns:+ - pattern: requests.request($M, $URL, ...)+ - metavariable-regex:+ metavariable: $URL+ regex: .*slack\.com/api.*+ - metavariable-pattern:+ metavariable: $URL+ pattern-either:+ - pattern: |+ "=~/.*slack\.com/api.*/"+ - pattern: |+ "=~/.*slack\.com/api.*/" + ...+ - pattern: |+ f"=~/.*slack\.com/api.*/"+ paths:+ include:+ - common/**/*.py+ - ee/**/*.py+ - posthog/**/*.py+ - products/**/*.py+ exclude:+ - posthog/egress/**+ - '**/test/**'+ - '**/tests/**'diff --git a/.semgrep/rules/devex/url-naming.py b/.semgrep/rules/devex/url-naming.pyindex 7481f924d0c3..491dc327cd6c 100644--- a/.semgrep/rules/devex/url-naming.py+++ b/.semgrep/rules/devex/url-naming.py@@ -72,3 +72,30 @@ def register_routes(routers):routers.projects.register(r"error_tracking/git-provider-file-links", LinksViewSet, "links")# ok: api-path-underscorerouters.projects.register(r"error_tracking/symbol_sets", SymbolSetViewSet, "symbol_sets")+++urlpatterns = [+ # ruleid: api-route-path-underscore+ opt_slash_path("api/signup/resend-invite", signup.SignupResendInviteViewset.as_view()),+ # ruleid: api-route-path-underscore+ path("api/oauth/connected-apps", ConnectedAppsView.as_view()),+ # ruleid: api-route-path-underscore+ re_path(r"^api/projects/(?P<team_id>[^/.]+)/set-default/?$", SetDefaultView.as_view()),+ # ok: api-route-path-underscore+ opt_slash_path("api/signup/resend_invite", signup.SignupResendInviteViewset.as_view()),+ # A route name may use hyphens.+ # ok: api-route-path-underscore+ path("api/streamlit_bridge/query/", BridgeView.as_view(), name="streamlit-bridge-query"),+ # A hyphen inside a regex character class is not a literal segment.+ # ok: api-route-path-underscore+ re_path(r"^api/files/(?P<path>[A-Za-z0-9_./-]+)$", FilesView.as_view()),+ # A route outside `api/` is not checked.+ # ok: api-route-path-underscore+ path("complete/github-link/", github_oauth_callback),+ # ok: api-route-path-underscore+ opt_slash_path(".well-known/http-message-signatures-directory", signatures_directory),+ # ok: api-route-path-underscore+ path("api/schema/swagger-ui/", SpectacularSwaggerView.as_view()),+ # nosemgrep: api-route-path-underscore+ path("api/signup/legacy-invite", LegacyInviteView.as_view()),+]diff --git a/.semgrep/rules/devex/url-naming.yaml b/.semgrep/rules/devex/url-naming.yamlindex 47407a239524..c61ba8409c86 100644--- a/.semgrep/rules/devex/url-naming.yaml+++ b/.semgrep/rules/devex/url-naming.yaml@@ -37,6 +37,43 @@ rules:metadata:category: best-practice+ - id: api-route-path-underscore+ message: |+ This API route uses a hyphen in a path segment. API paths use underscores+ (`set_default`, not `set-default`), so that the URL, the view name and the JSON fields all+ read the same way. This covers a route that starts with `api/` and is passed to `path()`,+ `re_path()` or `opt_slash_path()` in `posthog/urls.py` or an `ee/**/urls.py` file.++ Change the literal to use underscores. Route names (`name="..."`) and `<converter:param>`+ values are not checked.++ A hyphenated path that has already shipped keeps its name, because SDKs, MCP tools and+ customer scripts call it. It carries `# nosemgrep: api-route-path-underscore` on the line+ above. Use the same comment, with a reason, when a provider or an external contract+ dictates the path. Routes outside `api/` and the `api/schema/` docs routes are not checked.+ severity: WARNING+ languages: [python]+ paths:+ include:+ - 'posthog/urls.py'+ - 'ee/**/urls.py'+ exclude:+ - '**/test/**'+ - '**/tests/**'+ - '**/test_*.py'+ patterns:+ - pattern-either:+ - pattern: path("$PATH", ...)+ - pattern: re_path("$PATH", ...)+ - pattern: opt_slash_path("$PATH", ...)+ # Same segment check as `api-path-underscore`, limited to routes under `api/`. `^` may+ # start a `re_path` pattern. `api/schema/` serves the OpenAPI docs UI, not an API resource.+ - metavariable-regex:+ metavariable: $PATH+ regex: '^(?!\^?api/schema/)(?:\^)?api/(?:.*/)?[A-Za-z0-9_]+-[A-Za-z0-9_-]*(?=/|\(|\?|\$|$)'+ metadata:+ category: best-practice+- id: api-query-param-underscoremessage: |This API query parameter uses a hyphen. API query parameters use underscoresdiff --git a/AGENTS.md b/AGENTS.mdindex cace97b1acff..7d962cb752f1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -193,7 +193,7 @@ Each rule is tagged with what catches a violation.- **Do not use `posthoganalytics.capture()` in a Celery task** — events are silently lost. `[review]` Use `ph_scoped_capture` from `posthog.ph_client`; its docstring explains why.- **Temporal activity payloads cap at ~2 MiB — pass large data by reference.** `[review]` Activity inputs and outputs cross a gRPC boundary the server rejects above that (`blobSizeLimitError`). As a field-level rule: if a field could exceed ~256 KB serialized (query results, exported file contents, LLM context, rendered HTML, image bytes, unbounded `list[dict[str, Any]]`), write it to Postgres or object storage from inside the activity and return only the row ID or S3 key. The workflow already has any ID created earlier in the run. Shuttling large data through the workflow produces `PayloadSizeError` (`TMPRL1103`) as soon as the data crosses the limit.- **A Python `requests` call to GitHub or Slack under `common/`, `ee/`, `posthog/` or `products/` goes through `posthog/egress/`.** `[lint: github-api-calls-go-through-egress, slack-api-calls-go-through-egress]` Route it through the gated, recorded transport.-- **Every other call to those hosts is on review.** `[review]` The rules match an inline URL in a Python `requests` call inside those four directories. A URL bound to a variable first, another transport such as `httpx`, another language, or a caller under `tools/` all pass CI.+- **Every other call to those hosts goes through `posthog/egress/` too.** `[lint: github-api-calls-go-through-egress-wide, slack-api-calls-go-through-egress-wide]` The wide rules catch a URL bound to a variable or constant, `requests.Session`, `httpx`, `aiohttp`, `urllib.request`, and an aliased Slack SDK client. Another language, another vendor SDK, or a caller under `tools/` still passes CI, so a reader is the only control there.- **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.diff --git a/posthog/egress/README.md b/posthog/egress/README.mdindex 18e7b82cb766..ec84bede6d11 100644--- a/posthog/egress/README.md+++ b/posthog/egress/README.md@@ -144,8 +144,8 @@ Every client is token-agnostic: the caller passes its own credentials.Response handling, such as what to do on a 403 or 429, stays with the caller.Two semgrep rules in `.semgrep/rules/devex/` fail CI on a raw call that bypasses a domain: `github-api-calls-go-through-egress` (a `requests` call that names `api.github.com`) and `slack-api-calls-go-through-egress` (a `requests` call that names `slack.com/api`, or a bare `WebClient`).-The `requests` half of each rule reads the URL argument only, so a call that binds the URL to a variable first gets through. Keep the URL inline at the call site.-No rule covers the other domains.+A `-wide` twin of each rule catches the other shapes: a URL bound to a variable or constant, `requests.Session`, `httpx`, `aiohttp`, `urllib.request`, and an aliased Slack SDK client.+No rule covers the other domains, another language, or a caller under `tools/`.## The one identity rule