:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(hogli): detect namespace imports in codegen adoption scoring (#57860)
Rafael Audibertb23040294385
diff --git a/.flox/env/manifest.toml b/.flox/env/manifest.tomlindex 429b69316947..2f0faf6ddfe3 100644--- a/.flox/env/manifest.toml+++ b/.flox/env/manifest.toml@@ -38,6 +38,7 @@ golangci-lint = { pkg-path = "golangci-lint", pkg-group = "go" }air = { pkg-path = "air" }# CLI toolsgit-lfs = { pkg-path = "git-lfs" }+ripgrep = { pkg-path = "ripgrep" }mprocs = { pkg-path = "mprocs" }util-linux = { pkg-path = "util-linux" } # flockcmake = { pkg-path = "cmake", version = "3.31.5", pkg-group = "cmake" }diff --git a/products/legal_documents/backend/presentation/permissions.py b/products/legal_documents/backend/presentation/permissions.pynew file mode 100644index 000000000000..ea1c9fa4c1a0--- /dev/null+++ b/products/legal_documents/backend/presentation/permissions.py@@ -0,0 +1,50 @@+from typing import cast++from rest_framework import exceptions+from rest_framework.permissions import BasePermission+from rest_framework.request import Request+from rest_framework.views import APIView++from posthog.cloud_utils import is_cloud, is_dev_mode+from posthog.models.organization import OrganizationMembership+from posthog.models.user import User+++class IsCloudOrDevDeployment(BasePermission):+ """+ Gates the legal-documents API to cloud (or a local DEBUG environment, so+ we can test the flow). Self-hosted production deployments don't have the+ PandaDoc / Slack credentials and the feature is a PostHog-owned workflow,+ not something customers run on their own infrastructure.+ """++ message = "Legal documents are only available on PostHog Cloud."++ def has_permission(self, request: Request, view: APIView) -> bool:+ if not (is_cloud() or is_dev_mode()):+ raise exceptions.NotFound("Not found.")+ return True+++class IsOrganizationAdminOrOwner(BasePermission):+ """+ Allow access only to organization admins and owners (for every method,+ including reads). Mirrors the gate we apply to the Settings → Legal+ documents entry and the /legal scene in the frontend, so that non-admin+ members can't probe the API directly either.+ """++ message = "Your organization access level is insufficient."++ def has_permission(self, request: Request, view: "APIView") -> bool:+ organization = getattr(view, "organization", None)+ if organization is None:+ # Mixin hasn't resolved the org yet — defer. TeamAndOrgViewSetMixin+ # calls this after the URL kwarg has been parsed, so this branch is+ # effectively only hit on misconfigured routes.+ raise exceptions.NotFound("Organization not found.")+ try:+ membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)+ except OrganizationMembership.DoesNotExist:+ raise exceptions.NotFound("Organization not found.")+ return membership.level >= OrganizationMembership.Level.ADMINdiff --git a/products/legal_documents/backend/presentation/views.py b/products/legal_documents/backend/presentation/views.pyindex 1d72e121b5d3..7f81a9964fc9 100644--- a/products/legal_documents/backend/presentation/views.py+++ b/products/legal_documents/backend/presentation/views.py@@ -7,60 +7,17 @@ from django.http import HttpResponseRedirectfrom drf_spectacular.utils import extend_schemafrom rest_framework import exceptions, permissions, status, viewsetsfrom rest_framework.decorators import action-from rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework.response import Response-from rest_framework.views import APIViewfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.cloud_utils import is_cloud, is_dev_mode-from posthog.models.organization import OrganizationMembershipfrom posthog.models.user import Userfrom ..facade import api, contracts+from .permissions import IsCloudOrDevDeployment, IsOrganizationAdminOrOwnerfrom .serializers import CreateLegalDocumentSerializer, LegalDocumentSerializer-class IsCloudOrDevDeployment(BasePermission):- """- Gates the legal-documents API to cloud (or a local DEBUG environment, so- we can test the flow). Self-hosted production deployments don't have the- PandaDoc / Slack credentials and the feature is a PostHog-owned workflow,- not something customers run on their own infrastructure.- """-- message = "Legal documents are only available on PostHog Cloud."-- def has_permission(self, request: Request, view: APIView) -> bool:- if not (is_cloud() or is_dev_mode()):- raise exceptions.NotFound("Not found.")- return True---class IsOrganizationAdminOrOwner(BasePermission):- """- Allow access only to organization admins and owners (for every method,- including reads). Mirrors the gate we apply to the Settings → Legal- documents entry and the /legal scene in the frontend, so that non-admin- members can't probe the API directly either.- """-- message = "Your organization access level is insufficient."-- def has_permission(self, request: Request, view: "APIView") -> bool:- organization = getattr(view, "organization", None)- if organization is None:- # Mixin hasn't resolved the org yet — defer. TeamAndOrgViewSetMixin- # calls this after the URL kwarg has been parsed, so this branch is- # effectively only hit on misconfigured routes.- raise exceptions.NotFound("Organization not found.")- try:- membership = OrganizationMembership.objects.get(user=cast(User, request.user), organization=organization)- except OrganizationMembership.DoesNotExist:- raise exceptions.NotFound("Organization not found.")- return membership.level >= OrganizationMembership.Level.ADMIN--@extend_schema(tags=["core"])class LegalDocumentViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "legal_document"diff --git a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts b/products/legal_documents/frontend/scenes/legalDocumentsLogic.tsindex d9ff7e152d18..fb1a65351d6d 100644--- a/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts+++ b/products/legal_documents/frontend/scenes/legalDocumentsLogic.ts@@ -3,7 +3,6 @@ import { forms } from 'kea-forms'import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'-import api from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { billingLogic } from 'scenes/billing/billingLogic'import { organizationLogic } from 'scenes/organizationLogic'@@ -11,6 +10,7 @@ import { urls } from 'scenes/urls'import { BillingType } from '~/types'+import * as api from '../generated/api'import type { legalDocumentsLogicType } from './legalDocumentsLogicType'export type LegalDocumentType = 'BAA' | 'DPA'@@ -71,8 +71,7 @@ export const legalDocumentsLogic = kea<legalDocumentsLogicType>([if (!values.currentOrganizationId) {return []}- // nosemgrep: prefer-codegen-api- const response = await api.get(`api/organizations/${values.currentOrganizationId}/legal_documents`)+ const response = await api.legalDocumentsList(values.currentOrganizationId)return (response.results ?? []) as LegalDocument[]},},@@ -104,11 +103,7 @@ export const legalDocumentsLogic = kea<legalDocumentsLogicType>([// single DPA variant, so we never send it on the wire.const { dpa_mode: _dpaMode, ...payload } = formValuestry {- // nosemgrep: prefer-codegen-api- const legalDocument = await api.create<LegalDocument>(- `api/organizations/${values.currentOrganizationId}/legal_documents`,- payload- )+ const legalDocument = await api.legalDocumentsCreate(values.currentOrganizationId, payload)actions.loadLegalDocuments()actions.resetLegalDocument(defaultsFor(formValues.document_type))lemonToast.success(diff --git a/tools/hogli-commands/hogli_commands/product/maturity.py b/tools/hogli-commands/hogli_commands/product/maturity.pyindex 4fd611561371..ae68e0ce8348 100644--- a/tools/hogli-commands/hogli_commands/product/maturity.py+++ b/tools/hogli-commands/hogli_commands/product/maturity.py@@ -393,6 +393,11 @@ def _build_inbound_violation_map() -> dict[str, int] | None:continueif "/migrations/" in file_path:continue+ # Django admin's project-wide registry has to import each product's+ # admin classes and the models they reference — there's no facade+ # equivalent for `admin.site.register`.+ if "/posthog/admin/" in file_path or file_path.startswith("posthog/admin/"):+ continueif ".backend.facade" in import_text:continueif ".backend.presentation" in import_text:diff --git a/tools/hogli-commands/hogli_commands/product/ts_helpers.py b/tools/hogli-commands/hogli_commands/product/ts_helpers.pyindex c28df9f5539e..18717f3e9013 100644--- a/tools/hogli-commands/hogli_commands/product/ts_helpers.py+++ b/tools/hogli-commands/hogli_commands/product/ts_helpers.py@@ -22,6 +22,10 @@ def get_generated_imports_in_frontend(frontend_dir: Path) -> set[str]:Scans all .ts/.tsx files in the product's frontend/ directory, excluding thegenerated/ subdirectory itself. Returns the set of imported function names.++ Recognizes both named and namespace imports:+ import { funcA, funcB } from '../generated/api'+ import * as api from '../generated/api' // then any `api.funcA` usage"""generated_dir = frontend_dir / "generated"imported: set[str] = set()@@ -46,6 +50,19 @@ def get_generated_imports_in_frontend(frontend_dir: Path) -> set[str]:names = [n.strip().split(" as ")[0].strip() for n in match.group(1).split(",")]imported.update(n for n in names if n and not n.startswith("type "))+ # Match: import * as <alias> from '...generated/api'+ # Tree-shaken namespace imports — collect every `<alias>.<member>`+ # access. Non-endpoint members (e.g. URL helpers) are filtered later+ # against the known endpoint names.+ for match in re.finditer(+ r"import\s*\*\s*as\s+(\w+)\s*from\s*['\"][^'\"]*generated/api['\"]",+ collapsed,+ ):+ alias = match.group(1)+ usage_re = re.compile(rf"\b{re.escape(alias)}\.(\w+)")+ for usage in usage_re.finditer(content):+ imported.add(usage.group(1))+# Also match: import type { ... } from '...generated/api.schemas'# These are type-only imports and don't count as endpoint usage.# (We deliberately skip them.)