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(stamphog): gate review settings on the manager access level (#93123)

Julian Bez6acc06422db1
diff --git a/common/storybook/.storybook/app-context.ts b/common/storybook/.storybook/app-context.ts
index 10ac62b56a42..0b3d037d835f 100644
--- a/common/storybook/.storybook/app-context.ts
+++ b/common/storybook/.storybook/app-context.ts
@@ -91,5 +91,6 @@ export const getStorybookAppContext = (): AppContext => ({
error_tracking: 'manager',
metrics: 'manager',
replay_scanner: 'manager',
+ stamphog: 'manager',
},
})
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 76677efba39a..377edf4ec080 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -8293,9 +8293,9 @@ snapshots:
scenes-app-settings-authentication-domains--redesigned-needs-upgrade--light:
hash: v1.k794b7964.4b5a266868dc1940520295c984cfb39605c4d390c8c4ff95ea6e2feb18b83322.u3WQPP9cbRpyWOVVLcKqirce0oSloq_Kmf5nsxwe-uk
scenes-app-settings-environment--settings-environment-access-control--dark:
- hash: v1.k794b7964.aaa5cfaf171ff03f70b661188ff1929c429d4869f42447b613e3187c0f64676d.0FKBKOrxXxrhUqI7snoVtWkkOiBcQiq5PyBDkeVhtyw
+ hash: v1.k794b7964.c9ccaaba4bf03f6923b41fe85e387d17139a6d7d69a6e06913a37cb5dd019532.bpCeuesKb9InCkdPuMqRPNFckeU7o1u6QcQfQf5ogSE
scenes-app-settings-environment--settings-environment-access-control--light:
- hash: v1.k794b7964.186fbf23227d2d6dc06649434978123a3fb9bd1bf1b2199124397879059bacc6.tT3nI1FldKPItDCHz00NZgrH3dQJIseYExoZD9D51Us
+ hash: v1.k794b7964.e2a2721a0bbfca9bb459d0b991cedd912f1af81eff8ff15996bcc73984417aee.j7jFwv6YnpcoUKYfoXaZaluFS2_lDIFHE7TtSSvBOlI
scenes-app-settings-environment--settings-environment-autocapture--dark:
hash: v1.k794b7964.2183cf0082a1556d6df553572df4ab3813c96288a8b9a80e669c005908230c3e.-ybX8d6KyxaSa-yJDVccZm2CkK8Fl8qLSbw9jGhSIx4
scenes-app-settings-environment--settings-environment-autocapture--light:
diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts
index d1ed3e27157a..c02f4c9d2361 100644
--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts
+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/resourcesAccessControlLogic.ts
@@ -191,6 +191,7 @@ export const resourcesAccessControlLogic = kea<resourcesAccessControlLogicType>(
AccessControlResourceType.RevenueAnalytics,
AccessControlResourceType.SessionRecording,
AccessControlResourceType.SharingConfiguration,
+ AccessControlResourceType.Stamphog,
AccessControlResourceType.ErrorTracking,
AccessControlResourceType.ReplayScanner,
AccessControlResourceType.Survey,
diff --git a/frontend/src/lib/utils/accessControlUtils.ts b/frontend/src/lib/utils/accessControlUtils.ts
index 15bd31f242a3..790894dbdbbe 100644
--- a/frontend/src/lib/utils/accessControlUtils.ts
+++ b/frontend/src/lib/utils/accessControlUtils.ts
@@ -126,6 +126,9 @@ export const pluralizeResource = (resource: APIScopeObject): string => {
return 'tracing'
} else if (resource === AccessControlResourceType.SharingConfiguration) {
return 'sharing'
+ } else if (resource === AccessControlResourceType.Stamphog) {
+ // Product name, so it does not take a plural
+ return 'stamphog'
} else if (resource === AccessControlResourceType.Toolbar) {
return 'toolbar'
} else if (resource === AccessControlResourceType.LlmPlayground) {
@@ -195,6 +198,9 @@ export const resourceTypeToString = (resourceType: AccessControlResourceType): s
return 'MCP analytic'
} else if (resourceType === AccessControlResourceType.ReplayScanner) {
return 'replay vision resource'
+ } else if (resourceType === AccessControlResourceType.Stamphog) {
+ // Proper noun, so it stays capitalized inside "...permissions for this Stamphog resource."
+ return 'Stamphog resource'
}
return resourceType.replace(/_/g, ' ')
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 2906b005c45d..3e8a42e54447 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -173,6 +173,9 @@ export enum Scene {
Coupons = 'Coupons',
Sources = 'Sources',
StartupProgram = 'StartupProgram',
+ Stamphog = 'Stamphog',
+ StamphogRuns = 'StamphogRuns',
+ StamphogDigests = 'StamphogDigests',
Survey = 'Survey',
SurveyWizard = 'SurveyWizard',
SurveyFormBuilder = 'SurveyFormBuilder',
@@ -406,6 +409,11 @@ export const sceneToAccessControlResourceType: Partial<Record<Scene, AccessContr
[Scene.ErrorTrackingIssue]: AccessControlResourceType.ErrorTracking,
[Scene.ErrorTrackingIssueFingerprints]: AccessControlResourceType.ErrorTracking,
+ // Stamphog
+ [Scene.Stamphog]: AccessControlResourceType.Stamphog,
+ [Scene.StamphogRuns]: AccessControlResourceType.Stamphog,
+ [Scene.StamphogDigests]: AccessControlResourceType.Stamphog,
+
// Surveys
[Scene.Survey]: AccessControlResourceType.Survey,
[Scene.Surveys]: AccessControlResourceType.Survey,
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 0eed0873feff..380732a4453d 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -305,6 +305,7 @@ export enum AccessControlResourceType {
Ticket = 'ticket',
SessionRecording = 'session_recording',
SharingConfiguration = 'sharing_configuration',
+ Stamphog = 'stamphog',
RevenueAnalytics = 'revenue_analytics',
Survey = 'survey',
Logs = 'logs',
diff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.py
index c6f571721208..3d2baa2f3690 100644
--- a/products/access_control/backend/facade/user_access_control.py
+++ b/products/access_control/backend/facade/user_access_control.py
@@ -80,6 +80,7 @@ ACCESS_CONTROL_RESOURCES: tuple[APIScopeObject, ...] = (
"revenue_analytics",
"session_recording",
"sharing_configuration",
+ "stamphog",
"survey",
"ticket",
"web_analytics",
@@ -197,6 +198,9 @@ def resource_to_display_name(resource: APIScopeObject) -> str:
if resource == "llm_playground":
# The playground is a single page, not a collection of objects
return "LLM playground"
+ if resource == "stamphog":
+ # Product name: a proper noun, and it does not take a plural
+ return "Stamphog"
# Default: replace underscores and add 's' for plural
return f"{resource.replace('_', ' ')}s"
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 051c05378b74..135b676ac726 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -170,12 +170,20 @@ narrow:
## Trust boundaries
+- The review-gating fields (`enabled`, `review_mode`, `trigger_label`) and the soft-delete need the
+ `manager` level on the `stamphog` resource, because they decide whether a pull request is reviewed
+ at all. Naming one of those fields on a create takes `manager` too. Connecting a repository
+ without them, and the digest toggle, stay at `editor`.
- Review policy is read from the repo's **default branch**, never the PR head — a PR must not be
able to rewrite the policy that gates it. Same for the `digest:` channel declaration and the
root `owners.yaml` team registry the digest routes through.
-- A manually-created repo config (blank `installation_id`) binds **disabled** when a sync adopts
- it: its flags were set by someone who never proved GitHub access. Reinstall rebinds keep
- settings — those were configured under a verified binding.
+- A manually-created repo config (blank `installation_id`) binds **disabled** when a sync adopts it,
+ and its review policy (`review_mode`, `trigger_label`) resets to the model defaults: all of those
+ fields were set by someone who never proved GitHub access, so a pre-selected label mode would
+ otherwise go live the moment a manager enables the row. Reinstall rebinds keep settings — those
+ were configured under a verified binding. Such a row is also kept out of the digest candidates:
+ a blank installation can fetch no routing file, and every candidate is read, so leaving it in let
+ one placeholder silence the whole team's digest.
- Digest routing is derived every run from the repositories and never stored, so nothing here can
go stale silently — and nothing degrades either. A registry that cannot be read stops the whole
team's run (`RoutingUnavailable`) rather than falling through to derived channel names: the
diff --git a/products/stamphog/backend/facade/github.py b/products/stamphog/backend/facade/github.py
index 89cb5320125a..ff1125852022 100644
--- a/products/stamphog/backend/facade/github.py
+++ b/products/stamphog/backend/facade/github.py
@@ -54,11 +54,13 @@ def _adopt_preexisting_config(team_id: int, repository: str, installation_id: st
it skipped and leaving it unbound forever. Safe to rebind: this helper is team-scoped and only
reached from the sync flow, which already proved the caller owns the NEW installation.
- A never-bound placeholder binds DISABLED: its enabled flags were set by whoever created the row,
- who never proved GitHub access to the repo — otherwise a member could pre-arm ``enabled=True``
- for a private repo and have reviews start (under the syncing teammate's identity) the moment
- someone else completes the install. Reinstall rows keep their settings: they were configured
- while verifiably bound to a real installation.
+ A never-bound placeholder binds DISABLED and with its review policy back at the defaults: every
+ one of those fields was set by whoever created the row, who never proved GitHub access to the
+ repo — otherwise a member could pre-arm ``enabled=True`` for a private repo and have reviews
+ start (under the syncing teammate's identity) the moment someone else completes the install, or
+ pre-select label mode with a label nobody uses so the row reviews nothing once a manager enables
+ it. Reinstall rows keep their settings: they were configured while verifiably bound to a real
+ installation.
"""
# Writer pin: the writer-side unique constraint is what routed us here, so the row exists on the
# writer — a lagged reader missing it would mark the repo skipped and leave it unbound forever.
@@ -75,7 +77,10 @@ def _adopt_preexisting_config(team_id: int, repository: str, installation_id: st
if not existing.installation_id:
existing.enabled = False
existing.digest_enabled = False
- update_fields += ["enabled", "digest_enabled"]
+ # Read the defaults off the model so the reset cannot drift from what a fresh row gets.
+ existing.review_mode = StamphogRepoConfig._meta.get_field("review_mode").get_default()
+ existing.trigger_label = StamphogRepoConfig._meta.get_field("trigger_label").get_default()
+ update_fields += ["enabled", "digest_enabled", "review_mode", "trigger_label"]
existing.installation_id = installation_id
try:
existing.save(update_fields=update_fields)
diff --git a/products/stamphog/backend/logic/channel_resolution.py b/products/stamphog/backend/logic/channel_resolution.py
index e60e8af44185..be1e28ed660f 100644
--- a/products/stamphog/backend/logic/channel_resolution.py
+++ b/products/stamphog/backend/logic/channel_resolution.py
@@ -137,6 +137,10 @@ def _candidate_repo_configs(team_id: int) -> list[StamphogRepoConfig]:
return list(
StamphogRepoConfig.objects.for_team(team_id)
.using(router.db_for_write(StamphogRepoConfig))
+ # A blank installation cannot fetch a routing file or resolve a webhook, so the row carries
+ # no registry to read and no merges to report. Left in, its unreadable fetch would raise
+ # RoutingUnavailable and stop the whole team's run.
+ .exclude(installation_id="")
.filter(Q(enabled=True) | Q(digest_enabled=True))
.order_by("repository")
)
diff --git a/products/stamphog/backend/presentation/serializers.py b/products/stamphog/backend/presentation/serializers.py
index 27b0456472e7..dda42fbf7f1a 100644
--- a/products/stamphog/backend/presentation/serializers.py
+++ b/products/stamphog/backend/presentation/serializers.py
@@ -66,6 +66,25 @@ class _ReviewOutputSummarySerializer(serializers.Serializer):
@extend_schema_serializer(component_name="StamphogRepoConfig")
class StamphogRepoConfigSerializer(DataclassSerializer):
+ user_access_level = serializers.SerializerMethodField(
+ read_only=True,
+ help_text=(
+ "The caller's access level on the stamphog resource, resolved for the team that owns this "
+ "row. 'manager' is required to change enabled, review_mode, or trigger_label."
+ ),
+ )
+
+ @extend_schema_field(serializers.CharField(allow_null=True))
+ def get_user_access_level(self, _obj: contracts.RepoConfigDTO) -> str | None:
+ """The resource-wide level, not an object-level one: stamphog has no per-object rules.
+
+ The frontend gates the review settings on this rather than on the app context, which is
+ resolved for the environment in the URL while these rows belong to its parent project. The
+ view resolves it once per request, so every row on a page reports the same level.
+ """
+ view = self.context.get("view")
+ return view.stamphog_access_level if view else None
+
def get_fields(self) -> dict[str, serializers.Field]:
fields = super().get_fields()
# provider + repository are the config's identity: they resolve inbound webhooks and anchor
@@ -97,6 +116,7 @@ class StamphogRepoConfigSerializer(DataclassSerializer):
"digest_enabled",
"review_mode",
"trigger_label",
+ "user_access_level",
"created_at",
"updated_at",
]
diff --git a/products/stamphog/backend/presentation/views.py b/products/stamphog/backend/presentation/views.py
index 930ece9e7e0c..57fdd478c5e1 100644
--- a/products/stamphog/backend/presentation/views.py
+++ b/products/stamphog/backend/presentation/views.py
@@ -6,7 +6,7 @@ return serialized responses. No business logic here.
"""
from functools import cached_property
-from typing import Any
+from typing import Any, cast
from urllib.parse import quote
from django.conf import settings
@@ -26,6 +26,12 @@ from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication
from posthog.models.scoping.manager import resolve_effective_team_id
+from posthog.models.team import Team
+from posthog.models.user import User
+
+# UserAccessControl reaches stamphog through core: the product's tach boundary allows `posthog`
+# but not `products.access_control`, where the class is defined.
+from posthog.permissions import UserAccessControl, is_service_auth
from products.stamphog.backend.facade import (
api as facade_api,
@@ -60,6 +66,9 @@ logger = structlog.get_logger(__name__)
_INSTALL_STATE_SALT = "stamphog-install-state"
_INSTALL_STATE_MAX_AGE_SECONDS = 60 * 60
+# These decide whether a pull request gets reviewed, so writing any of them takes the manager level.
+REVIEW_GATE_FIELDS = ("enabled", "review_mode", "trigger_label")
+
class StamphogCanonicalTeamAccessPermission(BasePermission):
"""Authorize against the canonical (data-owning) team, not just the URL environment team.
@@ -120,6 +129,40 @@ class _StamphogTeamScopedViewSet(TeamAndOrgViewSetMixin):
def canonical_team_id(self) -> int:
return resolve_effective_team_id(self.team_id)
+ @cached_property
+ def canonical_team(self) -> Team | None:
+ """The team whose rows this request reads and writes, or None when there is no team yet."""
+ try:
+ team = self.team
+ except (Team.DoesNotExist, KeyError):
+ return None
+ if team.parent_team_id is None or team.parent_team_id == team.id or team.parent_team is None:
+ return team
+ return team.parent_team
+
+ @cached_property
+ def user_access_control(self) -> UserAccessControl:
+ """RBAC anchored to the canonical team, so resource levels are read where the rows live.
+
+ Overrides the mixin, which anchors to the URL team. Through a child environment that let the
+ child's stamphog level decide access to the parent's rows, in both directions: a grant on the
+ child alone reached the parent, and a grant on the parent alone was refused.
+
+ An instance only answers for the team it was built with, so this one cannot see the URL
+ team's own project rules. It does not have to: TeamMemberAccessPermission reads those
+ directly through UserPermissions.effective_membership_level, where an explicit "none" is a
+ denial, and that gate runs on every request here.
+ """
+ return UserAccessControl(
+ user=cast(User, self.request.user), team=self.canonical_team, organization_id=self.organization_id
+ )
+
+ @cached_property
+ def stamphog_access_level(self) -> str | None:
+ """The caller's resource-wide stamphog level, resolved once for the whole response."""
+ access = self.user_access_control.access_level_for_resource("stamphog")
+ return access.access_level if access else None
+
def get_serializer_context(self) -> dict[str, Any]:
# The mixin sets context["team_id"] to the RAW url team, but a serializer validating a
# team-scoped lookup reads it. stamphog rows canonicalize to the parent team on save, so
@@ -149,6 +192,22 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
return config
raise NotFound()
+ def _require_review_gate_manager(self, request: Request) -> None:
+ """Refuse a review-gating write below the manager level on the stamphog resource.
+
+ Service credentials (project secret keys, team secret tokens) are synthetic users the RBAC
+ layer cannot resolve, and a key is never a manager, so they are refused here rather than
+ silently passed through by AccessControlPermission's service-auth shortcut.
+ """
+ if not is_service_auth(request) and self.user_access_control.check_access_level_for_resource(
+ "stamphog", "manager"
+ ):
+ return
+ raise PermissionDenied(
+ "Only a Stamphog manager can change whether this repository is reviewed. "
+ "Ask an organization admin for manager access."
+ )
+
def list(self, request: Request, **kwargs) -> Response:
configs = facade_api.list_repo_configs(self.canonical_team_id)
page = self.paginate_queryset(configs)
@@ -159,8 +218,15 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
@extend_schema(request=StamphogRepoConfigWriteSerializer, responses={201: StamphogRepoConfigSerializer})
def create(self, request: Request, **kwargs) -> Response:
+ # Naming a gate field takes manager here for the same reason it does on update: a caller
+ # spelling out a review policy is making the review decision, whichever verb carries it.
+ # Leaving them out stays at editor. The row is created without an installation, which binds
+ # it disabled at sync time and keeps it out of the digest candidates, so the defaults reach
+ # nothing on their own.
serializer = StamphogRepoConfigWriteSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
+ if any(field in serializer.validated_data for field in REVIEW_GATE_FIELDS):
+ self._require_review_gate_manager(request)
try:
config = facade_api.create_repo_config(self.canonical_team_id, **serializer.validated_data)
except contracts.RepoAlreadyClaimedError:
@@ -180,6 +246,11 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
context=self.get_serializer_context(),
)
serializer.is_valid(raise_exception=True)
+ # A supplied gate field always takes manager, even when it matches what `current` holds:
+ # that snapshot was read before the facade refetches and saves, so a value that looks
+ # unchanged can still overwrite a manager's decision made in between.
+ if any(field in serializer.validated_data for field in REVIEW_GATE_FIELDS):
+ self._require_review_gate_manager(request)
config = facade_api.update_repo_config(self.canonical_team_id, str(pk), **serializer.validated_data)
return Response(self.get_serializer(config).data)
@@ -189,6 +260,8 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
def destroy(self, request: Request, pk: str | None = None, **kwargs) -> Response:
self._get_or_404(pk)
+ # A soft delete flips `enabled`, so it is a review-gating write like the PATCH above.
+ self._require_review_gate_manager(request)
facade_api.disable_repo_config(self.canonical_team_id, str(pk))
return Response(status=204)
@@ -318,7 +391,8 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
# The App isn't installed anywhere the user can see. Not an error: the frontend routes them
# to the GitHub install page (install_url) off app_not_installed.
data = StamphogSyncInstallationResponseSerializer(
- {"synced": [], "skipped": [], "app_not_installed": True, "installations": []}
+ {"synced": [], "skipped": [], "app_not_installed": True, "installations": []},
+ context=self.get_serializer_context(),
).data
return Response(data)
if len(discovered) > 1:
@@ -328,7 +402,8 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
# connect. Bind nothing; the frontend re-runs the flow with an explicit installation_id
# (which the explicit path above verifies).
data = StamphogSyncInstallationResponseSerializer(
- {"synced": [], "skipped": [], "app_not_installed": False, "installations": discovered}
+ {"synced": [], "skipped": [], "app_not_installed": False, "installations": discovered},
+ context=self.get_serializer_context(),
).data
return Response(data)
installation_ids = [discovered[0]["id"]]
@@ -353,8 +428,11 @@ class StamphogRepoConfigViewSet(_StamphogTeamScopedViewSet, viewsets.GenericView
synced.extend(installation_synced)
skipped.extend(installation_skipped)
+ # The nested repo config serializer reads user_access_level off the view, and DRF hands the
+ # root's context down to it. Without the context every synced row reports a null level.
data = StamphogSyncInstallationResponseSerializer(
- {"synced": synced, "skipped": skipped, "app_not_installed": False, "installations": []}
+ {"synced": synced, "skipped": skipped, "app_not_installed": False, "installations": []},
+ context=self.get_serializer_context(),
).data
return Response(data)
diff --git a/products/stamphog/backend/tests/test_api.py b/products/stamphog/backend/tests/test_api.py
index e93f1ff783c9..e858669a669d 100644
--- a/products/stamphog/backend/tests/test_api.py
+++ b/products/stamphog/backend/tests/test_api.py
@@ -11,11 +11,15 @@ from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
from rest_framework import status
+from posthog.constants import AvailableFeature
from posthog.models.activity_logging.activity_log import ActivityLog
+from posthog.models.organization import OrganizationMembership
from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
from posthog.models.team import Team
+from posthog.models.user import User
from posthog.models.utils import generate_random_token_personal, uuid7
+from products.access_control.backend.models.access_control import AccessControl
from products.stamphog.backend.facade import contracts
from products.stamphog.backend.facade.enums import ChannelResolutionSource, DigestRunStatus, ReviewMode, ReviewRunStatus
from products.stamphog.backend.models import DigestRun, PullRequest, ReviewRun, StamphogRepoConfig
@@ -40,6 +44,193 @@ class TestStamphogRepoConfigAPI(StamphogTeamScopedTestMixin, APIBaseTest):
def setUp(self) -> None:
super().setUp()
self.url = f"/api/projects/{self.team.id}/stamphog/repo_configs/"
+ # Flipping the review-gating fields takes the manager level, which org admins hold
+ # everywhere. The plain-member cases below cover the other side.
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+
+ def _create_config(self) -> str:
+ created = self.client.post(self.url, {"repository": "PostHog/posthog", "enabled": True}, format="json").json()
+ return created["id"]
+
+ def _login_as_member(self, *, stamphog_level: str | None = None, grant_team: Team | None = None) -> User:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
+ ]
+ self.organization.save()
+ member = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ if stamphog_level is not None:
+ AccessControl.objects.create(
+ team=grant_team or self.team,
+ resource="stamphog",
+ resource_id=None,
+ access_level=stamphog_level,
+ organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),
+ )
+ self.client.force_login(member)
+ return member
+
+ @parameterized.expand(
+ [
+ ("enabled", {"enabled": False}),
+ ("review_mode", {"review_mode": ReviewMode.LABEL}),
+ ("trigger_label", {"trigger_label": "review-me"}),
+ ]
+ )
+ def test_member_cannot_change_a_review_gating_field(self, _name: str, payload: dict) -> None:
+ # These three decide whether a pull request is reviewed at all, so a project member who is
+ # only an editor must not be able to switch reviews off or point them at a label nobody uses.
+ config_id = self._create_config()
+ self._login_as_member()
+
+ response = self.client.patch(f"{self.url}{config_id}/", payload, format="json")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert "manager" in response.json()["detail"]
+ assert StamphogRepoConfig.objects.unscoped().get(id=config_id).enabled is True
+
+ def test_member_can_still_change_the_digest_toggle(self) -> None:
+ # The digest only decides who reads about merges, so gating it on manager too would take a
+ # setting away from editors that was never a review decision.
+ config_id = self._create_config()
+ self._login_as_member()
+
+ response = self.client.patch(f"{self.url}{config_id}/", {"digest_enabled": True}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["digest_enabled"] is True
+
+ @parameterized.expand(
+ [
+ ("names_a_gate_field", {"enabled": True}, status.HTTP_403_FORBIDDEN),
+ ("leaves_the_defaults", {}, status.HTTP_201_CREATED),
+ ]
+ )
+ def test_member_create_is_gated_only_when_it_names_a_review_field(
+ self, _name: str, extra: dict, expected_status: int
+ ) -> None:
+ # Spelling out a review policy is the same decision whichever verb carries it, so create
+ # gates on the field being present, like update does. Connecting a repository without one
+ # stays an editor's job: the row binds disabled at sync and routes no digest until then.
+ self._login_as_member()
+
+ response = self.client.post(self.url, {"repository": "PostHog/new", **extra}, format="json")
+
+ assert response.status_code == expected_status, response.content
+ assert StamphogRepoConfig.objects.unscoped().filter(repository="PostHog/new").exists() is (
+ expected_status == status.HTTP_201_CREATED
+ )
+
+ def test_member_cannot_soft_delete_a_config(self) -> None:
+ # The soft delete flips `enabled` behind a different verb, so gating only PATCH would leave
+ # the same switch reachable through DELETE.
+ config_id = self._create_config()
+ self._login_as_member()
+
+ response = self.client.delete(f"{self.url}{config_id}/")
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert StamphogRepoConfig.objects.unscoped().get(id=config_id).enabled is True
+
+ def test_member_granted_manager_can_change_a_review_gating_field(self) -> None:
+ # An admin must be able to hand the review switch to somebody through the normal access
+ # control settings, or the manager gate would be an admin-only hardcode.
+ config_id = self._create_config()
+ self._login_as_member(stamphog_level="manager")
+
+ response = self.client.patch(f"{self.url}{config_id}/", {"enabled": False}, format="json")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["enabled"] is False
+
+ @parameterized.expand(
+ [
+ ("granted_on_the_child", False, status.HTTP_403_FORBIDDEN),
+ ("granted_on_the_parent", True, status.HTTP_200_OK),
+ ]
+ )
+ def test_editor_grant_is_read_on_the_team_that_owns_the_rows(
+ self, _name: str, grant_on_parent: bool, expected_status: int
+ ) -> None:
+ # Same canonicalization as the manager case, one level down: the digest toggle needs editor,
+ # and the level that counts is the one on the team the rows live under, not the URL team.
+ config_id = self._create_config()
+ env = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+ grant_team = self.team if grant_on_parent else env
+ member = self._login_as_member(stamphog_level="editor", grant_team=grant_team)
+ # "none" on the other team, so the request can only pass on the grant under test.
+ AccessControl.objects.create(
+ team=env if grant_on_parent else self.team,
+ resource="stamphog",
+ resource_id=None,
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{env.id}/stamphog/repo_configs/{config_id}/", {"digest_enabled": True}, format="json"
+ )
+
+ assert response.status_code == expected_status, response.content
+
+ def test_child_project_denial_still_blocks_the_request(self) -> None:
+ # The viewset anchors user_access_control to the parent, so AccessControlPermission can no
+ # longer see the child's own project rules. Somebody the child environment denies must still
+ # be refused, or canonicalizing the resource check would have opened the environment up.
+ config_id = self._create_config()
+ env = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+ member = self._login_as_member(stamphog_level="manager")
+ AccessControl.objects.create(
+ team=env,
+ resource="project",
+ resource_id=str(env.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(user=member, organization=self.organization),
+ )
+
+ response = self.client.patch(
+ f"/api/projects/{env.id}/stamphog/repo_configs/{config_id}/", {"enabled": False}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN, response.content
+ assert StamphogRepoConfig.objects.unscoped().get(id=config_id).enabled is True
+
+ @parameterized.expand(
+ [
+ ("granted_on_the_child", False, status.HTTP_403_FORBIDDEN),
+ ("granted_on_the_parent", True, status.HTTP_200_OK),
+ ]
+ )
+ def test_manager_grant_is_read_on_the_team_that_owns_the_rows(
+ self, _name: str, grant_on_parent: bool, expected_status: int
+ ) -> None:
+ # stamphog rows canonicalize to the parent team, so the manager check must read the parent
+ # too. Reading the URL team would let a grant on a child environment alone rewrite the
+ # parent's review settings through the child's URL.
+ config_id = self._create_config()
+ env = Team.objects.create(organization=self.organization, parent_team=self.team, name="env")
+ self._login_as_member(stamphog_level="manager", grant_team=self.team if grant_on_parent else env)
+
+ response = self.client.patch(
+ f"/api/projects/{env.id}/stamphog/repo_configs/{config_id}/", {"enabled": False}, format="json"
+ )
+
+ assert response.status_code == expected_status, response.content
+ assert StamphogRepoConfig.objects.unscoped().get(id=config_id).enabled == (not grant_on_parent)
+
+ @parameterized.expand([("admin", True, "manager"), ("member", False, "editor")])
+ def test_user_access_level_rides_on_the_repo_config(self, _name: str, as_admin: bool, expected: str) -> None:
+ # The scene disables the review controls off this field. Reading it from the app context
+ # instead would answer for the URL environment while the backend checks the parent, so the
+ # controls and the API would disagree through a child environment's URL.
+ config_id = self._create_config()
+ if not as_admin:
+ self._login_as_member()
+
+ response = self.client.get(f"{self.url}{config_id}/")
+
+ assert response.status_code == status.HTTP_200_OK, response.content
+ assert response.json()["user_access_level"] == expected
def test_create_ignores_client_supplied_installation_id(self) -> None:
# installation_id is read-only: a manual create must not let a caller claim an installation
@@ -450,6 +641,9 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert response.json()["app_not_installed"] is False
synced = sorted(row["repository"] for row in response.json()["synced"])
assert synced == ["PostHog/other", "PostHog/posthog"]
+ # The scene disables the review controls off this field, and it renders these rows straight
+ # from the sync response. A null here would leave every control disabled right after connecting.
+ assert {row["user_access_level"] for row in response.json()["synced"]} == {"editor"}
bound = StamphogRepoConfig.objects.unscoped().filter(team_id=self.team.id, installation_id="42")
assert bound.count() == 2
# Bind disabled: an install can surface hundreds of repos, so none starts reviewing until toggled.
@@ -476,9 +670,17 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
# team later syncs the verified installation, that row must be adopted (its installation stamped)
# rather than reported skipped and left unbound forever — but adopted DISABLED: the placeholder's
# flags were set by someone who never proved GitHub access, so a member could otherwise pre-arm
- # enabled=True for a private repo and have reviews start the moment a teammate installs.
+ # enabled=True for a private repo and have reviews start the moment a teammate installs. The
+ # review policy resets for the same reason: label mode pointed at a label nobody uses would
+ # go live, reviewing nothing, the moment a manager turns the row on.
manual = StamphogRepoConfig.objects.unscoped().create(
- team_id=self.team.id, repository="PostHog/posthog", installation_id="", enabled=True, digest_enabled=True
+ team_id=self.team.id,
+ repository="PostHog/posthog",
+ installation_id="",
+ enabled=True,
+ digest_enabled=True,
+ review_mode=ReviewMode.LABEL,
+ trigger_label="nobody-uses-this",
)
response = self.client.post(
self.url, {"installation_id": "42", "code": "oauth-code", "state": self.state}, format="json"
@@ -492,6 +694,8 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
assert manual.connected_by_user_id == self.user.id
assert manual.enabled is False
assert manual.digest_enabled is False
+ assert manual.review_mode == ReviewMode.ALL
+ assert manual.trigger_label == StamphogRepoConfig._meta.get_field("trigger_label").get_default()
@patch(f"{_GITHUB_FACADE}.list_user_accessible_repositories", return_value=["PostHog/posthog"])
@patch(f"{_VIEWS}.user_can_access_installation", return_value=True)
@@ -506,6 +710,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
repository="PostHog/posthog",
installation_id="41",
enabled=True,
+ review_mode=ReviewMode.LABEL,
connected_by_user_id=previous_connector_id,
)
response = self.client.post(
@@ -517,6 +722,7 @@ class TestSyncInstallationAPI(StamphogTeamScopedTestMixin, APIBaseTest):
stale.refresh_from_db()
assert stale.installation_id == "42"
assert stale.enabled is True # settings survive the rebind
+ assert stale.review_mode == ReviewMode.LABEL # including the review policy
assert stale.connected_by_user_id == self.user.id
# The restamp reads its before-value from the locked row, so the log names who held the
# connection before this sync took it over.
diff --git a/products/stamphog/backend/tests/test_digest.py b/products/stamphog/backend/tests/test_digest.py
index acb7613bdbe3..bdc3c15a44c3 100644
--- a/products/stamphog/backend/tests/test_digest.py
+++ b/products/stamphog/backend/tests/test_digest.py
@@ -24,6 +24,7 @@ from products.stamphog.backend.logic.channel_resolution import (
RoutingContext,
RoutingUnavailable,
SlackChannel,
+ _candidate_repo_configs,
)
from products.stamphog.backend.logic.digest import (
_HEADLINE_MAX_RETRIES,
@@ -450,6 +451,25 @@ def test_an_unreadable_registry_posts_nothing(team) -> None:
assert PullRequestAudience.objects.filter(digest_run__isnull=True).count() == 2
[email protected]_db(databases=PRODUCT_DATABASES)
+def test_a_blank_installation_placeholder_is_not_a_routing_candidate(team) -> None:
+ # A repo created through the API carries a blank installation and defaults to enabled, so it
+ # used to join the candidates. It can fetch no routing file, and every candidate is read, so the
+ # failed fetch raised RoutingUnavailable and silenced the whole team's digest. This does not
+ # relax that rule: a repo that was readable and broke still stops the run. A blank installation
+ # was never readable, resolves no webhook, and so reports no merges either.
+ repo_config = _seed_prs(team.id, pr_count=1)
+ with team_scope(team.id):
+ placeholder = StamphogRepoConfig.objects.for_team(team.id).create(
+ team_id=team.id, repository="acme/placeholder", installation_id="", enabled=True
+ )
+
+ candidates = _candidate_repo_configs(team.id)
+
+ assert [config.id for config in candidates] == [repo_config.id]
+ assert placeholder.id not in {config.id for config in candidates}
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
def test_claim_is_capped_per_run_and_backlog_drains_across_runs(team) -> None:
# An unbounded claim grows the LLM prompt and the Slack payload with the merge-burst size, and a
diff --git a/products/stamphog/frontend/generated/api.schemas.ts b/products/stamphog/frontend/generated/api.schemas.ts
index 7134811d6435..1cbdf97e5f9a 100644
--- a/products/stamphog/frontend/generated/api.schemas.ts
+++ b/products/stamphog/frontend/generated/api.schemas.ts
@@ -154,6 +154,11 @@ export interface StamphogRepoConfigApi {
readonly review_mode: ReviewModeEnumApi
/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */
trigger_label?: string
+ /**
+ * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'manager' is required to change enabled, review_mode, or trigger_label.
+ * @nullable
+ */
+ readonly user_access_level: string | null
readonly created_at: string
readonly updated_at: string
}
diff --git a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
index 9b2f5de992e0..0869ec354766 100644
--- a/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
+++ b/products/stamphog/frontend/scenes/StamphogScene/StamphogScene.tsx
@@ -5,16 +5,29 @@ import { LemonBanner, LemonButton, LemonInput, LemonSelect, LemonSwitch, LemonTa
import { TZLabel } from 'lib/components/TZLabel'
import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { getAccessControlDisabledReason, toAccessControlLevel } from 'lib/utils/accessControlUtils'
import { SceneExport } from 'scenes/sceneTypes'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { StamphogTabs } from '../../components/StamphogTabs'
import { ReviewModeEnumApi, type StamphogRepoConfigApi } from '../../generated/api.schemas'
import { REVIEW_MODE_LABELS } from '../../reviewModeLabels'
import { stamphogSceneLogic } from './stamphogSceneLogic'
+// Whether a repository is reviewed at all is a manager decision. The digest only changes who hears
+// about the work, and connecting a repository starts no review on its own, so both stay at editor.
+//
+// The level comes from the API rather than the app context, because the app context answers for the
+// environment in the URL while these rows belong to its parent project. Undefined when no repository
+// has loaded yet, which sends the check back to the app context.
+const managerDisabledReason = (level: AccessControlLevel | undefined): string | null =>
+ getAccessControlDisabledReason(AccessControlResourceType.Stamphog, AccessControlLevel.Manager, level)
+const editorDisabledReason = (level: AccessControlLevel | undefined): string | null =>
+ getAccessControlDisabledReason(AccessControlResourceType.Stamphog, AccessControlLevel.Editor, level)
+
export const scene: SceneExport = {
component: StamphogScene,
logic: stamphogSceneLogic,
@@ -23,7 +36,7 @@ export const scene: SceneExport = {
function ConnectRepositoryButton(): JSX.Element {
// Authorize-first: the connect button opens the OAuth authorize URL. An already-installed user gets a
// silent instant redirect back, so it never dead-ends on GitHub's "update installation" screen.
- const { authorizeUrl, installInfoLoading } = useValues(stamphogSceneLogic)
+ const { authorizeUrl, installInfoLoading, stamphogAccessLevel } = useValues(stamphogSceneLogic)
return (
<LemonButton
type="primary"
@@ -31,11 +44,12 @@ function ConnectRepositoryButton(): JSX.Element {
to={authorizeUrl || undefined}
disableClientSideRouting
disabledReason={
- installInfoLoading
+ editorDisabledReason(stamphogAccessLevel) ??
+ (installInfoLoading
? 'Loading install details'
: authorizeUrl
? undefined
- : 'GitHub App not configured yet'
+ : 'GitHub App not configured yet')
}
>
Connect a repository
@@ -120,6 +134,8 @@ function SyncedBanner(): JSX.Element | null {
function ReviewModeCell({ repo, updating }: { repo: StamphogRepoConfigApi; updating: boolean }): JSX.Element {
const { setReviewMode, setTriggerLabel } = useActions(stamphogSceneLogic)
+ const disabledReason =
+ managerDisabledReason(toAccessControlLevel(repo.user_access_level)) ?? (updating ? 'Updating' : undefined)
const saveTriggerLabel = (value: string): void => {
const trimmed = value.trim()
@@ -135,7 +151,7 @@ function ReviewModeCell({ repo, updating }: { repo: StamphogRepoConfigApi; updat
<LemonSelect
size="small"
value={repo.review_mode ?? ReviewModeEnumApi.All}
- disabledReason={updating ? 'Updating' : undefined}
+ disabledReason={disabledReason}
onChange={(mode) => setReviewMode(repo.id, mode)}
options={[
{ value: ReviewModeEnumApi.All, label: REVIEW_MODE_LABELS[ReviewModeEnumApi.All] },
@@ -151,7 +167,7 @@ function ReviewModeCell({ repo, updating }: { repo: StamphogRepoConfigApi; updat
className="w-40"
defaultValue={repo.trigger_label}
placeholder="Trigger label"
- disabled={updating}
+ disabledReason={disabledReason}
onBlur={(e) => saveTriggerLabel(e.currentTarget.value)}
onPressEnter={(e) => saveTriggerLabel(e.currentTarget.value)}
/>
@@ -177,7 +193,10 @@ function RepoConfigsTable(): JSX.Element {
render: (_, repo) => (
<LemonSwitch
checked={!!repo.enabled}
- disabledReason={updatingRepoIds.includes(repo.id) ? 'Updating' : undefined}
+ disabledReason={
+ managerDisabledReason(toAccessControlLevel(repo.user_access_level)) ??
+ (updatingRepoIds.includes(repo.id) ? 'Updating' : undefined)
+ }
onChange={(checked) => setRepoEnabled(repo.id, checked)}
/>
),
@@ -193,7 +212,10 @@ function RepoConfigsTable(): JSX.Element {
render: (_, repo) => (
<LemonSwitch
checked={!!repo.digest_enabled}
- disabledReason={updatingRepoIds.includes(repo.id) ? 'Updating' : undefined}
+ disabledReason={
+ editorDisabledReason(toAccessControlLevel(repo.user_access_level)) ??
+ (updatingRepoIds.includes(repo.id) ? 'Updating' : undefined)
+ }
onChange={(checked) => setDigestEnabled(repo.id, checked)}
/>
),
diff --git a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts
index 4f40ee0bf0b5..116baa0204e6 100644
--- a/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts
+++ b/products/stamphog/frontend/scenes/StamphogScene/stamphogSceneLogic.ts
@@ -3,9 +3,12 @@ import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { toAccessControlLevel } from 'lib/utils/accessControlUtils'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { AccessControlLevel } from '~/types'
+
import {
stamphogRepoConfigsInstallInfoRetrieve,
stamphogRepoConfigsList,
@@ -40,6 +43,7 @@ export interface stamphogSceneLogicValues {
repoConfigsLoading: boolean
repoSearch: string
skippedRepos: readonly string[]
+ stamphogAccessLevel: AccessControlLevel | undefined
syncResult: StamphogSyncInstallationResponseApi | null
syncResultLoading: boolean
syncedRepos: readonly StamphogRepoConfigApi[]
@@ -168,6 +172,7 @@ export interface stamphogSceneLogicMeta {
) => readonly StamphogDiscoveredInstallationApi[]
syncedRepos: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly StamphogRepoConfigApi[]
skippedRepos: (syncResult: StamphogSyncInstallationResponseApi | null) => readonly string[]
+ stamphogAccessLevel: (repoConfigs: StamphogRepoConfigApi[]) => AccessControlLevel | undefined
filteredRepoConfigs: (repoConfigs: StamphogRepoConfigApi[], repoSearch: string) => StamphogRepoConfigApi[]
}
}
@@ -301,6 +306,13 @@ export const stamphogSceneLogic = kea<stamphogSceneLogicType>([
(s) => [s.syncResult],
(syncResult: StamphogSyncInstallationResponseApi | null): readonly string[] => syncResult?.skipped ?? [],
],
+ // Every row reports the same team-wide level, so the first one answers for the whole scene.
+ // Undefined until a repository loads, which sends the access checks back to the app context.
+ stamphogAccessLevel: [
+ (s) => [s.repoConfigs],
+ (repoConfigs: StamphogRepoConfigApi[]): AccessControlLevel | undefined =>
+ repoConfigs.length > 0 ? toAccessControlLevel(repoConfigs[0].user_access_level) : undefined,
+ ],
// A GitHub App install can surface hundreds of repos, so the table filters client-side by name.
filteredRepoConfigs: [
(s) => [s.repoConfigs, s.repoSearch],
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 074f0f47726d..68792fa1015b 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -57235,6 +57235,11 @@ export namespace Schemas {
readonly review_mode: ReviewModeEnum;
/** Pull request label that triggers a review when review_mode is 'label'. Defaults to 'stamphog'. */
trigger_label?: string;
+ /**
+ * The caller's access level on the stamphog resource, resolved for the team that owns this row. 'manager' is required to change enabled, review_mode, or trigger_label.
+ * @nullable
+ */
+ readonly user_access_level: string | null;
readonly created_at: string;
readonly updated_at: string;
}