Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): add permission limitation for create release #8623

Merged
merged 7 commits into from
Feb 14, 2025
2 changes: 2 additions & 0 deletions packages/sanity/src/core/i18n/bundles/studio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,8 @@ export const studioLocaleStrings = defineLocalesResources('studio', {
'<strong>{{title}}</strong> version was successfully discarded',
/** Action message for when a new release is created off an existing version, draft or published document */
'release.action.new-release': 'New Release',
/** Tooltip message for not having permissions for creating new releases */
'release.action.permission.error': 'You do not have permission to perform this action',
/** Error message for when a version is set to be unpublished */
'release.action.unpublish-version.failure': 'Failed to set version to be unpublished on release',
/** Action message for when a version is set to be unpublished successfully */
Expand Down
23 changes: 20 additions & 3 deletions packages/sanity/src/core/perspective/navbar/ReleasesList.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import {AddIcon} from '@sanity/icons'
import {Box, Flex, MenuDivider, Spinner} from '@sanity/ui'
import {type RefObject, useCallback, useMemo} from 'react'
import {type RefObject, useCallback, useEffect, useMemo, useState} from 'react'
import {css, styled} from 'styled-components'

import {MenuItem} from '../../../ui-components/menuItem/MenuItem'
import {useTranslation} from '../../i18n/hooks/useTranslation'
import {useReleasesUpsell} from '../../releases/contexts/upsell/useReleasesUpsell'
import {useCreateReleaseMetadata} from '../../releases/hooks/useCreateReleaseMetadata'
import {type ReleaseDocument, type ReleaseType} from '../../releases/store/types'
import {useActiveReleases} from '../../releases/store/useActiveReleases'
import {LATEST} from '../../releases/util/const'
import {useReleaseOperations} from '../../releases/store/useReleaseOperations'
import {useReleasePermissions} from '../../releases/store/useReleasePermissions'
import {DEFAULT_RELEASE, LATEST} from '../../releases/util/const'
import {getReleaseIdFromReleaseDocumentId} from '../../releases/util/getReleaseIdFromReleaseDocumentId'
import {
getRangePosition,
Expand Down Expand Up @@ -60,8 +63,19 @@ export function ReleasesList({
}): React.JSX.Element {
const {guardWithReleaseLimitUpsell, mode} = useReleasesUpsell()
const {loading, data: releases} = useActiveReleases()
const {createRelease} = useReleaseOperations()
const {checkWithPermissionGuard} = useReleasePermissions()
const [hasCreatePermission, setHasCreatePermission] = useState<boolean | null>(null)
const createReleaseMetadata = useCreateReleaseMetadata()

const {t} = useTranslation()

useEffect(() => {
checkWithPermissionGuard(createRelease, createReleaseMetadata(DEFAULT_RELEASE)).then(
setHasCreatePermission,
)
}, [checkWithPermissionGuard, createRelease, createReleaseMetadata])

const handleCreateBundleClick = useCallback(
() => guardWithReleaseLimitUpsell(() => setCreateBundleDialogOpen(true)),
[guardWithReleaseLimitUpsell, setCreateBundleDialogOpen],
Expand Down Expand Up @@ -156,10 +170,13 @@ export function ReleasesList({
<MenuDivider />
<MenuItem
icon={AddIcon}
disabled={mode === 'disabled'}
disabled={!hasCreatePermission || mode === 'disabled'}
onClick={handleCreateBundleClick}
text={t('release.action.create-new')}
data-testid="create-new-release-button"
tooltipProps={{
content: !hasCreatePermission && t('release.action.permission.error'),
}}
/>
</>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,20 @@ import {
mockUseActiveReleases,
useActiveReleasesMockReturn,
} from '../../../releases/store/__tests__/__mocks/useActiveReleases.mock'
import {
mockUseReleasePermissions,
useReleasePermissionsMockReturn,
} from '../../../releases/store/__tests__/__mocks/useReleasePermissions.mock'
import {ReleasesList} from '../ReleasesList'

vi.mock('../../../releases/contexts/upsell/useReleasesUpsell', () => ({
useReleasesUpsell: vi.fn(() => useReleasesUpsellMockReturn),
}))

vi.mock('../../../releases/store/useReleasePermissions', () => ({
useReleasePermissions: vi.fn(() => useReleasePermissionsMockReturn),
}))

vi.mock('../../../releases/store/useActiveReleases', () => ({
useActiveReleases: vi.fn(() => useActiveReleasesMockReturn),
}))
Expand All @@ -32,6 +40,9 @@ describe('ReleasesList', () => {
...useActiveReleasesMockReturn,
data: [activeASAPRelease, activeScheduledRelease, activeUndecidedRelease],
})
mockUseReleasePermissions.mockReturnValue({
checkWithPermissionGuard: async () => true,
})
const wrapper = await createTestProvider()
render(
<Menu>
Expand All @@ -55,7 +66,11 @@ describe('ReleasesList', () => {
expect(screen.getByText('undecided Release')).toBeInTheDocument()
})

it('calls setCreateBundleDialogOpen when create new release button is clicked', () => {
it('calls setCreateBundleDialogOpen when create new release button is clicked', async () => {
await waitFor(() =>
expect(screen.getByTestId('create-new-release-button')).not.toBeDisabled(),
)

fireEvent.click(screen.getByTestId('create-new-release-button'))
expect(setCreateBundleDialogOpen).toHaveBeenCalledWith(true)
})
Expand Down Expand Up @@ -100,4 +115,35 @@ describe('ReleasesList', () => {
expect(screen.queryByTestId('create-new-release-button')).toBeNull()
})
})

describe('when releases are enabled without permissions', () => {
beforeEach(async () => {
mockUseActiveReleases.mockReturnValue({
...useActiveReleasesMockReturn,
data: [activeASAPRelease, activeScheduledRelease, activeUndecidedRelease],
})
mockUseReleasePermissions.mockReturnValue({
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ahh nice!

checkWithPermissionGuard: async () => false,
})
const wrapper = await createTestProvider()
render(
<Menu>
<ReleasesList
setScrollContainer={vi.fn()}
onScroll={vi.fn()}
isRangeVisible={false}
selectedReleaseId={undefined}
setCreateBundleDialogOpen={setCreateBundleDialogOpen}
scrollElementRef={{current: null}}
areReleasesEnabled
/>
</Menu>,
{wrapper},
)
})

it('calls doesnt open the create dialog user has no permissions', async () => {
await waitFor(() => expect(screen.getByTestId('create-new-release-button')).toBeDisabled())
})
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,17 @@ import {
} from '../../../releases/__fixtures__/release.fixture'
import {useReleasesUpsellMockReturn} from '../../../releases/contexts/upsell/__mocks__/useReleasesUpsell.mock'
import {useActiveReleasesMockReturn} from '../../../releases/store/__tests__/__mocks/useActiveReleases.mock'
import {
mockUseReleasePermissions,
useReleasePermissionsMockReturn,
} from '../../../releases/store/__tests__/__mocks/useReleasePermissions.mock'
import {LATEST} from '../../../releases/util/const'
import {ReleasesNav} from '../ReleasesNav'

vi.mock('../../../releases/store/useReleasePermissions', () => ({
useReleasePermissions: vi.fn(() => useReleasePermissionsMockReturn),
}))

vi.mock('../../../releases/contexts/upsell/useReleasesUpsell', () => ({
useReleasesUpsell: vi.fn(() => useReleasesUpsellMockReturn),
}))
Expand Down Expand Up @@ -60,6 +68,10 @@ const renderTest = async () => {
describe('ReleasesNav', () => {
beforeEach(() => {
vi.clearAllMocks()

mockUseReleasePermissions.mockReturnValue({
checkWithPermissionGuard: async () => true,
})
})
it('should have link to releases tool', async () => {
await renderTest()
Expand Down Expand Up @@ -186,6 +198,12 @@ describe('ReleasesNav', () => {

expect(screen.getByRole('dialog')).toHaveAttribute('id', 'create-release-dialog')
})

it('disables button when no permissions are met', async () => {
mockUseReleasePermissions.mockReturnValue({
checkWithPermissionGuard: async () => true,
})
})
})

describe('release layering', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ import {releasesLocaleNamespace} from '../../i18n'
import {isReleaseLimitError} from '../../store/isReleaseLimitError'
import {type EditableReleaseDocument} from '../../store/types'
import {useReleaseOperations} from '../../store/useReleaseOperations'
import {DEFAULT_RELEASE_TYPE} from '../../util/const'
import {createReleaseId} from '../../util/createReleaseId'
import {DEFAULT_RELEASE} from '../../util/const'
import {getIsScheduledDateInPast} from '../../util/getIsScheduledDateInPast'
import {getReleaseIdFromReleaseDocumentId} from '../../util/getReleaseIdFromReleaseDocumentId'
import {ReleaseForm} from './ReleaseForm'
Expand All @@ -33,14 +32,7 @@ export function CreateReleaseDialog(props: CreateReleaseDialogProps): React.JSX.
const createReleaseMetadata = useCreateReleaseMetadata()

const [release, setRelease] = useState((): EditableReleaseDocument => {
return {
_id: createReleaseId(),
metadata: {
title: '',
description: '',
releaseType: DEFAULT_RELEASE_TYPE,
},
} as const
return DEFAULT_RELEASE
})
const [isSubmitting, setIsSubmitting] = useState(false)
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ export const VersionChip = memo(function VersionChip(props: {
disabled={contextMenuDisabled}
onCreateVersion={handleAddVersion}
locked={locked}
type={documentType}
/>
}
fallbackPlacements={[]}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import {AddIcon, CalendarIcon, CopyIcon, TrashIcon} from '@sanity/icons'
import {Menu, MenuDivider, Spinner, Stack} from '@sanity/ui'
import {memo} from 'react'
import {memo, useEffect, useState} from 'react'
import {IntentLink} from 'sanity/router'
import {styled} from 'styled-components'

import {MenuGroup} from '../../../../../ui-components/menuGroup/MenuGroup'
import {MenuItem} from '../../../../../ui-components/menuItem/MenuItem'
import {useTranslation} from '../../../../i18n/hooks/useTranslation'
import {isPublishedId} from '../../../../util/draftUtils'
import {useDocumentPairPermissions} from '../../../../store/_legacy/grants/documentPairPermissions'
import {getPublishedId, isDraftId, isPublishedId} from '../../../../util/draftUtils'
import {useReleasesUpsell} from '../../../contexts/upsell/useReleasesUpsell'
import {type ReleaseDocument} from '../../../store/types'
import {useReleaseOperations} from '../../../store/useReleaseOperations'
import {useReleasePermissions} from '../../../store/useReleasePermissions'
import {DEFAULT_RELEASE} from '../../../util/const'
import {isReleaseScheduledOrScheduling} from '../../../util/util'
import {VersionContextMenuItem} from './VersionContextMenuItem'

Expand All @@ -30,6 +34,7 @@ export const VersionContextMenu = memo(function VersionContextMenu(props: {
onCreateVersion: (targetId: string) => void
disabled?: boolean
locked?: boolean
type: string
}) {
const {
documentId,
Expand All @@ -42,6 +47,7 @@ export const VersionContextMenu = memo(function VersionContextMenu(props: {
onCreateVersion,
disabled,
locked,
type,
} = props
const {t} = useTranslation()
const {mode} = useReleasesUpsell()
Expand All @@ -50,7 +56,22 @@ export const VersionContextMenu = memo(function VersionContextMenu(props: {
value: release,
}))

const {checkWithPermissionGuard} = useReleasePermissions()
const {createRelease} = useReleaseOperations()
const [hasCreatePermission, setHasCreatePermission] = useState<boolean | null>(null)

const releaseId = isVersion ? fromRelease : documentId
const [permissions, isPermissionsLoading] = useDocumentPairPermissions({
id: getPublishedId(documentId),
type,
version: releaseId,
permission: isDraftId(documentId) ? 'discardDraft' : 'discardVersion',
})
const hasDiscardPermission = !isPermissionsLoading && permissions?.granted

useEffect(() => {
checkWithPermissionGuard(createRelease, DEFAULT_RELEASE).then(setHasCreatePermission)
}, [checkWithPermissionGuard, createRelease])

return (
<>
Expand All @@ -71,7 +92,11 @@ export const VersionContextMenu = memo(function VersionContextMenu(props: {
icon={CopyIcon}
popover={{placement: 'right-start'}}
text={t('release.action.copy-to')}
disabled={disabled}
disabled={disabled || !hasCreatePermission}
tooltipProps={{
disabled: !hasCreatePermission,
content: t('release.action.permission.error'),
}}
>
<ReleasesList key={fromRelease} space={1}>
{optionsReleaseList.map((option) => {
Expand All @@ -83,7 +108,10 @@ export const VersionContextMenu = memo(function VersionContextMenu(props: {
onClick={() => onCreateVersion(option.value._id)}
renderMenuItem={() => <VersionContextMenuItem release={option.value} />}
disabled={disabled || isReleaseScheduled}
tooltipProps={{content: isReleaseScheduled && t('release.tooltip.locked')}}
tooltipProps={{
disabled: isReleaseScheduled,
content: t('release.tooltip.locked'),
}}
/>
)
})}
Expand All @@ -103,7 +131,10 @@ export const VersionContextMenu = memo(function VersionContextMenu(props: {
icon={TrashIcon}
onClick={onDiscard}
text={t('release.action.discard-version')}
disabled={disabled || locked}
disabled={disabled || locked || !hasDiscardPermission}
tooltipProps={{
content: !hasDiscardPermission && t('release.action.permission.error'),
}}
/>
</>
)}
Expand Down
Loading
Loading