Skip to content

: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.

feat(authorization): add the authorization product interface (#120880)

Yaseneb66218829c7
diff --git a/frontend/package.json b/frontend/package.json
index 14a893b19bfc..7a24f91a6dc2 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -92,6 +92,7 @@
"@posthog/products-analytics-platform": "workspace:*",
"@posthog/products-annotations": "workspace:*",
"@posthog/products-apm": "workspace:*",
+ "@posthog/products-authorization": "workspace:*",
"@posthog/products-autoresearch": "workspace:*",
"@posthog/products-batch-exports": "workspace:*",
"@posthog/products-billing-alerts": "workspace:*",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e6f7635db42d..86892802c719 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -669,6 +669,9 @@ importers:
'@posthog/products-apm':
specifier: workspace:*
version: link:../products/apm
+ '@posthog/products-authorization':
+ specifier: workspace:*
+ version: link:../products/authorization
'@posthog/products-autoresearch':
specifier: workspace:*
version: link:../products/autoresearch
@@ -2661,6 +2664,8 @@ importers:
products/approvals: {}
+ products/authorization: {}
+
products/autoresearch:
dependencies:
'@posthog/brand':
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index cb29bba4e254..39e96b7a7d0b 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -139,6 +139,7 @@ PRODUCTS_APPS = [
"products.groups.backend.apps.GroupsConfig",
"products.subscriptions.backend.apps.SubscriptionsConfig",
"products.uptime_monitoring.backend.apps.UptimeMonitoringConfig",
+ "products.authorization.backend.apps.AuthorizationConfig",
]
INSTALLED_APPS = [
diff --git a/products/authorization/__init__.py b/products/authorization/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/authorization/backend/__init__.py b/products/authorization/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/authorization/backend/apps.py b/products/authorization/backend/apps.py
new file mode 100644
index 000000000000..3e5cac5ce734
--- /dev/null
+++ b/products/authorization/backend/apps.py
@@ -0,0 +1,8 @@
+"""Django app configuration for authorization."""
+
+from django.apps import AppConfig
+
+
+class AuthorizationConfig(AppConfig):
+ name = "products.authorization.backend"
+ label = "authorization"
diff --git a/products/authorization/backend/facade/__init__.py b/products/authorization/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/authorization/backend/facade/api.py b/products/authorization/backend/facade/api.py
new file mode 100644
index 000000000000..8af27a20601e
--- /dev/null
+++ b/products/authorization/backend/facade/api.py
@@ -0,0 +1,126 @@
+"""
+Facade for authorization.
+
+The ONLY module other products are allowed to import.
+Accept frozen dataclasses, call logic/, return frozen
+dataclasses. Never return ORM instances or import DRF.
+
+Each function raises NotImplementedError until its logic lands.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import overload
+from uuid import UUID
+
+from . import contracts
+from .enums import Action, Level, SubjectType
+
+
+def synchronize_organization(organization_id: UUID) -> None:
+ """Reconcile the organization's authorization graph with committed database state."""
+ raise NotImplementedError
+
+
+def get_openfga_status() -> contracts.OpenFgaStatus:
+ """Return whether OpenFGA is reachable, and the store and authorization model the client uses."""
+ raise NotImplementedError
+
+
+@overload
+def check(
+ *,
+ resource: contracts.Resource,
+ action: Action,
+ subject: contracts.Subject | None = None,
+ context: contracts.Context | None = None,
+) -> bool: ...
+
+
+@overload
+def check(
+ requests: Sequence[contracts.CheckRequest],
+ /,
+ *,
+ context: contracts.Context | None = None,
+) -> list[bool]: ...
+
+
+def check(
+ requests: Sequence[contracts.CheckRequest] | None = None,
+ /,
+ *,
+ resource: contracts.Resource | None = None,
+ action: Action | None = None,
+ subject: contracts.Subject | None = None,
+ context: contracts.Context | None = None,
+) -> bool | list[bool]:
+ """Return whether the subject may take the action on the resource, or one result per request, in order."""
+ raise NotImplementedError
+
+
+def permissions(
+ *,
+ resource: contracts.Resource,
+ subject: contracts.Subject | None = None,
+ context: contracts.Context | None = None,
+) -> frozenset[Action]:
+ """Return every action the subject may take on the resource."""
+ raise NotImplementedError
+
+
+def list_objects(
+ *,
+ resource: contracts.Resource,
+ action: Action,
+ subject: contracts.Subject | None = None,
+ context: contracts.Context | None = None,
+ limit: int | None = None,
+ creator_exempt: bool = False,
+) -> contracts.ObjectIds:
+ """Return project-scoped IDs for the requested action.
+
+ VIEW and QUERY return an inclusion or exclusion filter for rows. A complete result with
+ `excluded=True` allows every ID except those returned. Other actions retain inclusion-only IDs.
+ An incomplete result allows nothing. `creator_exempt` requests a creator predicate only when
+ the rules permit it.
+ """
+ raise NotImplementedError
+
+
+def list_subjects(
+ *,
+ resource: contracts.Resource,
+ action: Action,
+ subject_type: SubjectType,
+ context: contracts.Context | None = None,
+) -> list[contracts.Subject]:
+ """Return the subjects of `subject_type` that may take the action on the resource."""
+ raise NotImplementedError
+
+
+def write(changes: Sequence[contracts.AddRelationshipRequest | contracts.DeleteRelationshipRequest], /) -> None:
+ """Apply the relationship adds and deletes."""
+ raise NotImplementedError
+
+
+def dangerous_query_relation(*, subject: contracts.Subject, resource: contracts.Resource, level: Level) -> bool:
+ """Return whether the subject holds the relation `level` on the resource, without evaluating actions or context.
+
+ Use it only in access-rule editors and for debugging. Authorization decisions must use `check`.
+ """
+ raise NotImplementedError
+
+
+def dangerous_explain(
+ request: contracts.CheckRequest,
+ /,
+ *,
+ context: contracts.Context | None = None,
+) -> contracts.Explanation:
+ """Return the decision for one check and the path of rules that produced it.
+
+ Use it only in access-rule editors and for debugging. Authorization decisions must use `check`.
+ """
+ raise NotImplementedError
diff --git a/products/authorization/backend/facade/contracts.py b/products/authorization/backend/facade/contracts.py
new file mode 100644
index 000000000000..a26f09f6344a
--- /dev/null
+++ b/products/authorization/backend/facade/contracts.py
@@ -0,0 +1,161 @@
+"""
+Contract types for authorization.
+
+Frozen dataclasses that define what this product exposes.
+No Django imports. Used by facade as inputs/outputs.
+
+Uses ``pydantic.dataclasses.dataclass`` rather than the stdlib
+variant — same syntax, same ``is_dataclass()`` compatibility (so
+``DataclassSerializer`` keeps working), but with runtime type
+validation on construction.
+"""
+
+from dataclasses import field, fields
+from typing import Self
+from uuid import UUID
+
+from pydantic.dataclasses import dataclass
+
+from .enums import Action, Level, ResourceType
+
+
+@dataclass(frozen=True, kw_only=True)
+class OpenFgaStatus:
+ """Whether the OpenFGA server answers, and which store and authorization model the client uses."""
+
+ reachable: bool
+ api_url: str
+ store_name: str | None
+ store_id: str | None
+ authorization_model_id: str | None
+ error: str | None
+
+
+@dataclass(frozen=True, kw_only=True)
+class Resource:
+ """One resource, or with `id=None` every resource of `type`, for list and create checks."""
+
+ type: ResourceType
+ id: str | None = None
+ project_id: int | None = None
+ organization_id: UUID | None = None
+
+
+@dataclass(frozen=True, kw_only=True)
+class Subject:
+ """The principal a check or a relationship is about. Set exactly one field."""
+
+ user_id: int | None = None
+ api_key_id: str | None = None
+ share_link_id: int | None = None
+ export_token: str | None = field(default=None, repr=False)
+ project_secret_key_id: str | None = None
+ service: str | None = None
+ role_id: UUID | None = None
+ members_of: Resource | None = None
+
+ def __post_init__(self) -> None:
+ set_count = sum(getattr(self, subject_field.name) is not None for subject_field in fields(self))
+ if set_count != 1:
+ raise ValueError(f"Set exactly one field of Subject, got {set_count}.")
+
+ @classmethod
+ def members(cls, of: Resource) -> Self:
+ """Every member of the project or organization that `of` names."""
+ return cls(members_of=of)
+
+
+@dataclass(frozen=True, kw_only=True)
+class Context:
+ """Request facts that conditional access rules read.
+
+ By default each set field overrides the request's value and each `None` field keeps it.
+ With `replace=True` the request context is ignored, and a `None` field means unknown.
+ """
+
+ entitlements: frozenset[str] | None = None
+ channel: str | None = None
+ password_verified: bool | None = None
+ replace: bool = False
+
+ @classmethod
+ def override(
+ cls,
+ *,
+ entitlements: frozenset[str] | None = None,
+ channel: str | None = None,
+ password_verified: bool | None = None,
+ ) -> Self:
+ """A context that replaces the request context instead of merging into it."""
+ return cls(entitlements=entitlements, channel=channel, password_verified=password_verified, replace=True)
+
+
+@dataclass(frozen=True, kw_only=True)
+class CheckRequest:
+ """One check in a batch. `subject=None` means the current request's subject."""
+
+ resource: Resource
+ action: Action
+ subject: Subject | None = None
+
+
+@dataclass(frozen=True, kw_only=True)
+class AddRelationshipRequest:
+ """Give the subject the relation `level` on the resource."""
+
+ subject: Subject
+ resource: Resource
+ level: Level
+
+
+@dataclass(frozen=True, kw_only=True)
+class DeleteRelationshipRequest:
+ """Remove the relation `level` from the subject, or every relation when `level=None`."""
+
+ subject: Subject
+ resource: Resource
+ level: Level | None = None
+
+
+@dataclass(frozen=True, kw_only=True)
+class ObjectIds:
+ """The resources of one type a subject may act on, as the short list that differs from the rest.
+
+ `excluded=False`: `ids` are the only resources allowed. `excluded=True`: every resource except `ids`
+ is allowed, which is the usual answer when the project grants access by default. So an empty `ids`
+ means nothing when `excluded` is False and everything when it is True.
+ `creator_exempt` means resources the subject created are allowed whatever `ids` say. The caller
+ supplies the creator column, because only the enforcement point knows it.
+ `complete=False` means the list was capped. `ids` is then empty and `excluded` False, so the caller
+ fails closed.
+ """
+
+ ids: frozenset[str]
+ complete: bool
+ excluded: bool = False
+ creator_exempt: bool = False
+
+ def __post_init__(self) -> None:
+ if not self.complete and (self.ids or self.excluded):
+ raise ValueError("A capped result allows nothing, so the caller fails closed.")
+
+ @property
+ def restricts(self) -> bool:
+ """Whether applying the result can remove rows."""
+ return not (self.excluded and not self.ids)
+
+ def allows(self, id: str, *, created_by_user_id: int | None = None, subject_user_id: int | None = None) -> bool:
+ """Whether one resource is allowed. Same rule as the QuerySet and HogQL adapters, for one object."""
+ if not self.complete:
+ return False
+ if self.creator_exempt and subject_user_id is not None and created_by_user_id == subject_user_id:
+ return True
+ return (id in self.ids) != self.excluded
+
+
+@dataclass(frozen=True, kw_only=True)
+class Explanation:
+ """The decision of one check, and the rules it went through to reach it, in order."""
+
+ allowed: bool
+ path: tuple[str, ...]
diff --git a/products/authorization/backend/facade/enums.py b/products/authorization/backend/facade/enums.py
new file mode 100644
index 000000000000..070567e3011d
--- /dev/null
+++ b/products/authorization/backend/facade/enums.py
@@ -0,0 +1,129 @@
+"""
+Exported enums for authorization.
+
+If an enum appears in a contract dataclass field, it belongs here.
+Internal-only constants (DB magic values, feature flags) stay in
+the implementation (logic.py, models.py).
+
+No Django imports: use LabeledStrEnum or LabeledIntEnum, not
+models.TextChoices, for an enum that backs model or serializer choices.
+"""
+
+from enum import StrEnum
+
+
+class Action(StrEnum):
+ """An operation a subject asks to perform on a resource."""
+
+ VIEW = "view"
+ EDIT = "edit"
+ DELETE = "delete"
+ SHARE = "share"
+ MANAGE_ACCESS = "manage_access"
+ CREATE = "create"
+ QUERY = "query"
+ JOIN = "join"
+ MANAGE_OWNERS = "manage_owners"
+ EDIT_MEMBER_SETTINGS = "edit_member_settings"
+ SUPPORT = "support"
+ APPROVE = "approve"
+ MANAGE_BILLING = "manage_billing"
+
+
+class Level(StrEnum):
+ """A relation a subject holds on a resource, project or organization.
+
+ A level that more than one layer uses has one member here.
+ """
+
+ NONE = "none"
+ VIEWER = "viewer"
+ EDITOR = "editor"
+ MANAGER = "manager"
+ MEMBER = "member"
+ ADMIN = "admin"
+ OWNER = "owner"
+
+
+class ResourceType(StrEnum):
+ """A type of resource that access rules can target."""
+
+ ORGANIZATION = "organization"
+ PROJECT = "project"
+ ROLE = "role"
+ # Keep in sync with ACCESS_CONTROL_RESOURCES in products/access_control/backend/facade/user_access_control.py.
+ # Also cover every `access_scope` a HogQL PostgresTable declares. These are not in that tuple:
+ ACCOUNT = "account"
+ ALERT = "alert"
+ ANNOTATION = "annotation"
+ AUTORESEARCH = "autoresearch"
+ BATCH_EXPORT = "batch_export"
+ CANVAS = "canvas"
+ CUSTOMER_TASK = "customer_task"
+ DATASET = "dataset"
+ HOG_FUNCTION = "hog_function"
+ INTEGRATION = "integration"
+ SESSION_RECORDING_PLAYLIST = "session_recording_playlist"
+ TASK = "task"
+ USAGE_METRIC = "usage_metric"
+ ACTION = "action"
+ CUSTOMER_ANALYTICS = "customer_analytics"
+ DATA_CATALOG = "data_catalog"
+ DATA_DELETION = "data_deletion"
+ DASHBOARD = "dashboard"
+ EARLY_ACCESS_FEATURE = "early_access_feature"
+ ENDPOINT = "endpoint"
+ EXPERIMENT = "experiment"
+ EXPORT = "export"
+ EXTERNAL_DATA_SOURCE = "external_data_source"
+ WAREHOUSE_OBJECTS = "warehouse_objects"
+ FEATURE_FLAG = "feature_flag"
+ HEATMAP = "heatmap"
+ HOG_FLOW = "hog_flow"
+ INSIGHT = "insight"
+ LLM_ANALYTICS = "llm_analytics"
+ EVALUATION = "evaluation"
+ TAGGER = "tagger"
+ LLM_SKILL = "llm_skill"
+ AI_OBSERVABILITY_CLUSTERS = "ai_observability_clusters"
+ NOTEBOOK = "notebook"
+ REVENUE_ANALYTICS = "revenue_analytics"
+ SESSION_RECORDING = "session_recording"
+ LLM_PROVIDER_KEY = "llm_provider_key"
+ LLM_PROMPT = "llm_prompt"
+ CUSTOMER_JOURNEY = "customer_journey"
+ EXPERIMENT_SAVED_METRIC = "experiment_saved_metric"
+ EXPERIMENT_HOLDOUT = "experiment_holdout"
+ DASHBOARD_TEMPLATE = "dashboard_template"
+ MARKETING_ANALYTICS = "marketing_analytics"
+ VISION_ALERT = "vision_alert"
+ SHARING_CONFIGURATION = "sharing_configuration"
+ STAMPHOG = "stamphog"
+ SURVEY = "survey"
+ TICKET = "ticket"
+ WEB_ANALYTICS = "web_analytics"
+ ACTIVITY_LOG = "activity_log"
+ BUSINESS_KNOWLEDGE = "business_knowledge"
+ ERROR_TRACKING = "error_tracking"
+ LOGS = "logs"
+ MCP_ANALYTICS = "mcp_analytics"
+ METRICS = "metrics"
+ TRACING = "tracing"
+ REPLAY_SCANNER = "replay_scanner"
+ TOOLBAR = "toolbar"
+ LLM_PLAYGROUND = "llm_playground"
+ # Query access checks resolve warehouse tables and views one object at a time.
+ WAREHOUSE_TABLE = "warehouse_table"
+ WAREHOUSE_VIEW = "warehouse_view"
+
+
+class SubjectType(StrEnum):
+ """A kind of principal that can hold relations or act on a resource."""
+
+ USER = "user"
+ API_KEY = "api_key"
+ SHARE_LINK = "share_link"
+ EXPORT_TOKEN = "export_token"
+ PROJECT_SECRET_KEY = "project_secret_key"
+ SERVICE = "service"
+ ROLE = "role"
diff --git a/products/authorization/backend/logic/__init__.py b/products/authorization/backend/logic/__init__.py
new file mode 100644
index 000000000000..599313967c4e
--- /dev/null
+++ b/products/authorization/backend/logic/__init__.py
@@ -0,0 +1,11 @@
+"""Internals for authorization. Only facade/api.py calls this package.
+
+The implementation lands here in small steps:
+- an OpenFGA client, and the bootstrap of its store and authorization model,
+- the authorization model sources, which define the relations and permissions of each resource type,
+- the projection that writes each organization's members, roles, access rules and share links as relationships,
+- the checks and object lists that answer the facade,
+- the rollout that moves each organization from the access control rules to these checks.
+
+Nothing outside this product calls the facade until the rollout is in place.
+"""
diff --git a/products/authorization/backend/tests/__init__.py b/products/authorization/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/authorization/backend/tests/test_contracts.py b/products/authorization/backend/tests/test_contracts.py
new file mode 100644
index 000000000000..adfcfb138433
--- /dev/null
+++ b/products/authorization/backend/tests/test_contracts.py
@@ -0,0 +1,47 @@
+from typing import Any
+from uuid import UUID
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.authorization.backend.facade.contracts import ObjectIds, Resource, Subject
+from products.authorization.backend.facade.enums import ResourceType
+
+PROJECT = Resource(type=ResourceType.PROJECT, id="1")
+
+
+class TestSubject(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("no_field", {}),
+ ("two_ids", {"user_id": 1, "api_key_id": "key_1"}),
+ ("id_and_members", {"role_id": UUID(int=1), "members_of": PROJECT}),
+ ]
+ )
+ def test_rejects_zero_or_several_fields(self, _name: str, kwargs: dict[str, Any]) -> None:
+ with self.assertRaises(ValueError):
+ Subject(**kwargs)
+
+ @parameterized.expand([("user_id", {"user_id": 1}), ("members_of", {"members_of": PROJECT})])
+ def test_accepts_exactly_one_field(self, _name: str, kwargs: dict[str, Any]) -> None:
+ Subject(**kwargs)
+
+
+class TestObjectIds(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("only", ObjectIds(ids=frozenset({"1"}), complete=True), True, False, False),
+ ("except", ObjectIds(ids=frozenset({"1"}), complete=True, excluded=True), False, True, True),
+ ("all", ObjectIds(ids=frozenset(), complete=True, excluded=True), True, True, True),
+ ("none", ObjectIds(ids=frozenset(), complete=True), False, False, False),
+ ("creator", ObjectIds(ids=frozenset(), complete=True, creator_exempt=True), False, False, True),
+ ("capped_creator", ObjectIds(ids=frozenset(), complete=False, creator_exempt=True), False, False, False),
+ ]
+ )
+ def test_membership_and_creator_exemption(
+ self, _name: str, result: ObjectIds, first: bool, other: bool, own: bool
+ ) -> None:
+ assert result.allows("1") is first
+ assert result.allows("2", created_by_user_id=None, subject_user_id=1) is other
+ assert result.allows("2", created_by_user_id=1, subject_user_id=1) is own
diff --git a/products/authorization/manifest.tsx b/products/authorization/manifest.tsx
new file mode 100644
index 000000000000..bd059dedbaca
--- /dev/null
+++ b/products/authorization/manifest.tsx
@@ -0,0 +1,23 @@
+/**
+ * Product manifest for authorization.
+ *
+ * Defines scenes, routes, URLs, and navigation for this product.
+ */
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'Authorization',
+ scenes: {
+ // Define scenes here
+ },
+ routes: {
+ // Define routes here
+ },
+ redirects: {},
+ urls: {
+ // Define URL helpers here
+ },
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/authorization/package.json b/products/authorization/package.json
new file mode 100644
index 000000000000..919b2ea6ba81
--- /dev/null
+++ b/products/authorization/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@posthog/products-authorization",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
+ }
+}
diff --git a/products/authorization/product.yaml b/products/authorization/product.yaml
new file mode 100644
index 000000000000..0fc4cba1e9f7
--- /dev/null
+++ b/products/authorization/product.yaml
@@ -0,0 +1,3 @@
+name: Authorization
+owners:
+ - team-platform-features
diff --git a/products/authorization/tsconfig.json b/products/authorization/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/authorization/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/authorization/turbo.json b/products/authorization/turbo.json
new file mode 100644
index 000000000000..0f13f3b421f9
--- /dev/null
+++ b/products/authorization/turbo.json
@@ -0,0 +1,17 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/webhook_consumers.py",
+ "backend/tasks/**",
+ "backend/models.py",
+ "backend/migrations/**"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/tach.toml b/tach.toml
index e1ebedb94fd8..0a2df5c1ad2d 100644
--- a/tach.toml
+++ b/tach.toml
@@ -1840,3 +1840,16 @@ expose = [
from = [
"products.uptime_monitoring",
]
+
+[[modules]]
+path = "products.authorization"
+depends_on = []
+layer = "modules"
+
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+]
+from = [
+ "products.authorization",
+]