: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
fix(flags): show flags across all compared projects in Projects grid (#65280)
Gustavo H. Strassburger4f903fd49a1a
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 479df1ae202a..cce2f069711d 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -177,6 +177,7 @@ import {MediaUploadResponse,NewEarlyAccessFeatureType,ObjectMediaPreview,+ OrganizationFeatureFlagKeysResponse,OrganizationFeatureFlags,OrganizationFeatureFlagsCopyBody,OrganizationMemberScopedApiKeysResponse,@@ -485,6 +486,10 @@ export class ApiRequest {.addPathComponent('copy_flags')}+ public organizationFeatureFlagKeys(orgId: OrganizationType['id']): ApiRequest {+ return this.organizations().addPathComponent(orgId).addPathComponent('feature_flags').addPathComponent('keys')+ }+// # Projectspublic projects(): ApiRequest {return this.addPathComponent('projects')@@ -2632,6 +2637,15 @@ const api = {): Promise<{ success: FeatureFlagType[]; failed: any }> {return await new ApiRequest().copyOrganizationFeatureFlags(orgId).create({ data })},+ async keys(+ orgId: OrganizationType['id'] = ApiConfig.getCurrentOrganizationId(),+ params: { team_ids: number[]; search?: string; limit?: number; offset?: number }+ ): Promise<OrganizationFeatureFlagKeysResponse> {+ return await new ApiRequest()+ .organizationFeatureFlagKeys(orgId)+ .withQueryString(toParams(params, true))+ .get()+ },},actions: {diff --git a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.test.tsx b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.test.tsxnew file mode 100644index 000000000000..a30f6499673d--- /dev/null+++ b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.test.tsx@@ -0,0 +1,130 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'++import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { OrganizationFeatureFlag, OrganizationFeatureFlagRow } from '~/types'++import { ProjectsGrid, cellStateFor } from './ProjectsGrid'++const CURRENT_TEAM_ID = 1+const OTHER_TEAM_ID = 2++function buildRow(overrides: Partial<OrganizationFeatureFlagRow> = {}): OrganizationFeatureFlagRow {+ return {+ id: 10,+ team_id: CURRENT_TEAM_ID,+ key: 'flag_key',+ name: 'Flag',+ active: true,+ filters: { groups: [] },+ ...overrides,+ }+}++function buildSibling(teamId: number): OrganizationFeatureFlag {+ return {+ flag_id: 99,+ team_id: teamId,+ created_by: null,+ created_at: '2024-01-01T00:00:00Z',+ filters: { groups: [] },+ active: true,+ }+}++describe('cellStateFor', () => {+ const accessible = new Set([CURRENT_TEAM_ID, OTHER_TEAM_ID])++ it('does not paint a cross-project representative into the current team column before siblings load', () => {+ // Regression guard for #63155: the row's representative lives in another project, so the+ // current team's cell must wait for siblings instead of rendering the other flag's data.+ const row = buildRow({ team_id: OTHER_TEAM_ID })++ const state = cellStateFor(row, CURRENT_TEAM_ID, CURRENT_TEAM_ID, accessible, undefined, false)++ expect(state.kind).toBe('loading')+ })++ it('renders the current team cell from the representative when it belongs to the current team', () => {+ const row = buildRow({ team_id: CURRENT_TEAM_ID })++ const state = cellStateFor(row, CURRENT_TEAM_ID, CURRENT_TEAM_ID, accessible, undefined, false)++ expect(state).toEqual({ kind: 'present', sibling: expect.objectContaining({ team_id: CURRENT_TEAM_ID }) })+ })++ it('renders from the matching sibling once siblings have loaded', () => {+ const row = buildRow({ team_id: CURRENT_TEAM_ID })+ const siblings = [buildSibling(OTHER_TEAM_ID)]++ const state = cellStateFor(row, OTHER_TEAM_ID, CURRENT_TEAM_ID, accessible, siblings, false)++ expect(state).toEqual({ kind: 'present', sibling: siblings[0] })+ })++ it('marks a flag missing in a project once siblings loaded without that team', () => {+ const row = buildRow({ team_id: CURRENT_TEAM_ID })++ const state = cellStateFor(row, OTHER_TEAM_ID, CURRENT_TEAM_ID, accessible, [], false)++ expect(state.kind).toBe('missing')+ })++ it('marks a project the user cannot access as no-access', () => {+ const row = buildRow({ team_id: CURRENT_TEAM_ID })++ const state = cellStateFor(row, OTHER_TEAM_ID, CURRENT_TEAM_ID, new Set([CURRENT_TEAM_ID]), [], false)++ expect(state.kind).toBe('no-access')+ })+})++describe('ProjectsGrid', () => {+ const FLAG_TEAM_ID = MOCK_TEAM_ID + 1 // a project other than the current one++ beforeAll(() => {+ // jsdom has no IntersectionObserver; the infinite-scroll sentinel effect needs it.+ global.IntersectionObserver = class {+ observe(): void {}+ unobserve(): void {}+ disconnect(): void {}+ } as unknown as typeof IntersectionObserver+ })++ beforeEach(() => {+ useMocks({+ get: {+ '/api/organizations/:org/feature_flags/keys/': {+ count: 1,+ next: null,+ previous: null,+ results: [+ {+ id: 42,+ team_id: FLAG_TEAM_ID,+ key: 'cross-project-flag',+ name: 'Cross Project Flag',+ active: true,+ filters: { groups: [] },+ },+ ],+ },+ '/api/organizations/:org/feature_flags/:key/': [],+ },+ })+ initKeaTests()+ })++ afterEach(() => cleanup())++ it('links each flag row to that flag in its own project', async () => {+ render(<ProjectsGrid />)++ const link = await screen.findByRole('link', { name: /Cross Project Flag/i })+ expect(link).toHaveAttribute('href', `/project/${FLAG_TEAM_ID}/feature_flags/42`)+ })+})diff --git a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsxindex 8bed5fe4873a..8f79f4187a76 100644--- a/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx+++ b/frontend/src/scenes/feature-flags/projects-grid/ProjectsGrid.tsx@@ -10,14 +10,14 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { SceneSection } from '~/layout/scenes/components/SceneSection'-import { FeatureFlagType, OrganizationFeatureFlag } from '~/types'+import { OrganizationFeatureFlag, OrganizationFeatureFlagRow } from '~/types'import { CellState, ProjectsGridCell } from './ProjectsGridCell'import { projectsGridLogic } from './projectsGridLogic'import { ProjectsGridToolbar } from './ProjectsGridToolbar'-function cellStateFor(- flag: FeatureFlagType,+export function cellStateFor(+ flag: OrganizationFeatureFlagRow,teamId: number,currentTeamId: number,accessibleTeamIds: Set<number>,@@ -29,18 +29,20 @@ function cellStateFor(return { kind: 'present', sibling: siblingForTeam }}- // Before siblings load, render the current team's cell from the flag directly- // (eval count unavailable until siblings arrive).- if (teamId === currentTeamId) {+ // Before siblings load, render the current team's cell directly from the row's representative+ // flag, but only when that representative actually belongs to the current team (eval count+ // unavailable until siblings arrive).+ if (teamId === currentTeamId && flag.team_id === currentTeamId) {return {kind: 'present',sibling: {flag_id: flag.id,team_id: teamId,- created_by: flag.created_by ?? null,filters: flag.filters,- created_at: flag.created_at ?? '',active: flag.active,+ // Not rendered by ProjectsGridCell; the row doesn't carry them to avoid a per-row join.+ created_by: null,+ created_at: '',},}}@@ -98,14 +100,14 @@ export function ProjectsGrid(): JSX.Element {const columnWidth = `${100 / (visibleColumns.length + 1)}%`- const columns: LemonTableColumns<FeatureFlagType> = [+ const columns: LemonTableColumns<OrganizationFeatureFlagRow> = [{title: 'Flag',key: 'flag',width: columnWidth,render: (_, flag) => (<LemonTableLink- to={urls.featureFlag(flag.id as number)}+ to={urls.project(flag.team_id, urls.featureFlag(flag.id))}title={flag.name || flag.key}description={flag.key}/>@@ -122,7 +124,7 @@ export function ProjectsGrid(): JSX.Element {),key: `project-${teamId}`,width: columnWidth,- render: (_: unknown, flag: FeatureFlagType) => (+ render: (_: unknown, flag: OrganizationFeatureFlagRow) => (<ProjectsGridCellstate={cellStateFor(flag,diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.tsindex 7a20ce8061be..59ae23524b4c 100644--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts@@ -1,3 +1,5 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'import { useMocks } from '~/mocks/jest'@@ -7,19 +9,25 @@ import { projectsGridLogic } from './projectsGridLogic'interface MockFlag {id: number+ team_id: numberkey: stringname: stringfilters: { groups: [] }active: boolean+ created_at: string+ created_by: null}function buildFlag(i: number): MockFlag {return {id: i,+ team_id: 1,key: `flag_${i}`,name: `Flag ${i}`,filters: { groups: [] },active: true,+ created_at: '2024-01-01T00:00:00Z',+ created_by: null,}}@@ -30,7 +38,7 @@ describe('projectsGridLogic', () => {beforeEach(() => {useMocks({get: {- '/api/projects/:team/feature_flags/': ({ request }) => {+ '/api/organizations/:org/feature_flags/keys/': ({ request }) => {const offset = Number(new URL(request.url).searchParams.get('offset') ?? 0)const count = 40const remaining = Math.max(0, count - offset)@@ -40,6 +48,7 @@ describe('projectsGridLogic', () => {{count,next: offset + pageSize < count ? 'next' : null,+ previous: null,results: Array.from({ length: pageSize }, (_, i) => buildFlag(offset + i + 1)),},]@@ -88,9 +97,10 @@ describe('projectsGridLogic', () => {useMocks({get: {- '/api/projects/:team/feature_flags/': {+ '/api/organizations/:org/feature_flags/keys/': {count: 3,next: null,+ previous: null,results: [buildFlag(1), buildFlag(2), buildFlag(3)],},'/api/organizations/:org/feature_flags/:key/': async ({ params }) => {@@ -133,7 +143,12 @@ describe('projectsGridLogic', () => {localStorage.clear()useMocks({get: {- '/api/projects/:team/feature_flags/': { count: 0, next: null, results: [] },+ '/api/organizations/:org/feature_flags/keys/': {+ count: 0,+ next: null,+ previous: null,+ results: [],+ },'/api/organizations/:org/feature_flags/:key/': [],},})@@ -177,5 +192,57 @@ describe('projectsGridLogic', () => {expect(logic.values.pickedTeamIds).toEqual([])expect(localStorage.getItem(`ff-projects-grid.picked-teams.${teamId}`)).toBeNull()})++ it('reloads rows when pickedTeamIds changes', async () => {+ logic = projectsGridLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => logic.actions.setPickedTeamIds([3, 4])).toDispatchActions([+ 'loadFlagsPage',+ 'loadFlagsPageSuccess',+ ])+ await expectLogic(logic, () => logic.actions.resetPickedTeamIds()).toDispatchActions([+ 'loadFlagsPage',+ 'loadFlagsPageSuccess',+ ])+ })+ })++ describe('afterMount hydration', () => {+ let keysCalls: number++ beforeEach(() => {+ localStorage.clear()+ keysCalls = 0+ useMocks({+ get: {+ '/api/organizations/:org/feature_flags/keys/': () => {+ keysCalls += 1+ return [200, { count: 0, next: null, previous: null, results: [] }]+ },+ '/api/organizations/:org/feature_flags/:key/': [],+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ if (logic.cache.mounted) {+ logic.unmount()+ }+ })++ it('loads rows exactly once on mount when picked teams are hydrated', async () => {+ localStorage.setItem(`ff-projects-grid.picked-teams.${MOCK_TEAM_ID}`, JSON.stringify([3, 4]))++ logic = projectsGridLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ // Hydrating via setPickedTeamIds triggers the load; the afterMount return prevents a second one.+ expect(logic.values.pickedTeamIds).toEqual([3, 4])+ expect(keysCalls).toBe(1)+ })})})diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.tsindex d82f7ffbddba..ec17de030b35 100644--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.ts@@ -3,12 +3,10 @@ import { loaders } from 'kea-loaders'import api from 'lib/api'import { getCurrentTeamId } from 'lib/utils/getAppContext'-import { toParams } from 'lib/utils/url'import { organizationLogic } from 'scenes/organizationLogic'-import { projectLogic } from 'scenes/projectLogic'import { teamLogic } from 'scenes/teamLogic'-import { FeatureFlagType, OrganizationFeatureFlag, OrganizationType } from '~/types'+import { OrganizationFeatureFlag, OrganizationFeatureFlagRow, OrganizationType } from '~/types'import type { projectsGridLogicType } from './projectsGridLogicType'@@ -17,9 +15,8 @@ export const PAGE_SIZE = 25export interface LoadFlagsResult {offset: numbersearch: string- count: numbernext: string | null- results: FeatureFlagType[]+ results: OrganizationFeatureFlagRow[]}const storageKey = (teamId: number): string => `ff-projects-grid.picked-teams.${teamId}`@@ -27,14 +24,7 @@ const storageKey = (teamId: number): string => `ff-projects-grid.picked-teams.${export const projectsGridLogic = kea<projectsGridLogicType>([path(['scenes', 'feature-flags', 'projects-grid', 'projectsGridLogic']),connect(() => ({- values: [- teamLogic,- ['currentTeamId'],- organizationLogic,- ['currentOrganization'],- projectLogic,- ['currentProjectId'],- ],+ values: [teamLogic, ['currentTeamId'], organizationLogic, ['currentOrganization']],})),actions({setSearch: (search: string) => ({ search }),@@ -52,11 +42,13 @@ export const projectsGridLogic = kea<projectsGridLogicType>([reducers({search: ['', { setSearch: (_, { search }) => search }],flags: [- [] as FeatureFlagType[],+ [] as OrganizationFeatureFlagRow[],{loadFlagsPageSuccess: (state, { flagsPage }: { flagsPage: LoadFlagsResult }) =>flagsPage.offset === 0 ? flagsPage.results : [...state, ...flagsPage.results],setSearch: () => [],+ setPickedTeamIds: () => [],+ resetPickedTeamIds: () => [],},],flagsOffset: [@@ -65,6 +57,8 @@ export const projectsGridLogic = kea<projectsGridLogicType>([loadFlagsPageSuccess: (_, { flagsPage }: { flagsPage: LoadFlagsResult }) =>flagsPage.offset + flagsPage.results.length,setSearch: () => 0,+ setPickedTeamIds: () => 0,+ resetPickedTeamIds: () => 0,},],flagsHasMore: [@@ -72,6 +66,8 @@ export const projectsGridLogic = kea<projectsGridLogicType>([{loadFlagsPageSuccess: (_, { flagsPage }: { flagsPage: LoadFlagsResult }) => flagsPage.next !== null,setSearch: () => true,+ setPickedTeamIds: () => true,+ resetPickedTeamIds: () => true,},],siblingsByFlagKey: [@@ -112,12 +108,20 @@ export const projectsGridLogic = kea<projectsGridLogicType>([flagsPage: [null as LoadFlagsResult | null,{- loadFlagsPage: async ({ offset, search }: { offset: number; search: string }) => {- const params = toParams({ limit: PAGE_SIZE, offset, search })- const response = await api.get<Omit<LoadFlagsResult, 'offset' | 'search'>>(- `api/projects/${values.currentProjectId}/feature_flags/?${params}`- )- return { offset, search, ...response }+ loadFlagsPage: async ({ offset, search }: { offset: number; search: string }, breakpoint) => {+ const orgId = values.currentOrganization?.id+ if (!orgId) {+ return { offset, search, next: null, results: [] }+ }+ const response = await api.organizationFeatureFlags.keys(orgId, {+ team_ids: values.visibleColumns,+ search,+ limit: PAGE_SIZE,+ offset,+ })+ // Abort if a newer load (e.g. from a project-picker change) superseded this one.+ breakpoint()+ return { offset, search, next: response.next, results: response.results }},},],@@ -160,9 +164,12 @@ export const projectsGridLogic = kea<projectsGridLogicType>([},setPickedTeamIds: ({ teamIds }) => {localStorage.setItem(storageKey(getCurrentTeamId()), JSON.stringify(teamIds))+ // Comparing more projects can surface flags that only exist in those projects, so reload rows.+ actions.loadFlagsPage({ offset: 0, search: values.search })},resetPickedTeamIds: () => {localStorage.removeItem(storageKey(getCurrentTeamId()))+ actions.loadFlagsPage({ offset: 0, search: values.search })},})),afterMount(({ actions }) => {@@ -171,7 +178,9 @@ export const projectsGridLogic = kea<projectsGridLogicType>([try {const parsed = JSON.parse(raw)if (Array.isArray(parsed) && parsed.every((x) => typeof x === 'number')) {+ // setPickedTeamIds triggers the initial row load with the hydrated projects.actions.setPickedTeamIds(parsed)+ return}} catch {// ignore malformed entrydiff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 58252a5d64c6..53455ec88d89 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -4262,6 +4262,25 @@ export interface OrganizationFeatureFlag {evaluations_7d?: number | null}+export interface OrganizationFeatureFlagRow {+ id: number+ team_id: number+ key: string+ name: string+ // active + filters power the instant first paint of the current team's cell and are free+ // (already on the row). created_by/created_at are omitted: the grid never renders them, and+ // serializing created_by would force a per-row join.+ active: boolean+ filters: FeatureFlagFilters+}++export interface OrganizationFeatureFlagKeysResponse {+ count: number+ next: string | null+ previous: string | null+ results: OrganizationFeatureFlagRow[]+}+export interface OrganizationFeatureFlagsCopyBody {feature_flag_key: FeatureFlagType['key']from_project: TeamType['id']diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.pyindex 249a115acb69..548e84bbaa74 100644--- a/products/feature_flags/backend/api/organization_feature_flag.py+++ b/products/feature_flags/backend/api/organization_feature_flag.py@@ -1,24 +1,31 @@import copyfrom typing import cast+from django.db.models import Case, IntegerField, Q, QuerySet, Value, When+import structlogfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameterfrom rest_framework import mixins, serializers, status, viewsetsfrom rest_framework.response import Response+from rest_framework.utils.urls import replace_query_paramfrom posthog.api.cohort import CohortSerializerfrom posthog.api.documentation import _FallbackSerializer, extend_schemafrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.utils import action-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.models.filters.filter import Filter+from posthog.rbac.user_access_control import UserAccessControlfrom posthog.user_permissions import UserPermissionsfrom products.cohorts.backend.models.cohort import Cohort, CohortOrEmptyfrom products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer-from products.feature_flags.backend.encrypted_flag_payloads import get_decrypted_flag_payloads+from products.feature_flags.backend.encrypted_flag_payloads import (+ get_decrypted_flag_payloads,+ get_decrypted_flag_payloads_protected,+)from products.feature_flags.backend.flag_analytics import get_cached_evaluations_7d_by_teamfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChange@@ -63,6 +70,24 @@ class CopyFlagsResponseSerializer(serializers.Serializer):failed = CopyFlagsResultSerializer(many=True, help_text="List of failed copy attempts")+class OrganizationFeatureFlagRowSerializer(serializers.Serializer):+ id = serializers.IntegerField(help_text="ID of the representative feature flag for this key")+ team_id = serializers.IntegerField(help_text="Team ID the representative feature flag belongs to")+ key = serializers.CharField(help_text="Feature flag key, unique within the compared projects")+ name = serializers.CharField(allow_blank=True, help_text="Human-readable name of the representative feature flag")+ active = serializers.BooleanField(help_text="Whether the representative feature flag is enabled")+ filters = serializers.JSONField(help_text="Release condition filters of the representative feature flag")+++class OrganizationFeatureFlagKeysResponseSerializer(serializers.Serializer):+ count = serializers.IntegerField(help_text="Total number of distinct flag keys across the compared projects")+ next = serializers.CharField(allow_null=True, help_text="URL for the next page of results, or null if none")+ previous = serializers.CharField(allow_null=True, help_text="URL for the previous page of results, or null if none")+ results = OrganizationFeatureFlagRowSerializer(+ many=True, help_text="One representative flag per distinct key across the compared projects"+ )++logger = structlog.get_logger(__name__)@@ -79,6 +104,17 @@ class OrganizationFeatureFlagView(lookup_field = "feature_flag_key"+ @staticmethod+ def _redact_encrypted_payloads(request, flag: FeatureFlag) -> None:+ """Replace encrypted remote-config payload ciphertext with a redacted placeholder, in place.++ Mirrors the project-scoped flag read paths: only requests authenticated with a personal API+ key get decrypted values; everyone else (session, OAuth) sees the redacted placeholder, so the+ ciphertext is never returned over the org-wide endpoints.+ """+ if flag.has_encrypted_payloads:+ flag.filters["payloads"] = get_decrypted_flag_payloads_protected(request, flag.filters.get("payloads", {}))+@extend_schema(operation_id="org_feature_flags_retrieve",parameters=[OpenApiParameter("feature_flag_key", OpenApiTypes.STR, OpenApiParameter.PATH)],@@ -92,10 +128,14 @@ class OrganizationFeatureFlagView(org_team_ids = set(self.organization.teams.values_list("id", flat=True))team_ids = list(org_team_ids & set(accessible_team_ids))- flags = FeatureFlag.objects.filter(+ flags_qs = FeatureFlag.objects.filter(key=feature_flag_key,team_id__in=team_ids,)+ flags_qs = self._filter_flags_by_rbac(flags_qs, team_ids)+ flags = list(flags_qs)+ for flag in flags:+ self._redact_encrypted_payloads(request, flag)counts_by_team = get_cached_evaluations_7d_by_team(cast(str, feature_flag_key), [flag.team_id for flag in flags]@@ -118,6 +158,94 @@ class OrganizationFeatureFlagView(return Response(flags_data)+ @extend_schema(+ operation_id="org_feature_flags_keys",+ parameters=[+ OpenApiParameter("search", OpenApiTypes.STR, OpenApiParameter.QUERY, description="Filter by key or name"),+ OpenApiParameter("limit", OpenApiTypes.INT, OpenApiParameter.QUERY, description="Page size (max 100)"),+ OpenApiParameter("offset", OpenApiTypes.INT, OpenApiParameter.QUERY, description="Pagination offset"),+ OpenApiParameter(+ "team_ids",+ OpenApiTypes.INT,+ OpenApiParameter.QUERY,+ many=True,+ description="Teams to compare, in priority order. Defaults to all accessible teams in the org.",+ ),+ ],+ responses={200: OrganizationFeatureFlagKeysResponseSerializer},+ )+ @action(detail=False, methods=["get"], url_path="keys")+ def keys(self, request, *args, **kwargs):+ """Paginated, de-duplicated list of feature flag keys across the org's compared projects.++ Unlike the project-scoped flag list, this enumerates the union of flag keys across every+ compared project, so flags that exist only in another project still appear as rows.+ """+ # Restrict to teams in this org that the user can access.+ user_permissions = UserPermissions(user=request.user)+ accessible_team_ids = set(user_permissions.team_ids_visible_for_user)+ org_team_ids = set(self.organization.teams.values_list("id", flat=True))+ allowed_team_ids = org_team_ids & accessible_team_ids++ # Accept team_ids as repeated params (?team_ids=1&team_ids=2) or comma-separated (?team_ids=1,2).+ try:+ requested_team_ids = [+ int(part) for value in request.query_params.getlist("team_ids") for part in value.split(",") if part+ ]+ limit = max(min(int(request.query_params.get("limit") or 25), 100), 1)+ offset = max(int(request.query_params.get("offset") or 0), 0)+ except ValueError:+ return Response({"error": "Invalid query parameter."}, status=status.HTTP_400_BAD_REQUEST)++ # Preserve the caller's team ordering, de-duplicated (used to pick the representative per key).+ ordered_team_ids: list[int] = []+ seen_teams: set[int] = set()+ for team_id in requested_team_ids:+ if team_id in allowed_team_ids and team_id not in seen_teams:+ seen_teams.add(team_id)+ ordered_team_ids.append(team_id)+ if not ordered_team_ids:+ ordered_team_ids = sorted(allowed_team_ids)+ if not ordered_team_ids:+ return Response({"count": 0, "next": None, "previous": None, "results": []})++ search = (request.query_params.get("search") or "").strip()+ flags_qs = FeatureFlag.objects.filter(team_id__in=ordered_team_ids, deleted=False)+ flags_qs = self._filter_flags_by_rbac(flags_qs, ordered_team_ids)+ if search:+ flags_qs = flags_qs.filter(Q(key__icontains=search) | Q(name__icontains=search))++ distinct_keys_qs = flags_qs.order_by("key").values_list("key", flat=True).distinct()+ count = distinct_keys_qs.count()+ page_keys = list(distinct_keys_qs[offset : offset + limit])++ # Choose one representative flag per key, preferring earlier teams in the requested order.+ # Select from the search-filtered queryset so the representative always matches the search,+ # and let Postgres do the per-key dedup (DISTINCT ON key, ordered by team rank) so we load+ # one row per key instead of every team's copy. Ordering by key matches page_keys' order.+ rank_whens = [When(team_id=team_id, then=Value(rank)) for rank, team_id in enumerate(ordered_team_ids)]+ representatives = list(+ flags_qs.filter(key__in=page_keys)+ .annotate(_rank=Case(*rank_whens, output_field=IntegerField()))+ .order_by("key", "_rank")+ .distinct("key")+ )+ for flag in representatives:+ self._redact_encrypted_payloads(request, flag)+ # OrganizationFeatureFlagRowSerializer is the single source of truth for the row shape.+ results = OrganizationFeatureFlagRowSerializer(representatives, many=True).data++ next_url = (+ replace_query_param(request.build_absolute_uri(), "offset", offset + limit)+ if offset + limit < count+ else None+ )+ previous_url = (+ replace_query_param(request.build_absolute_uri(), "offset", max(offset - limit, 0)) if offset > 0 else None+ )++ return Response({"count": count, "next": next_url, "previous": previous_url, "results": results})+@extend_schema(request=CopyFlagsRequestSerializer,responses={200: CopyFlagsResponseSerializer},@@ -414,6 +542,28 @@ class OrganizationFeatureFlagView(return updated_payload+ def _filter_flags_by_rbac(self, flags_qs: QuerySet, team_ids: list[int]) -> QuerySet:+ """Apply per-team RBAC object-level filtering to a cross-team flag queryset.++ For each team, instantiate a UserAccessControl scoped to that team and apply+ filter_queryset_by_access_level so that flags the user has been explicitly denied+ (via resource-level or object-level access controls) are excluded. Org admins+ always pass through — filter_queryset_by_access_level short-circuits for them.+ """+ teams = {t.id: t for t in Team.objects.filter(id__in=team_ids)}++ allowed_ids: set[int] = set()+ for team_id in team_ids:+ team = teams.get(team_id)+ if team is None:+ continue+ uac = UserAccessControl(user=cast(User, self.request.user), team=team)+ team_qs = flags_qs.filter(team_id=team_id)+ filtered_qs = uac.filter_queryset_by_access_level(team_qs, include_all_if_admin=True)+ allowed_ids.update(filtered_qs.values_list("id", flat=True))++ return flags_qs.filter(id__in=allowed_ids)+def _extract_cohort_ids_from_schedules(self, schedules):"""Extract all cohort IDs referenced in pending scheduled changes."""cohort_ids = set()diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambrindex 201abb0ae7d0..88dad03d8cb3 100644--- a/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr+++ b/products/feature_flags/backend/api/test/__snapshots__/test_organization_feature_flag.ambr@@ -4298,9 +4298,16 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.2+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.10'''- SELECT "posthog_organization"."id",+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id","posthog_organization"."name","posthog_organization"."slug","posthog_organization"."logo_media_id",@@ -4335,21 +4342,35 @@"posthog_organization"."personalization","posthog_organization"."domain_whitelist","posthog_organization"."is_platform"- FROM "posthog_organization"- WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)LIMIT 21'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.3+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.11'''- SELECT 1 AS "a"- FROM "posthog_organizationmembership"- WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid- AND "posthog_organizationmembership"."user_id" = 99999)- LIMIT 1+ SELECT "posthog_featureflag"."id" AS "id"+ FROM "posthog_featureflag"+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")+ WHERE (NOT ("posthog_featureflag"."deleted")+ AND "posthog_featureflag"."key" = 'key-1'+ AND "posthog_featureflag"."team_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ AND ("posthog_featureflag"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_featureflag"."team_id" = 99999)))'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.4+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.12'''SELECT "posthog_organizationmembership"."id","posthog_organizationmembership"."organization_id",@@ -4395,25 +4416,33 @@"posthog_organization"."is_platform"FROM "posthog_organizationmembership"INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")- WHERE "posthog_organizationmembership"."user_id" = 99999- '''-# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.5- '''- SELECT "posthog_team"."id",- "posthog_team"."organization_id"- FROM "posthog_team"- WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 21'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.6+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.13'''- SELECT "posthog_team"."id" AS "id"- FROM "posthog_team"- WHERE "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ SELECT "posthog_featureflag"."id" AS "id"+ FROM "posthog_featureflag"+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")+ WHERE (NOT ("posthog_featureflag"."deleted")+ AND "posthog_featureflag"."key" = 'key-1'+ AND "posthog_featureflag"."team_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ AND ("posthog_featureflag"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_featureflag"."team_id" = 99999)))'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.7+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.14'''SELECT "posthog_featureflag"."id","posthog_featureflag"."key",@@ -4445,10 +4474,15 @@2,3,4,- 5 /* ... */))+ 5 /* ... */)+ AND "posthog_featureflag"."id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */))'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.8+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.15'''SELECT "posthog_user"."id","posthog_user"."password",@@ -4494,7 +4528,7 @@LIMIT 21'''# ----# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.9+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.16'''SELECT "posthog_user"."id","posthog_user"."password",@@ -4540,3 +4574,295 @@LIMIT 21'''# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.2+ '''+ SELECT "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organization"+ WHERE "posthog_organization"."id" = '00000000-0000-0000-0000-000000000000'::uuid+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.3+ '''+ SELECT 1 AS "a"+ FROM "posthog_organizationmembership"+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 1+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.4+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE "posthog_organizationmembership"."user_id" = 99999+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.5+ '''+ SELECT "posthog_team"."id",+ "posthog_team"."organization_id"+ FROM "posthog_team"+ WHERE "posthog_team"."organization_id" IN ('00000000-0000-0000-0000-000000000000'::uuid)+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.6+ '''+ SELECT "posthog_team"."id" AS "id"+ FROM "posthog_team"+ WHERE "posthog_team"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.7+ '''+ SELECT "posthog_team"."id",+ "posthog_team"."uuid",+ "posthog_team"."organization_id",+ "posthog_team"."parent_team_id",+ "posthog_team"."project_id",+ "posthog_team"."api_token",+ "posthog_team"."app_urls",+ "posthog_team"."name",+ "posthog_team"."slack_incoming_webhook",+ "posthog_team"."created_at",+ "posthog_team"."updated_at",+ "posthog_team"."anonymize_ips",+ "posthog_team"."completed_snippet_onboarding",+ "posthog_team"."has_completed_onboarding_for",+ "posthog_team"."onboarding_tasks",+ "posthog_team"."ingested_event",+ "posthog_team"."ingested_production_event",+ "posthog_team"."ingested_production_event_last_checked_at",+ "posthog_team"."person_processing_opt_out",+ "posthog_team"."secret_api_token",+ "posthog_team"."secret_api_token_backup",+ "posthog_team"."session_recording_opt_in",+ "posthog_team"."session_recording_sample_rate",+ "posthog_team"."session_recording_minimum_duration_milliseconds",+ "posthog_team"."session_recording_linked_flag",+ "posthog_team"."session_recording_network_payload_capture_config",+ "posthog_team"."session_recording_masking_config",+ "posthog_team"."session_recording_url_trigger_config",+ "posthog_team"."session_recording_url_blocklist_config",+ "posthog_team"."session_recording_event_trigger_config",+ "posthog_team"."session_recording_trigger_match_type_config",+ "posthog_team"."session_recording_trigger_groups",+ "posthog_team"."session_replay_config",+ "posthog_team"."session_recording_retention_period",+ "posthog_team"."conversations_enabled",+ "posthog_team"."conversations_settings",+ "posthog_team"."proactive_tasks_enabled",+ "posthog_team"."survey_config",+ "posthog_team"."surveys_opt_in",+ "posthog_team"."product_tours_opt_in",+ "posthog_team"."capture_console_log_opt_in",+ "posthog_team"."capture_performance_opt_in",+ "posthog_team"."capture_dead_clicks",+ "posthog_team"."autocapture_opt_out",+ "posthog_team"."autocapture_web_vitals_opt_in",+ "posthog_team"."autocapture_web_vitals_allowed_metrics",+ "posthog_team"."autocapture_exceptions_opt_in",+ "posthog_team"."autocapture_exceptions_errors_to_ignore",+ "posthog_team"."logs_settings",+ "posthog_team"."llm_gateway_enabled_at",+ "posthog_team"."llm_gateway_revoked_at",+ "posthog_team"."llm_gateway_overspend_allowance_usd",+ "posthog_team"."heatmaps_opt_in",+ "posthog_team"."receive_org_level_activity_logs",+ "posthog_team"."web_analytics_pre_aggregated_tables_enabled",+ "posthog_team"."web_analytics_pre_aggregated_tables_version",+ "posthog_team"."flags_persistence_default",+ "posthog_team"."feature_flag_confirmation_enabled",+ "posthog_team"."feature_flag_confirmation_message",+ "posthog_team"."default_evaluation_environments_enabled",+ "posthog_team"."require_evaluation_environment_tags",+ "posthog_team"."default_evaluation_contexts_enabled",+ "posthog_team"."require_evaluation_contexts",+ "posthog_team"."session_recording_version",+ "posthog_team"."signup_token",+ "posthog_team"."is_demo",+ "posthog_team"."access_control",+ "posthog_team"."week_start_day",+ "posthog_team"."inject_web_apps",+ "posthog_team"."test_account_filters",+ "posthog_team"."test_account_filters_default_checked",+ "posthog_team"."path_cleaning_filters",+ "posthog_team"."timezone",+ "posthog_team"."data_attributes",+ "posthog_team"."person_display_name_properties",+ "posthog_team"."live_events_columns",+ "posthog_team"."recording_domains",+ "posthog_team"."human_friendly_comparison_periods",+ "posthog_team"."cookieless_server_hash_mode",+ "posthog_team"."primary_dashboard_id",+ "posthog_team"."default_data_theme",+ "posthog_team"."extra_settings",+ "posthog_team"."modifiers",+ "posthog_team"."correlation_config",+ "posthog_team"."session_recording_retention_period_days",+ "posthog_team"."external_data_workspace_id",+ "posthog_team"."external_data_workspace_last_synced_at",+ "posthog_team"."api_query_rate_limit",+ "posthog_team"."revenue_tracking_config",+ "posthog_team"."drop_events_older_than",+ "posthog_team"."base_currency",+ "posthog_team"."experiment_recalculation_time",+ "posthog_team"."default_experiment_confidence_level",+ "posthog_team"."default_experiment_stats_method",+ "posthog_team"."business_model"+ FROM "posthog_team"+ WHERE "posthog_team"."id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.8+ '''+ SELECT "posthog_organizationmembership"."id",+ "posthog_organizationmembership"."organization_id",+ "posthog_organizationmembership"."user_id",+ "posthog_organizationmembership"."level",+ "posthog_organizationmembership"."joined_at",+ "posthog_organizationmembership"."updated_at",+ "posthog_organizationmembership"."invited_by_id",+ "posthog_organization"."id",+ "posthog_organization"."name",+ "posthog_organization"."slug",+ "posthog_organization"."logo_media_id",+ "posthog_organization"."created_at",+ "posthog_organization"."updated_at",+ "posthog_organization"."is_active",+ "posthog_organization"."is_not_active_reason",+ "posthog_organization"."session_cookie_age",+ "posthog_organization"."is_member_join_email_enabled",+ "posthog_organization"."is_ai_data_processing_approved",+ "posthog_organization"."is_ai_training_opted_in",+ "posthog_organization"."is_ai_training_locked",+ "posthog_organization"."is_ai_training_cta_shown",+ "posthog_organization"."enforce_2fa",+ "posthog_organization"."members_can_invite",+ "posthog_organization"."members_can_create_projects",+ "posthog_organization"."members_can_use_personal_api_keys",+ "posthog_organization"."allow_publicly_shared_resources",+ "posthog_organization"."default_role_id",+ "posthog_organization"."plugins_access_level",+ "posthog_organization"."for_internal_metrics",+ "posthog_organization"."default_experiment_stats_method",+ "posthog_organization"."default_anonymize_ips",+ "posthog_organization"."is_hipaa",+ "posthog_organization"."is_pending_deletion",+ "posthog_organization"."customer_id",+ "posthog_organization"."available_product_features",+ "posthog_organization"."usage",+ "posthog_organization"."never_drop_data",+ "posthog_organization"."customer_trust_scores",+ "posthog_organization"."setup_section_2_completed",+ "posthog_organization"."personalization",+ "posthog_organization"."domain_whitelist",+ "posthog_organization"."is_platform"+ FROM "posthog_organizationmembership"+ INNER JOIN "posthog_organization" ON ("posthog_organizationmembership"."organization_id" = "posthog_organization"."id")+ WHERE ("posthog_organizationmembership"."organization_id" = '00000000-0000-0000-0000-000000000000'::uuid+ AND "posthog_organizationmembership"."user_id" = 99999)+ LIMIT 21+ '''+# ---+# name: TestOrganizationFeatureFlagGet.test_get_feature_flag_success.9+ '''+ SELECT "posthog_featureflag"."id" AS "id"+ FROM "posthog_featureflag"+ INNER JOIN "posthog_team" ON ("posthog_featureflag"."team_id" = "posthog_team"."id")+ WHERE (NOT ("posthog_featureflag"."deleted")+ AND "posthog_featureflag"."key" = 'key-1'+ AND "posthog_featureflag"."team_id" IN (1,+ 2,+ 3,+ 4,+ 5 /* ... */)+ AND ("posthog_featureflag"."team_id" =+ (SELECT U0."parent_team_id" AS "parent_team_id"+ FROM "posthog_team" U0+ WHERE U0."id" = 99999+ LIMIT 1)+ OR ("posthog_team"."parent_team_id" IS NULL+ AND "posthog_featureflag"."team_id" = 99999)))+ '''+# ---diff --git a/products/feature_flags/backend/api/test/test_organization_feature_flag.py b/products/feature_flags/backend/api/test/test_organization_feature_flag.pyindex 3d56c9fbadcf..0c7f49a16053 100644--- a/products/feature_flags/backend/api/test/test_organization_feature_flag.py+++ b/products/feature_flags/backend/api/test/test_organization_feature_flag.py@@ -27,6 +27,7 @@ from products.cohorts.backend.models.util import sort_cohorts_topologicallyfrom products.dashboards.backend.api.dashboard import Dashboardfrom products.early_access_features.backend.models import EarlyAccessFeaturefrom products.experiments.backend.models.experiment import Experiment+from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUEfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.feature_flags.backend.models.scheduled_change import ScheduledChangefrom products.surveys.backend.models import Survey@@ -96,6 +97,21 @@ class TestOrganizationFeatureFlagGet(APIBaseTest, QueryMatchingTest):self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)+ def test_get_feature_flag_redacts_encrypted_payloads(self):+ FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="encrypted-key",+ has_encrypted_payloads=True,+ filters={"groups": [], "payloads": {"true": "ciphertext-blob"}},+ )++ url = f"/api/organizations/{self.organization.id}/feature_flags/encrypted-key"+ response = self.client.get(url)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()[0]["filters"]["payloads"]["true"], REDACTED_PAYLOAD_VALUE)+def test_get_feature_flag_filters_inaccessible_teams(self):"""Test that flags from teams the user cannot access are not returned."""from posthog.constants import AvailableFeature@@ -132,6 +148,242 @@ class TestOrganizationFeatureFlagGet(APIBaseTest, QueryMatchingTest):self.assertEqual(len(response_data), 1)self.assertEqual(response_data[0]["team_id"], self.team_1.id)+ def test_get_feature_flag_filters_flag_denied_by_object_level_access_control(self):+ from posthog.constants import AvailableFeature++ self.organization.available_product_features = [+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()++ from ee.models.rbac.access_control import AccessControl++ # Create a second user and log in as them (not the flag creator) so that+ # the "creator is always visible" exception does not apply.+ other_user = self._create_user("[email protected]")+ self.client.force_login(other_user)++ # Deny the non-creator user access to feature_flag_2 at the object level.+ AccessControl.objects.create(+ team=self.team_2,+ resource="feature_flag",+ resource_id=str(self.feature_flag_2.id),+ organization_member=None,+ role=None,+ access_level="none",+ )++ url = f"/api/organizations/{self.organization.id}/feature_flags/{self.feature_flag_key}"+ response = self.client.get(url)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ response_data = response.json()+ # Only team_1's flag should be returned; team_2's flag is denied.+ self.assertEqual(len(response_data), 1)+ self.assertEqual(response_data[0]["team_id"], self.team_1.id)+++class TestOrganizationFeatureFlagKeys(APIBaseTest):+ def setUp(self):+ self.team_1 = self.team+ self.team_2 = Team.objects.create(organization=self.organization)++ # Shared key exists in both projects; each project also has a unique key.+ FeatureFlag.objects.create(team=self.team_1, created_by=self.user, key="shared")+ FeatureFlag.objects.create(team=self.team_2, created_by=self.user, key="shared")+ FeatureFlag.objects.create(team=self.team_1, created_by=self.user, key="only-in-1")+ FeatureFlag.objects.create(team=self.team_2, created_by=self.user, key="only-in-2")+ FeatureFlag.objects.create(team=self.team_2, created_by=self.user, key="deleted", deleted=True)++ super().setUp()++ def _keys_url(self, **params: Any) -> str:+ url = f"/api/organizations/{self.organization.id}/feature_flags/keys/"+ query = "&".join(f"{k}={v}" for k, v in params.items())+ return f"{url}?{query}" if query else url++ def test_keys_returns_union_across_compared_projects(self):+ response = self.client.get(self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ data = response.json()+ self.assertEqual(data["count"], 3)+ self.assertEqual(sorted(row["key"] for row in data["results"]), ["only-in-1", "only-in-2", "shared"])++ def test_keys_excludes_deleted_flags(self):+ response = self.client.get(self._keys_url(team_ids=self.team_2.id))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ keys = [row["key"] for row in response.json()["results"]]+ self.assertNotIn("deleted", keys)+ self.assertCountEqual(keys, ["shared", "only-in-2"])++ def test_keys_redacts_encrypted_payloads(self):+ # Session reads must never receive encrypted remote-config ciphertext.+ FeatureFlag.objects.create(+ team=self.team_1,+ created_by=self.user,+ key="secret-config",+ has_encrypted_payloads=True,+ filters={"groups": [], "payloads": {"true": "ciphertext-blob"}},+ )++ response = self.client.get(self._keys_url(team_ids=self.team_1.id))++ row = next(r for r in response.json()["results"] if r["key"] == "secret-config")+ self.assertEqual(row["filters"]["payloads"]["true"], REDACTED_PAYLOAD_VALUE)+ self.assertNotIn("ciphertext-blob", str(row["filters"]))++ def test_keys_representative_prefers_earlier_team_in_order(self):+ # team_2 listed first -> the shared row should be represented by team_2's flag.+ response = self.client.get(self._keys_url(team_ids=self.team_2.id) + f"&team_ids={self.team_1.id}")++ shared = next(row for row in response.json()["results"] if row["key"] == "shared")+ self.assertEqual(shared["team_id"], self.team_2.id)++ def test_keys_deduplicates_team_ids_preserving_priority(self):+ # team_1 repeated at the end must not override its first-seen priority over team_2.+ response = self.client.get(+ self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}&team_ids={self.team_1.id}"+ )++ shared = next(row for row in response.json()["results"] if row["key"] == "shared")+ self.assertEqual(shared["team_id"], self.team_1.id)++ def test_keys_search_picks_representative_matching_search(self):+ # Same key in both teams, but only the lower-priority team's name matches the search term.+ FeatureFlag.objects.create(team=self.team_1, created_by=self.user, key="billing-flag", name="Alpha")+ FeatureFlag.objects.create(team=self.team_2, created_by=self.user, key="billing-flag", name="SearchTarget")++ response = self.client.get(+ self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}&search=SearchTarget"+ )++ rows = response.json()["results"]+ self.assertEqual([row["key"] for row in rows], ["billing-flag"])+ self.assertEqual(rows[0]["team_id"], self.team_2.id)+ self.assertEqual(rows[0]["name"], "SearchTarget")++ def test_keys_search_filters_by_key(self):+ response = self.client.get(self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}&search=only")++ keys = [row["key"] for row in response.json()["results"]]+ self.assertCountEqual(keys, ["only-in-1", "only-in-2"])++ def test_keys_paginates_distinct_keys(self):+ first = self.client.get(+ self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}&limit=2&offset=0"+ )+ self.assertEqual(first.json()["count"], 3)+ self.assertEqual(len(first.json()["results"]), 2)+ self.assertIsNotNone(first.json()["next"])+ self.assertIsNone(first.json()["previous"])++ second = self.client.get(+ self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}&limit=2&offset=2"+ )+ self.assertEqual(len(second.json()["results"]), 1)+ self.assertIsNone(second.json()["next"])+ self.assertIsNotNone(second.json()["previous"])++ def test_keys_pagination_urls_preserve_team_ids_and_search(self):+ # The next/previous links must carry the same team_ids and search, or paging would+ # silently switch to the wrong projects or drop the filter.+ first = self.client.get(+ self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}&search=only&limit=1&offset=0"+ )+ next_url = first.json()["next"]+ self.assertIsNotNone(next_url)+ self.assertIn(f"team_ids={self.team_1.id}", next_url)+ self.assertIn(f"team_ids={self.team_2.id}", next_url)+ self.assertIn("search=only", next_url)++ second = self.client.get(+ self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}&search=only&limit=1&offset=1"+ )+ previous_url = second.json()["previous"]+ self.assertIsNotNone(previous_url)+ self.assertIn(f"team_ids={self.team_1.id}", previous_url)+ self.assertIn(f"team_ids={self.team_2.id}", previous_url)+ self.assertIn("search=only", previous_url)++ def test_keys_negative_limit_returns_400(self):+ response = self.client.get(self._keys_url(team_ids=self.team_1.id) + "&limit=-5")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ # A negative limit is clamped to 1, not passed to a negative slice (which would 500).+ self.assertLessEqual(len(response.json()["results"]), 1)++ def test_keys_accepts_comma_separated_team_ids(self):+ response = self.client.get(self._keys_url(team_ids=f"{self.team_1.id},{self.team_2.id}"))++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(sorted(row["key"] for row in response.json()["results"]), ["only-in-1", "only-in-2", "shared"])++ def test_keys_defaults_to_all_accessible_teams_when_unspecified(self):+ response = self.client.get(self._keys_url())++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ keys = [row["key"] for row in response.json()["results"]]+ self.assertCountEqual(keys, ["shared", "only-in-1", "only-in-2"])++ def test_keys_ignores_teams_outside_the_organization(self):+ other_org = Organization.objects.create(name="other")+ other_team = Team.objects.create(organization=other_org)+ FeatureFlag.objects.create(team=other_team, created_by=self.user, key="other-org-flag")++ response = self.client.get(self._keys_url(team_ids=other_team.id))++ # The team is not in this org, so it falls back to all accessible teams in the org.+ keys = [row["key"] for row in response.json()["results"]]+ self.assertNotIn("other-org-flag", keys)+ self.assertCountEqual(keys, ["shared", "only-in-1", "only-in-2"])++ def test_keys_unauthorized(self):+ self.client.logout()+ response = self.client.get(self._keys_url(team_ids=self.team_1.id))+ self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)++ def test_keys_invalid_param_returns_400(self):+ response = self.client.get(self._keys_url(team_ids=self.team_1.id) + "&limit=abc")+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ def test_keys_excludes_flags_denied_by_object_level_access_control(self):+ from posthog.constants import AvailableFeature++ self.organization.available_product_features = [+ {"name": AvailableFeature.ACCESS_CONTROL, "key": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()++ from ee.models.rbac.access_control import AccessControl++ # Use a second user (not the flag creator) so the creator-always-visible+ # exception in filter_queryset_by_access_level does not apply.+ other_user = self._create_user("[email protected]")+ self.client.force_login(other_user)++ # Deny the non-creator user access to the "shared" flag in team_2 at the object level.+ shared_flag_team2 = FeatureFlag.objects.get(team=self.team_2, key="shared")+ AccessControl.objects.create(+ team=self.team_2,+ resource="feature_flag",+ resource_id=str(shared_flag_team2.id),+ organization_member=None,+ role=None,+ access_level="none",+ )++ response = self.client.get(self._keys_url(team_ids=self.team_1.id) + f"&team_ids={self.team_2.id}")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ # "shared" key still appears because team_1's copy is accessible; team_2's is excluded.+ rows = response.json()["results"]+ keys = [row["key"] for row in rows]+ self.assertIn("shared", keys)+ shared_row = next(row for row in rows if row["key"] == "shared")+ # Representative must be from team_1, not team_2 (team_2's flag is denied).+ self.assertEqual(shared_row["team_id"], self.team_1.id)+class TestOrganizationFeatureFlagCopy(APIBaseTest, QueryMatchingTest):def setUp(self):diff --git a/products/feature_flags/frontend/generated/api.schemas.ts b/products/feature_flags/frontend/generated/api.schemas.tsindex 45e1d0321466..05b16970a063 100644--- a/products/feature_flags/frontend/generated/api.schemas.ts+++ b/products/feature_flags/frontend/generated/api.schemas.ts@@ -50,6 +50,38 @@ export interface CopyFlagsResponseApi {failed: CopyFlagsResultApi[]}+export interface OrganizationFeatureFlagRowApi {+ /** ID of the representative feature flag for this key */+ id: number+ /** Team ID the representative feature flag belongs to */+ team_id: number+ /** Feature flag key, unique within the compared projects */+ key: string+ /** Human-readable name of the representative feature flag */+ name: string+ /** Whether the representative feature flag is enabled */+ active: boolean+ /** Release condition filters of the representative feature flag */+ filters: unknown+}++export interface OrganizationFeatureFlagKeysResponseApi {+ /** Total number of distinct flag keys across the compared projects */+ count: number+ /**+ * URL for the next page of results, or null if none+ * @nullable+ */+ next: string | null+ /**+ * URL for the previous page of results, or null if none+ * @nullable+ */+ previous: string | null+ /** One representative flag per distinct key across the compared projects */+ results: OrganizationFeatureFlagRowApi[]+}+export interface EvaluationContextSuggestionRequestApi {/*** Name of the evaluation context to hide from (POST) or restore to (DELETE) the flag editor's suggestion list. Case-insensitive and whitespace-trimmed.@@ -1398,6 +1430,25 @@ export interface PatchedScheduledChangeApi {readonly timezone?: string | null}+export type OrgFeatureFlagsKeysParams = {+ /**+ * Page size (max 100)+ */+ limit?: number+ /**+ * Pagination offset+ */+ offset?: number+ /**+ * Filter by key or name+ */+ search?: string+ /**+ * Teams to compare, in priority order. Defaults to all accessible teams in the org.+ */+ team_ids?: number[]+}+export type OrganizationsProjectsEvaluationContextSuggestionsDestroyParams = {/*** Name of the evaluation context to restore to suggestions.diff --git a/products/feature_flags/frontend/generated/api.ts b/products/feature_flags/frontend/generated/api.tsindex 07c4b0863745..fb37bb63f3fc 100644--- a/products/feature_flags/frontend/generated/api.ts+++ b/products/feature_flags/frontend/generated/api.ts@@ -36,6 +36,8 @@ import type {FlagValueResponseApi,FlagValueValuesRetrieveParams,MyFlagsResponseApi,+ OrgFeatureFlagsKeysParams,+ OrganizationFeatureFlagKeysResponseApi,OrganizationsProjectsEvaluationContextSuggestionsDestroyParams,PaginatedFeatureFlagListApi,PaginatedScheduledChangeListApi,@@ -96,6 +98,39 @@ export const featureFlagsCopyFlagsCreate = async (})}+export const getOrgFeatureFlagsKeysUrl = (organizationId: string, params?: OrgFeatureFlagsKeysParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/organizations/${organizationId}/feature_flags/keys/?${stringifiedParams}`+ : `/api/organizations/${organizationId}/feature_flags/keys/`+}++/**+ * Paginated, de-duplicated list of feature flag keys across the org's compared projects.+ *+ * Unlike the project-scoped flag list, this enumerates the union of flag keys across every+ * compared project, so flags that exist only in another project still appear as rows.+ */+export const orgFeatureFlagsKeys = async (+ organizationId: string,+ params?: OrgFeatureFlagsKeysParams,+ options?: RequestInit+): Promise<OrganizationFeatureFlagKeysResponseApi> => {+ return apiMutator<OrganizationFeatureFlagKeysResponseApi>(getOrgFeatureFlagsKeysUrl(organizationId, params), {+ ...options,+ method: 'GET',+ })+}+export const getOrganizationsProjectsEvaluationContextSuggestionsCreateUrl = (organizationId: string, id: number) => {return `/api/organizations/${organizationId}/projects/${id}/evaluation_context_suggestions/`}diff --git a/products/feature_flags/mcp/tools.yaml b/products/feature_flags/mcp/tools.yamlindex 81732c260fa0..c4a4cd4794f7 100644--- a/products/feature_flags/mcp/tools.yaml+++ b/products/feature_flags/mcp/tools.yaml@@ -334,6 +334,9 @@ tools:flag-value-values-retrieve:operation: flag_value_values_retrieveenabled: false+ org-feature-flags-keys:+ operation: org_feature_flags_keys+ enabled: falseorg-feature-flags-retrieve:operation: org_feature_flags_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5852d7e4e2d2..0450d2eb6943 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -29289,6 +29289,38 @@ export namespace Schemas {id_jag_allowed_clients?: string[];}+ export interface OrganizationFeatureFlagRow {+ /** ID of the representative feature flag for this key */+ id: number;+ /** Team ID the representative feature flag belongs to */+ team_id: number;+ /** Feature flag key, unique within the compared projects */+ key: string;+ /** Human-readable name of the representative feature flag */+ name: string;+ /** Whether the representative feature flag is enabled */+ active: boolean;+ /** Release condition filters of the representative feature flag */+ filters: unknown;+ }++ export interface OrganizationFeatureFlagKeysResponse {+ /** Total number of distinct flag keys across the compared projects */+ count: number;+ /**+ * URL for the next page of results, or null if none+ * @nullable+ */+ next: string | null;+ /**+ * URL for the previous page of results, or null if none+ * @nullable+ */+ previous: string | null;+ /** One representative flag per distinct key across the compared projects */+ results: OrganizationFeatureFlagRow[];+ }+/*** * `vercel` - Vercel*/@@ -56388,6 +56420,25 @@ export namespace Schemas {offset?: number;};+ export type OrgFeatureFlagsKeysParams = {+ /**+ * Page size (max 100)+ */+ limit?: number;+ /**+ * Pagination offset+ */+ offset?: number;+ /**+ * Filter by key or name+ */+ search?: string;+ /**+ * Teams to compare, in priority order. Defaults to all accessible teams in the org.+ */+ team_ids?: number[];+ };+export type OrgOrganizationsIntegrationsListParams = {/*** Number of results to return per page.