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.

fix(reminders): accept OAuth tokens on the reminders API (#100148)

Yasen562cf4ab7e4a
diff --git a/products/reminders/backend/api/reminder.py b/products/reminders/backend/api/reminder.py
index f00c692516b7..235706e65953 100644
--- a/products/reminders/backend/api/reminder.py
+++ b/products/reminders/backend/api/reminder.py
@@ -7,25 +7,144 @@ from django.utils import timezone
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, viewsets
-from rest_framework.exceptions import ValidationError
+from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.permissions import IsAuthenticated
+from rest_framework.request import Request
from posthog.api.shared import UserBasicSerializer
-from posthog.auth import PersonalAPIKeyAuthentication, SessionAuthentication
-from posthog.models import Organization, Team, User
-from posthog.permissions import APIScopePermission
+from posthog.auth import (
+ IDJagAccessTokenAuthentication,
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ SessionAuthentication,
+)
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, Team, User
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.organization_caching import get_cached_organization_membership
+from posthog.permissions import (
+ ActiveOrganizationPermission,
+ APIScopePermission,
+ MCPAccessPermission,
+ VerifiedDomainEnforcementPermission,
+ get_authenticator_scoped_organization_ids,
+ get_authenticator_scoped_team_ids,
+ get_authenticator_user_credential,
+)
from posthog.user_permissions import UserPermissions
+from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.reminders.backend.constants import MAX_ACTIVE_REMINDERS_PER_USER, RESOURCE_MODELS, RESOURCE_TYPES
from products.reminders.backend.models import Reminder
from products.reminders.backend.scheduling import compute_next_fire_at, exceeds_daily_frequency_cap, resolve_timezone
+def token_scope_restrictions(request: Request) -> tuple[list[str] | None, list[int] | None]:
+ """APIScopePermission.check_team_and_org_permissions returns early for `scope_object = "user"`,
+ because /api/users/@me/ takes no organization or project. This viewset takes both, so it applies
+ the credential's restrictions itself.
+ """
+ authenticator = getattr(request, "successful_authenticator", None)
+ return (
+ get_authenticator_scoped_organization_ids(authenticator),
+ get_authenticator_scoped_team_ids(authenticator),
+ )
+
+
+# Tenant boundaries TeamAndOrgViewSetMixin appends in get_permissions, which a view may not remove.
+# MCPAccessPermission is write-only: it reads the action to decide, so including it in the read
+# filter would drop a row out of the queryset before the write path could refuse it, turning a
+# refusal into a 404.
+READ_BOUNDARY_PERMISSIONS = (
+ VerifiedDomainEnforcementPermission,
+ ActiveOrganizationPermission,
+)
+ORGANIZATION_BOUNDARY_PERMISSIONS = (*READ_BOUNDARY_PERMISSIONS, MCPAccessPermission)
+
+
+def personal_api_key_denial(request: Request, organization: Organization) -> str | None:
+ """The third leg of what check_team_and_org_permissions skips for `scope_object = "user"`.
+ Mirrors APIScopePermission._check_organization_personal_api_key_restrictions, which is private
+ and resolves its organization from routing attributes a root viewset does not have. The
+ platform check gates every method, so this one feeds the read filter as well as the writes.
+ """
+ credential = get_authenticator_user_credential(getattr(request, "successful_authenticator", None))
+ if not isinstance(credential, PersonalAPIKey):
+ return None
+ if not organization.is_feature_available(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS):
+ return None
+ membership = get_cached_organization_membership(organization.id, cast(User, request.user))
+ if membership is None:
+ return None
+ if not organization.members_can_use_personal_api_keys and membership.level < OrganizationMembership.Level.ADMIN:
+ return (
+ f"Organization '{organization.name}' does not allow using personal API keys. "
+ f"Contact an admin to enable personal API keys for this organization."
+ )
+ return None
+
+
+def deny_restricted_personal_api_key(request: Request, organization: Organization) -> None:
+ denial = personal_api_key_denial(request, organization)
+ if denial is not None:
+ raise PermissionDenied(denial)
+
+
+def readable_organization_ids(view: viewsets.ModelViewSet) -> list[Any]:
+ """Organizations this request may read reminders from.
+
+ A reminder row outlives the access that created it: the writer can lose membership, and the
+ organization can be deactivated, start enforcing verified domains, or stop allowing personal
+ API keys. Reads run the same boundaries as writes, or a row stays readable once its access is
+ gone. A refused organization drops out of the list rather than failing the whole request,
+ because the caller may hold reminders in several.
+ """
+ user = cast(User, view.request.user)
+ memberships = UserPermissions(user).organization_memberships
+ organizations = Organization.objects.filter(id__in=list(memberships.keys()))
+ return [
+ organization.id
+ for organization in organizations
+ if organization_boundary_denial(view, organization, READ_BOUNDARY_PERMISSIONS) is None
+ ]
+
+
+def organization_boundary_denial(
+ view: viewsets.ModelViewSet,
+ organization: Organization,
+ permission_classes: tuple[type, ...] = ORGANIZATION_BOUNDARY_PERMISSIONS,
+) -> str | None:
+ """The first boundary that refuses this organization, or None when all of them admit it.
+
+ Each class either returns False or raises, depending on the class, so both are collected here.
+ Which ones apply is left to the classes: ActiveOrganizationPermission exempts session callers,
+ and MCPAccessPermission admits every read.
+ """
+ for permission_class in permission_classes:
+ permission = permission_class()
+ try:
+ if not permission.has_object_permission(view.request, view, organization):
+ return str(getattr(permission, "message", "You cannot reach this organization."))
+ except PermissionDenied as denial:
+ return str(denial.detail)
+ return personal_api_key_denial(view.request, organization)
+
+
+def enforce_organization_boundaries(view: viewsets.ModelViewSet, organization: Organization) -> None:
+ """Each boundary resolves its target from routing attributes a root viewset does not have, so
+ the mixin's chain would fall back to the user's current organization, which is a UI preference.
+ Hand each one the organization the request actually acts on instead.
+ """
+ denial = organization_boundary_denial(view, organization)
+ if denial is not None:
+ raise PermissionDenied(denial)
+
+
class ReminderSerializer(serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
- # User-scoped endpoint: the user picks the org/team from their own memberships and
- # _validate_membership enforces access — there is no single org/team in request context
- # for the scoped PK fields to derive from, so suppress the IDOR scoping rule here.
+ # User-scoped endpoint: no single org/team is in request context for the scoped PK fields to
+ # derive from, so suppress the IDOR scoping rule. __init__ narrows both querysets to the
+ # caller's own reach instead.
organization = serializers.PrimaryKeyRelatedField( # nosemgrep: unscoped-primary-key-related-field
queryset=Organization.objects.all(),
help_text="ID of the organization this reminder belongs to. You must be a member of it.",
@@ -40,6 +159,26 @@ class ReminderSerializer(serializers.ModelSerializer):
),
)
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ request = self.context.get("request")
+ if request is None or not isinstance(request.user, User):
+ return
+ # Resolve both relations against the caller's reach, so an id outside it fails as
+ # "does not exist" like an unallocated one. Judging reach after resolution instead tells
+ # the caller which ids exist, which maps allocated projects across other tenants.
+ permissions = UserPermissions(cast(User, request.user))
+ organization_ids = list(permissions.organization_memberships.keys())
+ scoped_organizations, scoped_teams = token_scope_restrictions(request)
+ if scoped_organizations is not None:
+ organization_ids = [id for id in organization_ids if str(id) in scoped_organizations]
+ organization_field = cast(serializers.PrimaryKeyRelatedField, self.fields["organization"])
+ organization_field.queryset = Organization.objects.filter(id__in=organization_ids)
+ teams = Team.objects.filter(organization_id__in=organization_ids)
+ if scoped_teams is not None:
+ teams = teams.filter(id__in=scoped_teams)
+ cast(serializers.PrimaryKeyRelatedField, self.fields["team"]).queryset = teams
+
class Meta:
model = Reminder
fields = [
@@ -58,6 +197,7 @@ class ReminderSerializer(serializers.ModelSerializer):
"next_fire_at",
"last_fired_at",
"status",
+ "deleted",
"created_by",
"created_at",
"updated_at",
@@ -125,6 +265,25 @@ class ReminderSerializer(serializers.ModelSerializer):
if permissions.team(team).effective_membership_level is None:
raise ValidationError("You do not have access to this team.")
+ request = self.context["request"]
+ scoped_organizations, scoped_teams = token_scope_restrictions(request)
+ if scoped_organizations is not None and str(organization.id) not in scoped_organizations:
+ raise PermissionDenied(f"This credential has no access to organization ID {organization.id}.")
+ if scoped_teams is not None:
+ # RootTeamMixin.save stores the row under the parent project, so judge the team the
+ # row lands on. A credential scoped to a child environment does not reach that parent.
+ stored_team_id = (team.parent_team_id or team.id) if team is not None else None
+ if stored_team_id is None or stored_team_id not in scoped_teams:
+ raise PermissionDenied("This credential is restricted to specific projects.")
+
+ view = self.context["view"]
+ enforce_organization_boundaries(view, organization)
+ # A PATCH may re-point `organization`. The row's current organization caps the write too,
+ # or a move out of a capped organization would escape that organization's own policy.
+ current_organization = getattr(self.instance, "organization", None)
+ if current_organization is not None and current_organization.id != organization.id:
+ enforce_organization_boundaries(view, current_organization)
+
def _validate_resource(self, attrs: dict[str, Any], team: Team | None) -> None:
instance = self.instance
resource_type = attrs.get("resource_type", getattr(instance, "resource_type", None))
@@ -141,7 +300,14 @@ class ReminderSerializer(serializers.ModelSerializer):
raise ValidationError(f"Unknown resource_type: {resource_type}")
model, lookup_field, _ = RESOURCE_MODELS[resource_type]
- if not model._default_manager.filter(team=team, **{lookup_field: resource_id}).exists():
+ resource = model._default_manager.filter(team=team, **{lookup_field: resource_id}).first()
+ if resource is None:
+ raise ValidationError(f"No {resource_type} with id {resource_id} in this project.")
+
+ # Membership in the project is not access to every object in it. Report an object the
+ # caller cannot view as missing, so the message does not confirm that it exists.
+ user = cast(User, self.context["request"].user)
+ if not UserAccessControl(user=user, team=team).check_access_level_for_object(resource, "viewer"):
raise ValidationError(f"No {resource_type} with id {resource_id} in this project.")
def _validate_active_cap(self) -> None:
@@ -229,16 +395,34 @@ class ReminderViewSet(viewsets.ModelViewSet):
scope_object = "user"
serializer_class = ReminderSerializer
permission_classes = [IsAuthenticated, APIScopePermission]
- authentication_classes = [PersonalAPIKeyAuthentication, SessionAuthentication]
+ # Root-level viewset, so TeamAndOrgViewSetMixin adds no authenticators and every accepted
+ # class must be listed here. PersonalAPIKeyAuthentication returns None for a `pha_` OAuth
+ # token, so without OAuthAccessTokenAuthentication an OAuth call gets a 401.
+ # Session last: DRF takes the first authenticator that returns a user, so a request carrying
+ # both a cookie and a bearer token must resolve as the token, or the token's reach goes unchecked.
+ authentication_classes = [
+ IDJagAccessTokenAuthentication,
+ OAuthAccessTokenAuthentication,
+ PersonalAPIKeyAuthentication,
+ SessionAuthentication,
+ ]
queryset = Reminder.objects.none()
def get_queryset(self) -> QuerySet[Reminder]:
- return (
+ queryset = (
Reminder.objects.filter(created_by=cast(User, self.request.user), deleted=False)
.select_related("created_by", "team", "organization")
.order_by("-created_at")
)
+ queryset = queryset.filter(organization_id__in=readable_organization_ids(self))
+ scoped_organizations, scoped_teams = token_scope_restrictions(self.request)
+ if scoped_organizations is not None:
+ queryset = queryset.filter(organization_id__in=scoped_organizations)
+ if scoped_teams is not None:
+ queryset = queryset.filter(team_id__in=scoped_teams)
+ return queryset
def perform_destroy(self, instance: Reminder) -> None:
+ enforce_organization_boundaries(self, instance.organization)
instance.deleted = True
instance.save(update_fields=["deleted"])
diff --git a/products/reminders/backend/test/test_api.py b/products/reminders/backend/test/test_api.py
new file mode 100644
index 000000000000..57521cd389c0
--- /dev/null
+++ b/products/reminders/backend/test/test_api.py
@@ -0,0 +1,417 @@
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.auth import MCP_USER_AGENT_MARKER
+from posthog.constants import AvailableFeature
+from posthog.models import Organization, OrganizationMembership, Team
+from posthog.models.oauth import OAuthAccessToken, OAuthApplication
+from posthog.models.organization_domain import OrganizationDomain
+from posthog.models.personal_api_key import PersonalAPIKey, hash_key_value
+from posthog.models.utils import generate_random_token_personal
+
+from products.access_control.backend.models.access_control import AccessControl
+from products.dashboards.backend.models.dashboard import Dashboard
+from products.reminders.backend.models import Reminder
+
+
+class TestReminderAPI(APIBaseTest):
+ def _authenticate_with_oauth(
+ self,
+ scopes: str,
+ scoped_teams: list[int] | None = None,
+ scoped_organizations: list[str] | None = None,
+ ) -> None:
+ application = OAuthApplication.objects.create(
+ name="Reminders MCP",
+ client_id="reminders-test-client",
+ client_type=OAuthApplication.CLIENT_CONFIDENTIAL,
+ authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
+ redirect_uris="https://example.com/callback",
+ algorithm="RS256",
+ organization=self.organization,
+ user=self.user,
+ )
+ token = OAuthAccessToken.objects.create(
+ user=self.user,
+ application=application,
+ token="pha_reminders_test",
+ scope=scopes,
+ expires=timezone.now() + timedelta(hours=1),
+ scoped_teams=scoped_teams if scoped_teams is not None else [self.team.id],
+ scoped_organizations=scoped_organizations or [],
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.token}")
+
+ def _authenticate_with_personal_api_key(self, scopes: list[str]) -> None:
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="reminders",
+ user=self.user,
+ secure_value=hash_key_value(value),
+ scopes=scopes,
+ )
+ self.client.logout()
+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {value}")
+
+ @parameterized.expand(
+ [
+ ("oauth_token",),
+ ("personal_api_key",),
+ ("session",),
+ ]
+ )
+ def test_list_reminders_accepts_every_supported_credential(self, credential: str) -> None:
+ fire_at = timezone.now() + timedelta(days=1)
+ Reminder.objects.create(
+ organization=self.organization,
+ team=self.team,
+ created_by=self.user,
+ title="Check the funnel",
+ scheduled_at=fire_at,
+ next_fire_at=fire_at,
+ )
+ if credential == "oauth_token":
+ self._authenticate_with_oauth("user:read")
+ elif credential == "personal_api_key":
+ self._authenticate_with_personal_api_key(["user:read"])
+
+ response = self.client.get("/api/reminders/")
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(len(response.json()["results"]), 1)
+
+ def test_create_reminder_with_oauth_token(self) -> None:
+ self._authenticate_with_oauth("user:read user:write")
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "team": self.team.id,
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ "timezone": "UTC",
+ },
+ )
+
+ self.assertEqual(response.status_code, 201, response.content)
+ self.assertEqual(Reminder.objects.filter(created_by=self.user).count(), 1)
+
+ def test_create_reminder_is_rejected_without_the_write_scope(self) -> None:
+ self._authenticate_with_oauth("user:read")
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ },
+ )
+
+ self.assertEqual(response.status_code, 403, response.content)
+ self.assertEqual(Reminder.objects.count(), 0)
+
+ @parameterized.expand(
+ [
+ ("scoped_to_another_project",),
+ ("scoped_to_another_organization",),
+ ]
+ )
+ def test_create_reminder_rejects_a_target_outside_the_credential_reach(self, restriction: str) -> None:
+ other_organization, _, other_team = Organization.objects.bootstrap(self.user)
+ if restriction == "scoped_to_another_project":
+ self._authenticate_with_oauth("user:write", scoped_teams=[other_team.id])
+ else:
+ self._authenticate_with_oauth("user:write", scoped_organizations=[str(other_organization.id)])
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "team": self.team.id,
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ },
+ )
+
+ # Rejected at field resolution, with the same error an unallocated id gets, so the
+ # response cannot be used to map which projects exist.
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertIn("does not exist", response.content.decode())
+ self.assertEqual(Reminder.objects.count(), 0)
+
+ def test_list_reminders_hides_a_project_outside_the_credential_reach(self) -> None:
+ _, _, other_team = Organization.objects.bootstrap(self.user)
+ fire_at = timezone.now() + timedelta(days=1)
+ for team in (self.team, other_team):
+ Reminder.objects.create(
+ organization=team.organization,
+ team=team,
+ created_by=self.user,
+ title="Check the funnel",
+ scheduled_at=fire_at,
+ next_fire_at=fire_at,
+ )
+ self._authenticate_with_oauth("user:read", scoped_teams=[self.team.id])
+
+ response = self.client.get("/api/reminders/")
+
+ self.assertEqual(response.status_code, 200, response.content)
+ returned_teams = [result["team"] for result in response.json()["results"]]
+ self.assertEqual(returned_teams, [self.team.id])
+
+ def _restrict_organization_to_read_only_mcp(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS, "name": "Security settings"}
+ ]
+ self.organization.read_only_mcp_access = True
+ self.organization.save(update_fields=["available_product_features", "read_only_mcp_access"])
+
+ def test_create_reminder_over_mcp_is_denied_when_the_organization_is_read_only(self) -> None:
+ self._restrict_organization_to_read_only_mcp()
+ self._authenticate_with_oauth("user:write")
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "team": self.team.id,
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ },
+ HTTP_USER_AGENT=MCP_USER_AGENT_MARKER,
+ )
+
+ self.assertEqual(response.status_code, 403, response.content)
+ self.assertEqual(Reminder.objects.count(), 0)
+
+ def test_delete_reminder_over_mcp_is_denied_when_the_organization_is_read_only(self) -> None:
+ fire_at = timezone.now() + timedelta(days=1)
+ reminder = Reminder.objects.create(
+ organization=self.organization,
+ team=self.team,
+ created_by=self.user,
+ title="Check the funnel",
+ scheduled_at=fire_at,
+ next_fire_at=fire_at,
+ )
+ self._restrict_organization_to_read_only_mcp()
+ self._authenticate_with_oauth("user:write")
+
+ response = self.client.delete(f"/api/reminders/{reminder.id}/", HTTP_USER_AGENT=MCP_USER_AGENT_MARKER)
+
+ self.assertEqual(response.status_code, 403, response.content)
+ reminder.refresh_from_db()
+ self.assertFalse(reminder.deleted)
+
+ def test_a_session_cookie_does_not_outrank_a_bearer_token(self) -> None:
+ _, _, other_team = Organization.objects.bootstrap(self.user)
+ fire_at = timezone.now() + timedelta(days=1)
+ Reminder.objects.create(
+ organization=other_team.organization,
+ team=other_team,
+ created_by=self.user,
+ title="Check the funnel",
+ scheduled_at=fire_at,
+ next_fire_at=fire_at,
+ )
+ self._authenticate_with_oauth("user:read", scoped_teams=[self.team.id])
+ self.client.force_login(self.user)
+
+ response = self.client.get("/api/reminders/")
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["results"], [])
+
+ def _make_reminder(self, team: Team | None = None) -> Reminder:
+ team = team or self.team
+ fire_at = timezone.now() + timedelta(days=1)
+ return Reminder.objects.create(
+ organization=team.organization,
+ team=team,
+ created_by=self.user,
+ title="Check the funnel",
+ scheduled_at=fire_at,
+ next_fire_at=fire_at,
+ )
+
+ def test_the_soft_delete_patch_the_mcp_tool_sends_actually_deletes(self) -> None:
+ reminder = self._make_reminder()
+ self._authenticate_with_oauth("user:write")
+
+ response = self.client.patch(
+ f"/api/reminders/{reminder.id}/", {"deleted": True}, content_type="application/json"
+ )
+
+ self.assertEqual(response.status_code, 200, response.content)
+ reminder.refresh_from_db()
+ self.assertTrue(reminder.deleted)
+
+ def test_update_cannot_move_a_reminder_out_of_a_capped_organization(self) -> None:
+ reminder = self._make_reminder()
+ _, _, other_team = Organization.objects.bootstrap(self.user)
+ self._restrict_organization_to_read_only_mcp()
+ self._authenticate_with_oauth("user:write", scoped_teams=[self.team.id, other_team.id])
+
+ response = self.client.patch(
+ f"/api/reminders/{reminder.id}/",
+ {"organization": str(other_team.organization.id), "team": other_team.id},
+ content_type="application/json",
+ HTTP_USER_AGENT=MCP_USER_AGENT_MARKER,
+ )
+
+ self.assertEqual(response.status_code, 403, response.content)
+ reminder.refresh_from_db()
+ self.assertEqual(reminder.organization_id, self.organization.id)
+
+ def test_writes_are_denied_when_the_organization_is_deactivated(self) -> None:
+ self.organization.is_active = False
+ self.organization.save(update_fields=["is_active"])
+ self._authenticate_with_oauth("user:write")
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "team": self.team.id,
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ },
+ )
+
+ self.assertEqual(response.status_code, 403, response.content)
+ self.assertEqual(Reminder.objects.count(), 0)
+
+ def test_writes_are_denied_when_the_organization_disallows_personal_api_keys(self) -> None:
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS, "name": "Security settings"}
+ ]
+ self.organization.members_can_use_personal_api_keys = False
+ self.organization.save(update_fields=["available_product_features", "members_can_use_personal_api_keys"])
+ membership = self.organization.memberships.get(user=self.user)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save(update_fields=["level"])
+ self._authenticate_with_personal_api_key(["user:write"])
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "team": self.team.id,
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ },
+ )
+
+ self.assertEqual(response.status_code, 403, response.content)
+ self.assertEqual(Reminder.objects.count(), 0)
+
+ def test_a_child_environment_token_cannot_write_onto_the_parent_project(self) -> None:
+ child = Team.objects.create(
+ organization=self.organization, project=self.team.project, parent_team=self.team, name="staging"
+ )
+ self._authenticate_with_oauth("user:write", scoped_teams=[child.id])
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "team": child.id,
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ },
+ )
+
+ # RootTeamMixin.save would store this against the parent project, which the credential
+ # does not reach, so the reach check has to judge the team the row lands on.
+ self.assertEqual(response.status_code, 403, response.content)
+ self.assertEqual(Reminder.objects.count(), 0)
+
+ def test_list_hides_reminders_from_an_organization_the_user_left(self) -> None:
+ _, _, other_team = Organization.objects.bootstrap(self.user)
+ self._make_reminder(other_team)
+ other_team.organization.memberships.filter(user=self.user).delete()
+ self._authenticate_with_oauth("user:read", scoped_teams=[self.team.id, other_team.id])
+
+ response = self.client.get("/api/reminders/")
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_list_hides_reminders_from_a_deactivated_organization(self) -> None:
+ self._make_reminder()
+ self.organization.is_active = False
+ self.organization.save(update_fields=["is_active"])
+ self._authenticate_with_oauth("user:read")
+
+ response = self.client.get("/api/reminders/")
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_list_hides_reminders_when_the_organization_disallows_personal_api_keys(self) -> None:
+ self._make_reminder()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ORGANIZATION_SECURITY_SETTINGS, "name": "Security settings"}
+ ]
+ self.organization.members_can_use_personal_api_keys = False
+ self.organization.save(update_fields=["available_product_features", "members_can_use_personal_api_keys"])
+ membership = self.organization.memberships.get(user=self.user)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save(update_fields=["level"])
+ self._authenticate_with_personal_api_key(["user:read"])
+
+ response = self.client.get("/api/reminders/")
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_attaching_a_resource_the_caller_cannot_view_is_refused(self) -> None:
+ dashboard = Dashboard.objects.create(team=self.team, name="Revenue")
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": "Access control"}
+ ]
+ self.organization.save(update_fields=["available_product_features"])
+ AccessControl.objects.create(team=self.team, resource="dashboard", access_level="none")
+ membership = self.organization.memberships.get(user=self.user)
+ membership.level = OrganizationMembership.Level.MEMBER
+ membership.save(update_fields=["level"])
+ self._authenticate_with_oauth("user:write")
+
+ response = self.client.post(
+ "/api/reminders/",
+ {
+ "organization": str(self.organization.id),
+ "team": self.team.id,
+ "title": "Review the weekly numbers",
+ "recurrence_interval": "weekly",
+ "resource_type": "dashboard",
+ "resource_id": str(dashboard.pk),
+ },
+ )
+
+ self.assertEqual(response.status_code, 400, response.content)
+ # Same message an absent dashboard gets, so the refusal does not confirm it exists.
+ self.assertIn("No dashboard with id", response.content.decode())
+ self.assertEqual(Reminder.objects.count(), 0)
+
+ def test_list_hides_reminders_from_an_organization_enforcing_a_domain_the_user_is_outside(self) -> None:
+ self._make_reminder()
+ OrganizationDomain.objects.create(
+ organization=self.organization, domain="verified-example.com", verified_at=timezone.now()
+ )
+ self.organization.enforce_verified_domains = True
+ self.organization.save(update_fields=["enforce_verified_domains"])
+ self._authenticate_with_oauth("user:read")
+
+ response = self.client.get("/api/reminders/")
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["results"], [])
diff --git a/products/reminders/frontend/generated/api.schemas.ts b/products/reminders/frontend/generated/api.schemas.ts
index cf8da02bf9ab..3623b9170a1e 100644
--- a/products/reminders/frontend/generated/api.schemas.ts
+++ b/products/reminders/frontend/generated/api.schemas.ts
@@ -153,6 +153,7 @@ export interface ReminderApi {
/** @nullable */
readonly last_fired_at: string | null
readonly status: ReminderStatusEnumApi
+ deleted?: boolean
readonly created_by: UserBasicApi
readonly created_at: string
/** @nullable */
@@ -229,6 +230,7 @@ export interface PatchedReminderApi {
/** @nullable */
readonly last_fired_at?: string | null
readonly status?: ReminderStatusEnumApi
+ deleted?: boolean
readonly created_by?: UserBasicApi
readonly created_at?: string
/** @nullable */
diff --git a/products/reminders/frontend/generated/api.zod.ts b/products/reminders/frontend/generated/api.zod.ts
index 2591574e2b9c..508e9efae8de 100644
--- a/products/reminders/frontend/generated/api.zod.ts
+++ b/products/reminders/frontend/generated/api.zod.ts
@@ -78,6 +78,7 @@ export const RemindersCreateBody = /* @__PURE__ */ zod.object({
.datetime({ offset: true })
.nullish()
.describe('Optional: recurring reminders stop (status=completed) after this time.'),
+ deleted: zod.boolean().optional(),
})
export const remindersUpdateBodyTitleMax = 255
@@ -149,6 +150,7 @@ export const RemindersUpdateBody = /* @__PURE__ */ zod.object({
.datetime({ offset: true })
.nullish()
.describe('Optional: recurring reminders stop (status=completed) after this time.'),
+ deleted: zod.boolean().optional(),
})
export const remindersPartialUpdateBodyTitleMax = 255
@@ -224,4 +226,5 @@ export const RemindersPartialUpdateBody = /* @__PURE__ */ zod.object({
.datetime({ offset: true })
.nullish()
.describe('Optional: recurring reminders stop (status=completed) after this time.'),
+ deleted: zod.boolean().optional(),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f78b30288545..d5e7a9a50213 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -58207,6 +58207,7 @@ export namespace Schemas {
/** @nullable */
readonly last_fired_at: string | null;
readonly status: ReminderStatusEnum;
+ deleted?: boolean;
readonly created_by: UserBasic;
readonly created_at: string;
/** @nullable */
@@ -68969,6 +68970,7 @@ export namespace Schemas {
/** @nullable */
readonly last_fired_at?: string | null;
readonly status?: ReminderStatusEnum;
+ deleted?: boolean;
readonly created_by?: UserBasic;
readonly created_at?: string;
/** @nullable */
diff --git a/services/mcp/src/generated/reminders/api.ts b/services/mcp/src/generated/reminders/api.ts
index 2f48c4626af2..92d7f5183712 100644
--- a/services/mcp/src/generated/reminders/api.ts
+++ b/services/mcp/src/generated/reminders/api.ts
@@ -82,6 +82,7 @@ export const RemindersCreateBody = () => zod.object({
.datetime({ offset: true })
.nullish()
.describe('Optional: recurring reminders stop (status=completed) after this time.'),
+ deleted: zod.boolean().optional(),
})
export const RemindersRetrieveParams = () => zod.object({
@@ -165,6 +166,7 @@ export const RemindersPartialUpdateBody = () => zod.object({
.datetime({ offset: true })
.nullish()
.describe('Optional: recurring reminders stop (status=completed) after this time.'),
+ deleted: zod.boolean().optional(),
})
export const RemindersDestroyParams = () => zod.object({
diff --git a/services/mcp/src/tools/generated/reminders.ts b/services/mcp/src/tools/generated/reminders.ts
index a1c1f79689e6..4861539ed129 100644
--- a/services/mcp/src/tools/generated/reminders.ts
+++ b/services/mcp/src/tools/generated/reminders.ts
@@ -49,6 +49,9 @@ const reminderCreate = (): ToolBase<ReturnType<typeof ReminderCreateSchema>, Sch
if (params.end_date !== undefined) {
body['end_date'] = params.end_date
}
+ if (params.deleted !== undefined) {
+ body['deleted'] = params.deleted
+ }
const result = await context.api.request<Schemas.Reminder>({
method: 'POST',
path: `/api/reminders/`,
@@ -137,6 +140,9 @@ const reminderUpdate = (): ToolBase<ReturnType<typeof ReminderUpdateSchema>, Sch
if (params.end_date !== undefined) {
body['end_date'] = params.end_date
}
+ if (params.deleted !== undefined) {
+ body['deleted'] = params.deleted
+ }
const result = await context.api.request<Schemas.Reminder>({
method: 'PATCH',
path: `/api/reminders/${encodeURIComponent(String(params.id))}/`,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-create.json
index be5ccd9d4208..f3387ea2ef5d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-create.json
@@ -13,6 +13,9 @@
],
"description": "For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."
},
+ "deleted": {
+ "type": "boolean"
+ },
"end_date": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-update.json
index 1076218a9ddd..e62309a95674 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/reminder-update.json
@@ -13,6 +13,9 @@
],
"description": "For a recurring reminder: a 5-field cron expression (e.g. '0 9 * * 1' = Mondays 9am). May fire at most 4 times per day. Mutually exclusive with recurrence_interval."
},
+ "deleted": {
+ "type": "boolean"
+ },
"end_date": {
"anyOf": [
{
diff --git a/tach.toml b/tach.toml
index 6617eb6ae37a..dc79731021f7 100644
--- a/tach.toml
+++ b/tach.toml
@@ -732,6 +732,7 @@ layer = "modules"
path = "products.reminders"
depends_on = [
"posthog",
+ "products.access_control",
"products.dashboards",
"products.error_tracking",
"products.experiments",