: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): pull access rules into a local snapshot (#103028)
Yasen5d352181bb5e
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex c2505fd3adc4..7b70658171f8 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -435,6 +435,8 @@ jobs:- 'posthog/temporal/ingestion_acceptance_test/**'- 'posthog/temporal/backfill_group_type_created_at/**'- 'posthog/temporal/backfill_materialized_property/**'+ - 'products/security/backend/temporal/**'+ - 'products/security/backend/logic/**'- 'posthog/kafka_client/**'- 'posthog/temporal/common/**'- 'posthog/management/commands/start_temporal_worker.py'diff --git a/frontend/package.json b/frontend/package.jsonindex 46711c114a9b..eaf1f77fae2a 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -138,6 +138,7 @@"@posthog/products-replay-vision": "workspace:*","@posthog/products-revenue-analytics": "workspace:*","@posthog/products-review-hog": "workspace:*",+ "@posthog/products-security": "workspace:*","@posthog/products-session-replay": "workspace:*","@posthog/products-signals": "workspace:*","@posthog/products-skills": "workspace:*",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4d71604058b0..90f7cc1078fb 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -812,6 +812,9 @@ importers:'@posthog/products-review-hog':specifier: workspace:*version: link:../products/review_hog+ '@posthog/products-security':+ specifier: workspace:*+ version: link:../products/security'@posthog/products-session-replay':specifier: workspace:*version: link:../products/session_replay@@ -4586,6 +4589,8 @@ importers:specifier: 'catalog:'version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))+ products/security: {}+products/session_replay:dependencies:'@types/react':diff --git a/posthog/jwt.py b/posthog/jwt.pyindex 78b776ecf57e..c8a7f6828d89 100644--- a/posthog/jwt.py+++ b/posthog/jwt.py@@ -31,6 +31,8 @@ class PosthogJwtAudience(Enum):WORKFLOW_SCOUT_RUN = "posthog:workflows:scout_run"CONVERSATIONS_TICKETS = "posthog:conversations:tickets"CUSTOMER_ANALYTICS_ACCOUNTS = "posthog:customer_analytics:accounts"+ SECURITY_HUB_RULES = "posthog:security_hub:rules"+ SECURITY_HUB_INTERNAL = "posthog:security_hub:internal"def signing_key_fingerprint(key: str) -> str:diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 4f17ce6ba2e8..28882f15bd48 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -262,6 +262,10 @@ from products.review_hog.backend.temporal import (ACTIVITIES as REVIEW_HOG_ACTIVITIES,WORKFLOWS as REVIEW_HOG_WORKFLOWS,)+from products.security.backend.facade.temporal import (+ ACTIVITIES as SECURITY_ACTIVITIES,+ WORKFLOWS as SECURITY_WORKFLOWS,+)from products.signals.backend.emission.temporal_settings import (EMIT_SIGNALS_ACTIVITIES as DATA_IMPORT_EMIT_SIGNALS_ACTIVITIES,EMIT_SIGNALS_WORKFLOWS as DATA_IMPORT_EMIT_SIGNALS_WORKFLOWS,@@ -364,7 +368,8 @@ _task_queue_specs = [+ NOTEBOOKS_WORKFLOWS+ GROWTH_WORKFLOWS+ LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS- + CONTEXT_LAYER_WORKFLOWS,+ + CONTEXT_LAYER_WORKFLOWS+ + SECURITY_WORKFLOWS,PROXY_SERVICE_ACTIVITIES+ DELETE_PERSONS_ACTIVITIES+ DELETE_TEAMS_ACTIVITIES@@ -389,7 +394,8 @@ _task_queue_specs = [+ CI_SIGNALS_ACTIVITIES+ NOTEBOOKS_ACTIVITIES+ GROWTH_ACTIVITIES- + LOGS_RETENTION_ENTITLEMENTS_ACTIVITIES,+ + LOGS_RETENTION_ENTITLEMENTS_ACTIVITIES+ + SECURITY_ACTIVITIES,),# Dedicated landing zone for signup enrichment. Defaults to the general-purpose queue name (so it# merges into that fleet until a dedicated worker exists); setting SIGNUP_ENRICHMENT_TASK_QUEUE on adiff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.pyindex 3b761a2b3672..d34a9cae32c5 100644--- a/posthog/settings/__init__.py+++ b/posthog/settings/__init__.py@@ -54,6 +54,7 @@ from posthog.settings.signals import *from posthog.settings.integrations import *from posthog.settings.payments import *from posthog.settings.personhog import *+from posthog.settings.security_hub import *from posthog.settings.ses import *from posthog.settings.email import *from posthog.settings.exports import *diff --git a/posthog/settings/security_hub.py b/posthog/settings/security_hub.pynew file mode 100644index 000000000000..e6d7faff01f7--- /dev/null+++ b/posthog/settings/security_hub.py@@ -0,0 +1,22 @@+from posthog.settings.base_variables import DEBUG, TEST+from posthog.settings.utils import get_from_env, get_list++# The security hub owns access rules; this deployment pulls them.+# Unset → no sync, and decisions run against an empty rule set.+SECURITY_HUB_URL: str = get_from_env("SECURITY_HUB_URL", "")++# This deployment's region as the hub knows it ("us", "eu"). Tokens in both directions+# carry it, so a token for one region can't be replayed against another.+SECURITY_HUB_REGION: str = get_from_env("SECURITY_HUB_REGION", "dev" if DEBUG or TEST else "")++# Verifies the tokens the hub signs for this region's /api/security/ routes.+# Comma-separated, newest first. Empty in prod until provisioned, so the routes refuse+# every call.+SECURITY_HUB_INBOUND_JWT_SECRETS: list[str] = get_list(+ get_from_env("SECURITY_HUB_INBOUND_JWT_SECRETS", "local-dev-security-hub-inbound" if DEBUG or TEST else "")+)++# Signs this region's snapshot requests to the hub. Comma-separated, newest first.+SECURITY_HUB_OUTBOUND_JWT_SECRETS: list[str] = get_list(+ get_from_env("SECURITY_HUB_OUTBOUND_JWT_SECRETS", "local-dev-security-hub-outbound" if DEBUG or TEST else "")+)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex c183db0c470e..6bb59f8f8486 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -118,6 +118,7 @@ PRODUCTS_APPS = ["products.pulse.backend.apps.PulseConfig","products.data_catalog.backend.apps.DataCatalogConfig","products.data_quality.backend.apps.DataQualityConfig",+ "products.security.backend.apps.SecurityConfig",]INSTALLED_APPS = [diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex b0f8185f60c8..b777950bd123 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -127,6 +127,7 @@ from products.replay_vision.backend.temporal.reconciler import create_replay_visfrom products.replay_vision.backend.temporal.search_suggestions import create_replay_vision_search_suggestions_schedulefrom products.replay_vision.backend.temporal.vision_alerts.schedule import create_vision_alert_check_schedulefrom products.review_hog.backend.temporal.outcomes_schedule import create_review_hog_finding_outcomes_schedule+from products.security.backend.facade.temporal import create_sync_access_rules_schedulefrom products.signals.backend.emission.conversations_schedule import create_conversations_signals_coordinator_schedulefrom products.signals.backend.temporal.agentic.schedule import (create_scout_suggestions_coordinator_schedule,@@ -956,6 +957,7 @@ schedules = [create_ci_signals_coordinator_schedule,create_cleanup_data_quality_check_runs_schedule,create_reconcile_metric_schedules_schedule,+ create_sync_access_rules_schedule,]# AI observability summarization and clustering call the cloud-only guard indiff --git a/products/security/README.md b/products/security/README.mdnew file mode 100644index 000000000000..ef90ca24d485--- /dev/null+++ b/products/security/README.md@@ -0,0 +1,42 @@+# Security++Access rules that the security hub owns.+This product pulls them, decides them in-process, and answers the hub's questions.++## How it works++- A Temporal schedule (`security-sync-access-rules`, general-purpose queue) pulls this region's snapshot every 5 minutes.+ The hub also asks for a pull right after every change (`/api/security/sync-now/`).+- The snapshot lives in Redis with no TTL. Each process keeps an indexed copy and checks the Redis version at most every 30 seconds.+ When the hub is down, the last snapshot stays in force. When nothing is loaded, nobody is blocked and the login email code stays required.+- `facade.api.decide(subject, surface)` returns allow, block or exempt with the deciding rule.+ A posthog.com account is never blocked.+- Phase 1 enforces only `email_code` exemptions. Signup, login, sessions and the AI gateway call `shadow_check`, which logs `security_access_would_block` and counts `posthog_security_access_would_block_total`, and blocks nobody.++## Hub endpoints++`/api/security/{resolve,count-accounts,org-member-count,posthog-membership,sync-now,mfa-bypass-export}/`.+They are public because the hub runs outside the cluster.+A scoped HS256 token (`posthog:security_hub:internal`) pinned to this region and one operation is the only gate.+All six routes share one limit of 100 requests per minute.++## Settings++| Setting | Purpose |+| ----------------------------------- | ------------------------------------------------------------------------------------- |+| `SECURITY_HUB_URL` | the hub's base URL; unset → no sync |+| `SECURITY_HUB_REGION` | this region's id at the hub (`us`, `eu`) |+| `SECURITY_HUB_INBOUND_JWT_SECRETS` | verifies the hub's tokens; same value as the hub's `REGION_<ID>_OUTBOUND_JWT_SECRETS` |+| `SECURITY_HUB_OUTBOUND_JWT_SECRETS` | signs snapshot requests; same value as the hub's `REGION_<ID>_INBOUND_JWT_SECRETS` |++Every value is unique per environment and region. Both secrets are comma-separated, newest first.++## Matching contract++`backend/tests/fixtures/access-rules.json` copies the hub's `test-vectors/access-rules.json`.+Change the hub's copy first, then copy it here, and keep both test suites passing.++## Alerts++Alert when `time() - posthog_security_access_rules_last_sync_timestamp_seconds` exceeds 30 minutes, and when `posthog_security_access_decision_errors_total` rises.+Every process that calls `current_snapshot()` — web, Celery and the worker — refreshes both gauges from the shared Redis state at most every 30 seconds, not only the worker that runs the sync. This keeps the alert accurate on any pod, including one that has never run a sync itself.diff --git a/products/security/__init__.py b/products/security/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/security/backend/__init__.py b/products/security/backend/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/security/backend/apps.py b/products/security/backend/apps.pynew file mode 100644index 000000000000..fb3a7bb7a353--- /dev/null+++ b/products/security/backend/apps.py@@ -0,0 +1,8 @@+"""Django app configuration for security."""++from django.apps import AppConfig+++class SecurityConfig(AppConfig):+ name = "products.security.backend"+ label = "security"diff --git a/products/security/backend/facade/__init__.py b/products/security/backend/facade/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/security/backend/facade/api.py b/products/security/backend/facade/api.pynew file mode 100644index 000000000000..b25db68c2766--- /dev/null+++ b/products/security/backend/facade/api.py@@ -0,0 +1,77 @@+"""+Facade for security.++The ONLY module other products are allowed to import.+Accept frozen dataclasses, call logic/, return frozen+dataclasses. Never return ORM instances or import DRF.+"""++from __future__ import annotations++from datetime import UTC, datetime++import structlog++from ..logic.accounts import email_for_user+from ..logic.decisions import deciding_rule+from ..logic.snapshot import current_snapshot+from ..logic.subjects import normalize_subject+from ..metrics import DECISION_ERRORS_COUNTER, WOULD_BLOCK_COUNTER+from . import contracts+from .enums import Outcome, Surface++logger = structlog.get_logger(__name__)++_OUTCOME_FOR_MATCH = {Surface.EMAIL_CODE: Outcome.EXEMPT}+++def decide(subject: contracts.SubjectInput, surface: Surface) -> contracts.Decision:+ # Without the email, a posthog.com user named only by ID would skip the protection.+ email = subject.email or (email_for_user(subject.user_uuid) if subject.user_uuid else None)+ normalized = normalize_subject(+ email=email,+ user_uuid=subject.user_uuid,+ organization_ids=subject.organization_ids,+ ip=subject.ip,+ )+ rule = deciding_rule(current_snapshot().index, normalized, surface, datetime.now(UTC))+ if rule is None:+ return contracts.Decision(surface=surface, outcome=Outcome.ALLOW)+ return contracts.Decision(+ surface=surface,+ outcome=_OUTCOME_FOR_MATCH.get(surface, Outcome.BLOCK),+ rule_id=rule.id,+ target_type=rule.target_type,+ )+++def is_email_code_exempt(email: str) -> bool:+ """Whether a rule lets this address skip the emailed login code. Any failure keeps the code."""+ try:+ return decide(contracts.SubjectInput(email=email), Surface.EMAIL_CODE).outcome == Outcome.EXEMPT+ except Exception:+ logger.exception("security_email_code_exemption_check_failed")+ DECISION_ERRORS_COUNTER.labels(call_site="email_code").inc()+ return False+++def shadow_check(subject: contracts.SubjectInput, surface: Surface, *, call_site: str) -> None:+ """Records what a block rule would do here, and changes nothing. Never raises."""+ try:+ decision = decide(subject, surface)+ if decision.outcome != Outcome.BLOCK:+ return+ WOULD_BLOCK_COUNTER.labels(+ surface=surface.value, call_site=call_site, target_type=decision.target_type or ""+ ).inc()+ logger.info(+ "security_access_would_block",+ surface=surface.value,+ call_site=call_site,+ rule_id=decision.rule_id,+ target_type=decision.target_type,+ user_uuid=subject.user_uuid,+ )+ except Exception:+ logger.exception("security_access_shadow_check_failed", call_site=call_site)+ DECISION_ERRORS_COUNTER.labels(call_site=call_site).inc()diff --git a/products/security/backend/facade/contracts.py b/products/security/backend/facade/contracts.pynew file mode 100644index 000000000000..f245fa118715--- /dev/null+++ b/products/security/backend/facade/contracts.py@@ -0,0 +1,23 @@+"""Contract types for security."""++from pydantic.dataclasses import dataclass++from .enums import Outcome, Surface+++@dataclass(frozen=True)+class SubjectInput:+ """Everything a call site knows about a request. Leave a field unset when it is unknown."""++ email: str | None = None+ user_uuid: str | None = None+ organization_ids: tuple[str, ...] = ()+ ip: str | None = None+++@dataclass(frozen=True)+class Decision:+ surface: Surface+ outcome: Outcome+ rule_id: str | None = None+ target_type: str | None = Nonediff --git a/products/security/backend/facade/enums.py b/products/security/backend/facade/enums.pynew file mode 100644index 000000000000..8d5e90d33e2a--- /dev/null+++ b/products/security/backend/facade/enums.py@@ -0,0 +1,19 @@+"""Exported enums for security."""++from enum import StrEnum+++class Surface(StrEnum):+ """What a request is trying to do. A rule's scope covers one or more surfaces."""++ SIGNUP = "signup"+ APP = "app"+ AI_GATEWAY = "ai_gateway"+ EMAIL_CODE = "email_code"+++class Outcome(StrEnum):+ ALLOW = "allow"+ BLOCK = "block"+ # Only on EMAIL_CODE: the user skips the emailed login code.+ EXEMPT = "exempt"diff --git a/products/security/backend/facade/temporal.py b/products/security/backend/facade/temporal.pynew file mode 100644index 000000000000..6f63351d6a3c--- /dev/null+++ b/products/security/backend/facade/temporal.py@@ -0,0 +1,8 @@+from ..temporal import (+ ACTIVITIES as ACTIVITIES,+ WORKFLOWS as WORKFLOWS,+)+from ..temporal.schedule import (+ create_sync_access_rules_schedule as create_sync_access_rules_schedule,+ start_sync_now as start_sync_now,+)diff --git a/products/security/backend/logic/__init__.py b/products/security/backend/logic/__init__.pynew file mode 100644index 000000000000..0be17bf2d350--- /dev/null+++ b/products/security/backend/logic/__init__.py@@ -0,0 +1 @@+"""Business logic for security."""diff --git a/products/security/backend/logic/accounts.py b/products/security/backend/logic/accounts.pynew file mode 100644index 000000000000..fcf1f59ad1ff--- /dev/null+++ b/products/security/backend/logic/accounts.py@@ -0,0 +1,136 @@+"""What the security hub asks this region about accounts. Every count stops at COUNT_CAP."""++import re+import uuid+from typing import Literal++from django.db.models import Q, QuerySet++from posthog.dataclasses import frozen+from posthog.helpers.email_utils import EmailLookupHandler+from posthog.models import Organization, OrganizationMembership, User++from .decisions import PROTECTED_DOMAIN+from .subjects import DOT_INSENSITIVE_DOMAINS++# An email root or domain count has no index to use, so an uncapped count would scan+# every row of posthog_user while the admin waits.+COUNT_CAP = 500++CountableType = Literal["email", "email_root", "email_domain"]+++@frozen+class ResolvedUser:+ uuid: str+ email: str+ is_active: bool+++@frozen+class Resolution:+ kind: Literal["user", "organization", "none"]+ user: ResolvedUser | None = None+ organization_ids: tuple[str, ...] = ()+++@frozen+class CappedCount:+ count: int+ capped: bool+++NOTHING = Resolution(kind="none")+++def _parse_uuid(value: str) -> uuid.UUID | None:+ try:+ return uuid.UUID(value)+ except ValueError:+ return None+++def _user_resolution(user: User) -> Resolution:+ organization_ids = OrganizationMembership.objects.filter(user=user).values_list("organization_id", flat=True)+ return Resolution(+ kind="user",+ user=ResolvedUser(uuid=str(user.uuid), email=user.email, is_active=user.is_active),+ organization_ids=tuple(sorted(str(org_id) for org_id in organization_ids)),+ )+++def resolve_subject(query: str) -> Resolution:+ text = query.strip()+ if not text:+ return NOTHING+ if "@" in text:+ user = EmailLookupHandler.get_user_by_email(text, is_active=None)+ return _user_resolution(user) if user else NOTHING+ parsed = _parse_uuid(text)+ if parsed is None:+ return NOTHING+ user = User.objects.filter(uuid=parsed).first()+ if user:+ return _user_resolution(user)+ if Organization.objects.filter(id=parsed).exists():+ return Resolution(kind="organization", organization_ids=(str(parsed),))+ return NOTHING+++def _capped(queryset: QuerySet) -> CappedCount:+ # One row over the cap, so a full count and a capped count look different.+ found = queryset.values("pk")[: COUNT_CAP + 1].count()+ return CappedCount(count=min(found, COUNT_CAP), capped=found > COUNT_CAP)+++def _email_root_regex(root: str) -> str:+ """Every stored address that folds to this root."""+ local, _, domain = root.rpartition("@")+ suffix = r"(\+[^@]*)?"+ if domain in DOT_INSENSITIVE_DOMAINS:+ dotted_local = r"\.*".join(re.escape(char) for char in local)+ return rf"^{dotted_local}{suffix}@(gmail|googlemail)\.com$"+ return rf"^{re.escape(local)}{suffix}@{re.escape(domain)}$"+++def count_active_accounts(target_type: CountableType, value: str) -> CappedCount:+ if target_type == "email":+ # Matches resolve_subject's fold (LOWER via EmailLookupHandler), not `iexact` (UPPER):+ # the two fold Unicode differently, so a count on one fold could disagree with who resolves.+ return _capped(EmailLookupHandler.users_matching_email(value, User.objects.filter(is_active=True)))+ match target_type:+ case "email_root":+ condition = Q(email__iregex=_email_root_regex(value))+ case "email_domain":+ condition = Q(email__iendswith=f"@{value}") | Q(email__iendswith=f".{value}")+ return _capped(User.objects.filter(condition, is_active=True))+++def count_active_org_members(organization_id: str) -> tuple[bool, CappedCount]:+ parsed = _parse_uuid(organization_id)+ if parsed is None or not Organization.objects.filter(id=parsed).exists():+ return False, CappedCount(count=0, capped=False)+ members = OrganizationMembership.objects.filter(organization_id=parsed, user__is_active=True)+ return True, _capped(members)+++def _is_protected_email(email: str | None) -> bool:+ domain = (email or "").lower().rpartition("@")[2]+ return domain == PROTECTED_DOMAIN or domain.endswith(f".{PROTECTED_DOMAIN}")+++def email_for_user(user_uuid: str) -> str | None:+ parsed = _parse_uuid(user_uuid)+ if parsed is None:+ return None+ return User.objects.filter(uuid=parsed).values_list("email", flat=True).first()+++def has_posthog_account(*, user_uuid: str | None = None, organization_id: str | None = None) -> bool:+ if user_uuid is not None:+ return _is_protected_email(email_for_user(user_uuid))+ parsed = _parse_uuid(organization_id or "")+ if parsed is None:+ return False+ protected = Q(user__email__iendswith=f"@{PROTECTED_DOMAIN}") | Q(user__email__iendswith=f".{PROTECTED_DOMAIN}")+ return OrganizationMembership.objects.filter(protected, organization_id=parsed).exists()diff --git a/products/security/backend/logic/decisions.py b/products/security/backend/logic/decisions.pynew file mode 100644index 000000000000..0b1f8f8e59c0--- /dev/null+++ b/products/security/backend/logic/decisions.py@@ -0,0 +1,51 @@+"""What a subject's matching rules mean for one surface."""++from datetime import datetime++from ..facade.enums import Surface+from .matching import RuleIndex, candidates, rule_matches+from .rules import SnapshotRule+from .subjects import Subject++SCOPE_SURFACES: dict[str, frozenset[Surface]] = {+ "all_access": frozenset({Surface.SIGNUP, Surface.APP, Surface.AI_GATEWAY}),+ "signup": frozenset({Surface.SIGNUP}),+ "ai_gateway": frozenset({Surface.AI_GATEWAY}),+ "email_code": frozenset({Surface.EMAIL_CODE}),+}++# The effect a rule needs to decide each surface.+SURFACE_EFFECT: dict[Surface, str] = {+ Surface.SIGNUP: "block",+ Surface.APP: "block",+ Surface.AI_GATEWAY: "block",+ Surface.EMAIL_CODE: "exempt",+}++PROTECTED_DOMAIN = "posthog.com"+++def is_protected_domain(domain: str | None) -> bool:+ return domain is not None and (domain == PROTECTED_DOMAIN or domain.endswith(f".{PROTECTED_DOMAIN}"))+++def _is_active(rule: SnapshotRule, now: datetime) -> bool:+ return rule.expires_at is None or rule.expires_at > now+++def deciding_rule(index: RuleIndex, subject: Subject, surface: Surface, now: datetime) -> SnapshotRule | None:+ """The oldest active rule that decides this surface, or None when the subject is allowed."""+ effect = SURFACE_EFFECT[surface]+ # A rule written before the hub's save-time check still never blocks a posthog.com+ # account. Exemptions still apply to one.+ if effect == "block" and is_protected_domain(subject.domain):+ return None+ for rule in candidates(index, subject):+ if (+ rule.effect == effect+ and surface in SCOPE_SURFACES.get(rule.scope, frozenset())+ and _is_active(rule, now)+ and rule_matches(rule, subject)+ ):+ return rule+ return Nonediff --git a/products/security/backend/logic/hub_auth.py b/products/security/backend/logic/hub_auth.pynew file mode 100644index 000000000000..944e945ad84d--- /dev/null+++ b/products/security/backend/logic/hub_auth.py@@ -0,0 +1,51 @@+"""Tokens between this region and the security hub, one secret per direction."""++import time+from collections.abc import Mapping+from datetime import timedelta+from typing import Any, TypeGuard++from django.conf import settings++from posthog.jwt import PosthogJwtAudience+from posthog.scoped_service_jwt import ScopedServiceJwtPurpose++# The hub refuses a token that lives longer than this.+MAX_TOKEN_LIFETIME_SECONDS = 60+# Below the limit, because encode_jwt sets exp from its own clock read after iat.+_MINT_TTL = timedelta(seconds=55)++RULES_PURPOSE = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.SECURITY_HUB_RULES,+ settings_name="SECURITY_HUB_OUTBOUND_JWT_SECRETS",+ default_ttl=_MINT_TTL,+)++INTERNAL_PURPOSE = ScopedServiceJwtPurpose(+ audience=PosthogJwtAudience.SECURITY_HUB_INTERNAL,+ settings_name="SECURITY_HUB_INBOUND_JWT_SECRETS",+ default_ttl=_MINT_TTL,+)+++def mint_rules_token() -> str:+ return RULES_PURPOSE.mint({"region": settings.SECURITY_HUB_REGION, "op": "rules:read", "iat": int(time.time())})+++def _is_int(value: object) -> TypeGuard[int]:+ return isinstance(value, int) and not isinstance(value, bool)+++def claims_allow(claims: Mapping[str, Any] | None, op: str) -> bool:+ """Signature, expiry and audience are already verified. This pins the region, the+ operation and a short lifetime, so one leaked token opens one operation briefly."""+ if not claims:+ return False+ iat, exp = claims.get("iat"), claims.get("exp")+ return (+ claims.get("region") == settings.SECURITY_HUB_REGION+ and claims.get("op") == op+ and _is_int(iat)+ and _is_int(exp)+ and exp - iat <= MAX_TOKEN_LIFETIME_SECONDS+ )diff --git a/products/security/backend/logic/matching.py b/products/security/backend/logic/matching.pynew file mode 100644index 000000000000..2998e435b6f6--- /dev/null+++ b/products/security/backend/logic/matching.py@@ -0,0 +1,96 @@+"""Which snapshot rules can match a subject, and whether one does.++Every target type except IP ranges is an exact lookup, so a decision stays fast with+thousands of rules. Domain rules are looked up once per suffix of the subject's domain.+"""++from collections import defaultdict+from collections.abc import Callable, Iterable, Mapping++from posthog.dataclasses import frozen++from .rules import SnapshotRule+from .subjects import Subject++_EXACT_TYPES = frozenset({"user_uuid", "email", "email_root", "email_domain", "organization_id", "everyone"})+++def _match_ip(rule: SnapshotRule, subject: Subject) -> bool:+ if rule.network is None or subject.ip is None:+ return False+ # Containment across IP versions is False, not an error.+ if subject.ip in rule.network:+ return True+ mapped = getattr(subject.ip, "ipv4_mapped", None)+ return mapped is not None and mapped in rule.network+++def _match_domain(rule: SnapshotRule, subject: Subject) -> bool:+ # A domain rule also covers its subdomains; a shared suffix is not a subdomain.+ domain = subject.domain+ return domain is not None and (domain == rule.target_value or domain.endswith(f".{rule.target_value}"))+++_MATCHERS: dict[str, Callable[[SnapshotRule, Subject], bool]] = {+ "user_uuid": lambda rule, subject: subject.user_uuid == rule.target_value,+ "email": lambda rule, subject: subject.email == rule.target_value,+ "email_root": lambda rule, subject: subject.email_root == rule.target_value,+ "email_domain": _match_domain,+ "organization_id": lambda rule, subject: rule.target_value in subject.organization_ids,+ "ip": _match_ip,+ "everyone": lambda rule, subject: True,+}+++def rule_matches(rule: SnapshotRule, subject: Subject) -> bool:+ # A type from another release matches nothing rather than failing every check.+ matcher = _MATCHERS.get(rule.target_type)+ return matcher is not None and matcher(rule, subject)+++@frozen+class RuleIndex:+ exact: Mapping[tuple[str, str], tuple[SnapshotRule, ...]]+ networks: tuple[SnapshotRule, ...]+++EMPTY_INDEX = RuleIndex(exact={}, networks=())+++def build_index(rules: Iterable[SnapshotRule]) -> RuleIndex:+ exact: defaultdict[tuple[str, str], list[SnapshotRule]] = defaultdict(list)+ networks: list[SnapshotRule] = []+ for rule in rules:+ if rule.target_type == "ip":+ networks.append(rule)+ elif rule.target_type in _EXACT_TYPES:+ exact[(rule.target_type, rule.target_value)].append(rule)+ return RuleIndex(exact={key: tuple(value) for key, value in exact.items()}, networks=tuple(networks))+++def _domain_suffixes(domain: str | None) -> list[str]:+ if not domain:+ return []+ labels = domain.split(".")+ return [".".join(labels[i:]) for i in range(len(labels))]+++def candidates(index: RuleIndex, subject: Subject) -> list[SnapshotRule]:+ keys: list[tuple[str, str]] = [("everyone", "")]+ if subject.email:+ keys.append(("email", subject.email))+ if subject.email_root:+ keys.append(("email_root", subject.email_root))+ if subject.user_uuid:+ keys.append(("user_uuid", subject.user_uuid))+ keys.extend(("organization_id", org) for org in subject.organization_ids)+ keys.extend(("email_domain", suffix) for suffix in _domain_suffixes(subject.domain))++ found: dict[str, SnapshotRule] = {}+ for key in keys:+ for rule in index.exact.get(key, ()):+ found[rule.id] = rule+ if subject.ip is not None:+ for rule in index.networks:+ found[rule.id] = rule+ return sorted(found.values(), key=lambda rule: rule.id)diff --git a/products/security/backend/logic/rules.py b/products/security/backend/logic/rules.pynew file mode 100644index 000000000000..044b2357b8f8--- /dev/null+++ b/products/security/backend/logic/rules.py@@ -0,0 +1,61 @@+"""One rule as the hub's snapshot delivers it. Values are already normalized by the hub."""++import ipaddress+from datetime import datetime+from typing import Any++from posthog.dataclasses import frozen++_TEXT_FIELDS = ("id", "targetType", "targetValue", "effect", "scope")+++@frozen+class SnapshotRule:+ id: str+ target_type: str+ target_value: str+ effect: str+ scope: str+ expires_at: datetime | None = None+ # Parsed once when the snapshot loads, so a decision never re-parses a range.+ network: ipaddress.IPv4Network | ipaddress.IPv6Network | None = None++ @classmethod+ def from_wire(cls, raw: object) -> "SnapshotRule | None":+ """The rule, or None when the hub sent something this release can't read."""+ if not isinstance(raw, dict):+ return None+ values: dict[str, Any] = {key: raw.get(key) for key in _TEXT_FIELDS}+ if not all(isinstance(value, str) for value in values.values()):+ return None++ expires_at: datetime | None = None+ expires_raw = raw.get("expiresAt")+ if expires_raw is not None:+ if not isinstance(expires_raw, str):+ return None+ try:+ expires_at = datetime.fromisoformat(expires_raw)+ except ValueError:+ return None+ # A naive value can't compare against the aware `now` a decision uses, which+ # raises TypeError inside decide and fails the whole check closed.+ if expires_at.utcoffset() is None:+ return None++ network = None+ if values["targetType"] == "ip":+ try:+ network = ipaddress.ip_network(values["targetValue"])+ except ValueError:+ return None++ return cls(+ id=values["id"],+ target_type=values["targetType"],+ target_value=values["targetValue"],+ effect=values["effect"],+ scope=values["scope"],+ expires_at=expires_at,+ network=network,+ )diff --git a/products/security/backend/logic/snapshot.py b/products/security/backend/logic/snapshot.pynew file mode 100644index 000000000000..7854976b98e3--- /dev/null+++ b/products/security/backend/logic/snapshot.py@@ -0,0 +1,178 @@+"""The region's copy of the hub's rules.++The sync job writes one Redis key with no TTL, so a hub outage never empties it. Each+process keeps the parsed, indexed rules in memory and checks the Redis version at most+every 30 seconds. When Redis is unreachable or empty, the process keeps what it has.+With nothing loaded at all, every decision is allow: nobody is blocked, and the login+email code stays required.+"""++import json+import time+import threading+from datetime import datetime++import structlog+from redis.commands.core import Script++from posthog.dataclasses import frozen+from posthog.redis import get_client++from ..metrics import LAST_SYNC_GAUGE, RULES_GAUGE, SKIPPED_RULES_COUNTER+from .matching import EMPTY_INDEX, RuleIndex, build_index+from .rules import SnapshotRule++logger = structlog.get_logger(__name__)++SNAPSHOT_KEY = "security:access_rules:snapshot"+VERSION_KEY = "security:access_rules:version"+LAST_SYNC_KEY = "security:access_rules:last_sync_at"+GENERATED_AT_KEY = "security:access_rules:generated_at"+MEMO_TTL_SECONDS = 30++# KEYS[1] generated-at key, KEYS[2] snapshot key, KEYS[3] version key.+# ARGV[1] this write's generatedAt (epoch ms, from the hub), ARGV[2] snapshot+# JSON, ARGV[3] version. Applies unless a stored generatedAt is already newer,+# so a slower, older fetch can't overwrite a snapshot a later one already+# stored. The hub is one deployment, so its own generatedAt orders writes+# without a counter this store would have to keep in sync: a missing key+# (never written, or flushed) simply means apply, so nothing can wedge.+_WRITE_LUA = """+local stored = tonumber(redis.call('GET', KEYS[1]))+local generated_at = tonumber(ARGV[1])+if stored ~= nil and generated_at < stored then+ return 0+end+redis.call('SET', KEYS[2], ARGV[2])+redis.call('SET', KEYS[3], ARGV[3])+redis.call('SET', KEYS[1], generated_at)+return 1+"""++_write_script: Script | None = None+++@frozen+class WriteOutcome:+ applied: bool+ # None for a dropped write: its count was never applied, so it isn't the store's count.+ rule_count: int | None+++@frozen+class Snapshot:+ version: str+ index: RuleIndex+ rule_count: int+++EMPTY_SNAPSHOT = Snapshot(version="", index=EMPTY_INDEX, rule_count=0)++_lock = threading.Lock()+_memo: Snapshot = EMPTY_SNAPSHOT+_checked_at: float | None = None+++def _parse(raw_rules: list[object]) -> tuple[RuleIndex, int]:+ rules: list[SnapshotRule] = []+ for raw in raw_rules:+ rule = SnapshotRule.from_wire(raw)+ if rule is None:+ SKIPPED_RULES_COUNTER.inc()+ else:+ rules.append(rule)+ return build_index(rules), len(rules)+++def _get_write_script() -> Script:+ global _write_script+ if _write_script is None:+ _write_script = get_client().register_script(_WRITE_LUA)+ return _write_script+++def write_snapshot(version: str, raw_rules: list[object], generated_at_ms: int | None = None) -> WriteOutcome:+ if generated_at_ms is None:+ generated_at_ms = int(time.time() * 1000)+ _, count = _parse(raw_rules)+ payload = json.dumps({"version": version, "rules": raw_rules})+ applied = bool(+ _get_write_script()(+ keys=[GENERATED_AT_KEY, SNAPSHOT_KEY, VERSION_KEY], args=[generated_at_ms, payload, version]+ )+ )+ if not applied:+ logger.warning("security_access_rules_write_stale", generated_at_ms=generated_at_ms)+ return WriteOutcome(applied=False, rule_count=None)+ RULES_GAUGE.set(count)+ return WriteOutcome(applied=True, rule_count=count)+++def _decode(value: bytes | str | None) -> str | None:+ if value is None:+ return None+ return value.decode() if isinstance(value, bytes) else value+++def stored_version() -> str | None:+ return _decode(get_client().get(VERSION_KEY))+++def mark_synced(now: datetime) -> None:+ get_client().set(LAST_SYNC_KEY, now.isoformat())+++def last_synced_at() -> datetime | None:+ value = _decode(get_client().get(LAST_SYNC_KEY))+ return datetime.fromisoformat(value) if value else None+++def _load(version: str) -> Snapshot | None:+ raw = _decode(get_client().get(SNAPSHOT_KEY))+ if raw is None:+ return None+ payload = json.loads(raw)+ if payload.get("version") != version or not isinstance(payload.get("rules"), list):+ return None+ index, count = _parse(payload["rules"])+ return Snapshot(version=version, index=index, rule_count=count)+++def current_snapshot() -> Snapshot:+ global _memo, _checked_at+ # time.time(), not time.monotonic(): this repo's clock-freezing tool for tests+ # (time_machine) doesn't patch monotonic, so a frozen test clock would never+ # cross the memo window.+ now = time.time()+ if _checked_at is not None and now - _checked_at < MEMO_TTL_SECONDS:+ return _memo++ # Redis I/O and the index rebuild happen outside the lock, so a slow refresh doesn't stall other threads.+ starting_memo = _memo+ memo = starting_memo+ try:+ version = stored_version()+ if version and version != memo.version:+ loaded = _load(version)+ if loaded is not None:+ memo = loaded+ synced_at = last_synced_at()+ if synced_at is not None:+ LAST_SYNC_GAUGE.set(synced_at.timestamp())+ except Exception:+ logger.warning("security_access_rules_snapshot_read_failed", exc_info=True)++ with _lock:+ # Only commit if nothing advanced _memo while this refresh ran outside the lock.+ if _memo is starting_memo:+ _memo = memo+ RULES_GAUGE.set(_memo.rule_count)+ _checked_at = now+ return _memo+++def reset_memo() -> None:+ global _memo, _checked_at+ with _lock:+ _memo = EMPTY_SNAPSHOT+ _checked_at = Nonediff --git a/products/security/backend/logic/subjects.py b/products/security/backend/logic/subjects.pynew file mode 100644index 000000000000..fd5380c9ddbf--- /dev/null+++ b/products/security/backend/logic/subjects.py@@ -0,0 +1,82 @@+"""Who or what a decision is about, normalized once per decision."""++import uuid+import ipaddress+from collections.abc import Iterable++from posthog.dataclasses import frozen++# Gmail ignores dots in the local part, so one mailbox has many spellings.+DOT_INSENSITIVE_DOMAINS = frozenset({"gmail.com", "googlemail.com"})++# SMTP caps a deliverable address at 254 characters. Longer input is refused so the domain suffix expansion stays small.+MAX_ADDRESS_LENGTH = 254+++@frozen+class Subject:+ email: str | None = None+ email_root: str | None = None+ domain: str | None = None+ user_uuid: str | None = None+ organization_ids: frozenset[str] = frozenset()+ ip: ipaddress.IPv4Address | ipaddress.IPv6Address | None = None+++def fold_email_root(address: str) -> str | None:+ """The mailbox an address delivers to: the +suffix dropped, and Gmail's dots removed."""+ local, at, domain = address.strip().lower().rpartition("@")+ if not at or not local or not domain:+ return None+ root_local = local.split("+", 1)[0]+ if not root_local:+ return None+ if domain in DOT_INSENSITIVE_DOMAINS:+ return f"{root_local.replace('.', '')}@gmail.com"+ return f"{root_local}@{domain}"+++def _canonical_uuid(value: str | None) -> str | None:+ if not value:+ return None+ try:+ return str(uuid.UUID(value.strip()))+ except ValueError:+ return None+++def _parse_ip(value: str | None) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:+ if not value:+ return None+ try:+ return ipaddress.ip_address(value.strip())+ except ValueError:+ return None+++def normalize_subject(+ *,+ email: str | None = None,+ domain: str | None = None,+ user_uuid: str | None = None,+ organization_ids: Iterable[str] = (),+ ip: str | None = None,+) -> Subject:+ address = (email or "").strip().lower() or None+ if address and len(address) > MAX_ADDRESS_LENGTH:+ address = None+ if address:+ subject_domain = address.rpartition("@")[2] or None+ else:+ subject_domain = (domain or "").strip().lower().removeprefix("@") or None+ if subject_domain and len(subject_domain) > MAX_ADDRESS_LENGTH:+ subject_domain = None+ organizations = frozenset(filter(None, (_canonical_uuid(org) for org in organization_ids)))+ return Subject(+ email=address,+ email_root=fold_email_root(address) if address else None,+ domain=subject_domain,+ user_uuid=_canonical_uuid(user_uuid),+ organization_ids=organizations,+ ip=_parse_ip(ip),+ )diff --git a/products/security/backend/logic/sync.py b/products/security/backend/logic/sync.pynew file mode 100644index 000000000000..5169a471a680--- /dev/null+++ b/products/security/backend/logic/sync.py@@ -0,0 +1,112 @@+"""Pulls this region's access rules from the security hub into the snapshot store."""++import time+from datetime import UTC, datetime+from typing import Literal+from urllib.parse import urlparse++from django.conf import settings++import requests+import structlog++from posthog.dataclasses import frozen++from ..metrics import LAST_SYNC_GAUGE, SYNC_COUNTER+from .hub_auth import RULES_PURPOSE, mint_rules_token+from .snapshot import mark_synced, stored_version, write_snapshot++logger = structlog.get_logger(__name__)++REQUEST_TIMEOUT_SECONDS = 10+SNAPSHOT_PATH = "/webhooks/access-rules/snapshot"+_LOCAL_HOSTS = {"localhost", "127.0.0.1"}+++class InvalidSnapshot(Exception):+ pass+++@frozen+class SyncResult:+ status: Literal["updated", "unchanged", "not_configured", "stale"]+ rule_count: int | None = None+++def _mark_success() -> None:+ mark_synced(datetime.now(UTC))+ LAST_SYNC_GAUGE.set(time.time())+++def _hub_url_is_https_or_local(url: str) -> bool:+ """Refuses cleartext bearer tokens. http:// is allowed only for a local hub in DEBUG or TEST."""+ parsed = urlparse(url)+ if parsed.scheme == "https":+ return True+ return parsed.scheme == "http" and parsed.hostname in _LOCAL_HOSTS and (settings.DEBUG or settings.TEST)+++def _parse_generated_at_ms(value: object) -> int | None:+ if not isinstance(value, str):+ return None+ try:+ parsed = datetime.fromisoformat(value)+ except ValueError:+ return None+ # A naive value has no fixed instant: .timestamp() would read it in the process's+ # local timezone rather than the hub's, silently misordering writes.+ if parsed.utcoffset() is None:+ return None+ return int(parsed.timestamp() * 1000)+++def sync_access_rules() -> SyncResult:+ if not settings.SECURITY_HUB_URL or not settings.SECURITY_HUB_REGION or not RULES_PURPOSE.enabled():+ SYNC_COUNTER.labels(result="not_configured").inc()+ return SyncResult(status="not_configured")++ if not _hub_url_is_https_or_local(settings.SECURITY_HUB_URL):+ logger.warning("security_hub_url_refused_insecure_scheme")+ SYNC_COUNTER.labels(result="not_configured").inc()+ return SyncResult(status="not_configured")++ headers = {"Authorization": f"Bearer {mint_rules_token()}"}+ version = stored_version()+ if version:+ headers["If-None-Match"] = f'"{version}"'++ try:+ response = requests.get(+ f"{settings.SECURITY_HUB_URL.rstrip('/')}{SNAPSHOT_PATH}",+ params={"region": settings.SECURITY_HUB_REGION},+ headers=headers,+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if response.status_code == 304:+ _mark_success()+ SYNC_COUNTER.labels(result="unchanged").inc()+ return SyncResult(status="unchanged")+ response.raise_for_status()+ body = response.json()+ generated_at_ms = _parse_generated_at_ms(body.get("generatedAt")) if isinstance(body, dict) else None+ if (+ not isinstance(body, dict)+ or not isinstance(body.get("version"), str)+ or not isinstance(body.get("rules"), list)+ or body.get("region") != settings.SECURITY_HUB_REGION+ or generated_at_ms is None+ ):+ raise InvalidSnapshot("The hub answered with a snapshot this region can't use.")+ except Exception:+ SYNC_COUNTER.labels(result="failed").inc()+ raise++ outcome = write_snapshot(body["version"], body["rules"], generated_at_ms)+ # The hub answered, so this counts as contact even if the write lost the ordering race.+ _mark_success()+ if not outcome.applied:+ SYNC_COUNTER.labels(result="stale").inc()+ return SyncResult(status="stale", rule_count=outcome.rule_count)+ SYNC_COUNTER.labels(result="updated").inc()+ logger.info("security_access_rules_synced", version=body["version"], rule_count=outcome.rule_count)+ return SyncResult(status="updated", rule_count=outcome.rule_count)diff --git a/products/security/backend/metrics.py b/products/security/backend/metrics.pynew file mode 100644index 000000000000..1ff3c33a0f02--- /dev/null+++ b/products/security/backend/metrics.py@@ -0,0 +1,34 @@+from prometheus_client import Counter, Gauge++WOULD_BLOCK_COUNTER = Counter(+ "posthog_security_access_would_block_total",+ "Requests an access rule would block, while blocks are logged only",+ labelnames=["surface", "call_site", "target_type"],+)+DECISION_ERRORS_COUNTER = Counter(+ "posthog_security_access_decision_errors_total",+ "Access decisions that raised and were treated as allow",+ labelnames=["call_site"],+)+SKIPPED_RULES_COUNTER = Counter(+ "posthog_security_access_rules_skipped_total",+ "Snapshot rules this release could not read",+)+SYNC_COUNTER = Counter(+ "posthog_security_access_rules_sync_total",+ "Snapshot pulls from the security hub, by result",+ labelnames=["result"], # updated | unchanged | not_configured | failed | stale+)+LAST_SYNC_GAUGE = Gauge(+ "posthog_security_access_rules_last_sync_timestamp_seconds",+ "Unix time of the last successful snapshot pull; alert when it falls behind",+)+RULES_GAUGE = Gauge(+ "posthog_security_access_rules_count",+ "Readable rules in the last stored snapshot",+)+HUB_API_AUTH_COUNTER = Counter(+ "posthog_security_hub_api_calls_total",+ "Authenticated calls from the security hub, by operation",+ labelnames=["op"],+)diff --git a/products/security/backend/presentation/__init__.py b/products/security/backend/presentation/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/security/backend/temporal/__init__.py b/products/security/backend/temporal/__init__.pynew file mode 100644index 000000000000..c169d0fdeceb--- /dev/null+++ b/products/security/backend/temporal/__init__.py@@ -0,0 +1,12 @@+from collections.abc import Callable+from typing import Any++from posthog.temporal.common.base import PostHogWorkflow++from .activities import sync_access_rules_activity+from .workflows import SyncAccessRulesWorkflow++WORKFLOWS: list[type[PostHogWorkflow]] = [SyncAccessRulesWorkflow]+ACTIVITIES: list[Callable[..., Any]] = [sync_access_rules_activity]++__all__ = ["ACTIVITIES", "WORKFLOWS"]diff --git a/products/security/backend/temporal/activities.py b/products/security/backend/temporal/activities.pynew file mode 100644index 000000000000..5a3f287b0e77--- /dev/null+++ b/products/security/backend/temporal/activities.py@@ -0,0 +1,18 @@+from asgiref.sync import sync_to_async+from temporalio import activity++from posthog.dataclasses import frozen++from ..logic.sync import sync_access_rules+++@frozen+class SyncOutcome:+ status: str+ rule_count: int | None+++async def sync_access_rules_activity() -> SyncOutcome:+ result = await sync_to_async(sync_access_rules)()+ return SyncOutcome(status=result.status, rule_count=result.rule_count)diff --git a/products/security/backend/temporal/schedule.py b/products/security/backend/temporal/schedule.pynew file mode 100644index 000000000000..ab0a2bf1fba8--- /dev/null+++ b/products/security/backend/temporal/schedule.py@@ -0,0 +1,57 @@+import asyncio+import datetime as dt++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleIntervalSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)+from temporalio.common import RetryPolicy, WorkflowIDConflictPolicy, WorkflowIDReusePolicy++from posthog.temporal.common.client import sync_connect+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++from .workflows import WORKFLOW_NAME++SCHEDULE_ID = "security-sync-access-rules-schedule"+SYNC_NOW_WORKFLOW_ID = "security-sync-access-rules-now"+EXECUTION_TIMEOUT = dt.timedelta(minutes=4)+++async def create_sync_access_rules_schedule(client: Client) -> None:+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ WORKFLOW_NAME,+ id=SCHEDULE_ID,+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ execution_timeout=EXECUTION_TIMEOUT,+ ),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=dt.timedelta(minutes=5))]),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )+ if await a_schedule_exists(client, SCHEDULE_ID):+ await a_update_schedule(client, SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, SCHEDULE_ID, schedule, trigger_immediately=True)+++def start_sync_now() -> None:+ """Starts a pull at once. A pull that is already running absorbs the request."""+ temporal = sync_connect()+ asyncio.run(+ temporal.start_workflow(+ WORKFLOW_NAME,+ id=SYNC_NOW_WORKFLOW_ID,+ task_queue=settings.GENERAL_PURPOSE_TASK_QUEUE,+ execution_timeout=EXECUTION_TIMEOUT,+ id_conflict_policy=WorkflowIDConflictPolicy.USE_EXISTING,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ )diff --git a/products/security/backend/temporal/workflows.py b/products/security/backend/temporal/workflows.pynew file mode 100644index 000000000000..f87aae4548f5--- /dev/null+++ b/products/security/backend/temporal/workflows.py@@ -0,0 +1,25 @@+import datetime as dt++from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++from .activities import SyncOutcome, sync_access_rules_activity++WORKFLOW_NAME = "security-sync-access-rules"++[email protected](name=WORKFLOW_NAME)+class SyncAccessRulesWorkflow(PostHogWorkflow):+ @staticmethod+ def parse_inputs(inputs: list[str]) -> None:+ return None++ @workflow.run+ async def run(self) -> SyncOutcome:+ return await workflow.execute_activity(+ sync_access_rules_activity,+ start_to_close_timeout=dt.timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3, initial_interval=dt.timedelta(seconds=5)),+ )diff --git a/products/security/backend/tests/__init__.py b/products/security/backend/tests/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/security/backend/tests/conftest.py b/products/security/backend/tests/conftest.pynew file mode 100644index 000000000000..ae3f00200968--- /dev/null+++ b/products/security/backend/tests/conftest.py@@ -0,0 +1,13 @@+import pytest++from posthog.models.scoping import team_scope++[email protected](autouse=True)+def _set_team_scope(request):+ if request.node.get_closest_marker("django_db") is None:+ yield+ return+ team = request.getfixturevalue("team")+ with team_scope(team.id):+ yielddiff --git a/products/security/backend/tests/fixtures/README.md b/products/security/backend/tests/fixtures/README.mdnew file mode 100644index 000000000000..8f83467d92a7--- /dev/null+++ b/products/security/backend/tests/fixtures/README.md@@ -0,0 +1,3 @@+`access-rules.json` is a copy of `test-vectors/access-rules.json` in the security hub repository, the canonical file.+It is the matching contract between the security hub and Django: both test suites run every case.+Change the hub copy first, then copy it here.diff --git a/products/security/backend/tests/fixtures/access-rules.json b/products/security/backend/tests/fixtures/access-rules.jsonnew file mode 100644index 000000000000..43a3a7597758--- /dev/null+++ b/products/security/backend/tests/fixtures/access-rules.json@@ -0,0 +1,82 @@+{+ "_format": "Shared matching contract. The canonical copy lives in the security hub repository at test-vectors/access-rules.json. The PostHog Django repository keeps a copy at products/security/backend/tests/fixtures/access-rules.json; change both together. Each case's expect string has one letter per surface in the order signup, app, ai_gateway, email_code: B = blocked, A = allowed (email_code: code required), E = exempt (email_code: code skipped). Rules are already normalized. The optional deciding map names the rule that must decide a surface.",+ "suites": [+ {+ "name": "blocks and per-email exemptions",+ "now": "2026-09-17T12:00:00Z",+ "rules": [+ {"id": "01920000-0000-7000-8000-000000000001", "targetType": "email_root", "targetValue": "[email protected]", "effect": "block", "scope": "all_access", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000002", "targetType": "email_domain", "targetValue": "throwaway.example", "effect": "block", "scope": "all_access", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000003", "targetType": "email_domain", "targetValue": "mailinator.com", "effect": "block", "scope": "signup", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000004", "targetType": "organization_id", "targetValue": "1111aaaa-1111-4111-8111-11111111aaaa", "effect": "block", "scope": "ai_gateway", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000005", "targetType": "email_root", "targetValue": "[email protected]", "effect": "block", "scope": "ai_gateway", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000006", "targetType": "ip", "targetValue": "93.184.216.0/24", "effect": "block", "scope": "all_access", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000007", "targetType": "user_uuid", "targetValue": "2222abcd-2222-4222-8222-22222222abcd", "effect": "block", "scope": "all_access", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000008", "targetType": "ip", "targetValue": "203.0.113.0/24", "effect": "block", "scope": "all_access", "expiresAt": "2026-09-01T00:00:00Z"},+ {"id": "01920000-0000-7000-8000-000000000009", "targetType": "email_domain", "targetValue": "posthog.com", "effect": "block", "scope": "all_access", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000010", "targetType": "user_uuid", "targetValue": "3333abcd-3333-4333-8333-33333333abcd", "effect": "block", "scope": "all_access", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000011", "targetType": "email", "targetValue": "[email protected]", "effect": "exempt", "scope": "email_code", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000012", "targetType": "email", "targetValue": "[email protected]", "effect": "exempt", "scope": "email_code", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000013", "targetType": "everyone", "targetValue": "", "effect": "exempt", "scope": "email_code", "expiresAt": "2026-09-10T00:00:00Z"},+ {"id": "01920000-0000-7000-8000-000000000014", "targetType": "team_id", "targetValue": "42", "effect": "block", "scope": "ai_gateway", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000015", "targetType": "email", "targetValue": "[email protected]", "effect": "block", "scope": "future_scope", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000016", "targetType": "email", "targetValue": "[email protected]", "effect": "limit", "scope": "all_access", "expiresAt": null},+ {"id": "01920000-0000-7000-8000-000000000017", "targetType": "email", "targetValue": "[email protected]", "effect": "exempt", "scope": "all_access", "expiresAt": null}+ ],+ "cases": [+ {"name": "alias of an email root", "subject": {"email": "[email protected]"}, "expect": "BBBA"},+ {"name": "upper-case alias of an email root", "subject": {"email": "[email protected]"}, "expect": "BBBA"},+ {"name": "email root with spaces", "subject": {"email": " [email protected] "}, "expect": "BBBA"},+ {"name": "dots matter outside gmail", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "different domain", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "cyrillic lookalike", "subject": {"email": "fа[email protected]"}, "expect": "AAAA"},+ {"name": "member of a blocked organization", "subject": {"email": "[email protected]", "organizationIds": ["1111aaaa-1111-4111-8111-11111111aaaa"]}, "expect": "AABA"},+ {"name": "member of a bystander organization", "subject": {"email": "[email protected]", "organizationIds": ["4444aaaa-4444-4444-8444-44444444aaaa"]}, "expect": "AAAA"},+ {"name": "blocked organization by id", "subject": {"organizationIds": ["1111AAAA-1111-4111-8111-11111111AAAA"]}, "expect": "AABA"},+ {"name": "bystander organization by id", "subject": {"organizationIds": ["4444aaaa-4444-4444-8444-44444444aaaa"]}, "expect": "AAAA"},+ {"name": "blocked user by email and uuid", "subject": {"email": "[email protected]", "userUuid": "2222abcd-2222-4222-8222-22222222abcd"}, "expect": "BBBA"},+ {"name": "blocked user by upper-case uuid", "subject": {"userUuid": "2222ABCD-2222-4222-8222-22222222ABCD"}, "expect": "BBBA"},+ {"name": "gmail root through googlemail", "subject": {"email": "[email protected]"}, "expect": "AABA"},+ {"name": "different gmail mailbox", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "subdomain of a blocked domain", "subject": {"email": "[email protected]"}, "expect": "BBBA"},+ {"name": "blocked domain on its own", "subject": {"domain": "throwaway.example"}, "expect": "BBBA"},+ {"name": "blocked domain inside another domain", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "shared suffix only", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "unrelated domain", "subject": {"domain": "example.com"}, "expect": "AAAA"},+ {"name": "signup-only domain", "subject": {"email": "[email protected]"}, "expect": "BAAA"},+ {"name": "first address of a blocked range", "subject": {"ip": "93.184.216.0"}, "expect": "BBBA"},+ {"name": "last address of a blocked range", "subject": {"ip": "93.184.216.255"}, "expect": "BBBA"},+ {"name": "mapped address in a blocked range", "subject": {"ip": "::ffff:93.184.216.34"}, "expect": "BBBA"},+ {"name": "address after the range", "subject": {"ip": "93.184.217.0"}, "expect": "AAAA"},+ {"name": "address before the range", "subject": {"ip": "93.184.215.255"}, "expect": "AAAA"},+ {"name": "mapped address outside the range", "subject": {"ip": "::ffff:93.184.217.1"}, "expect": "AAAA"},+ {"name": "loopback", "subject": {"ip": "127.0.0.1"}, "expect": "AAAA"},+ {"name": "address in an expired rule's range", "subject": {"ip": "203.0.113.5"}, "expect": "AAAA"},+ {"name": "unreadable address", "subject": {"ip": "not-an-ip"}, "expect": "AAAA"},+ {"name": "empty subject", "subject": {}, "expect": "AAAA"},+ {"name": "clean email from a blocked range", "subject": {"email": "[email protected]", "ip": "93.184.216.1"}, "expect": "BBBA"},+ {"name": "oldest matching rule decides", "subject": {"email": "[email protected]", "ip": "93.184.216.1"}, "expect": "BBBA", "deciding": {"signup": "01920000-0000-7000-8000-000000000001", "ai_gateway": "01920000-0000-7000-8000-000000000001"}},+ {"name": "posthog.com account with matching blocks and an exemption", "subject": {"email": "[email protected]", "userUuid": "3333abcd-3333-4333-8333-33333333abcd"}, "expect": "AAAE"},+ {"name": "posthog.com alias", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "posthog.com subdomain", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "posthog.com account on a blocked range", "subject": {"email": "[email protected]", "ip": "93.184.216.10"}, "expect": "AAAE"},+ {"name": "exempt email", "subject": {"email": "[email protected]"}, "expect": "AAAE"},+ {"name": "exempt email in mixed case", "subject": {"email": "[email protected]"}, "expect": "AAAE"},+ {"name": "alias of an exempt email", "subject": {"email": "[email protected]"}, "expect": "AAAA"},+ {"name": "unknown type, scope and effect match nothing", "subject": {"email": "[email protected]"}, "expect": "AAAA"}+ ]+ },+ {+ "name": "global MFA bypass",+ "now": "2026-09-17T12:00:00Z",+ "rules": [+ {"id": "01920000-0000-7000-8000-000000000101", "targetType": "everyone", "targetValue": "", "effect": "exempt", "scope": "email_code", "expiresAt": "2026-09-20T00:00:00Z"}+ ],+ "cases": [+ {"name": "any email", "subject": {"email": "[email protected]"}, "expect": "AAAE"},+ {"name": "empty subject", "subject": {}, "expect": "AAAE"},+ {"name": "posthog.com account", "subject": {"email": "[email protected]"}, "expect": "AAAE"}+ ]+ }+ ]+}diff --git a/products/security/backend/tests/helpers.py b/products/security/backend/tests/helpers.pynew file mode 100644index 000000000000..11bac06cf666--- /dev/null+++ b/products/security/backend/tests/helpers.py@@ -0,0 +1,23 @@+from itertools import count+from typing import Any++from products.security.backend.logic.snapshot import reset_memo, write_snapshot++_ids = count(1)+++def _rule(overrides: dict[str, Any], **defaults: Any) -> dict[str, Any]:+ return {"id": f"01920000-0000-7000-8000-{next(_ids):012d}", "expiresAt": None, **defaults, **overrides}+++def block_rule(**overrides: Any) -> dict[str, Any]:+ return _rule(overrides, targetType="email", targetValue="[email protected]", effect="block", scope="all_access")+++def exempt_rule(**overrides: Any) -> dict[str, Any]:+ return _rule(overrides, targetType="email", targetValue="[email protected]", effect="exempt", scope="email_code")+++def seed_rules(*rules: dict[str, Any]) -> None:+ write_snapshot(f"test-{next(_ids)}", list(rules))+ reset_memo()diff --git a/products/security/backend/tests/test_accounts.py b/products/security/backend/tests/test_accounts.pynew file mode 100644index 000000000000..c41aae2f6c2f--- /dev/null+++ b/products/security/backend/tests/test_accounts.py@@ -0,0 +1,74 @@+from posthog.test.base import BaseTest++from parameterized import parameterized++from posthog.models import Organization, OrganizationMembership, User++from products.security.backend.logic.accounts import (+ COUNT_CAP,+ count_active_accounts,+ count_active_org_members,+ email_for_user,+ has_posthog_account,+ resolve_subject,+)+++class TestAccounts(BaseTest):+ def _user(self, email: str, org: Organization | None = None, active: bool = True) -> User:+ user = User.objects.create_and_join(org or self.organization, email, "password1234", is_active=active)+ return user++ def test_resolve_email_user_and_orgs(self) -> None:+ user = self._user("[email protected]")+ resolved = resolve_subject("[email protected]")+ assert resolved.kind == "user"+ assert resolved.user is not None and resolved.user.uuid == str(user.uuid)+ assert resolved.organization_ids == (str(self.organization.id),)++ @parameterized.expand([("[email protected]",), ("12345",), ("' OR 1=1 --",), ("",)])+ def test_resolve_misses(self, query: str) -> None:+ assert resolve_subject(query).kind == "none"++ def test_resolve_uuid_user_then_organization(self) -> None:+ user = self._user("[email protected]")+ assert resolve_subject(str(user.uuid).upper()).kind == "user"+ org_resolution = resolve_subject(str(self.organization.id))+ assert org_resolution.kind == "organization"+ assert org_resolution.organization_ids == (str(self.organization.id),)++ def test_counts(self) -> None:+ self._user("[email protected]")+ self._user("[email protected]")+ self._user("[email protected]", active=False)+ self._user("[email protected]")+ self._user("[email protected]")+ assert count_active_accounts("email_root", "[email protected]").count == 1+ assert count_active_accounts("email", "[email protected]").count == 1+ assert count_active_accounts("email_domain", "throwaway.example").count == 1+ assert count_active_accounts("email_root", "[email protected]").count == 1++ def test_counts_are_capped(self) -> None:+ User.objects.bulk_create(+ [+ User(email=f"bulk{i}@capped.example", is_active=True, distinct_id=f"capped-{i}")+ for i in range(COUNT_CAP + 2)+ ]+ )+ result = count_active_accounts("email_domain", "capped.example")+ assert (result.count, result.capped) == (COUNT_CAP, True)++ def test_org_member_count_and_posthog_membership(self) -> None:+ other = Organization.objects.create(name="Bystander")+ self._user("[email protected]", org=other)+ exists, members = count_active_org_members(str(other.id))+ assert exists and members.count == 1+ assert count_active_org_members("9999aaaa-9999-4999-8999-99999999aaaa")[0] is False+ assert has_posthog_account(organization_id=str(other.id)) is False++ staff = self._user("[email protected]", org=other)+ assert has_posthog_account(organization_id=str(other.id)) is True+ assert has_posthog_account(user_uuid=str(staff.uuid)) is True+ assert email_for_user(str(staff.uuid)) == "[email protected]"+ assert email_for_user("9999aaaa-9999-4999-8999-99999999aaaa") is None+ assert OrganizationMembership.objects.filter(organization=other).count() == 2diff --git a/products/security/backend/tests/test_decisions.py b/products/security/backend/tests/test_decisions.pynew file mode 100644index 000000000000..100b790a2a39--- /dev/null+++ b/products/security/backend/tests/test_decisions.py@@ -0,0 +1,121 @@+import json+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++from unittest import TestCase++from parameterized import parameterized++from products.security.backend.facade.enums import Surface+from products.security.backend.logic.decisions import deciding_rule, is_protected_domain+from products.security.backend.logic.matching import build_index+from products.security.backend.logic.rules import SnapshotRule+from products.security.backend.logic.subjects import normalize_subject++VECTORS = json.loads((Path(__file__).parent / "fixtures" / "access-rules.json").read_text())+ORDER = [Surface.SIGNUP, Surface.APP, Surface.AI_GATEWAY, Surface.EMAIL_CODE]+LETTERS = {Surface.EMAIL_CODE: "E"}+++def _cases() -> list[tuple[str, dict[str, Any], dict[str, Any]]]:+ return [(f"{suite['name']}: {case['name']}", suite, case) for suite in VECTORS["suites"] for case in suite["cases"]]+++def _letter(surface: Surface, rule: SnapshotRule | None) -> str:+ if rule is None:+ return "A"+ return LETTERS.get(surface, "B")+++class TestVectors(TestCase):+ @parameterized.expand(_cases())+ def test_vector(self, _name: str, suite: dict[str, Any], case: dict[str, Any]) -> None:+ rules = [SnapshotRule.from_wire(raw) for raw in suite["rules"]]+ index = build_index(rule for rule in rules if rule is not None)+ now = datetime.fromisoformat(suite["now"])+ raw = case["subject"]+ subject = normalize_subject(+ email=raw.get("email"),+ domain=raw.get("domain"),+ user_uuid=raw.get("userUuid"),+ organization_ids=tuple(raw.get("organizationIds", ())),+ ip=raw.get("ip"),+ )+ decided = {surface: deciding_rule(index, subject, surface, now) for surface in ORDER}+ assert "".join(_letter(s, decided[s]) for s in ORDER) == case["expect"]+ for surface, rule_id in case.get("deciding", {}).items():+ rule = decided[Surface(surface)]+ assert rule is not None and rule.id == rule_id+++class TestWireParsing(TestCase):+ @parameterized.expand(+ [+ ("not a dict", "rule"),+ ("missing field", {"id": "a", "targetType": "email", "targetValue": "x", "effect": "block"}),+ (+ "non-string field",+ {"id": 1, "targetType": "email", "targetValue": "x", "effect": "block", "scope": "signup"},+ ),+ (+ "bad expiry",+ {+ "id": "a",+ "targetType": "email",+ "targetValue": "x",+ "effect": "block",+ "scope": "signup",+ "expiresAt": "soon",+ },+ ),+ (+ "naive expiry",+ {+ "id": "a",+ "targetType": "email",+ "targetValue": "x",+ "effect": "block",+ "scope": "signup",+ "expiresAt": "2026-09-01T00:00:00",+ },+ ),+ (+ "bad network",+ {"id": "a", "targetType": "ip", "targetValue": "not-a-range", "effect": "block", "scope": "signup"},+ ),+ ]+ )+ def test_malformed_rules_are_skipped(self, _name: str, raw: object) -> None:+ assert SnapshotRule.from_wire(raw) is None++ def test_expiry_is_timezone_aware(self) -> None:+ rule = SnapshotRule.from_wire(+ {+ "id": "a",+ "targetType": "email",+ "targetValue": "x",+ "effect": "block",+ "scope": "signup",+ "expiresAt": "2026-09-01T00:00:00.000Z",+ }+ )+ assert rule is not None and rule.expires_at == datetime(2026, 9, 1, tzinfo=UTC)+++class TestProtectedDomain(TestCase):+ @parameterized.expand([("posthog.com", True), ("eu.posthog.com", True), ("notposthog.com", False), (None, False)])+ def test_is_protected_domain(self, domain: str | None, expected: bool) -> None:+ assert is_protected_domain(domain) is expected+++class TestSubjectLength(TestCase):+ @parameterized.expand(+ [+ ("address", {"email": "x@" + "a." * 150_000 + "com"}),+ ("bare domain", {"domain": "a." * 150_000 + "com"}),+ ]+ )+ def test_overlong_input_carries_no_email_or_domain(self, _name: str, kwargs: dict[str, str]) -> None:+ subject = normalize_subject(**kwargs)+ assert subject.email is None and subject.domain is Nonediff --git a/products/security/backend/tests/test_facade.py b/products/security/backend/tests/test_facade.pynew file mode 100644index 000000000000..e7793df33743--- /dev/null+++ b/products/security/backend/tests/test_facade.py@@ -0,0 +1,54 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from prometheus_client import REGISTRY++from posthog.models import User++from products.security.backend.facade.api import decide, is_email_code_exempt, shadow_check+from products.security.backend.facade.contracts import SubjectInput+from products.security.backend.facade.enums import Outcome, Surface+from products.security.backend.tests.helpers import block_rule, exempt_rule, seed_rules+++def _would_block(call_site: str) -> float:+ return (+ REGISTRY.get_sample_value(+ "posthog_security_access_would_block_total",+ {"surface": "app", "call_site": call_site, "target_type": "user_uuid"},+ )+ or 0.0+ )+++class TestFacade(BaseTest):+ def test_a_uuid_only_subject_is_resolved_before_the_posthog_check(self) -> None:+ staff = User.objects.create_and_join(self.organization, "[email protected]", "password1234")+ seed_rules(block_rule(targetType="user_uuid", targetValue=str(staff.uuid)))+ assert decide(SubjectInput(user_uuid=str(staff.uuid)), Surface.APP).outcome == Outcome.ALLOW++ def test_decide_reports_the_rule(self) -> None:+ rule = block_rule(targetType="ip", targetValue="93.184.216.0/24")+ seed_rules(rule)+ decision = decide(SubjectInput(ip="93.184.216.7"), Surface.SIGNUP)+ assert (decision.outcome, decision.rule_id, decision.target_type) == (Outcome.BLOCK, rule["id"], "ip")+ assert decide(SubjectInput(ip="garbage"), Surface.SIGNUP).outcome == Outcome.ALLOW++ def test_email_code_exemption(self) -> None:+ seed_rules(exempt_rule(targetValue="[email protected]"))+ assert is_email_code_exempt("[email protected]") is True+ assert is_email_code_exempt("[email protected]") is False++ def test_email_code_exemption_fails_closed(self) -> None:+ with patch("products.security.backend.facade.api.current_snapshot", side_effect=RuntimeError("boom")):+ assert is_email_code_exempt("[email protected]") is False++ def test_shadow_check_counts_and_never_raises(self) -> None:+ user = User.objects.create_and_join(self.organization, "[email protected]", "password1234")+ seed_rules(block_rule(targetType="user_uuid", targetValue=str(user.uuid)))+ before = _would_block("test_site")+ shadow_check(SubjectInput(email=user.email, user_uuid=str(user.uuid)), Surface.APP, call_site="test_site")+ assert _would_block("test_site") == before + 1++ with patch("products.security.backend.facade.api.current_snapshot", side_effect=RuntimeError("boom")):+ shadow_check(SubjectInput(email=user.email), Surface.APP, call_site="test_site")diff --git a/products/security/backend/tests/test_hub_auth.py b/products/security/backend/tests/test_hub_auth.pynew file mode 100644index 000000000000..0dcd97c5c80c--- /dev/null+++ b/products/security/backend/tests/test_hub_auth.py@@ -0,0 +1,39 @@+import time++from django.test import SimpleTestCase, override_settings++import jwt as pyjwt+from parameterized import parameterized++from products.security.backend.logic.hub_auth import claims_allow, mint_rules_token+++@override_settings(SECURITY_HUB_REGION="us", SECURITY_HUB_OUTBOUND_JWT_SECRETS=["new", "old"])+class TestHubAuth(SimpleTestCase):+ def test_rules_token_claims(self) -> None:+ claims = pyjwt.decode(mint_rules_token(), "new", algorithms=["HS256"], audience="posthog:security_hub:rules")+ assert claims["region"] == "us"+ assert claims["op"] == "rules:read"+ assert 0 < claims["exp"] - claims["iat"] <= 60++ @parameterized.expand(+ [+ ("valid", {"region": "us", "op": "subject:resolve", "iat": 100, "exp": 160}, True),+ ("wrong op", {"region": "us", "op": "rules:sync_now", "iat": 100, "exp": 160}, False),+ ("wrong region", {"region": "eu", "op": "subject:resolve", "iat": 100, "exp": 160}, False),+ ("too long", {"region": "us", "op": "subject:resolve", "iat": 100, "exp": 161}, False),+ ("no iat", {"region": "us", "op": "subject:resolve", "exp": 160}, False),+ ("string iat", {"region": "us", "op": "subject:resolve", "iat": "100", "exp": 160}, False),+ ]+ )+ def test_claims_allow(self, _name: str, claims: dict, expected: bool) -> None:+ assert claims_allow(claims, "subject:resolve") is expected++ def test_claims_allow_rejects_missing_claims(self) -> None:+ assert claims_allow(None, "subject:resolve") is False+ assert (+ claims_allow(+ {"region": "us", "op": "subject:resolve", "iat": int(time.time()), "exp": True}, "subject:resolve"+ )+ is False+ )diff --git a/products/security/backend/tests/test_snapshot.py b/products/security/backend/tests/test_snapshot.pynew file mode 100644index 000000000000..a4befcc3d4df--- /dev/null+++ b/products/security/backend/tests/test_snapshot.py@@ -0,0 +1,118 @@+import json+from datetime import UTC, datetime++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import patch++from posthog.redis import get_client++from products.security.backend.logic import snapshot+from products.security.backend.logic.snapshot import (+ EMPTY_SNAPSHOT,+ Snapshot,+ current_snapshot,+ last_synced_at,+ mark_synced,+ reset_memo,+ stored_version,+ write_snapshot,+)++RULE = {+ "id": "r1",+ "targetType": "email",+ "targetValue": "[email protected]",+ "effect": "block",+ "scope": "signup",+ "expiresAt": None,+}+++class TestSnapshot(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ reset_memo()++ def test_empty_until_written(self) -> None:+ assert current_snapshot().rule_count == 0+ assert stored_version() is None++ def test_write_counts_readable_rules_and_skips_the_rest(self) -> None:+ outcome = write_snapshot("v1", [RULE, "junk", {"id": "r2"}])+ assert (outcome.applied, outcome.rule_count) == (True, 1)+ assert stored_version() == "v1"+ assert current_snapshot().rule_count == 1++ def test_memo_rechecks_the_version_every_30_seconds(self) -> None:+ with time_machine.travel("2026-09-17T12:00:00Z", tick=False) as frozen:+ write_snapshot("v1", [RULE])+ assert current_snapshot().version == "v1"+ write_snapshot("v2", [RULE, {**RULE, "id": "r2"}])+ assert current_snapshot().version == "v1"+ frozen.shift(31)+ assert current_snapshot().version == "v2"+ assert current_snapshot().rule_count == 2++ def test_redis_errors_and_flushes_keep_the_memo(self) -> None:+ with time_machine.travel("2026-09-17T12:00:00Z", tick=False) as frozen:+ write_snapshot("v1", [RULE])+ assert current_snapshot().version == "v1"+ get_client().flushdb()+ frozen.shift(31)+ assert current_snapshot().version == "v1"+ frozen.shift(31)+ with patch.object(snapshot, "get_client", side_effect=ConnectionError("down")):+ assert current_snapshot().version == "v1"++ def test_last_synced_at_round_trip(self) -> None:+ assert last_synced_at() is None+ when = datetime(2026, 9, 17, 12, tzinfo=UTC)+ mark_synced(when)+ assert last_synced_at() == when++ def test_stored_payload_is_json(self) -> None:+ write_snapshot("v1", [RULE])+ raw = get_client().get(snapshot.SNAPSHOT_KEY)+ assert raw is not None+ payload = json.loads(raw)+ assert payload == {"version": "v1", "rules": [RULE]}++ def test_older_generated_at_does_not_clobber_the_newer_snapshot(self) -> None:+ write_snapshot("v1", [RULE], generated_at_ms=2000)+ # The dropped write parses a different rule count than the stored one, so this also+ # proves a dropped write's rule_count is None rather than the rejected value.+ outcome = write_snapshot("v0", [], generated_at_ms=1000)+ assert (outcome.applied, outcome.rule_count) == (False, None)+ assert stored_version() == "v1"+ assert current_snapshot().rule_count == 1++ def test_equal_generated_at_applies_idempotently(self) -> None:+ write_snapshot("v1", [RULE], generated_at_ms=2000)+ outcome = write_snapshot("v1", [RULE], generated_at_ms=2000)+ assert outcome.applied is True+ assert stored_version() == "v1"++ def test_flushed_generated_at_key_applies_the_next_write_regardless_of_its_value(self) -> None:+ write_snapshot("v1", [RULE], generated_at_ms=5000)+ get_client().delete(snapshot.GENERATED_AT_KEY)+ outcome = write_snapshot("v2", [RULE], generated_at_ms=1000)+ assert outcome.applied is True+ assert stored_version() == "v2"++ def test_slow_refresh_does_not_clobber_a_memo_another_thread_already_installed(self) -> None:+ with time_machine.travel("2026-09-17T12:00:00Z", tick=False) as frozen:+ write_snapshot("v1", [RULE])+ assert current_snapshot().version == "v1"+ frozen.shift(31)++ concurrent_memo = Snapshot(version="v2", index=EMPTY_SNAPSHOT.index, rule_count=9)++ def install_concurrent_memo(*args: object, **kwargs: object) -> None:+ snapshot._memo = concurrent_memo++ with patch.object(snapshot, "last_synced_at", side_effect=install_concurrent_memo):+ result = current_snapshot()++ assert result is concurrent_memo+ assert snapshot._memo is concurrent_memodiff --git a/products/security/backend/tests/test_sync.py b/products/security/backend/tests/test_sync.pynew file mode 100644index 000000000000..8819388157dc--- /dev/null+++ b/products/security/backend/tests/test_sync.py@@ -0,0 +1,177 @@+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.test import override_settings++import jwt as pyjwt+import requests+from parameterized import parameterized++from products.security.backend.logic.snapshot import (+ current_snapshot,+ last_synced_at,+ reset_memo,+ stored_version,+ write_snapshot,+)+from products.security.backend.logic.sync import InvalidSnapshot, sync_access_rules++RULE = {+ "id": "r1",+ "targetType": "email",+ "targetValue": "[email protected]",+ "effect": "block",+ "scope": "signup",+ "expiresAt": None,+}+GENERATED_AT = "2026-09-17T12:00:00Z"+HUB = {+ "SECURITY_HUB_URL": "https://hub.example.com/",+ "SECURITY_HUB_REGION": "us",+ "SECURITY_HUB_OUTBOUND_JWT_SECRETS": ["out-us"],+}+++def _response(status: int, body: object = None) -> MagicMock:+ response = MagicMock(status_code=status)+ response.json.return_value = body+ response.raise_for_status.side_effect = None if status < 400 else requests.HTTPError(str(status), response=response)+ return response+++@override_settings(**HUB)+class TestSync(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ reset_memo()++ @patch("products.security.backend.logic.sync.requests.get")+ def test_first_pull_stores_rules_and_sends_a_region_token(self, get: MagicMock) -> None:+ get.return_value = _response(+ 200, {"version": "v1", "region": "us", "rules": [RULE], "generatedAt": GENERATED_AT}+ )+ result = sync_access_rules()+ assert (result.status, result.rule_count) == ("updated", 1)+ assert stored_version() == "v1"+ assert last_synced_at() is not None+ assert current_snapshot().rule_count == 1++ (url,), kwargs = get.call_args+ assert url == "https://hub.example.com/webhooks/access-rules/snapshot"+ assert kwargs["params"] == {"region": "us"}+ assert kwargs["timeout"] == 10+ assert "If-None-Match" not in kwargs["headers"]+ token = kwargs["headers"]["Authorization"].removeprefix("Bearer ")+ claims = pyjwt.decode(token, "out-us", algorithms=["HS256"], audience="posthog:security_hub:rules")+ assert claims["op"] == "rules:read"++ @patch("products.security.backend.logic.sync.requests.get")+ def test_a_write_older_than_the_stored_generated_at_reports_stale_not_updated(self, get: MagicMock) -> None:+ write_snapshot("v-current", [RULE], generated_at_ms=10**15)+ # The dropped fetch has a different rule count than the stored write, so a bug that+ # forwards the rejected count instead of None would show up as a value, not a coincidence.+ get.return_value = _response(+ 200,+ {+ "version": "v-late",+ "region": "us",+ "rules": [RULE, {**RULE, "id": "r2"}],+ "generatedAt": GENERATED_AT,+ },+ )+ result = sync_access_rules()+ assert (result.status, result.rule_count) == ("stale", None)+ assert stored_version() == "v-current"+ # The hub still answered, so contact with it counts as successful.+ assert last_synced_at() is not None++ @patch("products.security.backend.logic.sync.requests.get")+ def test_unchanged_snapshot_sends_the_etag_and_keeps_rules(self, get: MagicMock) -> None:+ get.return_value = _response(+ 200, {"version": "v1", "region": "us", "rules": [RULE], "generatedAt": GENERATED_AT}+ )+ sync_access_rules()+ get.return_value = _response(304)+ assert sync_access_rules().status == "unchanged"+ assert get.call_args.kwargs["headers"]["If-None-Match"] == '"v1"'+ assert stored_version() == "v1"++ @parameterized.expand(+ [+ ("wrong region", {"version": "v2", "region": "eu", "rules": []}),+ ("no rules list", {"version": "v2", "region": "us", "rules": "x"}),+ ("no version", {"region": "us", "rules": []}),+ ("no generatedAt", {"version": "v2", "region": "us", "rules": []}),+ ("unparseable generatedAt", {"version": "v2", "region": "us", "rules": [], "generatedAt": "not-a-date"}),+ (+ "naive generatedAt",+ {"version": "v2", "region": "us", "rules": [], "generatedAt": "2026-09-17T12:00:00"},+ ),+ ]+ )+ @patch("products.security.backend.logic.sync.requests.get")+ def test_bad_bodies_raise_and_keep_the_stored_snapshot(self, _name: str, body: dict, get: MagicMock) -> None:+ get.return_value = _response(+ 200, {"version": "v1", "region": "us", "rules": [RULE], "generatedAt": GENERATED_AT}+ )+ sync_access_rules()+ get.return_value = _response(200, body)+ with self.assertRaises(InvalidSnapshot):+ sync_access_rules()+ assert stored_version() == "v1"++ @patch("products.security.backend.logic.sync.requests.get")+ def test_hub_errors_raise_and_keep_the_stored_snapshot(self, get: MagicMock) -> None:+ get.return_value = _response(+ 200, {"version": "v1", "region": "us", "rules": [RULE], "generatedAt": GENERATED_AT}+ )+ sync_access_rules()+ get.return_value = _response(503)+ with self.assertRaises(requests.HTTPError):+ sync_access_rules()+ get.side_effect = requests.ConnectionError("down")+ with self.assertRaises(requests.ConnectionError):+ sync_access_rules()+ get.side_effect = None+ non_json = _response(200)+ non_json.json.side_effect = requests.exceptions.JSONDecodeError("bad json", "", 0)+ get.return_value = non_json+ with self.assertRaises(requests.exceptions.JSONDecodeError):+ sync_access_rules()+ assert stored_version() == "v1"++ @parameterized.expand(+ [+ ("no url", {"SECURITY_HUB_URL": ""}),+ ("purpose disabled", {"SECURITY_HUB_OUTBOUND_JWT_SECRETS": []}),+ ]+ )+ @patch("products.security.backend.logic.sync.requests.get")+ def test_not_configured_does_nothing(self, _name: str, overrides: dict, get: MagicMock) -> None:+ with override_settings(**overrides):+ assert sync_access_rules().status == "not_configured"+ get.assert_not_called()++ @parameterized.expand(+ [+ ("https in production", "https://hub.example.com/", False, False, "updated"),+ ("http localhost under debug", "http://localhost:1234/", True, False, "updated"),+ ("http localhost under test", "http://localhost:1234/", False, True, "updated"),+ ("http in production", "http://hub.example.com/", False, False, "not_configured"),+ ("http localhost outside debug or test", "http://localhost:1234/", False, False, "not_configured"),+ ]+ )+ @patch("products.security.backend.logic.sync.requests.get")+ @patch("products.security.backend.logic.sync.mint_rules_token")+ def test_hub_url_scheme_is_validated(+ self, _name: str, url: str, debug: bool, test_flag: bool, expected: str, mint: MagicMock, get: MagicMock+ ) -> None:+ get.return_value = _response(+ 200, {"version": "v1", "region": "us", "rules": [RULE], "generatedAt": GENERATED_AT}+ )+ mint.return_value = "token"+ with override_settings(SECURITY_HUB_URL=url, DEBUG=debug, TEST=test_flag):+ assert sync_access_rules().status == expected+ if expected == "not_configured":+ mint.assert_not_called()+ get.assert_not_called()diff --git a/products/security/manifest.tsx b/products/security/manifest.tsxnew file mode 100644index 000000000000..44d2a435f26c--- /dev/null+++ b/products/security/manifest.tsx@@ -0,0 +1,23 @@+/**+ * Product manifest for security.+ *+ * Defines scenes, routes, URLs, and navigation for this product.+ */+import { ProductManifest } from '../../frontend/src/types'++export const manifest: ProductManifest = {+ name: 'Security',+ scenes: {+ // Define scenes here+ },+ routes: {+ // Define routes here+ },+ redirects: {},+ urls: {+ // Define URL helpers here+ },+ fileSystemTypes: {},+ treeItemsNew: [],+ treeItemsProducts: [],+}diff --git a/products/security/package.json b/products/security/package.jsonnew file mode 100644index 000000000000..b4e12af2e23f--- /dev/null+++ b/products/security/package.json@@ -0,0 +1,7 @@+{+ "name": "@posthog/products-security",+ "scripts": {+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",+ "backend:contract-check": "echo 'Contract files unchanged'"+ }+}diff --git a/products/security/product.yaml b/products/security/product.yamlnew file mode 100644index 000000000000..18be18b20b6b--- /dev/null+++ b/products/security/product.yaml@@ -0,0 +1,3 @@+name: Security+owners:+ - team-platform-featuresdiff --git a/products/security/tsconfig.json b/products/security/tsconfig.jsonnew file mode 100644index 000000000000..fe425d6fcba8--- /dev/null+++ b/products/security/tsconfig.json@@ -0,0 +1,6 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "composite": true+ }+}diff --git a/products/security/turbo.json b/products/security/turbo.jsonnew file mode 100644index 000000000000..a3d49c9bfd7b--- /dev/null+++ b/products/security/turbo.json@@ -0,0 +1,18 @@+{+ "extends": ["//"],+ "tasks": {+ "backend:contract-check": {+ "inputs": [+ "backend/facade/**",+ "backend/presentation/**",+ "backend/webhook_consumers.py",+ "backend/tasks/**",+ "backend/temporal/**",+ "backend/models.py",+ "backend/migrations/**"+ ],+ "outputs": [],+ "cache": true+ }+ }+}diff --git a/tach.toml b/tach.tomlindex 9f167c9cdd90..0dc15a009b99 100644--- a/tach.toml+++ b/tach.toml@@ -146,6 +146,7 @@ depends_on = ["products.workflows","products.actions","products.alerts", "products.warehouse_sources", "products.data_tools", "products.exports", "products.annotations",+ "products.security",]layer = "modules"@@ -1607,3 +1608,17 @@ expose = [from = ["products.ai_training",]++[[modules]]+path = "products.security"+depends_on = ["posthog"]+layer = "modules"++[[interfaces]]+expose = [+ "backend\\.facade.*",+ "backend\\.presentation\\.views.*",+]+from = [+ "products.security",+]