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(sharing): warn when public links bypass access controls (#119831)

Alex Lider55ff8895ea1a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f9c1a05cd375..e44944478189 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2605,9 +2605,9 @@ snapshots:
components-sharing--dashboard-sharing--light:
hash: v1.k794b7964.2266e798b1301b8286b4201ead43bde1277102e40a3034c22789d2febadbde7e.yeiOyqofT5eGkoUr6f4O7CBHQe8eqLIbzKI6L9QDV_A
components-sharing--dashboard-sharing-licensed--dark:
- hash: v1.k794b7964.71fd9822b623d19986d9ab0d8df9e3e8029ad149430302e7de697ec82070ba0a.QiBdnpLNH6DfeO13Ey8eTE3AbGalbD_PuRYEtbg-w3s
+ hash: v1.k794b7964.4e6f30fc641b418a26613da75b8f564e688057d42e30bea21d8c2009bb869c6e.Bxx-MouI7bj4MKQ_bJvMwgWeUZ6uCKNzi_CatPpWb5Q
components-sharing--dashboard-sharing-licensed--light:
- hash: v1.k794b7964.0c82241ff70b4db8ea10e2b0956161fc243647ee4663ae0174bd7dbbd4c4356d.NS0GnhbIqoTcNTNGqEji0_Qj4H_cWaPkoUS0jmdQ184
+ hash: v1.k794b7964.ea957888499b5d61c4a399a1440f8374a332aa0ac5407763ac2be4714b57fa71.3i-BMwJc2TE4Sur8nJ98Xcu1hw4fvM1pze1dJzE94xc
components-sharing--insight-sharing--dark:
hash: v1.k794b7964.f70196365c8d0e6f25c44a7d88972903cc48c8ba0c8937271379db7e94c75115.o-GkawWjO1KefxBwndIZmsQBk-3AB-T_WgTZAwt6G_U
components-sharing--insight-sharing--light:
@@ -2615,7 +2615,11 @@ snapshots:
components-sharing--insight-sharing-licensed--dark:
hash: v1.k794b7964.53f6a69d6d21e488c755db82bcb993d6c638752b83d2f772164d0868de0a6386.imGLPRxZUEV0h7zyHS8AuofnDxn5QuPnE4RvsvK8d_I
components-sharing--insight-sharing-licensed--light:
- hash: v1.k794b7964.cd8cb4e1d564f65f5bd96c205406c67a4eb569186adedf6a8763ef89c5ed2013.zcz40vC4K1cA9XH1wnRvmkCLHB4z-RLxtghWuvnXRLw
+ hash: v1.k794b7964.d7d31d882f3729a7164a08c9056d3c18c5d1c03d98caaba0dec3f3c2337576a3.AXmVzhJ9gr12K2M6eOsBQkdiYX-EDlVw36z2yfq1tv4
+ components-sharing--notebook-sharing-with-access-controls--dark:
+ hash: v1.k794b7964.f4824ebe30e72b8cccb7fd5f9813ceecd9518ccc7f337e470ba301e8ef5bab55.HlvKsO9MkHlliGiQNh1hST0nRVJjOcfon3Fjf0i8dnE
+ components-sharing--notebook-sharing-with-access-controls--light:
+ hash: v1.k794b7964.3aa651e9650e5bded798238274398e26bf87800c29bbbe597d729d85e98dfe8c.Zzz6FQQ2Yo_Se0T9E9_S4yuadDoVTA9oGGSfRAy2Pds
components-sharing--recording-sharing-licensed--dark:
hash: v1.k794b7964.9a607e1c8b67aa4caf736f532eae8f04172a08b1519a5b233caed383cd61ac2e.oJJ1rz584k526jS3YRjmGoRSSlONVnNRC_gh0BpAWDw
components-sharing--recording-sharing-licensed--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index af757a952e4e..c1ad8762ee55 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -4681,6 +4681,8 @@ export interface SharingConfigurationApi {
* @nullable
*/
readonly user_access_level: string | null
+ /** Whether the project has configured access controls for shared content or its underlying data. */
+ readonly has_relevant_access_controls: boolean
}
/**
diff --git a/frontend/src/lib/components/Sharing/SharingModal.stories.tsx b/frontend/src/lib/components/Sharing/SharingModal.stories.tsx
index 700710cd892f..ab0c4a10e78a 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.stories.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.stories.tsx
@@ -19,7 +19,12 @@ const fakeInsight: Partial<InsightModel> = {
query: examples.InsightTrendsQuery,
}
-type StoryArgs = SharingModalProps & { licensed?: boolean; passwordRequired?: boolean }
+type StoryArgs = SharingModalProps & {
+ licensed?: boolean
+ passwordRequired?: boolean
+ hasRelevantAccessControls?: boolean
+ sharingEnabled?: boolean
+}
const meta: Meta<StoryArgs> = {
title: 'Components/Sharing',
@@ -29,10 +34,24 @@ const meta: Meta<StoryArgs> = {
viewMode: 'story',
},
render: (args) => {
- const { licensed = false, passwordRequired = false, ...props } = args
+ const {
+ licensed = false,
+ passwordRequired = false,
+ hasRelevantAccessControls = false,
+ sharingEnabled = true,
+ ...props
+ } = args
const [modalOpen, setModalOpen] = useState(false)
- useAvailableFeatures(licensed ? [AvailableFeature.WHITE_LABELLING, AvailableFeature.ACCESS_CONTROL] : [])
+ useAvailableFeatures(
+ licensed
+ ? [
+ AvailableFeature.WHITE_LABELLING,
+ AvailableFeature.ACCESS_CONTROL,
+ AvailableFeature.ORGANIZATION_SECURITY_SETTINGS,
+ ]
+ : []
+ )
useStorybookMocks({
get: {
@@ -40,12 +59,14 @@ const meta: Meta<StoryArgs> = {
'/api/environments/:id/insights/:insight_id/sharing/',
'/api/environments/:id/dashboards/:dashboard_id/sharing/',
'/api/environments/:id/session_recordings/:recording_id/sharing/',
+ '/api/environments/:id/notebooks/:notebook_id/sharing/',
].reduce(
(acc, url) =>
Object.assign(acc, {
[url]: {
created_at: '2022-06-28T12:30:51.459746Z',
- enabled: true,
+ enabled: sharingEnabled,
+ has_relevant_access_controls: hasRelevantAccessControls,
access_token: '1AEQjQ2xNLGoiyI0UnNlLzOiBZWWMQ',
password_required: passwordRequired,
},
@@ -58,6 +79,7 @@ const meta: Meta<StoryArgs> = {
'/api/environments/:id/insights/:insight_id/sharing/',
'/api/environments/:id/dashboards/:dashboard_id/sharing/',
'/api/environments/:id/session_recordings/:recording_id/sharing/',
+ '/api/environments/:id/notebooks/:notebook_id/sharing/',
].reduce(
(acc, url) =>
Object.assign(acc, {
@@ -67,7 +89,8 @@ const meta: Meta<StoryArgs> = {
200,
{
created_at: '2022-06-28T12:30:51.459746Z',
- enabled: true,
+ enabled: sharingEnabled,
+ has_relevant_access_controls: hasRelevantAccessControls,
access_token: '1AEQjQ2xNLGoiyI0UnNlLzOiBZWWMQ',
password_required: passwordRequired,
...body,
@@ -124,7 +147,13 @@ export const DashboardSharing: Story = {
}
export const DashboardSharingLicensed: Story = {
- args: { title: 'Dashboard permissions', licensed: true, passwordRequired: true, dashboardId: 123 },
+ args: {
+ title: 'Dashboard permissions',
+ licensed: true,
+ passwordRequired: true,
+ hasRelevantAccessControls: true,
+ dashboardId: 123,
+ },
decorators: [
(Story) => (
<BindLogic logic={dashboardLogic} props={{ id: 123 }}>
@@ -157,3 +186,13 @@ export const InsightSharingLicensed: Story = {
export const RecordingSharingLicensed: Story = {
args: { title: 'Share Recording', recordingId: 'fake-id', licensed: true, previewIframe: true },
}
+
+export const NotebookSharingWithAccessControls: Story = {
+ args: {
+ title: 'Notebook permissions & sharing',
+ notebookShortId: 'example-notebook',
+ licensed: true,
+ hasRelevantAccessControls: true,
+ sharingEnabled: false,
+ },
+}
diff --git a/frontend/src/lib/components/Sharing/SharingModal.test.tsx b/frontend/src/lib/components/Sharing/SharingModal.test.tsx
index 2dac66bf4c53..a47e0aa5621e 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.test.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.test.tsx
@@ -1,13 +1,16 @@
+import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'
+
import '@testing-library/jest-dom'
import { cleanup, render, screen, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expectLogic } from 'kea-test-utils'
+import { OrganizationMembershipLevel } from 'lib/constants'
import { themeLogic } from 'lib/logic/themeLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { useAvailableFeatures } from '~/mocks/features'
+import { getAvailableProductFeatures, useAvailableFeatures } from '~/mocks/features'
import { useMocks } from '~/mocks/jest'
import { NodeKind } from '~/queries/schema/schema-general'
import { initKeaTests } from '~/test/init'
@@ -26,15 +29,18 @@ const defaultInsightId = 456
function mockDashboardSharingConfiguration({
enabled = true,
passwordRequired = false,
+ hasRelevantAccessControls = false,
}: {
enabled?: boolean
passwordRequired?: boolean
+ hasRelevantAccessControls?: boolean
}): Record<string, any> {
const sharingConfiguration = {
created_at: createdAt,
enabled,
access_token: accessToken,
password_required: passwordRequired,
+ has_relevant_access_controls: hasRelevantAccessControls,
}
return {
@@ -82,14 +88,45 @@ describe('SharingModal (dashboard)', () => {
// consumer) can't commit a deferred render after a later file resets the kea store.
afterEach(() => cleanup())
- function DashboardSharingModalWrapper({ extraProps }: { extraProps?: Partial<SharingModalProps> }): JSX.Element {
+ function DashboardSharingModalWrapper({
+ extraProps,
+ accessControlAvailable = false,
+ hasRelevantAccessControls = false,
+ enabled = true,
+ securitySettingsAvailable = false,
+ sharingAllowed = true,
+ }: {
+ extraProps?: Partial<SharingModalProps>
+ accessControlAvailable?: boolean
+ hasRelevantAccessControls?: boolean
+ enabled?: boolean
+ securitySettingsAvailable?: boolean
+ sharingAllowed?: boolean
+ }): JSX.Element {
// Render the dashboard sharing modal with `WHITE_LABELLING` so the UI shows
// the branding option in the form.
- useAvailableFeatures([AvailableFeature.WHITE_LABELLING])
- initKeaTests()
+ useAvailableFeatures([
+ AvailableFeature.WHITE_LABELLING,
+ ...(accessControlAvailable ? [AvailableFeature.ACCESS_CONTROL] : []),
+ ...(securitySettingsAvailable ? [AvailableFeature.ORGANIZATION_SECURITY_SETTINGS] : []),
+ ])
+ initKeaTests(true, undefined, undefined, {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: getAvailableProductFeatures(),
+ membership_level: OrganizationMembershipLevel.Admin,
+ allow_publicly_shared_resources: sharingAllowed,
+ })
themeLogic.mount()
useMocks({
- get: mockDashboardSharingConfiguration({}),
+ get: {
+ ...mockDashboardSharingConfiguration({ enabled, hasRelevantAccessControls }),
+ '/api/environments/:team_id/notebooks/:notebook_id/sharing/': {
+ created_at: createdAt,
+ enabled,
+ access_token: accessToken,
+ has_relevant_access_controls: hasRelevantAccessControls,
+ },
+ },
})
const props: SharingModalProps = {
@@ -118,6 +155,126 @@ describe('SharingModal (dashboard)', () => {
expect(screen.queryByText(/Show insight details/i)).toBeNull()
})
+ it.each([
+ {
+ scenario: 'before enabling sharing',
+ resource: 'dashboard',
+ available: true,
+ configured: true,
+ enabled: false,
+ allowed: true,
+ settingsAvailable: true,
+ warning: true,
+ },
+ {
+ scenario: 'sharing enabled without security settings',
+ resource: 'dashboard',
+ available: true,
+ configured: true,
+ enabled: true,
+ allowed: true,
+ settingsAvailable: false,
+ warning: true,
+ },
+ {
+ scenario: 'sharing a notebook',
+ resource: 'notebook',
+ available: true,
+ configured: true,
+ enabled: false,
+ allowed: true,
+ settingsAvailable: true,
+ warning: true,
+ },
+ {
+ scenario: 'no access-control feature',
+ resource: 'dashboard',
+ available: false,
+ configured: true,
+ enabled: true,
+ allowed: true,
+ settingsAvailable: true,
+ warning: false,
+ },
+ {
+ scenario: 'no configured rules',
+ resource: 'dashboard',
+ available: true,
+ configured: false,
+ enabled: true,
+ allowed: true,
+ settingsAvailable: true,
+ warning: false,
+ },
+ {
+ scenario: 'organization disallows sharing',
+ resource: 'dashboard',
+ available: true,
+ configured: true,
+ enabled: true,
+ allowed: false,
+ settingsAvailable: true,
+ warning: false,
+ },
+ ])('$scenario', async ({ resource, available, configured, enabled, allowed, settingsAvailable, warning }) => {
+ render(
+ <DashboardSharingModalWrapper
+ accessControlAvailable={available}
+ hasRelevantAccessControls={configured}
+ enabled={enabled}
+ sharingAllowed={allowed}
+ securitySettingsAvailable={settingsAvailable}
+ extraProps={
+ resource === 'notebook' ? { dashboardId: undefined, notebookShortId: 'example-notebook' } : {}
+ }
+ />
+ )
+
+ await screen.findByText(`Share ${resource} publicly`)
+ const banner = screen.queryByText(new RegExp(`Access controls do not apply when viewing public ${resource}s`))
+ const link = screen.queryByText('Disable public sharing for your organization')
+ if (warning) {
+ expect(banner).toBeInTheDocument()
+ } else {
+ expect(banner).not.toBeInTheDocument()
+ }
+ if (warning && settingsAvailable) {
+ expect(link).toHaveAttribute('href', expect.stringMatching(/\/settings\/organization-security$/))
+ } else {
+ expect(link).not.toBeInTheDocument()
+ }
+ if (!allowed) {
+ expect(screen.getByTestId('sharing-switch')).toBeDisabled()
+ expect(screen.getByTestId('sharing-switch')).toHaveAttribute('aria-checked', 'false')
+ expect(screen.queryByText('Public sharing is disabled for this organization.')).not.toBeInTheDocument()
+ }
+ })
+
+ it.each([
+ { membershipLevel: OrganizationMembershipLevel.Admin, securitySettingsAvailable: true, showsLink: true },
+ { membershipLevel: OrganizationMembershipLevel.Owner, securitySettingsAvailable: true, showsLink: true },
+ { membershipLevel: OrganizationMembershipLevel.Member, securitySettingsAvailable: true, showsLink: false },
+ { membershipLevel: OrganizationMembershipLevel.Admin, securitySettingsAvailable: false, showsLink: false },
+ ])(
+ 'gates the settings link for role $membershipLevel with security settings $securitySettingsAvailable',
+ async ({ membershipLevel, securitySettingsAvailable, showsLink }) => {
+ useAvailableFeatures(securitySettingsAvailable ? [AvailableFeature.ORGANIZATION_SECURITY_SETTINGS] : [])
+ initKeaTests(true, undefined, undefined, {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: getAvailableProductFeatures(),
+ membership_level: membershipLevel,
+ })
+ useMocks({ get: mockDashboardSharingConfiguration({}) })
+ const logic = sharingLogic({ dashboardId })
+
+ await expectLogic(logic, () => {
+ logic.mount()
+ }).toDispatchActions(['loadSharingConfigurationSuccess'])
+ expect(logic.values.canManagePublicSharing).toBe(showsLink)
+ logic.unmount()
+ }
+ )
+
it('updates the shared dashboard theme', async () => {
const user = userEvent.setup()
render(<DashboardSharingModalWrapper />)
diff --git a/frontend/src/lib/components/Sharing/SharingModal.tsx b/frontend/src/lib/components/Sharing/SharingModal.tsx
index be77f735267c..5507e918904f 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.tsx
@@ -13,6 +13,7 @@ import {
LemonSegmentedButton,
LemonSkeleton,
LemonSwitch,
+ Link,
} from '@posthog/lemon-ui'
import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
@@ -27,7 +28,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { preflightLogic } from 'lib/logic/preflightLogic'
-import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'
+import { getAccessControlDisabledReason, pluralizeResource } from 'lib/utils/accessControlUtils'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
import { projectLogic } from 'scenes/projectLogic'
@@ -118,6 +119,7 @@ export function SharingModalContent({
const {
whitelabelAvailable,
accessControlAvailable,
+ canManagePublicSharing,
sharingConfiguration,
sharingConfigurationLoading,
showPreview,
@@ -237,21 +239,40 @@ export function SharingModalContent({
<h4 className="mb-3 text-xs font-semibold uppercase tracking-wide text-secondary">
Public sharing
</h4>
- {!sharingAllowed ? (
- <LemonBanner type="warning">Public sharing is disabled for this organization.</LemonBanner>
- ) : (
- <LemonSwitch
- id="sharing-switch"
- label={`Share ${resource} publicly`}
- checked={sharingConfiguration.enabled}
- data-attr="sharing-switch"
- onChange={(active) => setIsEnabled(active)}
- bordered
- fullWidth
- loading={sharingConfigurationLoading}
- disabledReason={sharingManageDisabledReason}
- />
- )}
+ {sharingAllowed &&
+ accessControlAvailable &&
+ sharingConfiguration.has_relevant_access_controls && (
+ <LemonBanner type="warning" className="mb-3">
+ <p className="mb-0">
+ {`Anyone with the public link can view this ${resource} and its data, including people outside your organization. Access controls do not apply when viewing public ${pluralizeResource(getResourceType(dashboardId, insightShortId, recordingId, notebookShortId))}.`}
+ </p>
+ {canManagePublicSharing && (
+ <p className="mt-2 mb-0">
+ <Link
+ to={urls.settings('organization-security')}
+ data-attr="sharing-public-sharing-settings"
+ >
+ Disable public sharing for your organization
+ </Link>
+ </p>
+ )}
+ </LemonBanner>
+ )}
+ <LemonSwitch
+ id="sharing-switch"
+ label={`Share ${resource} publicly`}
+ checked={sharingAllowed && sharingConfiguration.enabled}
+ data-attr="sharing-switch"
+ onChange={(active) => setIsEnabled(active)}
+ bordered
+ fullWidth
+ loading={sharingConfigurationLoading}
+ disabledReason={
+ !sharingAllowed
+ ? 'Public sharing is disabled for this organization.'
+ : sharingManageDisabledReason
+ }
+ />
{sharingAllowed && sharingConfiguration.enabled && sharingConfiguration.access_token ? (
<div className="mt-2 flex flex-col gap-2">
diff --git a/frontend/src/lib/components/Sharing/sharingLogic.ts b/frontend/src/lib/components/Sharing/sharingLogic.ts
index cf92c410181a..311ac6265985 100644
--- a/frontend/src/lib/components/Sharing/sharingLogic.ts
+++ b/frontend/src/lib/components/Sharing/sharingLogic.ts
@@ -62,6 +62,7 @@ const propsToApiParams = async (
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sharingLogicValues {
accessControlAvailable: boolean
+ canManagePublicSharing: boolean
embedCode: string
embedLink: string
iframeKey: number
@@ -297,6 +298,10 @@ export interface sharingLogicMeta {
accessControlAvailable: (
hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
) => boolean
+ canManagePublicSharing: (
+ isAdminOrOwner: boolean | null,
+ hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean
+ ) => boolean
sharingAllowed: (currentOrganization: OrganizationType | null) => boolean
params: (arg: any) => any
shareLink: (
@@ -452,6 +457,11 @@ export const sharingLogic = kea<sharingLogicType>([
(hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean) =>
hasAvailableFeature(AvailableFeature.ACCESS_CONTROL),
],
+ canManagePublicSharing: [
+ () => [organizationLogic.selectors.isAdminOrOwner, userLogic.selectors.hasAvailableFeature],
+ (isAdminOrOwner: boolean | null, hasAvailableFeature: (feature: AvailableFeature) => boolean): boolean =>
+ !!isAdminOrOwner && hasAvailableFeature(AvailableFeature.ORGANIZATION_SECURITY_SETTINGS),
+ ],
sharingAllowed: [
() => [organizationLogic.selectors.currentOrganization],
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index ca4edd702467..aab5a840f547 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -45,6 +45,7 @@ import type {
OrganizationTeamBasicApi,
OrganizationNotificationLockApi,
ProjectApi,
+ SharingConfigurationApi,
} from '~/generated/core/api.schemas'
import { RootAssistantMessage } from '~/queries/schema/schema-assistant-messages'
import type {
@@ -5824,6 +5825,7 @@ export interface SharePasswordType {
}
export interface SharingConfigurationType {
+ has_relevant_access_controls?: SharingConfigurationApi['has_relevant_access_controls']
enabled: boolean
access_token: string
created_at: string
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 565190b7d278..7f4d79ea90d8 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -59,6 +59,7 @@ from posthog.user_permissions import UserPermissions
from posthog.utils import get_ip_address, get_persisted_feature_flags_for_app_context, render_template
from posthog.views import preflight_check
+from products.access_control.backend.facade.api import team_has_public_sharing_access_rules
from products.access_control.backend.facade.user_access_control import (
AccessControlLevel,
UserAccessControl,
@@ -349,6 +350,9 @@ class SharePasswordCreateSerializer(serializers.Serializer):
class SharingConfigurationSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
settings = serializers.JSONField(required=False, allow_null=True)
share_passwords = serializers.SerializerMethodField()
+ has_relevant_access_controls = serializers.SerializerMethodField(
+ help_text="Whether the project has configured access controls for shared content or its underlying data."
+ )
class Meta:
model = SharingConfiguration
@@ -360,9 +364,18 @@ class SharingConfigurationSerializer(UserAccessControlSerializerMixin, serialize
"password_required",
"share_passwords",
"user_access_level",
+ "has_relevant_access_controls",
]
read_only_fields = ["created_at", "access_token", "share_passwords", "user_access_level"]
+ @extend_schema_field(serializers.BooleanField())
+ def get_has_relevant_access_controls(self, obj: SharingConfiguration) -> bool:
+ if not (obj.dashboard_id or obj.notebook_id or obj.insight_id):
+ return False
+ if not obj.team.organization.is_feature_available(AvailableFeature.ACCESS_CONTROL):
+ return False
+ return team_has_public_sharing_access_rules(team_id=obj.team_id)
+
def validate_settings(self, value: Optional[dict[str, Any]]) -> Optional[dict[str, Any]]:
if value is None:
return None
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index d6d35a689180..e28416b1020d 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -13,7 +13,7 @@ from django.http import HttpResponse
from django.utils import timezone
from django.utils.timezone import now
-from parameterized import parameterized
+from parameterized import param, parameterized
from rest_framework import status
from rest_framework.exceptions import PermissionDenied
from rest_framework.test import APIClient
@@ -29,7 +29,7 @@ from posthog.api.sharing_publish_gate import dashboard_filter_leaves
from posthog.auth import SharingPasswordProtectedAuthentication
from posthog.constants import AvailableFeature
from posthog.jwt import PosthogJwtAudience, decode_jwt
-from posthog.models import ActivityLog, OrganizationMembership
+from posthog.models import ActivityLog, OrganizationMembership, PropertyDefinition, Team
from posthog.models.data_color_theme import DataColorTheme
from posthog.models.share_password import SharePassword
from posthog.models.sharing_configuration import SharingConfiguration
@@ -39,6 +39,7 @@ from posthog.test.insight_queries import browser_filtered_pageview_query
from posthog.test.warehouse_access import WAREHOUSE_ACCESS_CONTROL_FLAG, deny_warehouse_table_to_member
from products.access_control.backend.models.access_control import AccessControl
+from products.access_control.backend.models.property_access_control import PropertyAccessControl
from products.alerts.backend.models.alert import AlertConfiguration
from products.dashboards.backend.access import DashboardAccessMethod
from products.dashboards.backend.models.dashboard import Dashboard
@@ -158,8 +159,69 @@ class TestSharing(APIBaseTest):
"settings": None,
"share_passwords": [],
"user_access_level": "editor",
+ "has_relevant_access_controls": False,
}
+ @parameterized.expand(
+ [
+ param("dashboard", resource="dashboard"),
+ param("notebook", resource="notebook", shared_resource="notebook"),
+ param("insight", resource="insight", shared_resource="insight"),
+ param("project", resource="project"),
+ param("source", resource="external_data_source"),
+ param("warehouse_objects", resource="warehouse_objects"),
+ param("table", resource="warehouse_table"),
+ param("table_object", resource="warehouse_table", resource_id="example-object"),
+ param("view", resource="warehouse_view"),
+ param("property", resource="property_definition"),
+ param("no_rules", expected=False),
+ param("unrelated_rules", resource="feature_flag", expected=False),
+ param("unavailable_feature", resource="dashboard", entitled=False, expected=False),
+ param("other_team", resource="dashboard", other_team=True, expected=False),
+ param("other_team_property", resource="property_definition", other_team=True, expected=False),
+ ]
+ )
+ def test_sharing_config_reports_relevant_access_controls(
+ self,
+ _name: str,
+ *,
+ resource: str | None = None,
+ resource_id: str | None = None,
+ shared_resource: str = "dashboard",
+ entitled: bool = True,
+ other_team: bool = False,
+ expected: bool = True,
+ ) -> None:
+ self.organization.available_product_features = (
+ [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}] if entitled else []
+ )
+ self.organization.save()
+ rule_team = Team.objects.create(organization=self.organization) if other_team else self.team
+ if resource == "property_definition":
+ definition = PropertyDefinition.objects.create(
+ team=rule_team, name="example_property", type=PropertyDefinition.Type.EVENT
+ )
+ PropertyAccessControl.objects.create(team=rule_team, property_definition=definition, access_level="none")
+ elif resource:
+ AccessControl.objects.create(
+ team=rule_team,
+ resource=resource,
+ resource_id=resource_id,
+ access_level="viewer",
+ )
+
+ if shared_resource == "notebook":
+ notebook = Notebook.objects.create(team=self.team, created_by=self.user)
+ url = f"/api/projects/{self.team.id}/notebooks/{notebook.short_id}/sharing"
+ elif shared_resource == "insight":
+ url = f"/api/projects/{self.team.id}/insights/{self.insight.id}/sharing"
+ else:
+ url = f"/api/projects/{self.team.id}/dashboards/{self.dashboard.id}/sharing"
+ response = self.client.get(url)
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["has_relevant_access_controls"] is expected
+
@parameterized.expand(
[
("shared", "/shared/{token}", DashboardAccessMethod.SHARED),
@@ -233,6 +295,7 @@ class TestSharing(APIBaseTest):
"settings": None,
"share_passwords": [],
"user_access_level": "editor",
+ "has_relevant_access_controls": False,
}
response = self.client.patch(
@@ -247,6 +310,7 @@ class TestSharing(APIBaseTest):
"settings": None,
"share_passwords": [],
"user_access_level": "editor",
+ "has_relevant_access_controls": False,
}
@patch("products.exports.backend.api.exports.ExportedAssetSerializer._start_export_workflow")
diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.py
index 77165422da1b..d4e2b2f58dba 100644
--- a/products/access_control/backend/facade/api.py
+++ b/products/access_control/backend/facade/api.py
@@ -198,6 +198,25 @@ def team_has_property_access_rules(*, team_id: int) -> bool:
return PropertyAccessControl.objects.filter(team_id=team_id, property_definition__isnull=False).exists()
+def team_has_public_sharing_access_rules(*, team_id: int) -> bool:
+ return (
+ AccessControl.objects.filter(
+ team_id=team_id,
+ resource__in=[
+ "project",
+ "dashboard",
+ "notebook",
+ "insight",
+ "external_data_source",
+ "warehouse_objects",
+ "warehouse_table",
+ "warehouse_view",
+ ],
+ ).exists()
+ or PropertyAccessControl.objects.filter(team_id=team_id, property_definition__isnull=False).exists()
+ )
+
+
def user_organizations_use_access_controls(*, user_id: int) -> bool:
"""Whether access rules can narrow what the user reaches in one of their organizations.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 37f5411daebc..15587b5638de 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -103579,6 +103579,8 @@ export namespace Schemas {
* @nullable
*/
readonly user_access_level: string | null;
+ /** Whether the project has configured access controls for shared content or its underlying data. */
+ readonly has_relevant_access_controls: boolean;
}
export interface ShipVariant {