mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
feat(web): persist Access Control through network access groups
Keep Studio Access Control as a draft until Save, including the master switch. Show referenced apps when editing or deleting an IP policy, and bind workspace policies to apps through the console network access APIs.
This commit is contained in:
1 parent
d861a0f5b1
commit
f6a7e64dbd
49 files changed
+1618
-186
No files matched your search
@@ -5,7 +5,8 @@ import userEvent from '@testing-library/user-event'
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
|
||||
import { useState } from 'react'
|
||||
import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { seedNetworkAccessGroups } from '@/test/console/network-access'
|
||||
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { ACCOUNT_SETTING_TAB } from '../constants'
|
||||
import AccountSetting from '../index'
|
||||
|
||||
@@ -189,11 +190,15 @@ describe('AccountSetting', () => {
|
||||
)
|
||||
}
|
||||
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedNetworkAccessGroups(queryClient, { entitled: false, groups: [] })
|
||||
|
||||
return renderWithConsoleQuery(
|
||||
<NuqsTestingAdapter>
|
||||
<StatefulAccountSetting />
|
||||
</NuqsTestingAdapter>,
|
||||
{
|
||||
queryClient,
|
||||
features: {
|
||||
billing: { subscription: { plan: 'sandbox' } },
|
||||
can_replace_logo: canReplaceLogo,
|
||||
@@ -566,6 +571,20 @@ describe('AccountSetting', () => {
|
||||
).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should hide IP Policies for workspace members', () => {
|
||||
mockConsoleState.current = {
|
||||
...baseConsoleState,
|
||||
isCurrentWorkspaceManager: false,
|
||||
isCurrentWorkspaceOwner: false,
|
||||
}
|
||||
|
||||
renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.IP_POLICIES })
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'common.settings.ipPolicies' }),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('should change active tab when clicking on menu item', () => {
|
||||
// Arrange
|
||||
renderAccountSetting({ onTabChange: mockOnTabChange })
|
||||
|
||||
@@ -74,11 +74,10 @@ export default function AccountSetting({
|
||||
systemFeatures.deployment_edition === 'CLOUD' && !isCurrentWorkspaceDatasetOperator
|
||||
const canViewWorkflowLogArchives =
|
||||
systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceManager
|
||||
const canViewIpPolicies =
|
||||
systemFeatures.deployment_edition === 'CLOUD' && isCurrentWorkspaceManager
|
||||
const activeMenu = (() => {
|
||||
if (
|
||||
activeTab === ACCOUNT_SETTING_TAB.IP_POLICIES &&
|
||||
systemFeatures.deployment_edition !== 'CLOUD'
|
||||
)
|
||||
if (activeTab === ACCOUNT_SETTING_TAB.IP_POLICIES && !canViewIpPolicies)
|
||||
return ACCOUNT_SETTING_TAB.MEMBERS
|
||||
if (activeTab === ACCOUNT_SETTING_TAB.BILLING && !canViewBilling)
|
||||
return ACCOUNT_SETTING_TAB.PREFERENCES
|
||||
@@ -154,8 +153,7 @@ export default function AccountSetting({
|
||||
const visibleTabs: AccountSettingTab[] = []
|
||||
|
||||
visibleTabs.push(ACCOUNT_SETTING_TAB.MEMBERS)
|
||||
if (systemFeatures.deployment_edition === 'CLOUD')
|
||||
visibleTabs.push(ACCOUNT_SETTING_TAB.IP_POLICIES)
|
||||
if (canViewIpPolicies) visibleTabs.push(ACCOUNT_SETTING_TAB.IP_POLICIES)
|
||||
|
||||
if (canManageWorkspaceRoles) {
|
||||
visibleTabs.push(ACCOUNT_SETTING_TAB.ROLES_AND_PERMISSIONS)
|
||||
|
||||
+130
-3
@@ -1,11 +1,18 @@
|
||||
import { screen } from '@testing-library/react'
|
||||
import { screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { render } from '@/test/console/render'
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
|
||||
import {
|
||||
createNetworkAccessGroupFixture,
|
||||
seedNetworkAccessGroups,
|
||||
} from '@/test/console/network-access'
|
||||
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import IpPoliciesPage from '..'
|
||||
|
||||
const translations = vi.hoisted(() => ({
|
||||
'operation.cancel': 'Cancel',
|
||||
'operation.close': 'Close',
|
||||
'operation.delete': 'Delete',
|
||||
'operation.edit': 'Edit',
|
||||
'settings.ipPolicies': 'IP Policies',
|
||||
'settings.ipPoliciesDescription':
|
||||
'Reusable rules that control which IP addresses or ranges can access your apps',
|
||||
@@ -14,8 +21,15 @@ const translations = vi.hoisted(() => ({
|
||||
'settings.ipPolicyAllowlistHelp':
|
||||
'Single addresses (203.0.113.42) or CIDR ranges (10.0.0.0/8). IPv4 and IPv6 are both accepted.',
|
||||
'settings.ipPolicyCreate': 'Create',
|
||||
'settings.ipPolicyDeleteBound': 'This policy is in use',
|
||||
'settings.ipPolicyDeleteBoundDescription':
|
||||
'{{name}} is applied to {{count}} apps. Deleting it turns off IP restriction for those apps, so they can be reached from any IP. Other app permissions stay the same.',
|
||||
'settings.ipPolicyDeleteConfirm': 'Delete “{{name}}”?',
|
||||
'settings.ipPolicyEditUsedBy':
|
||||
'This policy is used by {{count}} apps. Saving updates the allowlist for all of them.',
|
||||
'settings.ipPolicyDialogDescription':
|
||||
'Specify which IP addresses or ranges can access your apps.',
|
||||
'settings.ipPolicyEditTitle': 'Edit IP Policy',
|
||||
'settings.ipPolicyName': 'Name',
|
||||
'settings.ipPolicyNamePlaceholder': 'e.g. Internal Network',
|
||||
'settings.ipPolicyNewTitle': 'New IP Policy',
|
||||
@@ -23,6 +37,7 @@ const translations = vi.hoisted(() => ({
|
||||
'studio.accessControl.emptyPoliciesDescription':
|
||||
'A policy is the list of IP addresses allowed in. Create one, then come back to apply it here.',
|
||||
'studio.accessControl.emptyPoliciesTitle': 'No IP policies in this workspace yet',
|
||||
'studio.accessControl.policySummaryTwo': 'Allows {{first}} and {{second}}',
|
||||
}))
|
||||
|
||||
vi.mock('react-i18next', async () => {
|
||||
@@ -33,11 +48,123 @@ vi.mock('react-i18next', async () => {
|
||||
describe('IpPoliciesPage', () => {
|
||||
it('opens the new policy dialog from Add', async () => {
|
||||
const user = userEvent.setup()
|
||||
render(<IpPoliciesPage />)
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedNetworkAccessGroups(queryClient, { entitled: true, groups: [] })
|
||||
renderWithConsoleQuery(
|
||||
<NuqsTestingAdapter>
|
||||
<IpPoliciesPage />
|
||||
</NuqsTestingAdapter>,
|
||||
{ queryClient },
|
||||
)
|
||||
|
||||
expect(screen.getByText('No IP policies in this workspace yet')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Add' }))
|
||||
expect(screen.getByRole('heading', { name: 'New IP Policy' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Create' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('lists existing policies and opens edit from the row', async () => {
|
||||
const user = userEvent.setup()
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedNetworkAccessGroups(queryClient, {
|
||||
entitled: true,
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
})
|
||||
renderWithConsoleQuery(
|
||||
<NuqsTestingAdapter>
|
||||
<IpPoliciesPage />
|
||||
</NuqsTestingAdapter>,
|
||||
{ queryClient },
|
||||
)
|
||||
|
||||
expect(screen.getByText('Internal Network')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
expect(screen.getByRole('heading', { name: 'Edit IP Policy' })).toBeInTheDocument()
|
||||
expect(screen.getByDisplayValue('Internal Network')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('warns that editing a used policy updates every referencing app', async () => {
|
||||
const user = userEvent.setup()
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedNetworkAccessGroups(queryClient, {
|
||||
entitled: true,
|
||||
groups: [
|
||||
createNetworkAccessGroupFixture({
|
||||
used_by_count: 2,
|
||||
app_ids: ['app-a', 'app-b'],
|
||||
apps: [
|
||||
{
|
||||
id: 'app-a',
|
||||
name: 'Support Bot',
|
||||
icon: null,
|
||||
icon_type: null,
|
||||
icon_background: null,
|
||||
},
|
||||
{ id: 'app-b', name: 'Helpdesk', icon: null, icon_type: null, icon_background: null },
|
||||
],
|
||||
}),
|
||||
],
|
||||
})
|
||||
renderWithConsoleQuery(
|
||||
<NuqsTestingAdapter>
|
||||
<IpPoliciesPage />
|
||||
</NuqsTestingAdapter>,
|
||||
{ queryClient },
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
expect(
|
||||
screen.getByText(
|
||||
'This policy is used by 2 apps. Saving updates the allowlist for all of them.',
|
||||
),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByRole('link', { name: 'Support Bot' })).toHaveAttribute(
|
||||
'href',
|
||||
'/app/app-a/overview',
|
||||
)
|
||||
})
|
||||
|
||||
it('lets the user delete a referenced policy after confirming the impact', async () => {
|
||||
const user = userEvent.setup()
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedNetworkAccessGroups(queryClient, {
|
||||
entitled: true,
|
||||
groups: [
|
||||
createNetworkAccessGroupFixture({
|
||||
used_by_count: 2,
|
||||
app_ids: ['app-a', 'app-b'],
|
||||
apps: [
|
||||
{
|
||||
id: 'app-a',
|
||||
name: 'Support Bot',
|
||||
icon: null,
|
||||
icon_type: null,
|
||||
icon_background: null,
|
||||
},
|
||||
{ id: 'app-b', name: 'Helpdesk', icon: null, icon_type: null, icon_background: null },
|
||||
],
|
||||
}),
|
||||
],
|
||||
})
|
||||
renderWithConsoleQuery(
|
||||
<NuqsTestingAdapter>
|
||||
<IpPoliciesPage />
|
||||
</NuqsTestingAdapter>,
|
||||
{ queryClient },
|
||||
)
|
||||
|
||||
await user.click(screen.getAllByRole('button', { name: 'Delete' })[0] as HTMLElement)
|
||||
expect(screen.getByRole('heading', { name: 'Delete “Internal Network”?' })).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Internal Network is applied to 2 apps. Deleting it turns off IP restriction for those apps, so they can be reached from any IP. Other app permissions stay the same.',
|
||||
),
|
||||
).toBeInTheDocument()
|
||||
const dialog = screen.getByRole('alertdialog')
|
||||
expect(within(dialog).getByRole('button', { name: 'Delete' })).toBeEnabled()
|
||||
expect(within(dialog).getByRole('link', { name: 'Support Bot' })).toHaveAttribute(
|
||||
'href',
|
||||
'/app/app-a/overview',
|
||||
)
|
||||
})
|
||||
})
|
||||
+2
-2
@@ -34,7 +34,7 @@ function DialogHarness({
|
||||
onSubmit = vi.fn(),
|
||||
}: {
|
||||
currentIp?: string
|
||||
onSubmit?: (payload: { name: string; addresses: string[] }) => void
|
||||
onSubmit?: (payload: { name: string; allowed_cidrs: string[] }) => void
|
||||
}) {
|
||||
const [open, setOpen] = useState(true)
|
||||
return (
|
||||
@@ -107,7 +107,7 @@ describe('IpPolicyDialog', () => {
|
||||
|
||||
expect(onSubmit).toHaveBeenCalledWith({
|
||||
name: 'Internal Network',
|
||||
addresses: ['10.0.0.0/8', '203.0.113.42'],
|
||||
allowed_cidrs: ['10.0.0.0/8', '203.0.113.42/32'],
|
||||
})
|
||||
})
|
||||
})
|
||||
+41
-1
@@ -1,4 +1,12 @@
|
||||
import { canSubmitIpPolicy, collectIpAddresses, validateIpEntry } from '../validate-ip-entry'
|
||||
import {
|
||||
canSubmitIpPolicy,
|
||||
collectAllowedCidrs,
|
||||
collectIpAddresses,
|
||||
IP_POLICY_CIDR_MAX_COUNT,
|
||||
IP_POLICY_NAME_MAX_LENGTH,
|
||||
toAllowedCidr,
|
||||
validateIpEntry,
|
||||
} from '../validate-ip-entry'
|
||||
|
||||
describe('validateIpEntry', () => {
|
||||
it('treats blank input as empty, not invalid', () => {
|
||||
@@ -86,3 +94,35 @@ describe('collectIpAddresses', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('toAllowedCidr', () => {
|
||||
it('appends /32 to bare IPv4 addresses and /128 to bare IPv6 addresses', () => {
|
||||
expect(toAllowedCidr('203.0.113.42')).toBe('203.0.113.42/32')
|
||||
expect(toAllowedCidr('::1')).toBe('::1/128')
|
||||
expect(toAllowedCidr('10.0.0.0/8')).toBe('10.0.0.0/8')
|
||||
})
|
||||
})
|
||||
|
||||
describe('collectAllowedCidrs', () => {
|
||||
it('normalizes submitted entries to CIDR notation', () => {
|
||||
expect(collectAllowedCidrs([' 203.0.113.42 ', '', '10.0.0.0/8'])).toEqual([
|
||||
'203.0.113.42/32',
|
||||
'10.0.0.0/8',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('canSubmitIpPolicy limits', () => {
|
||||
it('rejects names longer than the API maximum', () => {
|
||||
expect(canSubmitIpPolicy('n'.repeat(IP_POLICY_NAME_MAX_LENGTH + 1), ['10.0.0.0/8'])).toBe(false)
|
||||
expect(canSubmitIpPolicy('n'.repeat(IP_POLICY_NAME_MAX_LENGTH), ['10.0.0.0/8'])).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects more CIDRs than the API maximum', () => {
|
||||
const cidrs = Array.from(
|
||||
{ length: IP_POLICY_CIDR_MAX_COUNT + 1 },
|
||||
(_, index) => `10.0.0.${index}`,
|
||||
)
|
||||
expect(canSubmitIpPolicy('Office', cidrs)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,13 +1,82 @@
|
||||
'use client'
|
||||
|
||||
import type { NetworkAccessGroupResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useQueryState } from 'nuqs'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { getNetworkAccessErrorStatus } from '@/app/components/app/access-point/access-control/network-access'
|
||||
import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'
|
||||
import {
|
||||
pricingQueryParamName,
|
||||
pricingQueryParser,
|
||||
} from '@/app/components/billing/pricing/query-params'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { IpPolicyDialog } from './policy-dialog'
|
||||
import { PolicyItem } from './policy-item'
|
||||
|
||||
type DialogState = { mode: 'create' } | { mode: 'edit'; group: NetworkAccessGroupResponse } | null
|
||||
|
||||
function IpPoliciesListSkeleton() {
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<div role="status" aria-label={t(($) => $.loading, { ns: 'common' })} className="space-y-2">
|
||||
{Array.from({ length: 2 }, (_, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="rounded-xl border-[0.5px] border-components-card-border bg-components-card-bg p-4 shadow-xs"
|
||||
>
|
||||
<SkeletonContainer className="h-14">
|
||||
<SkeletonRow>
|
||||
<div className="flex flex-1 flex-col gap-1">
|
||||
<SkeletonRectangle className="h-4 w-1/3 animate-pulse" />
|
||||
<SkeletonRectangle className="h-3 w-1/2 animate-pulse" />
|
||||
</div>
|
||||
</SkeletonRow>
|
||||
</SkeletonContainer>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default function IpPoliciesPage() {
|
||||
const { t } = useTranslation()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const queryClient = useQueryClient()
|
||||
const [_pricing, setPricing] = useQueryState(pricingQueryParamName, pricingQueryParser)
|
||||
const groupsQuery = consoleQuery.workspaces.current.networkAccessGroups.get.queryOptions({
|
||||
retry: false,
|
||||
})
|
||||
const { data, isPending, isError } = useQuery(groupsQuery)
|
||||
const createGroup = useMutation(
|
||||
consoleQuery.workspaces.current.networkAccessGroups.post.mutationOptions(),
|
||||
)
|
||||
const updateGroup = useMutation(
|
||||
consoleQuery.workspaces.current.networkAccessGroups.byGroupId.put.mutationOptions(),
|
||||
)
|
||||
const [dialogState, setDialogState] = useState<DialogState>(null)
|
||||
const groups = data?.groups ?? []
|
||||
const entitled = data?.entitled === true
|
||||
const editingGroup = dialogState?.mode === 'edit' ? dialogState.group : null
|
||||
const isSaving = createGroup.isPending || updateGroup.isPending
|
||||
|
||||
const refreshGroupsAfterConflict = async (groupId?: string) => {
|
||||
const refreshed = await queryClient.fetchQuery(groupsQuery)
|
||||
if (!groupId) return
|
||||
const nextGroup = refreshed.groups.find((group) => group.id === groupId)
|
||||
setDialogState(nextGroup ? { mode: 'edit', group: nextGroup } : null)
|
||||
}
|
||||
|
||||
const handleOpenCreate = () => {
|
||||
if (isError) return
|
||||
if (!entitled) {
|
||||
void setPricing('open')
|
||||
return
|
||||
}
|
||||
setDialogState({ mode: 'create' })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
@@ -20,21 +89,92 @@ export default function IpPoliciesPage() {
|
||||
{t(($) => $['settings.ipPoliciesDescription'], { ns: 'common' })}
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="primary" size="small" onClick={() => setDialogOpen(true)}>
|
||||
<Button variant="primary" size="small" onClick={handleOpenCreate}>
|
||||
{t(($) => $['settings.ipPolicyAddEntry'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center gap-1 py-10 text-center">
|
||||
<p className="system-sm-medium text-text-secondary">
|
||||
{t(($) => $['studio.accessControl.emptyPoliciesTitle'], { ns: 'deployments' })}
|
||||
{isPending && <IpPoliciesListSkeleton />}
|
||||
{!isPending && isError && (
|
||||
<p className="py-10 text-center system-sm-regular text-text-tertiary">
|
||||
{t(($) => $['common.loadFailed'], { ns: 'deployments' })}
|
||||
</p>
|
||||
<p className="max-w-md system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['studio.accessControl.emptyPoliciesDescription'], { ns: 'deployments' })}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dialogOpen && <IpPolicyDialog mode="create" open onOpenChange={setDialogOpen} />}
|
||||
{!isPending && !isError && groups.length === 0 && (
|
||||
<div className="flex flex-col items-center gap-1 py-10 text-center">
|
||||
<p className="system-sm-medium text-text-secondary">
|
||||
{t(($) => $['studio.accessControl.emptyPoliciesTitle'], { ns: 'deployments' })}
|
||||
</p>
|
||||
<p className="max-w-md system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['studio.accessControl.emptyPoliciesDescription'], { ns: 'deployments' })}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isPending && groups.length > 0 && (
|
||||
<div className="flex flex-col gap-2">
|
||||
{groups.map((group) => (
|
||||
<PolicyItem
|
||||
key={group.id}
|
||||
group={group}
|
||||
canMutate={entitled}
|
||||
onEdit={(nextGroup) => setDialogState({ mode: 'edit', group: nextGroup })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{dialogState && (
|
||||
<IpPolicyDialog
|
||||
mode={dialogState.mode}
|
||||
open
|
||||
initialName={editingGroup?.name}
|
||||
initialEntries={editingGroup?.allowed_cidrs}
|
||||
usedByCount={editingGroup?.used_by_count}
|
||||
referencedApps={editingGroup?.apps}
|
||||
isPending={isSaving}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDialogState(null)
|
||||
}}
|
||||
onSubmit={(payload) => {
|
||||
if (editingGroup) {
|
||||
updateGroup.mutate(
|
||||
{
|
||||
params: { group_id: editingGroup.id },
|
||||
body: {
|
||||
name: payload.name,
|
||||
description: editingGroup.description ?? '',
|
||||
allowed_cidrs: payload.allowed_cidrs,
|
||||
expected_version: editingGroup.version,
|
||||
},
|
||||
},
|
||||
{
|
||||
onSuccess: () => setDialogState(null),
|
||||
onError: (error) => {
|
||||
if (getNetworkAccessErrorStatus(error) !== 409) return
|
||||
void refreshGroupsAfterConflict(editingGroup.id)
|
||||
},
|
||||
},
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
createGroup.mutate(
|
||||
{
|
||||
body: {
|
||||
name: payload.name,
|
||||
description: '',
|
||||
allowed_cidrs: payload.allowed_cidrs,
|
||||
},
|
||||
},
|
||||
{
|
||||
onSuccess: () => setDialogState(null),
|
||||
},
|
||||
)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
'use client'
|
||||
|
||||
import type { NetworkAccessGroupResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
@@ -15,11 +16,16 @@ import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { AllowlistField } from './allowlist-field'
|
||||
import { createAllowlistRow } from './allowlist-row'
|
||||
import { canSubmitIpPolicy, collectIpAddresses } from './validate-ip-entry'
|
||||
import { PolicyReferencedApps } from './referenced-apps'
|
||||
import {
|
||||
canSubmitIpPolicy,
|
||||
collectAllowedCidrs,
|
||||
IP_POLICY_NAME_MAX_LENGTH,
|
||||
} from './validate-ip-entry'
|
||||
|
||||
export type IpPolicyDialogSubmit = {
|
||||
name: string
|
||||
addresses: string[]
|
||||
allowed_cidrs: string[]
|
||||
}
|
||||
|
||||
type IpPolicyDialogProps = {
|
||||
@@ -28,6 +34,9 @@ type IpPolicyDialogProps = {
|
||||
currentIp?: string
|
||||
initialName?: string
|
||||
initialEntries?: readonly string[]
|
||||
usedByCount?: number
|
||||
referencedApps?: NetworkAccessGroupResponse['apps']
|
||||
isPending?: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit?: (payload: IpPolicyDialogSubmit) => void
|
||||
}
|
||||
@@ -38,6 +47,9 @@ export function IpPolicyDialog({
|
||||
currentIp,
|
||||
initialName = '',
|
||||
initialEntries,
|
||||
usedByCount = 0,
|
||||
referencedApps = [],
|
||||
isPending = false,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: IpPolicyDialogProps) {
|
||||
@@ -68,6 +80,17 @@ export function IpPolicyDialog({
|
||||
<DialogDescription className="system-sm-regular text-text-tertiary">
|
||||
{t(($) => $['settings.ipPolicyDialogDescription'], { ns: 'common' })}
|
||||
</DialogDescription>
|
||||
{mode === 'edit' && usedByCount > 0 && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<p className="system-xs-regular text-text-warning">
|
||||
{t(($) => $['settings.ipPolicyEditUsedBy'], {
|
||||
ns: 'common',
|
||||
count: usedByCount,
|
||||
})}
|
||||
</p>
|
||||
<PolicyReferencedApps apps={referencedApps} usedByCount={usedByCount} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogClose
|
||||
render={
|
||||
@@ -89,7 +112,7 @@ export function IpPolicyDialog({
|
||||
if (!canSubmit) return
|
||||
onSubmit?.({
|
||||
name: name.trim(),
|
||||
addresses: collectIpAddresses(entryValues),
|
||||
allowed_cidrs: collectAllowedCidrs(entryValues),
|
||||
})
|
||||
}}
|
||||
>
|
||||
@@ -97,6 +120,7 @@ export function IpPolicyDialog({
|
||||
<FieldLabel>{t(($) => $['settings.ipPolicyName'], { ns: 'common' })}</FieldLabel>
|
||||
<Input
|
||||
value={name}
|
||||
maxLength={IP_POLICY_NAME_MAX_LENGTH}
|
||||
placeholder={t(($) => $['settings.ipPolicyNamePlaceholder'], { ns: 'common' })}
|
||||
onChange={(event) => setName(event.currentTarget.value)}
|
||||
/>
|
||||
@@ -108,7 +132,12 @@ export function IpPolicyDialog({
|
||||
<Button type="button" variant="secondary" onClick={() => onOpenChange(false)}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" disabled={!canSubmit}>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="primary"
|
||||
disabled={!canSubmit || isPending}
|
||||
loading={isPending}
|
||||
>
|
||||
{mode === 'edit'
|
||||
? t(($) => $['operation.save'], { ns: 'common' })
|
||||
: t(($) => $['settings.ipPolicyCreate'], { ns: 'common' })}
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
'use client'
|
||||
|
||||
import type { NetworkAccessGroupResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { AppIconType } from '@/types/app'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogActions,
|
||||
AlertDialogCancelButton,
|
||||
AlertDialogConfirmButton,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogTitle,
|
||||
} from '@langgenius/dify-ui/alert-dialog'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import AppIcon from '@/app/components/base/app-icon'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { PolicyReferencedApps } from './referenced-apps'
|
||||
import { splitPolicySummary } from './validate-ip-entry'
|
||||
|
||||
function toAppIconType(iconType: string | null | undefined): AppIconType | undefined {
|
||||
if (iconType === 'image' || iconType === 'emoji' || iconType === 'link') return iconType
|
||||
}
|
||||
|
||||
type PolicyItemProps = {
|
||||
group: NetworkAccessGroupResponse
|
||||
canMutate: boolean
|
||||
onEdit: (group: NetworkAccessGroupResponse) => void
|
||||
}
|
||||
|
||||
export function PolicyItem({ group, canMutate, onEdit }: PolicyItemProps) {
|
||||
const { t } = useTranslation()
|
||||
const [confirmDelete, setConfirmDelete] = useState(false)
|
||||
const deleteGroup = useMutation(
|
||||
consoleQuery.workspaces.current.networkAccessGroups.byGroupId.delete.mutationOptions(),
|
||||
)
|
||||
const summary = splitPolicySummary(group.allowed_cidrs)
|
||||
const isBound = group.used_by_count > 0
|
||||
const usedByNames = group.apps.map((app) => app.name).filter(Boolean)
|
||||
|
||||
const handleDelete = () => {
|
||||
if (!canMutate) return
|
||||
|
||||
deleteGroup.mutate(
|
||||
{
|
||||
params: { group_id: group.id },
|
||||
query: { expected_version: group.version },
|
||||
},
|
||||
{
|
||||
onSuccess: () => {
|
||||
setConfirmDelete(false)
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group flex items-center rounded-xl border-[0.5px] border-transparent bg-components-input-bg-normal px-4 py-3 focus-within:border-components-input-border-active focus-within:shadow-xs hover:border-components-input-border-active hover:shadow-xs">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate system-sm-medium text-text-secondary">{group.name}</p>
|
||||
<p className="truncate system-xs-regular text-text-tertiary">
|
||||
{summary.listed.length === 0
|
||||
? t(($) => $['studio.accessControl.policySummaryNone'], { ns: 'deployments' })
|
||||
: summary.listed.length === 1
|
||||
? t(($) => $['studio.accessControl.policySummaryOne'], {
|
||||
ns: 'deployments',
|
||||
address: summary.listed[0],
|
||||
})
|
||||
: summary.moreCount > 0
|
||||
? t(($) => $['studio.accessControl.policySummaryMany'], {
|
||||
ns: 'deployments',
|
||||
listed: summary.listed.join(', '),
|
||||
count: summary.moreCount,
|
||||
})
|
||||
: t(($) => $['studio.accessControl.policySummaryTwo'], {
|
||||
ns: 'deployments',
|
||||
first: summary.listed[0],
|
||||
second: summary.listed[1],
|
||||
})}
|
||||
</p>
|
||||
{isBound && (
|
||||
<div className="mt-1.5 flex min-w-0 items-center gap-1.5">
|
||||
<div className="flex items-center -space-x-1">
|
||||
{group.apps.slice(0, 3).map((app) => (
|
||||
<AppIcon
|
||||
key={app.id}
|
||||
size="xs"
|
||||
decorative
|
||||
iconType={toAppIconType(app.icon_type)}
|
||||
icon={app.icon ?? undefined}
|
||||
background={app.icon_background}
|
||||
className="rounded-sm ring-1 ring-components-panel-bg"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<p className="min-w-0 truncate system-xs-regular text-text-tertiary">
|
||||
{usedByNames.length > 0
|
||||
? usedByNames.join(', ')
|
||||
: t(($) => $['settings.ipPolicyUsedBy'], {
|
||||
ns: 'common',
|
||||
count: group.used_by_count,
|
||||
})}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="pointer-events-none flex shrink-0 items-center gap-1 opacity-0 transition-opacity group-focus-within:pointer-events-auto group-focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100">
|
||||
<Button disabled={!canMutate} onClick={() => canMutate && onEdit(group)}>
|
||||
<span className="i-ri-edit-line size-4" aria-hidden="true" />
|
||||
{t(($) => $['operation.edit'], { ns: 'common' })}
|
||||
</Button>
|
||||
<Button disabled={!canMutate} onClick={() => canMutate && setConfirmDelete(true)}>
|
||||
<span className="i-ri-delete-bin-line size-4" aria-hidden="true" />
|
||||
{t(($) => $['operation.delete'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
<AlertDialog open={confirmDelete} onOpenChange={setConfirmDelete}>
|
||||
<AlertDialogContent backdropProps={{ forceRender: true }} className="w-100">
|
||||
<div className="flex flex-col gap-2 p-6 pb-4">
|
||||
<AlertDialogTitle className="title-xl-semi-bold text-text-primary">
|
||||
{t(($) => $['settings.ipPolicyDeleteConfirm'], { ns: 'common', name: group.name })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="system-sm-regular text-text-secondary">
|
||||
{isBound
|
||||
? t(($) => $['settings.ipPolicyDeleteBoundDescription'], {
|
||||
ns: 'common',
|
||||
name: group.name,
|
||||
count: group.used_by_count,
|
||||
})
|
||||
: t(($) => $['settings.ipPolicyDeleteDescription'], { ns: 'common' })}
|
||||
</AlertDialogDescription>
|
||||
{isBound && (
|
||||
<PolicyReferencedApps apps={group.apps} usedByCount={group.used_by_count} />
|
||||
)}
|
||||
</div>
|
||||
<AlertDialogActions>
|
||||
<AlertDialogCancelButton variant="secondary">
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</AlertDialogCancelButton>
|
||||
<AlertDialogConfirmButton
|
||||
disabled={!canMutate || deleteGroup.isPending}
|
||||
onClick={handleDelete}
|
||||
>
|
||||
{t(($) => $['operation.delete'], { ns: 'common' })}
|
||||
</AlertDialogConfirmButton>
|
||||
</AlertDialogActions>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
'use client'
|
||||
|
||||
import type { NetworkAccessGroupResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { AppIconType } from '@/types/app'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import AppIcon from '@/app/components/base/app-icon'
|
||||
|
||||
type PolicyReferencedAppsProps = {
|
||||
apps: NetworkAccessGroupResponse['apps']
|
||||
usedByCount: number
|
||||
}
|
||||
|
||||
function toAppIconType(iconType: string | null | undefined): AppIconType | undefined {
|
||||
if (iconType === 'image' || iconType === 'emoji' || iconType === 'link') return iconType
|
||||
}
|
||||
|
||||
export function PolicyReferencedApps({ apps, usedByCount }: PolicyReferencedAppsProps) {
|
||||
const { t } = useTranslation()
|
||||
|
||||
if (apps.length === 0) {
|
||||
if (usedByCount <= 0) return null
|
||||
|
||||
return (
|
||||
<p className="system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['settings.ipPolicyUsedBy'], { ns: 'common', count: usedByCount })}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="flex flex-col gap-1">
|
||||
{apps.map((app) => (
|
||||
<li key={app.id}>
|
||||
<a
|
||||
href={`/app/${app.id}/overview`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex min-w-0 items-center gap-1.5 rounded-md py-0.5 pr-1 outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"
|
||||
>
|
||||
<AppIcon
|
||||
size="xs"
|
||||
decorative
|
||||
iconType={toAppIconType(app.icon_type)}
|
||||
icon={app.icon ?? undefined}
|
||||
background={app.icon_background}
|
||||
className="rounded-sm"
|
||||
/>
|
||||
<span className="min-w-0 truncate system-xs-medium text-text-secondary">
|
||||
{app.name}
|
||||
</span>
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -100,13 +100,17 @@ export function validateIpEntry(raw: string): IpEntryValidation {
|
||||
return { kind: 'invalid', code: 'unsupported' }
|
||||
}
|
||||
|
||||
export const IP_POLICY_NAME_MAX_LENGTH = 100
|
||||
export const IP_POLICY_CIDR_MAX_COUNT = 100
|
||||
|
||||
export function canSubmitIpPolicy(name: string, entries: readonly string[]) {
|
||||
if (name.trim() === '') return false
|
||||
const trimmedName = name.trim()
|
||||
if (trimmedName === '' || trimmedName.length > IP_POLICY_NAME_MAX_LENGTH) return false
|
||||
|
||||
const trimmed = entries.map((entry) => entry.trim())
|
||||
if (trimmed.every((entry) => entry === '')) return false
|
||||
const cidrs = collectAllowedCidrs(entries)
|
||||
if (cidrs.length === 0 || cidrs.length > IP_POLICY_CIDR_MAX_COUNT) return false
|
||||
|
||||
return trimmed.every((entry) => {
|
||||
return entries.every((entry) => {
|
||||
const result = validateIpEntry(entry)
|
||||
return result.kind === 'empty' || result.kind === 'valid'
|
||||
})
|
||||
@@ -115,3 +119,59 @@ export function canSubmitIpPolicy(name: string, entries: readonly string[]) {
|
||||
export function collectIpAddresses(entries: readonly string[]) {
|
||||
return entries.map((entry) => entry.trim()).filter((entry) => entry.length > 0)
|
||||
}
|
||||
|
||||
export function toAllowedCidr(entry: string): string {
|
||||
const value = entry.trim()
|
||||
if (value.includes('/')) return value
|
||||
if (value.includes(':')) return `${value}/128`
|
||||
return `${value}/32`
|
||||
}
|
||||
|
||||
export function collectAllowedCidrs(entries: readonly string[]) {
|
||||
return collectIpAddresses(entries).map(toAllowedCidr)
|
||||
}
|
||||
|
||||
export function splitPolicySummary(addresses: readonly string[]): {
|
||||
listed: readonly string[]
|
||||
moreCount: number
|
||||
} {
|
||||
if (addresses.length <= 2) return { listed: addresses, moreCount: 0 }
|
||||
return { listed: addresses.slice(0, 2), moreCount: addresses.length - 2 }
|
||||
}
|
||||
|
||||
function ipv4ToInt(ip: string): number | null {
|
||||
const parts = ip.split('.')
|
||||
if (parts.length !== 4) return null
|
||||
|
||||
let value = 0
|
||||
for (const part of parts) {
|
||||
if (!/^\d+$/.test(part)) return null
|
||||
const octet = Number(part)
|
||||
if (octet > 255) return null
|
||||
value = (value << 8) + octet
|
||||
}
|
||||
|
||||
return value >>> 0
|
||||
}
|
||||
|
||||
function ipv4InCidr(ip: string, network: string, prefix: number): boolean {
|
||||
const ipInt = ipv4ToInt(ip)
|
||||
const networkInt = ipv4ToInt(network)
|
||||
if (ipInt === null || networkInt === null) return false
|
||||
if (prefix === 0) return true
|
||||
const mask = prefix === 32 ? 0xffffffff : ~((1 << (32 - prefix)) - 1) >>> 0
|
||||
return (ipInt & mask) === (networkInt & mask)
|
||||
}
|
||||
|
||||
export function policyIncludesIp(addresses: readonly string[], ip: string): boolean {
|
||||
return addresses.some((entry) => {
|
||||
const cidr = toAllowedCidr(entry)
|
||||
const slash = cidr.indexOf('/')
|
||||
const network = slash === -1 ? cidr : cidr.slice(0, slash)
|
||||
const prefix = slash === -1 ? (cidr.includes(':') ? 128 : 32) : Number(cidr.slice(slash + 1))
|
||||
if (network.includes(':')) return cidr === ip || network === ip
|
||||
if (entry === ip || network === ip) return true
|
||||
if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false
|
||||
return ipv4InCidr(ip, network, prefix)
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user