: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
feat(flags): add blocked domains and IP addresses settings (#122284)
Gustavo H. Strassburger775b975593d9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex dd85c3ec3c4e..453466eb33c1 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -15223,9 +15223,9 @@ snapshots:scenes-app-settings-environment--settings-environment-experiments-multiple-recalculation-times--light:hash: v1.k794b7964.b4fc2da7f83bed627c7c299e12be0aeeb748caa68c52936cf68eb1c953ce99b1.aE-j5iUFcAPTMKDrjvl-8oTIG-JulsSZVpoXetf7t6cscenes-app-settings-environment--settings-environment-feature-flags--dark:- hash: v1.k794b7964.eb377d1f88a90916e32276cdad75b2d0c26bb20903ff48d1ef026976cf953466.T2zk-XaF_PYF1JRBHWuzFeO732CBEyCK6uJMO7ZJJtw+ hash: v1.k794b7964.97bbfb410f020af6882cbd074930a1d596d25c84692bd60fc75da0f198d28780.L9lRcqQAwXrxaer2ToQGbIXLtrKVgpIVPQB5aVsVcbUscenes-app-settings-environment--settings-environment-feature-flags--light:- hash: v1.k794b7964.d84178c3dc11a6532bf084fd187b33fca01ec3e0816155c2ea5a1c6ee6d81a27.AUj_yq16NyztGQ6apE0udpGUByM3-1xO6Ty7LSbQdVY+ hash: v1.k794b7964.eb8fd68135a429fa107eff98fa30b46891139087c803f7f63cf20d53eb3c09c3.jYO259NH47HRYQVH8NdfaPVKr5p38_x3xBBkmvrM2n4scenes-app-settings-environment--settings-environment-heatmaps--dark:hash: v1.k794b7964.ed41ee7503a63db6830c53aeaea3bb2088f7074e697724a321151e4cc286153b.bYh3Ex9SrtYiQMyl4rj_bdZ-UDUw-5PRn99YxVuFczAscenes-app-settings-environment--settings-environment-heatmaps--light:diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsxindex fe32bbcd17c5..25a7a16d2c25 100644--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsx+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.test.tsx@@ -55,9 +55,15 @@ describe('humanizeActivity', () => {changes: [{ field: 'session_recording_opt_in', after: true },{ field: 'effective_membership_level', after: 1 },+ {+ field: 'feature_flag_policy_config',+ before: { require_tags: false, blocked_hosts: ['old.example.com'], blocked_ips: [] },+ after: { require_tags: true, blocked_hosts: ['new.example.com'], blocked_ips: [] },+ },],- action: 'enabled session recording',- description: 'A user enabled session recording on Example',+ action: 'enabled session recording, enabled required tags on feature flags, added new.example.com to the blocked domains for feature flag requests, and removed old.example.com from the blocked domains for feature flag requests',+ description:+ 'A user enabled session recording, enabled required tags on feature flags, added new.example.com to the blocked domains for feature flag requests, and removed old.example.com from the blocked domains for feature flag requests on Example',},{scope: ActivityScope.EVENT_DEFINITION,diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsxindex dc23620e024e..47cd74aab90d 100644--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx@@ -160,6 +160,8 @@ export type LemonInputSelectProps<T = string> = Pick<onBlur?: () => voidonFocus?: () => voidonInputChange?: (newValue: string) => void+ /** Set on the inner input, so that a label with a matching `htmlFor` names it. */+ id?: string'data-attr'?: stringclassName?: stringpopoverClassName?: string@@ -201,6 +203,7 @@ export function LemonInputSelect<T = string>({autoFocus = false,className,popoverClassName,+ id,'data-attr': dataAttr,size = 'medium',transparentBackground,@@ -1058,6 +1061,7 @@ export function LemonInputSelect<T = string>({}><LemonInput+ id={id}inputRef={inputRef}placeholder={displayMode === 'count'diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex b53a577493ef..859a62cf1153 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -73,6 +73,7 @@ import { DataQualityGateToggle } from 'products/data_quality/frontend/settings/Dimport { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings'import { SuppressionRules } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/suppression_rules/SuppressionRules'import { MAX_LOOKBACK_DAYS, MIN_LOOKBACK_DAYS } from 'products/experiments/frontend/constants'+import { FeatureFlagRequestBlocklist } from 'products/feature_flags/frontend/FeatureFlagRequestBlocklist'import { LogsAlertingSection } from 'products/logs/frontend/components/LogsAlerting/LogsAlertingSection'import { LogsMetricRulesSection } from 'products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection'import { LogsSamplingSection } from 'products/logs/frontend/components/LogsSampling/LogsSamplingSection'@@ -1094,6 +1095,14 @@ export const SETTINGS_MAP: SettingSection[] = [component: <RequireFeatureFlagTags />,keywords: ['tag', 'tags', 'require', 'governance'],},+ {+ id: 'feature-flag-request-blocklist',+ title: 'Blocked domains and IP addresses',+ description:+ 'Feature flag requests from these domains or IP addresses get an empty response and are not billed. Use this when someone else uses your project token without permission.',+ component: <FeatureFlagRequestBlocklist />,+ keywords: ['block', 'blocklist', 'domain', 'ip', 'origin', 'abuse', 'token'],+ },{id: 'feature-flag-require-evaluation-contexts',title: 'Require evaluation contexts',diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 65b7f8637717..f669e038ee6e 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -197,6 +197,7 @@ export type SettingId =| 'feature-flag-default-release-conditions'| 'feature-flag-evaluation-context-suggestions'| 'feature-flag-require-tags'+ | 'feature-flag-request-blocklist'| 'feature-flag-require-evaluation-contexts'| 'feature-flag-secure-api-key'| 'feature-flags-interface'diff --git a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx b/frontend/src/scenes/team-activity/teamActivityDescriber.tsxindex bbc274b8497b..f491a1405671 100644--- a/frontend/src/scenes/team-activity/teamActivityDescriber.tsx+++ b/frontend/src/scenes/team-activity/teamActivityDescriber.tsx@@ -487,6 +487,43 @@ const TEAM_PROPERTIES_MAPPING: Record<human_friendly_comparison_periods: createBooleanToggleHandler('human friendly comparison periods'),receive_org_level_activity_logs: createBooleanToggleHandler('organization-level activity logs'),require_evaluation_contexts: createBooleanToggleHandler('require evaluation context tags'),+ feature_flag_policy_config: (change) => {+ const before = isObject(change.before) ? change.before : {}+ const after = isObject(change.after) ? change.after : {}+ const descriptions: JSX.Element[] = []+ if (!!before.require_tags !== !!after.require_tags) {+ descriptions.push(+ <>+ {after.require_tags ? 'enabled' : 'disabled'} <em>required tags on feature flags</em>+ </>+ )+ }+ const lists = [+ ['blocked_hosts', 'blocked domains for feature flag requests'],+ ['blocked_ips', 'blocked IP addresses for feature flag requests'],+ ] as const+ for (const [field, label] of lists) {+ const beforeEntries = (before[field] ?? []) as string[]+ const afterEntries = (after[field] ?? []) as string[]+ const added = afterEntries.filter((entry) => !beforeEntries.includes(entry))+ const removed = beforeEntries.filter((entry) => !afterEntries.includes(entry))+ if (added.length) {+ descriptions.push(+ <>+ added <code>{added.join(', ')}</code> to the <em>{label}</em>+ </>+ )+ }+ if (removed.length) {+ descriptions.push(+ <>+ removed <code>{removed.join(', ')}</code> from the <em>{label}</em>+ </>+ )+ }+ }+ return descriptions.length ? { description: descriptions } : null+ },test_account_filters: (change) => {// change.after is an array of property filters// change.before is an array o property filters@@ -809,7 +846,6 @@ const TEAM_PROPERTIES_MAPPING: Record<managed_viewsets: () => null,flag_evaluations_mode: () => null,workflows_config: () => null,- feature_flag_policy_config: () => null,}function describeWorkflowEmailSuspension(logItem: ActivityLogItem): HumanizedChange {diff --git a/frontend/src/scenes/teamLogic.test.ts b/frontend/src/scenes/teamLogic.test.tsindex 4c9927489913..83695a004c50 100644--- a/frontend/src/scenes/teamLogic.test.ts+++ b/frontend/src/scenes/teamLogic.test.ts@@ -57,6 +57,37 @@ describe('teamLogic', () => {expect(logic.values.currentTeam?.name).toBe(expectedTeamName)})++ it('sends blocklist counts, not entries, to analytics', async () => {+ await expectLogic(logic).toDispatchActions(['loadCurrentTeamSuccess'])+ useMocks({+ patch: {+ '/api/environments/:id': async ({ request }) => [+ 200,+ { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as Record<string, any>) },+ ],+ },+ })+ const capture = jest.spyOn(posthog, 'capture').mockImplementation()+ try {+ await expectLogic(logic, () => {+ logic.actions.updateCurrentTeam({+ feature_flag_policy_config: {+ require_tags: true,+ blocked_hosts: ['example.com', 'example.org'],+ blocked_ips: ['203.0.113.7'],+ },+ })+ }).toDispatchActions(['updateCurrentTeamSuccess'])++ expect(capture).toHaveBeenCalledWith('feature_flag_policy_config team setting updated', {+ setting: 'feature_flag_policy_config',+ value: { require_tags: true, blocked_hosts_count: 2, blocked_ips_count: 1 },+ })+ } finally {+ capture.mockRestore()+ }+ })})describe('when the team id differs from its project id', () => {diff --git a/frontend/src/scenes/teamLogic.tsx b/frontend/src/scenes/teamLogic.tsxindex 3552b42f1515..33899514937a 100644--- a/frontend/src/scenes/teamLogic.tsx+++ b/frontend/src/scenes/teamLogic.tsx@@ -46,9 +46,27 @@ const parseUpdatedAttributeName = (attr: keyof TeamType | null): string => {return 'Session recording minimum duration'}+ if (attr === 'feature_flag_policy_config') {+ return 'Feature flag settings'+ }+return attr ? identifierToHuman(attr) : 'Project'}+/** Blocklist entries are third-party IP addresses and domains, so analytics gets only their counts. */+function featureFlagPolicyConfigForAnalytics(+ config: TeamType['feature_flag_policy_config']+): Record<string, boolean | number | undefined> | undefined {+ if (!config) {+ return undefined+ }+ return {+ require_tags: config.require_tags,+ blocked_hosts_count: config.blocked_hosts?.length,+ blocked_ips_count: config.blocked_ips?.length,+ }+}+/** Return whether the provided value is a full TeamType object that's only available when authenticated. */export function isAuthenticatedTeam(team: TeamType | TeamPublicType | undefined | null): team is TeamType {return !!team && 'api_token' in team@@ -471,7 +489,10 @@ export const teamLogic = kea<teamLogicType>([Object.keys(payload).forEach((property) => {posthog.capture(`${property} team setting updated`, {setting: property,- value: payload[property as keyof TeamType],+ value:+ property === 'feature_flag_policy_config'+ ? featureFlagPolicyConfigForAnalytics(payload.feature_flag_policy_config)+ : payload[property as keyof TeamType],})})diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex bc37d1e184e5..04515b29b9f2 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -46,6 +46,7 @@ import type {OrganizationNotificationLockApi,ProjectApi,SharingConfigurationApi,+ TeamFeatureFlagPolicyConfigApi,} from '~/generated/core/api.schemas'import { RootAssistantMessage } from '~/queries/schema/schema-assistant-messages'import type {@@ -926,7 +927,7 @@ export interface TeamType extends TeamBasicType {customer_analytics_config: CustomerAnalyticsConfigworkflows_config: WorkflowsConfig// Optional so cached team objects from before this field shipped still typecheck.- feature_flag_policy_config?: FeatureFlagPolicyConfig+ feature_flag_policy_config?: TeamFeatureFlagPolicyConfigApibusiness_model?: 'b2b' | 'b2c' | 'other' | null}@@ -948,10 +949,6 @@ export interface WorkflowsConfig {marketing_frequency_cap_window_days?: number | null}-export interface FeatureFlagPolicyConfig {- require_tags: boolean-}-export interface ProductIntentType {product_type: stringcreated_at: stringdiff --git a/products/feature_flags/frontend/FeatureFlagRequestBlocklist.tsx b/products/feature_flags/frontend/FeatureFlagRequestBlocklist.tsxnew file mode 100644index 000000000000..d731f7377994--- /dev/null+++ b/products/feature_flags/frontend/FeatureFlagRequestBlocklist.tsx@@ -0,0 +1,64 @@+import { useActions, useValues } from 'kea'++import { LemonSkeleton } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'++import { featureFlagRequestBlocklistLogic } from './featureFlagRequestBlocklistLogic'++export function FeatureFlagRequestBlocklist(): JSX.Element {+ const { currentTeam, currentTeamLoading, blockedHosts, blockedIps } = useValues(featureFlagRequestBlocklistLogic)+ const { setBlockedHosts, setBlockedIps } = useActions(featureFlagRequestBlocklistLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ if (!currentTeam) {+ return <LemonSkeleton />+ }++ return (+ <div className="flex flex-col gap-4 max-w-160">+ <LemonField.Pure+ label="Blocked domains"+ htmlFor="feature-flag-blocked-hosts"+ help="Stops other websites that embed your project token from requesting flags. A domain also blocks its subdomains. Add up to 100 domains."+ >+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={blockedHosts}+ onChange={setBlockedHosts}+ placeholder="example.com"+ id="feature-flag-blocked-hosts"+ data-attr="feature-flag-blocked-hosts-select"+ loading={currentTeamLoading}+ disabled={currentTeamLoading}+ disabledReason={restrictedReason}+ />+ </LemonField.Pure>+ <LemonField.Pure+ label="Blocked IP addresses"+ htmlFor="feature-flag-blocked-ips"+ help="Stops scripts that request flags from known addresses. Enter up to 100 single addresses or CIDR ranges."+ >+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={blockedIps}+ onChange={setBlockedIps}+ placeholder="203.0.113.7 or 198.51.100.0/24"+ id="feature-flag-blocked-ips"+ data-attr="feature-flag-blocked-ips-select"+ loading={currentTeamLoading}+ disabled={currentTeamLoading}+ disabledReason={restrictedReason}+ />+ </LemonField.Pure>+ </div>+ )+}diff --git a/products/feature_flags/frontend/featureFlagRequestBlocklistLogic.test.ts b/products/feature_flags/frontend/featureFlagRequestBlocklistLogic.test.tsnew file mode 100644index 000000000000..2fa6b81f6182--- /dev/null+++ b/products/feature_flags/frontend/featureFlagRequestBlocklistLogic.test.ts@@ -0,0 +1,90 @@+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'++import { expectLogic } from 'kea-test-utils'++import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import type { TeamType } from '~/types'++import { featureFlagRequestBlocklistLogic } from './featureFlagRequestBlocklistLogic'++describe('featureFlagRequestBlocklistLogic', () => {+ let logic: ReturnType<typeof featureFlagRequestBlocklistLogic.build>+ let patchedPayload: Partial<TeamType> | undefined++ beforeEach(() => {+ patchedPayload = undefined+ useMocks({+ patch: {+ '/api/environments/:id': async ({ request }) => {+ const payload = (await request.json()) as Partial<TeamType>+ patchedPayload = payload+ const config = payload.feature_flag_policy_config+ return [+ 200,+ {+ ...MOCK_DEFAULT_TEAM,+ feature_flag_policy_config: {+ require_tags: false,+ blocked_hosts: ['saved.example.com'],+ blocked_ips: [],+ ...config,+ ...(config?.blocked_hosts && {+ blocked_hosts: config.blocked_hosts.map((host: string) => host.toLowerCase()),+ }),+ },+ },+ ]+ },+ },+ })+ initKeaTests()+ logic = featureFlagRequestBlocklistLogic()+ logic.mount()+ teamLogic.actions.loadCurrentTeamSuccess({+ ...MOCK_DEFAULT_TEAM,+ feature_flag_policy_config: { require_tags: false, blocked_hosts: ['saved.example.com'], blocked_ips: [] },+ })+ })++ afterEach(() => {+ logic.unmount()+ })++ it.each([+ [+ 'a domain',+ () => logic.actions.setBlockedHosts(['saved.example.com', 'NEW.example.com']),+ { blocked_hosts: ['saved.example.com', 'NEW.example.com'] },+ { blockedHosts: ['saved.example.com', 'new.example.com'], blockedIps: [] },+ ],+ [+ 'an IP address',+ () => logic.actions.setBlockedIps(['203.0.113.7']),+ { blocked_ips: ['203.0.113.7'] },+ { blockedHosts: ['saved.example.com'], blockedIps: ['203.0.113.7'] },+ ],+ ])('saves only the edited list after adding %s and shows what the API stored', async (_, edit, sent, shown) => {+ await expectLogic(logic, edit).toDispatchActions(teamLogic, ['updateCurrentTeamSuccess']).toMatchValues(shown)++ expect(patchedPayload?.feature_flag_policy_config).toEqual(sent)+ })++ it('shows the saved list when the API rejects an entry', async () => {+ useMocks({+ patch: {+ '/api/environments/:id': () => [400, { type: 'validation_error', detail: 'Not a valid domain.' }],+ },+ })++ await expectLogic(logic, () => {+ logic.actions.setBlockedHosts(['saved.example.com', '*.example.com'])+ })+ .toDispatchActions(teamLogic, ['updateCurrentTeamFailure'])+ .toFinishAllListeners()++ expect(logic.values.blockedHosts).toEqual(['saved.example.com'])+ })+})diff --git a/products/feature_flags/frontend/featureFlagRequestBlocklistLogic.ts b/products/feature_flags/frontend/featureFlagRequestBlocklistLogic.tsnew file mode 100644index 000000000000..d53aed12807f--- /dev/null+++ b/products/feature_flags/frontend/featureFlagRequestBlocklistLogic.ts@@ -0,0 +1,73 @@+import { MakeLogicType, actions, connect, kea, listeners, path, selectors } from 'kea'++import { teamLogic } from 'scenes/teamLogic'++import type { TeamPublicType, TeamType } from '~/types'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureFlagRequestBlocklistLogicValues {+ currentTeam: TeamPublicType | TeamType | null // teamLogic+ currentTeamLoading: boolean // teamLogic+ blockedHosts: string[]+ blockedIps: string[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureFlagRequestBlocklistLogicActions {+ updateCurrentTeam: (payload: Partial<TeamType>) => Partial<TeamType> // teamLogic+ setBlockedHosts: (blockedHosts: string[]) => {+ blockedHosts: string[]+ }+ setBlockedIps: (blockedIps: string[]) => {+ blockedIps: string[]+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface featureFlagRequestBlocklistLogicMeta {+ __keaTypeGenInternalSelectorTypes: {+ blockedHosts: (currentTeam: TeamPublicType | TeamType | null) => string[]+ blockedIps: (currentTeam: TeamPublicType | TeamType | null) => string[]+ }+}++export type featureFlagRequestBlocklistLogicType = MakeLogicType<+ featureFlagRequestBlocklistLogicValues,+ featureFlagRequestBlocklistLogicActions,+ Record<string, any>,+ featureFlagRequestBlocklistLogicMeta+>++export const featureFlagRequestBlocklistLogic = kea<featureFlagRequestBlocklistLogicType>([+ path(['products', 'feature_flags', 'frontend', 'featureFlagRequestBlocklistLogic']),+ connect(() => ({+ values: [teamLogic, ['currentTeam', 'currentTeamLoading']],+ actions: [teamLogic, ['updateCurrentTeam']],+ })),+ actions({+ setBlockedHosts: (blockedHosts: string[]) => ({ blockedHosts }),+ setBlockedIps: (blockedIps: string[]) => ({ blockedIps }),+ }),+ selectors({+ blockedHosts: [+ (s) => [s.currentTeam],+ (currentTeam: TeamPublicType | TeamType | null): string[] =>+ currentTeam?.feature_flag_policy_config?.blocked_hosts ?? [],+ ],+ blockedIps: [+ (s) => [s.currentTeam],+ (currentTeam: TeamPublicType | TeamType | null): string[] =>+ currentTeam?.feature_flag_policy_config?.blocked_ips ?? [],+ ],+ }),+ listeners(({ actions }) => ({+ // Send only the edited list. The API keeps a list the request leaves out, so a save+ // here does not overwrite a newer change to the other list with the value this page loaded.+ setBlockedHosts: ({ blockedHosts }) => {+ actions.updateCurrentTeam({ feature_flag_policy_config: { blocked_hosts: blockedHosts } })+ },+ setBlockedIps: ({ blockedIps }) => {+ actions.updateCurrentTeam({ feature_flag_policy_config: { blocked_ips: blockedIps } })+ },+ })),+])