: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
fix(support): harden scrub_person_properties and share a script lib (#72355)
Xander1d57187c1bf3
diff --git a/products/support/scripts/AGENTS.md b/products/support/scripts/AGENTS.mdnew file mode 100644index 000000000000..26f23ca86e74--- /dev/null+++ b/products/support/scripts/AGENTS.md@@ -0,0 +1,97 @@+# Support scripts++One-off operational CLIs that support and staff run against a live PostHog project+(scrub person properties, prune property definitions, and so on).+They talk to the public REST and query APIs over the network and are never imported by the app.+Shared plumbing lives in `lib/`, so a new script is mostly its own discovery/mutation logic plus a thin `main()`.++`scrub_person_properties.py` and `prune_property_definitions.py` are the reference implementations.+A new script should read like a third sibling of those two. Copy their shape.++## Use the shared lib, don't re-roll it++Import each name straight from its defining module (`lib` resolves because a script's own directory is on `sys.path` when run directly).+Don't re-export through `lib/__init__.py` - a `from .` re-export there trips the `no-init-reexports` semgrep rule.++```python+from lib.errors import PostHogScriptError # the one error type; raise for any expected, operator-facing failure+from lib.console import confirm, format_status_counts, log, printable+from lib.posthog_api import request_with_retries, resolve_host, setup_session_auth+```++- `lib.errors` - `PostHogScriptError`.+- `lib.console` - `log` (stderr output), `printable` (escape untrusted text), `confirm` (typed-keyword prompt, EOF-safe), `format_status_counts` (status histogram).+- `lib.posthog_api` - `resolve_host`, `request_with_retries` (every HTTP call), `setup_session_auth` (browser-session/impersonation auth), plus `MAX_RETRIES`.++Never re-implement retries, host resolution, auth, output, or the error type inside a script.+If a second script needs a new shared helper, add it to `lib/` (`errors` / `console` / `posthog_api`) instead of copying it.++## Networking++Route every request through `request_with_retries(session, method, url, ...)`.+It already retries 429 (with defensive Retry-After parsing) and 5xx with backoff.+Do not call `session.request` or `requests.get` directly.++Build one `requests.Session`.+For a personal API key set `session.headers["Authorization"] = f"Bearer {key}"`; for a browser session call `setup_session_auth(session, host, session_id)`.++Paginate defensively: honor the `next` URL for list APIs, and use keyset pagination (not `OFFSET`) for query-API scans, the way `find_affected_persons_hogql` does.++## Auth++Support both credentials, like the reference scripts:++- `--personal-api-key` / `POSTHOG_PERSONAL_API_KEY` (sent as a Bearer token).+- `--session-id` / `POSTHOG_SESSION_ID`, the browser `sessionid` cookie, for impersonated staff sessions.++`setup_session_auth` handles the CSRF token, the HTTPS-only host-scoped cookie, and the mandatory acting-user confirmation.+Just call it; don't set the cookie yourself.++## Output++All human output goes to **stderr** via `log()`, so **stdout** stays clean for `--output` JSON or piped data.+Do not use `print` (ruff `T2` flags it).++Wrap any value that originated from ingested data (property names, `distinct_id`s, an API error body) in `printable()` before logging it.+Those strings can carry terminal escape sequences that would otherwise spoof or wipe the operator's terminal.++## Arguments (argparse)++- Use `argparse.ArgumentDefaultsHelpFormatter`.+- Resolve env-backed args _after_ `parse_args()` so `--help` never prints a key read from the environment.+- Reuse the standard flags and their meanings: `--host` (through `resolve_host`; default `POSTHOG_HOST`, else US), `--project-id` (`POSTHOG_PROJECT_ID`, required), `--dry-run`, `--yes` / `-y`, `--output`, `--page-size`, `--batch-size`.+- Validate numeric args before any request runs: reject a non-positive `--page-size` / `--batch-size` with `parser.error(...)`. A zero step otherwise loops forever or crashes mid-run.++## Destructive-operation safety++Anything that writes or deletes follows this order:++1. Scan and dedupe the affected set.+2. Log a total, a per-target breakdown, and a sample (first ~10).+3. Offer `--output <file>` to dump the full affected set as JSON.+4. `--dry-run` returns here, changing nothing.+5. Otherwise confirm with `confirm(prompt, "<verb>", eof_message=...)` (a typed keyword such as `scrub` / `prune`), skippable with `--yes`.+6. When there is no bulk endpoint, mutate one item per request and report outcomes with `format_status_counts`: count only 2xx as success, surface a 403 hint (read-only credential or field-level access control), and cap the printed failure list.++Call out anything eventually-consistent (e.g. ingestion lag) in the module docstring so the operator isn't surprised when a value lingers after the run.++## Structure and style++- Module docstring first: what the script does, how it discovers targets, how it mutates them, any consistency caveats, and a usage block with the env vars and a `--dry-run` example.+- `parse_args() -> argparse.Namespace`, then `main() -> int` returning an exit code.+- Standard bottom guard:++ ```python+ if __name__ == "__main__":+ try:+ sys.exit(main())+ except PostHogScriptError as err:+ log(f"Error: {printable(str(err))}")+ sys.exit(1)+ except KeyboardInterrupt:+ log("\nInterrupted.")+ sys.exit(130)+ ```++- These files **are** type-checked and linted (this directory is not in the mypy or ruff script exclusions).+ Fully annotate every signature, keep imports at module level (no inline imports; `PLC0415` is enforced), and run `ruff check --fix && ruff format` on your changes.diff --git a/products/support/scripts/CLAUDE.md b/products/support/scripts/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/products/support/scripts/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/products/support/scripts/lib/__init__.py b/products/support/scripts/lib/__init__.pynew file mode 100644index 000000000000..c8607309f847--- /dev/null+++ b/products/support/scripts/lib/__init__.py@@ -0,0 +1,7 @@+"""Shared helpers for the PostHog support CLI scripts (scrub/prune).++Import the names you need straight from the defining module - `lib.errors`, `lib.console`,+`lib.posthog_api` - rather than re-exporting them here. Scripts run directly+(`python products/support/scripts/<name>.py`), which puts this directory on sys.path, so+`lib.<module>` imports without any packaging.+"""diff --git a/products/support/scripts/lib/console.py b/products/support/scripts/lib/console.pynew file mode 100644index 000000000000..461c12b3c5b1--- /dev/null+++ b/products/support/scripts/lib/console.py@@ -0,0 +1,43 @@+"""Terminal output and confirmation helpers shared by the support CLI scripts."""++import sys+from collections import Counter++from .errors import PostHogScriptError+++def log(message: str) -> None:+ """Write a progress/report line to stderr, keeping stdout free for piped data."""+ print(message, file=sys.stderr) # noqa: T201 - stderr logging is this CLI's output channel+++def printable(value: str) -> str:+ """Escape terminal control sequences in untrusted text (e.g. ingested property or person names).++ Ingested data can carry ANSI/control sequences that would otherwise spoof or wipe the+ operator's terminal when a name or an API error is previewed or reported.+ """+ return "".join(ch if ch.isprintable() else ch.encode("unicode_escape").decode("ascii") for ch in str(value))+++def format_status_counts(counts: Counter[str]) -> str:+ """Render a status-code histogram like 'HTTP 204: 39, HTTP 403: 11' (digit codes first)."""+ parts = []+ for code in sorted(counts, key=lambda c: (not c.isdigit(), c)):+ label = f"HTTP {code}" if code.isdigit() else code+ parts.append(f"{label}: {counts[code]}")+ return ", ".join(parts)+++def confirm(prompt: str, expected: str, *, eof_message: str) -> bool:+ """Read one line from stdin; return True iff it matches `expected` (trimmed, case-insensitive).++ A closed stdin (a piped or otherwise non-interactive run) raises PostHogScriptError with+ `eof_message` instead of a bare EOFError traceback, so the caller can point the operator at+ --yes or a personal API key.+ """+ try:+ reply = input(prompt)+ except EOFError as err:+ raise PostHogScriptError(eof_message) from err+ return reply.strip().lower() == expected.strip().lower()diff --git a/products/support/scripts/lib/errors.py b/products/support/scripts/lib/errors.pynew file mode 100644index 000000000000..f3dbb238bf3d--- /dev/null+++ b/products/support/scripts/lib/errors.py@@ -0,0 +1,9 @@+"""Shared exception type for the support CLI scripts."""+++class PostHogScriptError(Exception):+ """An expected, operator-facing failure (bad auth, an API error, an aborted run).++ Scripts catch this at the top level and print it as a one-line error, so raising it+ (rather than letting an arbitrary exception escape) is how a script fails cleanly.+ """diff --git a/products/support/scripts/lib/posthog_api.py b/products/support/scripts/lib/posthog_api.pynew file mode 100644index 000000000000..39f587dc48ca--- /dev/null+++ b/products/support/scripts/lib/posthog_api.py@@ -0,0 +1,112 @@+"""HTTP transport and browser-session auth shared by the support CLI scripts.++A tiny PostHog REST client: region/host resolution, a request wrapper that retries on rate+limits and 5xx, and session-cookie authentication for impersonated staff sessions. Both+scripts hit the same API surface, so keeping retry/backoff, defensive Retry-After parsing,+cookie scoping, and the acting-user safety check here means every script gets them.+"""++import time+from typing import Any+from urllib.parse import urlparse++import requests++from .console import confirm, log+from .errors import PostHogScriptError++MAX_RETRIES = 5+BACKOFF_BASE_SECONDS = 2.0+RETRY_AFTER_MAX_SECONDS = 60.0+REGION_HOSTS = {"us": "https://us.posthog.com", "eu": "https://eu.posthog.com"}+++def resolve_host(value: str) -> str:+ """Map a region shorthand ('us'/'eu', any case) to its Cloud host; pass explicit hosts through."""+ return REGION_HOSTS.get(value.strip().lower(), value).rstrip("/")+++def request_with_retries(+ session: requests.Session, method: str, url: str, max_retries: int = MAX_RETRIES, **kwargs: Any+) -> requests.Response:+ """Issue a request, retrying on 429 (honoring Retry-After) and 5xx with backoff."""+ last_error = ""+ for attempt in range(max_retries):+ try:+ response = session.request(method, url, timeout=60, **kwargs)+ except requests.RequestException as err:+ last_error = str(err)+ time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)+ continue+ if response.status_code == 429:+ last_error = f"HTTP {response.status_code}: {response.text[:200]}"+ default_wait = BACKOFF_BASE_SECONDS * 2**attempt+ raw_retry_after = response.headers.get("Retry-After")+ try:+ # Retry-After may be seconds or an HTTP-date; only the numeric form is honored+ retry_after = float(raw_retry_after) if raw_retry_after is not None else default_wait+ except ValueError:+ retry_after = default_wait+ retry_after = min(max(retry_after, 0.0), RETRY_AFTER_MAX_SECONDS)+ log(f" rate limited, retrying in {retry_after:.0f}s...")+ time.sleep(retry_after)+ continue+ if response.status_code >= 500:+ last_error = f"HTTP {response.status_code}: {response.text[:200]}"+ time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)+ continue+ return response+ raise PostHogScriptError(f"{method} {url} failed after {max_retries} attempts: {last_error}")+++def confirm_acting_user(email: str) -> None:+ """Make the operator type the session's email so the acting-as identity is conscious, not assumed."""+ log("Session auth acts as the browser session's logged-in user - including for read queries.")+ matched = confirm(+ "Enter that user's email to confirm you know who you're acting as: ",+ email,+ eof_message=(+ "Session auth requires interactively confirming the authenticated user; "+ "use a personal API key for non-interactive runs."+ ),+ )+ if not matched:+ raise PostHogScriptError(+ "That does not match the session's authenticated user - check whose session this is "+ "(e.g. the impersonated user in your browser) and rerun."+ )+++def setup_session_auth(session: requests.Session, host: str, session_id: str) -> None:+ """Authenticate with a browser session cookie (works for impersonated staff sessions).++ Django session auth requires a CSRF token on unsafe methods, so fetch the CSRF cookie+ from the login page and mirror it into the X-CSRFToken header, with the host as Referer.+ Before anything runs - reads included - the operator must type the authenticated user's+ email to confirm they know who the session acts as.+ """+ parsed = urlparse(host)+ is_local = parsed.hostname in ("localhost", "127.0.0.1")+ if parsed.scheme != "https" and not is_local:+ raise PostHogScriptError(f"Refusing to send a session cookie to a non-HTTPS host: {host}")+ # Scope the cookie to this host (and require HTTPS) so requests never attaches the+ # session to another origin - e.g. via a mistyped --host or a cross-origin redirect.+ session.cookies.set("sessionid", session_id, domain=parsed.hostname, secure=not is_local)+ request_with_retries(session, "GET", f"{host}/login")+ csrf_token = session.cookies.get("posthog_csrftoken")+ if not csrf_token:+ raise PostHogScriptError(f"Could not obtain a CSRF cookie from {host}/login - is this a PostHog instance?")+ session.headers["X-CSRFToken"] = csrf_token+ session.headers["Referer"] = f"{host}/"++ me = request_with_retries(session, "GET", f"{host}/api/users/@me/")+ if me.status_code != 200:+ raise PostHogScriptError(+ f"Session auth failed (HTTP {me.status_code}) - is the sessionid cookie value current? "+ "Impersonated sessions expire when the impersonation ends or times out."+ )+ email = me.json().get("email")+ if not email:+ raise PostHogScriptError("Could not determine the session's authenticated user")+ confirm_acting_user(email)+ log(f"Authenticated via session as {email}")diff --git a/products/support/scripts/prune_property_definitions.py b/products/support/scripts/prune_property_definitions.pyindex c1e385e7aabf..2d3a079c55e4 100644--- a/products/support/scripts/prune_property_definitions.py+++ b/products/support/scripts/prune_property_definitions.py@@ -35,127 +35,20 @@ before running anything - reads included - requires typing the authenticated useemail, so acting on behalf of an impersonated user is always a conscious choice."""-# ruff: noqa: T201 allow print statements in this CLI script-import osimport reimport sysimport json-import timeimport argparsefrom collections import Counterfrom collections.abc import Iteratorfrom typing import Any, Optional-from urllib.parse import urlencode, urlparse+from urllib.parse import urlencodeimport requests--MAX_RETRIES = 5-BACKOFF_BASE_SECONDS = 2.0-RETRY_AFTER_MAX_SECONDS = 60.0-REGION_HOSTS = {"us": "https://us.posthog.com", "eu": "https://eu.posthog.com"}---def resolve_host(value: str) -> str:- """Map a region shorthand ('us'/'eu', any case) to its Cloud host; pass explicit hosts through."""- return REGION_HOSTS.get(value.strip().lower(), value).rstrip("/")---class PruneError(Exception):- pass---def log(message: str) -> None:- print(message, file=sys.stderr)---def printable(value: str) -> str:- """Escape terminal control sequences in untrusted text (e.g. ingested property names)."""- return "".join(ch if ch.isprintable() else ch.encode("unicode_escape").decode("ascii") for ch in str(value))---def request_with_retries(- session: requests.Session, method: str, url: str, max_retries: int = MAX_RETRIES, **kwargs: Any-) -> requests.Response:- """Issue a request, retrying on 429 (honoring Retry-After) and 5xx with backoff."""- last_error = ""- for attempt in range(max_retries):- try:- response = session.request(method, url, timeout=60, **kwargs)- except requests.RequestException as err:- last_error = str(err)- time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)- continue- if response.status_code == 429:- default_wait = BACKOFF_BASE_SECONDS * 2**attempt- raw_retry_after = response.headers.get("Retry-After")- try:- # Retry-After may be seconds or an HTTP-date; only the numeric form is honored- retry_after = float(raw_retry_after) if raw_retry_after is not None else default_wait- except ValueError:- retry_after = default_wait- retry_after = min(max(retry_after, 0.0), RETRY_AFTER_MAX_SECONDS)- log(f" rate limited, retrying in {retry_after:.0f}s...")- time.sleep(retry_after)- continue- if response.status_code >= 500:- last_error = f"HTTP {response.status_code}: {response.text[:200]}"- time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)- continue- return response- raise PruneError(f"{method} {url} failed after {max_retries} attempts: {last_error}")---def confirm_acting_user(email: str) -> None:- """Make the operator type the session's email so the acting-as identity is conscious, not assumed."""- log("Session auth acts as the browser session's logged-in user - including for read queries.")- try:- entered = input("Enter that user's email to confirm you know who you're acting as: ")- except EOFError as err:- raise PruneError(- "Session auth requires interactively confirming the authenticated user; "- "use a personal API key for non-interactive runs."- ) from err- if entered.strip().lower() != email.strip().lower():- raise PruneError(- "That does not match the session's authenticated user - check whose session this is "- "(e.g. the impersonated user in your browser) and rerun."- )---def setup_session_auth(session: requests.Session, host: str, session_id: str) -> None:- """Authenticate with a browser session cookie (works for impersonated staff sessions).-- Django session auth requires a CSRF token on unsafe methods, so fetch the CSRF cookie- from the login page and mirror it into the X-CSRFToken header, with the host as Referer.- Before anything runs - reads included - the operator must type the authenticated user's- email to confirm they know who the session acts as.- """- parsed = urlparse(host)- is_local = parsed.hostname in ("localhost", "127.0.0.1")- if parsed.scheme != "https" and not is_local:- raise PruneError(f"Refusing to send a session cookie to a non-HTTPS host: {host}")- # Scope the cookie to this host (and require HTTPS) so requests never attaches the- # session to another origin - e.g. via a mistyped --host or a cross-origin redirect.- session.cookies.set("sessionid", session_id, domain=parsed.hostname, secure=not is_local)- request_with_retries(session, "GET", f"{host}/login")- csrf_token = session.cookies.get("posthog_csrftoken")- if not csrf_token:- raise PruneError(f"Could not obtain a CSRF cookie from {host}/login - is this a PostHog instance?")- session.headers["X-CSRFToken"] = csrf_token- session.headers["Referer"] = f"{host}/"-- me = request_with_retries(session, "GET", f"{host}/api/users/@me/")- if me.status_code != 200:- raise PruneError(- f"Session auth failed (HTTP {me.status_code}) - is the sessionid cookie value current? "- "Impersonated sessions expire when the impersonation ends or times out."- )- email = me.json().get("email")- if not email:- raise PruneError("Could not determine the session's authenticated user")- confirm_acting_user(email)- log(f"Authenticated via session as {email}")+from lib.console import confirm, format_status_counts, log, printable+from lib.errors import PostHogScriptError+from lib.posthog_api import request_with_retries, resolve_host, setup_session_authdef iter_property_definitions(@@ -184,7 +77,9 @@ def iter_property_definitions(while url:response = request_with_retries(session, "GET", url)if response.status_code != 200:- raise PruneError(f"Property definitions query failed (HTTP {response.status_code}): {response.text[:500]}")+ raise PostHogScriptError(+ f"Property definitions query failed (HTTP {response.status_code}): {response.text[:500]}"+ )data = response.json()page += 1log(f" page {page}: {len(data['results'])} definitions")@@ -215,15 +110,6 @@ def find_matching_definitions(return matched, not_found-def format_status_counts(counts: Counter[str]) -> str:- """Render a status-code histogram like 'HTTP 204: 39, HTTP 403: 11' (digit codes first)."""- parts = []- for code in sorted(counts, key=lambda c: (not c.isdigit(), c)):- label = f"HTTP {code}" if code.isdigit() else code- parts.append(f"{label}: {counts[code]}")- return ", ".join(parts)--def prune_definitions(session: requests.Session, host: str, project_id: str, matched: list[dict[str, Any]], batch_size: int) -> tuple[Counter[str], list[str]]:@@ -244,7 +130,7 @@ def prune_definitions(url = f"{host}/api/projects/{project_id}/property_definitions/{definition['id']}/"try:response = request_with_retries(session, "DELETE", url)- except PruneError as err:+ except PostHogScriptError as err:status_counts["error"] += 1batch_counts["error"] += 1failures.append(f"{definition['name']} ({definition['id']}): {err}")@@ -419,11 +305,9 @@ def main() -> int:f"\nAbout to permanently delete {len(matched)} {args.prop_type} property definitions "f"from project {args.project_id}. Type 'prune' to continue: ")- try:- confirmed = input(prompt).strip().lower()- except EOFError as err:- raise PruneError("Confirmation requires interactive input; pass --yes for non-interactive runs.") from err- if confirmed != "prune":+ if not confirm(+ prompt, "prune", eof_message="Confirmation requires interactive input; pass --yes for non-interactive runs."+ ):log("Aborted.")return 1@@ -449,7 +333,7 @@ def main() -> int:if __name__ == "__main__":try:sys.exit(main())- except PruneError as err:+ except PostHogScriptError as err:log(f"Error: {printable(str(err))}")sys.exit(1)except KeyboardInterrupt:diff --git a/products/support/scripts/scrub_person_properties.py b/products/support/scripts/scrub_person_properties.pyindex f4ae4702a4bb..0a9488160ab1 100644--- a/products/support/scripts/scrub_person_properties.py+++ b/products/support/scripts/scrub_person_properties.py@@ -36,106 +36,23 @@ before running anything - reads included - requires typing the authenticated useemail, so acting on behalf of an impersonated user is always a conscious choice."""-# ruff: noqa: T201 allow print statements in this CLI script-import osimport sysimport json-import timeimport argparse+from collections import Counterfrom collections.abc import Iteratorfrom typing import Any, Optionalfrom urllib.parse import urlencodeimport requests+from lib.console import confirm, format_status_counts, log, printable+from lib.errors import PostHogScriptError+from lib.posthog_api import MAX_RETRIES, request_with_retries, resolve_host, setup_session_auth-MAX_RETRIES = 5-BACKOFF_BASE_SECONDS = 2.0-REGION_HOSTS = {"us": "https://us.posthog.com", "eu": "https://eu.posthog.com"}---def resolve_host(value: str) -> str:- """Map a region shorthand ('us'/'eu', any case) to its Cloud host; pass explicit hosts through."""- return REGION_HOSTS.get(value.strip().lower(), value).rstrip("/")---class ScrubError(Exception):- pass---def log(message: str) -> None:- print(message, file=sys.stderr)---def request_with_retries(- session: requests.Session, method: str, url: str, max_retries: int = MAX_RETRIES, **kwargs: Any-) -> requests.Response:- """Issue a request, retrying on 429 (honoring Retry-After) and 5xx with backoff."""- last_error = ""- for attempt in range(max_retries):- try:- response = session.request(method, url, timeout=60, **kwargs)- except requests.RequestException as err:- last_error = str(err)- time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)- continue- if response.status_code == 429:- retry_after = float(response.headers.get("Retry-After", BACKOFF_BASE_SECONDS * 2**attempt))- log(f" rate limited, retrying in {retry_after:.0f}s...")- time.sleep(retry_after)- continue- if response.status_code >= 500:- last_error = f"HTTP {response.status_code}: {response.text[:200]}"- time.sleep(BACKOFF_BASE_SECONDS * 2**attempt)- continue- return response- raise ScrubError(f"{method} {url} failed after {max_retries} attempts: {last_error}")---def confirm_acting_user(email: str) -> None:- """Make the operator type the session's email so the acting-as identity is conscious, not assumed."""- log("Session auth acts as the browser session's logged-in user - including for read queries.")- try:- entered = input("Enter that user's email to confirm you know who you're acting as: ")- except EOFError as err:- raise ScrubError(- "Session auth requires interactively confirming the authenticated user; "- "use a personal API key for non-interactive runs."- ) from err- if entered.strip().lower() != email.strip().lower():- raise ScrubError(- "That does not match the session's authenticated user - check whose session this is "- "(e.g. the impersonated user in your browser) and rerun."- )---def setup_session_auth(session: requests.Session, host: str, session_id: str) -> None:- """Authenticate with a browser session cookie (works for impersonated staff sessions).-- Django session auth requires a CSRF token on unsafe methods, so fetch the CSRF cookie- from the login page and mirror it into the X-CSRFToken header, with the host as Referer.- Before anything runs - reads included - the operator must type the authenticated user's- email to confirm they know who the session acts as.- """- session.cookies.set("sessionid", session_id)- request_with_retries(session, "GET", f"{host}/login")- csrf_token = session.cookies.get("posthog_csrftoken")- if not csrf_token:- raise ScrubError(f"Could not obtain a CSRF cookie from {host}/login - is this a PostHog instance?")- session.headers["X-CSRFToken"] = csrf_token- session.headers["Referer"] = f"{host}/"-- me = request_with_retries(session, "GET", f"{host}/api/users/@me/")- if me.status_code != 200:- raise ScrubError(- f"Session auth failed (HTTP {me.status_code}) - is the sessionid cookie value current? "- "Impersonated sessions expire when the impersonation ends or times out."- )- email = me.json().get("email")- if not email:- raise ScrubError("Could not determine the session's authenticated user")- confirm_acting_user(email)- log(f"Authenticated via session as {email}")+# api mode has no bulk endpoint, so it deletes one (person, property) pair per request;+# report a status-code histogram every this many so a long run shows steady progress.+API_REPORT_EVERY = 50def run_hogql_query(@@ -150,7 +67,7 @@ def run_hogql_query(json={"query": {"kind": "HogQLQuery", "query": query}},)if response.status_code != 200:- raise ScrubError(f"HogQL query failed (HTTP {response.status_code}): {response.text[:500]}")+ raise PostHogScriptError(f"HogQL query failed (HTTP {response.status_code}): {response.text[:500]}")return response.json()["results"]@@ -169,7 +86,7 @@ def iter_persons(while url:response = request_with_retries(session, "GET", url)if response.status_code != 200:- raise ScrubError(f"Persons query failed (HTTP {response.status_code}): {response.text[:500]}")+ raise PostHogScriptError(f"Persons query failed (HTTP {response.status_code}): {response.text[:500]}")data = response.json()page += 1log(f" page {page}: {len(data['results'])} persons")@@ -267,8 +184,8 @@ def find_affected_persons("""Return affected persons keyed by uuid, each annotated with the target properties it has."""try:return find_affected_persons_hogql(session, host, project_id, properties, page_size)- except ScrubError as err:- log(f"WARNING: JSONHas scan via the query API failed: {err}")+ except PostHogScriptError as err:+ log(f"WARNING: JSONHas scan via the query API failed: {printable(str(err))}")log("Falling back to per-property is_set scans via the persons API. ""Persons whose only target properties hold null values may be missed."@@ -303,7 +220,7 @@ def scrub_via_events(session, "POST", f"{host}/batch/", json={"api_key": project_api_key, "batch": chunk})if response.status_code >= 400:- raise ScrubError(f"Batch capture failed (HTTP {response.status_code}): {response.text[:500]}")+ raise PostHogScriptError(f"Batch capture failed (HTTP {response.status_code}): {response.text[:500]}")sent += len(chunk)request_count += 1log(f" sent {sent}/{len(events)} scrub events ({request_count} batch requests)")@@ -312,25 +229,41 @@ def scrub_via_events(def scrub_via_api(session: requests.Session, host: str, project_id: str, affected: list[dict[str, Any]]-) -> tuple[int, list[str]]:- """Call delete_property per (person, property). Returns (pairs_attempted, failures)."""+) -> tuple[Counter[str], list[str]]:+ """Call delete_property per (person, property), one request each (there is no bulk endpoint).++ Returns (status_counts, failures). status_counts is keyed by HTTP status code (as a string),+ plus an "error" bucket for requests that never got a response; only a 2xx counts as a scrubbed+ value. A read-only key returns 403, and field-level access control can make some deletes 403+ while others succeed, so outcomes are reported as a status-code histogram, not assumed uniform.+ """+ status_counts: Counter[str] = Counter()failures: list[str] = []- attempted = 0total_pairs = sum(len(p["matched_properties"]) for p in affected)+ batch_counts: Counter[str] = Counter()+ batch_start = 1+ index = 0for person in affected:for prop in person["matched_properties"]:+ index += 1url = f"{host}/api/projects/{project_id}/persons/{person['uuid']}/delete_property/"- attempted += 1try:response = request_with_retries(session, "POST", url, json={"$unset": prop})- except ScrubError as err:+ except PostHogScriptError as err:+ status_counts["error"] += 1+ batch_counts["error"] += 1failures.append(f"{person['uuid']} / {prop}: {err}")else:- if response.status_code >= 400:- failures.append(f"{person['uuid']} / {prop}: HTTP {response.status_code} {response.text[:200]}")- if attempted % 50 == 0 or attempted == total_pairs:- log(f" {attempted}/{total_pairs} delete_property requests done")- return attempted, failures+ code = response.status_code+ status_counts[str(code)] += 1+ batch_counts[str(code)] += 1+ if not 200 <= code < 300:+ failures.append(f"{person['uuid']} / {prop}: HTTP {code} {response.text[:200]}")+ if index % API_REPORT_EVERY == 0 or index == total_pairs:+ log(f" deletes {batch_start}-{index} of {total_pairs}: {format_status_counts(batch_counts)}")+ batch_counts = Counter()+ batch_start = index + 1+ return status_counts, failuresdef parse_args() -> argparse.Namespace:@@ -385,6 +318,10 @@ def parse_args() -> argparse.Namespace:args.session_id = args.session_id or os.environ.get("POSTHOG_SESSION_ID")if not args.project_id:parser.error("--project-id (or POSTHOG_PROJECT_ID) is required")+ if args.batch_size <= 0:+ parser.error("--batch-size must be greater than zero")+ if args.page_size <= 0:+ parser.error("--page-size must be greater than zero")if not args.personal_api_key and not args.session_id:parser.error("either --personal-api-key (POSTHOG_PERSONAL_API_KEY) or --session-id (POSTHOG_SESSION_ID) is required"@@ -423,12 +360,14 @@ def main() -> int:log("Nothing to scrub.")return 0+ pair_count = sum(len(p["matched_properties"]) for p in affected)+preview = affected[:10]log("")log("Sample of affected persons:")for person in preview:distinct_id = person["distinct_ids"][0] if person["distinct_ids"] else "<no distinct_id>"- log(f" {person['uuid']} {distinct_id} -> would unset: {', '.join(person['matched_properties'])}")+ log(f" {person['uuid']} {printable(distinct_id)} -> would unset: {', '.join(person['matched_properties'])}")if len(affected) > len(preview):log(f" ... and {len(affected) - len(preview)} more (use --output to save the full list)")@@ -438,12 +377,13 @@ def main() -> int:return 0if not args.yes:- pair_count = sum(len(p["matched_properties"]) for p in affected)prompt = (f"\nAbout to permanently scrub {pair_count} property values "f"from {len(affected)} persons via {args.mode} mode. Type 'scrub' to continue: ")- if input(prompt).strip().lower() != "scrub":+ if not confirm(+ prompt, "scrub", eof_message="Confirmation requires interactive input; pass --yes for non-interactive runs."+ ):log("Aborted.")return 1@@ -453,11 +393,22 @@ def main() -> int:log(f"Done: sent {sent} scrub events in {request_count} batch requests.")log("Ingestion is asynchronous - properties disappear once the events are processed.")else:- attempted, failures = scrub_via_api(session, args.host, args.project_id, affected)+ status_counts, failures = scrub_via_api(session, args.host, args.project_id, affected)+ scrubbed = sum(n for code, n in status_counts.items() if code.isdigit() and 200 <= int(code) < 300)log("")- log(f"Done: attempted {attempted} delete_property requests, {len(failures)} failures.")+ log(+ f"Done: {scrubbed}/{pair_count} property values deleted. Status breakdown: {format_status_counts(status_counts)}"+ )+ forbidden = status_counts.get("403", 0)+ if forbidden:+ log(+ f" {forbidden} forbidden (HTTP 403): the credential can't delete these - a read-only "+ "key, or field-level access control on restricted persons/properties."+ )for failure in failures[:20]:- log(f" FAILED: {failure}")+ log(f" FAILED: {printable(failure)}")+ if len(failures) > 20:+ log(f" ... and {len(failures) - 20} more failures")if failures:return 1return 0@@ -466,8 +417,8 @@ def main() -> int:if __name__ == "__main__":try:sys.exit(main())- except ScrubError as err:- log(f"Error: {err}")+ except PostHogScriptError as err:+ log(f"Error: {printable(str(err))}")sys.exit(1)except KeyboardInterrupt:log("\nInterrupted.")