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
@@ -7,6 +7,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { seedAccountProfileQuery } from '@/test/console/account-profile'
|
||||
import { seedCurrentWorkspaceQuery } from '@/test/console/current-workspace'
|
||||
import { seedSystemFeatures } from '@/test/console/query-data'
|
||||
import { QueryClientTestProvider } from '@/test/console/query-provider'
|
||||
import { render } from '@/test/console/render'
|
||||
@@ -108,6 +109,7 @@ const renderAccessPoint = ({
|
||||
} = {}) => {
|
||||
const queryClient = createTestQueryClient()
|
||||
seedAccountProfileQuery(queryClient, mockConsoleState.userProfile)
|
||||
seedCurrentWorkspaceQuery(queryClient)
|
||||
seedSystemFeatures(queryClient)
|
||||
const queryOptions =
|
||||
consoleQuery.enterprise.appDeploy.deploymentService.listAppEnvironments.queryOptions({
|
||||
|
||||
@@ -31,20 +31,30 @@ describe('getInServiceCoverage', () => {
|
||||
})
|
||||
|
||||
describe('getAccessControlChipState', () => {
|
||||
it('returns pro for Cloud sandbox', () => {
|
||||
it('returns pro when the workspace is not entitled and has no assignment', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
plan: 'sandbox',
|
||||
assignment,
|
||||
entitled: false,
|
||||
assignment: null,
|
||||
availability,
|
||||
}).kind,
|
||||
).toBe('pro')
|
||||
})
|
||||
|
||||
it('keeps the saved assignment visible when the workspace is not entitled', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
entitled: false,
|
||||
assignment,
|
||||
availability,
|
||||
}).kind,
|
||||
).toBe('on')
|
||||
})
|
||||
|
||||
it('returns off when the app has never been configured', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
plan: 'professional',
|
||||
entitled: true,
|
||||
assignment: null,
|
||||
availability,
|
||||
}),
|
||||
@@ -54,7 +64,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns paused when a saved policy is not enforcing', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
plan: 'professional',
|
||||
entitled: true,
|
||||
assignment: { ...assignment, enabled: false },
|
||||
availability,
|
||||
}),
|
||||
@@ -69,7 +79,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns on when every in-service access point is covered', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
plan: 'team',
|
||||
entitled: true,
|
||||
assignment,
|
||||
availability,
|
||||
}),
|
||||
@@ -84,7 +94,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns partial when some in-service access points are excluded', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
plan: 'professional',
|
||||
entitled: true,
|
||||
assignment: {
|
||||
...assignment,
|
||||
scopes: { ...assignment.scopes, mcp: false },
|
||||
|
||||
@@ -22,12 +22,12 @@ const policies: AccessControlPolicy[] = [
|
||||
{
|
||||
id: 'internal-network',
|
||||
name: 'Internal Network',
|
||||
addresses: ['203.0.113.42', '198.51.100.0/24', '192.0.2.1', '192.0.2.2'],
|
||||
allowed_cidrs: ['203.0.113.42/32', '198.51.100.0/24', '192.0.2.1/32', '192.0.2.2/32'],
|
||||
},
|
||||
{
|
||||
id: 'office-vpn',
|
||||
name: 'Office VPN',
|
||||
addresses: ['198.51.100.0/24'],
|
||||
allowed_cidrs: ['198.51.100.0/24'],
|
||||
},
|
||||
]
|
||||
|
||||
@@ -113,7 +113,7 @@ describe('AccessControlConfigPanel', () => {
|
||||
await user.click(await screen.findByRole('option', { name: /Internal Network/ }))
|
||||
|
||||
expect(
|
||||
screen.getByText('Allows 203.0.113.42, 198.51.100.0/24 and 2 more addresses'),
|
||||
screen.getByText('Allows 203.0.113.42/32, 198.51.100.0/24 and 2 more addresses'),
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
|
||||
expect(screen.getByRole('switch', { name: 'Web App' })).not.toHaveAttribute(
|
||||
@@ -156,6 +156,7 @@ describe('AccessControlConfigPanel', () => {
|
||||
initialDraft={{
|
||||
...createDefaultAccessControlDraft(),
|
||||
selectedPolicyId: 'internal-network',
|
||||
enabled: true,
|
||||
}}
|
||||
availability={{ ...allScopesAvailable, mcp: false }}
|
||||
/>,
|
||||
@@ -174,6 +175,7 @@ describe('AccessControlConfigPanel', () => {
|
||||
initialDraft={{
|
||||
...createDefaultAccessControlDraft(),
|
||||
selectedPolicyId: 'internal-network',
|
||||
enabled: true,
|
||||
}}
|
||||
availability={{ webApp: true, serviceApi: true, mcp: false, trigger: false }}
|
||||
/>,
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import {
|
||||
policyIncludesIp,
|
||||
splitPolicySummary,
|
||||
} from '@/app/components/header/account-setting/ip-policies-page/validate-ip-entry'
|
||||
import { AppModeEnum } from '@/types/app'
|
||||
import {
|
||||
canSaveAccessControl,
|
||||
createDefaultAccessControlDraft,
|
||||
getAccessControlScopeAvailability,
|
||||
getAccessControlScopeSupport,
|
||||
policyIncludesIp,
|
||||
splitPolicySummary,
|
||||
} from '../draft'
|
||||
|
||||
const allScopesAvailable = {
|
||||
@@ -35,6 +37,7 @@ describe('canSaveAccessControl', () => {
|
||||
canSaveAccessControl({
|
||||
draft: {
|
||||
selectedPolicyId: 'policy-1',
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: false,
|
||||
serviceApi: false,
|
||||
@@ -61,6 +64,7 @@ describe('canSaveAccessControl', () => {
|
||||
canSaveAccessControl({
|
||||
draft: {
|
||||
selectedPolicyId: 'policy-1',
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: false,
|
||||
serviceApi: false,
|
||||
@@ -78,6 +82,7 @@ describe('canSaveAccessControl', () => {
|
||||
canSaveAccessControl({
|
||||
draft: {
|
||||
selectedPolicyId: 'policy-1',
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: false,
|
||||
serviceApi: false,
|
||||
@@ -89,6 +94,26 @@ describe('canSaveAccessControl', () => {
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('disables save when the draft matches the saved baseline', () => {
|
||||
expect(
|
||||
canSaveAccessControl({
|
||||
draft: selectedDraft,
|
||||
availability: { ...allScopesAvailable, trigger: false },
|
||||
baseline: selectedDraft,
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('allows saving a pause when a policy is already selected', () => {
|
||||
expect(
|
||||
canSaveAccessControl({
|
||||
draft: { ...selectedDraft, enabled: false },
|
||||
availability: { ...allScopesAvailable, trigger: false },
|
||||
baseline: selectedDraft,
|
||||
}),
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAccessControlScopeSupport', () => {
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import type { AppNetworkAccessGroupBindingResponse } from '@dify/contracts/api/console/apps/types.gen'
|
||||
import type { CloudPlan } from '@dify/contracts/api/console/features/types.gen'
|
||||
import type { NetworkAccessGroupResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import { screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useModalContext } from '@/context/modal-context'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import {
|
||||
createNetworkAccessGroupFixture,
|
||||
seedAppNetworkAccessGroup,
|
||||
seedNetworkAccessGroups,
|
||||
} from '@/test/console/network-access'
|
||||
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { AccessControlEntry } from '..'
|
||||
|
||||
const mockSetShowPricingModal = vi.fn()
|
||||
const mockSetPricing = vi.fn()
|
||||
const mockSetSettingsDestination = vi.fn()
|
||||
const accessControlTranslations = vi.hoisted(() => ({
|
||||
'operation.cancel': 'Cancel',
|
||||
@@ -35,16 +41,35 @@ const accessControlTranslations = vi.hoisted(() => ({
|
||||
'studio.accessControl.tooltipOff': 'Not set up',
|
||||
'studio.accessControl.tooltipPro': 'Access control requires the Pro plan',
|
||||
'studio.accessControl.turnOn': 'Turn on Access Control',
|
||||
'studio.accessControl.restrictByIp': 'Restrict by IP address',
|
||||
'studio.accessControl.restrictedTo': 'Restricted to {{name}}',
|
||||
'studio.accessControl.protectingAll': 'Protecting all {{count}} access points in service.',
|
||||
'studio.accessControl.policySummaryTwo': 'Allows {{first}} and {{second}}',
|
||||
'operation.edit': 'Edit',
|
||||
'studio.accessControl.turnOffTitle': 'Turn off access control?',
|
||||
'studio.accessControl.turnOffDescription': '{{points}} will be reachable from any IP.',
|
||||
'studio.accessControl.turnOffConfirm': 'Turn off',
|
||||
}))
|
||||
|
||||
vi.mock('@/context/modal-context', () => ({
|
||||
useModalContext: vi.fn(),
|
||||
useModalContextSelector: vi.fn(),
|
||||
vi.mock('@/app/components/app/store', () => ({
|
||||
useStore: (selector: (state: { appDetail: { id: string; mode: string } }) => unknown) =>
|
||||
selector({
|
||||
appDetail: {
|
||||
id: 'app-1',
|
||||
mode: 'chat',
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('nuqs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('nuqs')>()
|
||||
return { ...actual, useQueryState: () => [null, mockSetSettingsDestination] }
|
||||
return {
|
||||
...actual,
|
||||
useQueryState: (name: string) => {
|
||||
if (name === 'pricing') return [null, mockSetPricing]
|
||||
return [null, mockSetSettingsDestination]
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('react-i18next', async () => {
|
||||
@@ -55,11 +80,21 @@ vi.mock('react-i18next', async () => {
|
||||
const renderEntry = ({
|
||||
plan,
|
||||
deploymentEdition = 'CLOUD',
|
||||
groups = [],
|
||||
binding = null,
|
||||
}: {
|
||||
plan?: CloudPlan
|
||||
deploymentEdition?: 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE'
|
||||
groups?: NetworkAccessGroupResponse[]
|
||||
binding?: AppNetworkAccessGroupBindingResponse | null
|
||||
} = {}) => {
|
||||
const queryClient = createConsoleQueryClient()
|
||||
const entitled = plan === 'professional' || plan === 'team'
|
||||
seedNetworkAccessGroups(queryClient, { entitled, groups })
|
||||
seedAppNetworkAccessGroup(queryClient, 'app-1', { entitled, binding })
|
||||
|
||||
return renderWithConsoleQuery(<AccessControlEntry />, {
|
||||
queryClient,
|
||||
systemFeatures: { deployment_edition: deploymentEdition },
|
||||
features: plan
|
||||
? {
|
||||
@@ -76,17 +111,6 @@ const getChip = () => screen.getByRole('button', { name: /Access Control/ })
|
||||
describe('AccessControlEntry', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(useModalContext).mockReturnValue({
|
||||
hasBlockingModalOpen: false,
|
||||
setShowModerationSettingModal: vi.fn(),
|
||||
setShowExternalDataToolModal: vi.fn(),
|
||||
setShowPricingModal: mockSetShowPricingModal,
|
||||
setShowAnnotationFullModal: vi.fn(),
|
||||
setShowModelModal: vi.fn(),
|
||||
setShowExternalKnowledgeAPIModal: vi.fn(),
|
||||
setShowOpeningModal: vi.fn(),
|
||||
setShowUpdatePluginModal: vi.fn(),
|
||||
})
|
||||
})
|
||||
|
||||
it('does not render on community edition', () => {
|
||||
@@ -101,6 +125,31 @@ describe('AccessControlEntry', () => {
|
||||
expect(screen.queryByRole('button', { name: /Access Control/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a saved assignment on Cloud sandbox instead of hiding it behind the paywall', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEntry({
|
||||
plan: 'sandbox',
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
binding: {
|
||||
id: 'binding-1',
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'app-1',
|
||||
enabled: true,
|
||||
group_id: 'group-1',
|
||||
access_points: ['webapp', 'service_api', 'mcp'],
|
||||
version: 2,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
})
|
||||
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
await user.click(getChip())
|
||||
expect(screen.getByText('Restricted to Internal Network')).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Turn on Access Control' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a single chip with a non-interactive PRO badge for Cloud sandbox', () => {
|
||||
renderEntry({ plan: 'sandbox' })
|
||||
|
||||
@@ -138,7 +187,7 @@ describe('AccessControlEntry', () => {
|
||||
expect(turnOn).not.toHaveTextContent('PRO')
|
||||
await user.click(turnOn)
|
||||
|
||||
expect(mockSetShowPricingModal).toHaveBeenCalledTimes(1)
|
||||
expect(mockSetPricing).toHaveBeenCalledWith('open')
|
||||
})
|
||||
|
||||
it('closes the paywall on Escape without side effects', async () => {
|
||||
@@ -155,7 +204,7 @@ describe('AccessControlEntry', () => {
|
||||
screen.queryByText('Restrict this app to IP addresses you trust.'),
|
||||
).not.toBeInTheDocument()
|
||||
})
|
||||
expect(mockSetShowPricingModal).not.toHaveBeenCalled()
|
||||
expect(mockSetPricing).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('opens the first-time config popover for paid workspaces without a back control', async () => {
|
||||
@@ -209,6 +258,56 @@ describe('AccessControlEntry', () => {
|
||||
expect(screen.queryByText('No IP policies in this workspace yet')).not.toBeInTheDocument()
|
||||
})
|
||||
expect(mockSetSettingsDestination).not.toHaveBeenCalled()
|
||||
expect(mockSetShowPricingModal).not.toHaveBeenCalled()
|
||||
expect(mockSetPricing).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the saved binding status for a paid workspace', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEntry({
|
||||
plan: 'professional',
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
binding: {
|
||||
id: 'binding-1',
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'app-1',
|
||||
enabled: true,
|
||||
group_id: 'group-1',
|
||||
access_points: ['webapp', 'service_api', 'mcp'],
|
||||
version: 2,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
})
|
||||
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
await user.click(getChip())
|
||||
expect(screen.getByText('Restricted to Internal Network')).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Restrict by IP address' })).toBeChecked()
|
||||
})
|
||||
|
||||
it('keeps the saved chip state until a turned-off draft is saved', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEntry({
|
||||
plan: 'professional',
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
binding: {
|
||||
id: 'binding-1',
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'app-1',
|
||||
enabled: true,
|
||||
group_id: 'group-1',
|
||||
access_points: ['webapp', 'service_api', 'mcp'],
|
||||
version: 2,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
})
|
||||
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('switch', { name: 'Restrict by IP address' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Turn off' }))
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import {
|
||||
accessPointsFromScopes,
|
||||
availabilityFromAccessPoints,
|
||||
draftFromBinding,
|
||||
getNetworkAccessErrorStatus,
|
||||
scopesFromAccessPoints,
|
||||
toApiAccessPoint,
|
||||
toUiAccessPoint,
|
||||
} from '../network-access'
|
||||
|
||||
const allAvailable = {
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: true,
|
||||
trigger: true,
|
||||
}
|
||||
|
||||
describe('network access mappers', () => {
|
||||
it('maps UI access points to the Console contract', () => {
|
||||
expect(toApiAccessPoint('webApp')).toBe('webapp')
|
||||
expect(toApiAccessPoint('serviceApi')).toBe('service_api')
|
||||
expect(toUiAccessPoint('webapp')).toBe('webApp')
|
||||
expect(toUiAccessPoint('service_api')).toBe('serviceApi')
|
||||
})
|
||||
|
||||
it('builds availability from the server access-point matrix', () => {
|
||||
expect(availabilityFromAccessPoints(['webapp', 'service_api', 'mcp'], true)).toEqual({
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: true,
|
||||
trigger: false,
|
||||
})
|
||||
expect(
|
||||
availabilityFromAccessPoints(['webapp', 'service_api', 'mcp', 'trigger'], false),
|
||||
).toEqual({
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: true,
|
||||
trigger: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('reads HTTP status from Response and nested response objects', () => {
|
||||
expect(getNetworkAccessErrorStatus(new Response(null, { status: 409 }))).toBe(409)
|
||||
expect(getNetworkAccessErrorStatus({ response: { status: 409 } })).toBe(409)
|
||||
})
|
||||
|
||||
it('builds scopes from selected API access points and available ones', () => {
|
||||
expect(scopesFromAccessPoints(['webapp', 'mcp'], allAvailable)).toEqual({
|
||||
webApp: true,
|
||||
serviceApi: false,
|
||||
mcp: true,
|
||||
trigger: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('omits unavailable scopes when assembling a PUT payload', () => {
|
||||
expect(
|
||||
accessPointsFromScopes(
|
||||
{ webApp: true, serviceApi: true, mcp: true, trigger: true },
|
||||
{ ...allAvailable, trigger: false },
|
||||
),
|
||||
).toEqual(['webapp', 'service_api', 'mcp'])
|
||||
})
|
||||
|
||||
it('creates an empty draft when the app has no binding', () => {
|
||||
expect(draftFromBinding(null, allAvailable)).toEqual({
|
||||
selectedPolicyId: null,
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: true,
|
||||
trigger: true,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('hydrates a draft from a bound group', () => {
|
||||
expect(
|
||||
draftFromBinding(
|
||||
{
|
||||
id: 'binding-1',
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'app-1',
|
||||
enabled: true,
|
||||
group_id: 'group-1',
|
||||
access_points: ['webapp', 'service_api'],
|
||||
version: 3,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-01-01T00:00:00Z',
|
||||
},
|
||||
allAvailable,
|
||||
),
|
||||
).toEqual({
|
||||
selectedPolicyId: 'group-1',
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: false,
|
||||
trigger: false,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -32,19 +32,16 @@ export function getInServiceCoverage(
|
||||
}
|
||||
|
||||
export function getAccessControlChipState({
|
||||
plan,
|
||||
entitled,
|
||||
assignment,
|
||||
availability,
|
||||
}: {
|
||||
plan: string | undefined
|
||||
entitled?: boolean
|
||||
assignment: AccessControlAssignment | null
|
||||
availability: AccessControlScopeAvailability
|
||||
}): AccessControlChipState {
|
||||
if (plan === 'sandbox') {
|
||||
return { kind: 'pro', coveredCount: 0, inServiceCount: 0 }
|
||||
}
|
||||
|
||||
if (!assignment) {
|
||||
if (entitled === false) return { kind: 'pro', coveredCount: 0, inServiceCount: 0 }
|
||||
return { kind: 'off', coveredCount: 0, inServiceCount: 0 }
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { PopoverTitle } from '@langgenius/dify-ui/popover'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { canSaveAccessControl } from './draft'
|
||||
import { canSaveAccessControl, hasSelectedProtectableAccessPoint } from './draft'
|
||||
import { AccessControlPolicyField } from './policy-field'
|
||||
import { AccessControlScopeList } from './scope-list'
|
||||
|
||||
@@ -21,7 +21,9 @@ type AccessControlConfigPanelProps = {
|
||||
policies: readonly AccessControlPolicy[]
|
||||
currentIp?: string
|
||||
availability: AccessControlScopeAvailability
|
||||
baseline?: AccessControlDraft
|
||||
showBack?: boolean
|
||||
saving?: boolean
|
||||
onBack?: () => void
|
||||
onCancel: () => void
|
||||
onCreatePolicy: () => void
|
||||
@@ -35,7 +37,9 @@ export function AccessControlConfigPanel({
|
||||
policies,
|
||||
currentIp,
|
||||
availability,
|
||||
baseline,
|
||||
showBack = false,
|
||||
saving = false,
|
||||
onBack,
|
||||
onCancel,
|
||||
onCreatePolicy,
|
||||
@@ -46,7 +50,7 @@ export function AccessControlConfigPanel({
|
||||
const { t } = useTranslation()
|
||||
const title = t(($) => $['studio.accessControl.entryLabel'], { ns: 'deployments' })
|
||||
const hasSelectedPolicy = Boolean(draft.selectedPolicyId)
|
||||
const canSave = canSaveAccessControl({ draft, availability })
|
||||
const canSave = canSaveAccessControl({ draft, availability, baseline })
|
||||
|
||||
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
@@ -110,7 +114,7 @@ export function AccessControlConfigPanel({
|
||||
availability={availability}
|
||||
onDraftChange={onDraftChange}
|
||||
/>
|
||||
{hasSelectedPolicy && !canSave && (
|
||||
{hasSelectedPolicy && !hasSelectedProtectableAccessPoint(draft, availability) && (
|
||||
<p className="system-xs-regular text-text-warning">
|
||||
{t(($) => $['studio.accessControl.selectAccessPoint'], { ns: 'deployments' })}
|
||||
</p>
|
||||
@@ -121,7 +125,7 @@ export function AccessControlConfigPanel({
|
||||
<Button type="button" variant="secondary" onClick={onCancel}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" disabled={!canSave}>
|
||||
<Button type="submit" variant="primary" disabled={!canSave || saving} loading={saving}>
|
||||
{t(($) => $['operation.save'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -1,24 +1,23 @@
|
||||
import type { NetworkAccessGroupResponse } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { AppModeEnum } from '@/types/app'
|
||||
|
||||
export type AccessControlScopeAvailability = Record<AccessPoint, boolean>
|
||||
|
||||
export type AccessControlPolicy = {
|
||||
id: string
|
||||
name: string
|
||||
addresses: readonly string[]
|
||||
}
|
||||
export type AccessControlPolicy = Pick<NetworkAccessGroupResponse, 'id' | 'name' | 'allowed_cidrs'>
|
||||
|
||||
export type AccessControlDraft = {
|
||||
selectedPolicyId: string | null
|
||||
scopes: Record<AccessPoint, boolean>
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export const createDefaultAccessControlDraft = (
|
||||
availability?: AccessControlScopeAvailability,
|
||||
): AccessControlDraft => ({
|
||||
selectedPolicyId: null,
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: availability?.webApp ?? true,
|
||||
serviceApi: availability?.serviceApi ?? true,
|
||||
@@ -65,61 +64,34 @@ export function isProtectableAccessPoint(
|
||||
return availability[scope]
|
||||
}
|
||||
|
||||
export function canSaveAccessControl({
|
||||
draft,
|
||||
availability,
|
||||
}: {
|
||||
draft: AccessControlDraft
|
||||
availability: AccessControlScopeAvailability
|
||||
}) {
|
||||
if (!draft.selectedPolicyId) return false
|
||||
export function isAccessControlDraftEqual(left: AccessControlDraft, right: AccessControlDraft) {
|
||||
if (left.selectedPolicyId !== right.selectedPolicyId) return false
|
||||
if (left.enabled !== right.enabled) return false
|
||||
|
||||
return ACCESS_POINT_ORDER.every((scope) => left.scopes[scope] === right.scopes[scope])
|
||||
}
|
||||
|
||||
export function hasSelectedProtectableAccessPoint(
|
||||
draft: AccessControlDraft,
|
||||
availability: AccessControlScopeAvailability,
|
||||
) {
|
||||
return ACCESS_POINT_ORDER.some((scope) => {
|
||||
if (!isProtectableAccessPoint(scope, availability)) return false
|
||||
return draft.scopes[scope]
|
||||
})
|
||||
}
|
||||
|
||||
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) => {
|
||||
if (entry === ip) return true
|
||||
const slash = entry.indexOf('/')
|
||||
if (slash === -1) return false
|
||||
const network = entry.slice(0, slash)
|
||||
const prefix = Number(entry.slice(slash + 1))
|
||||
if (!Number.isInteger(prefix) || prefix < 0 || prefix > 32) return false
|
||||
return ipv4InCidr(ip, network, prefix)
|
||||
})
|
||||
export function canSaveAccessControl({
|
||||
draft,
|
||||
availability,
|
||||
baseline,
|
||||
}: {
|
||||
draft: AccessControlDraft
|
||||
availability: AccessControlScopeAvailability
|
||||
baseline?: AccessControlDraft
|
||||
}) {
|
||||
if (baseline && isAccessControlDraftEqual(draft, baseline)) return false
|
||||
if (!draft.enabled) return Boolean(draft.selectedPolicyId)
|
||||
if (!draft.selectedPolicyId) return false
|
||||
return hasSelectedProtectableAccessPoint(draft, availability)
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
'use client'
|
||||
|
||||
import type { AccessControlAssignment } from './chip-status'
|
||||
import type { AccessControlDraft, AccessControlPolicy } from './draft'
|
||||
import type { AccessControlDraft } from './draft'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import { useQueryState } from 'nuqs'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import {
|
||||
pricingQueryParamName,
|
||||
pricingQueryParser,
|
||||
} from '@/app/components/billing/pricing/query-params'
|
||||
import {
|
||||
settingsQueryParamName,
|
||||
settingsQueryParser,
|
||||
} from '@/app/components/header/account-setting/query-params'
|
||||
import { useModalContext } from '@/context/modal-context'
|
||||
import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'
|
||||
import { deploymentEditionAtom } from '@/features/system-features/state'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { useAppWorkflow } from '@/service/use-workflow'
|
||||
@@ -22,61 +26,111 @@ import { getPublishedWorkflowState, isAdvancedApp } from '../shared/utils'
|
||||
import { AccessControlChipAffix } from './chip-affix'
|
||||
import { getAccessControlChipState } from './chip-status'
|
||||
import { AccessControlConfigPanel } from './config-panel'
|
||||
import { createDefaultAccessControlDraft, getAccessControlScopeAvailability } from './draft'
|
||||
import {
|
||||
canSaveAccessControl,
|
||||
getAccessControlScopeAvailability,
|
||||
isAccessControlDraftEqual,
|
||||
} from './draft'
|
||||
import { AccessControlFreePaywall } from './free-paywall'
|
||||
import {
|
||||
accessPointsFromScopes,
|
||||
availabilityFromAccessPoints,
|
||||
draftFromBinding,
|
||||
getNetworkAccessErrorStatus,
|
||||
scopesFromAccessPoints,
|
||||
} from './network-access'
|
||||
import { AccessControlStatusPanel } from './status-panel'
|
||||
|
||||
type GtagHandler = (command: 'event', action: 'click_upgrade_btn', payload: { loc: string }) => void
|
||||
|
||||
const isPaidCloudPlan = (plan: string | undefined) => plan === 'professional' || plan === 'team'
|
||||
|
||||
export function AccessControlEntry() {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const deploymentEdition = useAtomValue(deploymentEditionAtom)
|
||||
const { data: plan } = useQuery(
|
||||
consoleQuery.features.get.queryOptions({
|
||||
enabled: deploymentEdition === 'CLOUD',
|
||||
select: (data) => data.billing.subscription.plan,
|
||||
const isManager = useAtomValue(isCurrentWorkspaceManagerAtom)
|
||||
const [_pricing, setPricing] = useQueryState(pricingQueryParamName, pricingQueryParser)
|
||||
const [_settingsDestination, setSettingsDestination] = useQueryState(
|
||||
settingsQueryParamName,
|
||||
settingsQueryParser,
|
||||
)
|
||||
const appInfo = useAppStore((state) => state.appDetail)
|
||||
const appId = appInfo?.id
|
||||
const canFetchNetworkAccess = deploymentEdition === 'CLOUD' && isManager
|
||||
const shouldFetchWorkflow = Boolean(appInfo && isAdvancedApp(appInfo))
|
||||
const { data: workflow } = useAppWorkflow(
|
||||
shouldFetchWorkflow && canFetchNetworkAccess && appInfo ? appInfo.id : '',
|
||||
)
|
||||
const groupsQuery = useQuery(
|
||||
consoleQuery.workspaces.current.networkAccessGroups.get.queryOptions({
|
||||
enabled: canFetchNetworkAccess,
|
||||
retry: false,
|
||||
}),
|
||||
)
|
||||
const { setShowPricingModal } = useModalContext()
|
||||
const [, setSettingsDestination] = useQueryState(settingsQueryParamName, settingsQueryParser)
|
||||
const appInfo = useAppStore((state) => state.appDetail)
|
||||
const isSandbox = plan === 'sandbox'
|
||||
const isPaid = isPaidCloudPlan(plan)
|
||||
const shouldFetchWorkflow = isPaid && Boolean(appInfo && isAdvancedApp(appInfo))
|
||||
const { data: workflow } = useAppWorkflow(shouldFetchWorkflow && appInfo ? appInfo.id : '')
|
||||
const bindingQuery = useQuery(
|
||||
consoleQuery.apps.byAppId.networkAccessGroup.get.queryOptions({
|
||||
input: appId ? { params: { app_id: appId } } : skipToken,
|
||||
context: { silent: true },
|
||||
retry: false,
|
||||
enabled: canFetchNetworkAccess && Boolean(appId),
|
||||
}),
|
||||
)
|
||||
const updateBinding = useMutation(
|
||||
consoleQuery.apps.byAppId.networkAccessGroup.put.mutationOptions(),
|
||||
)
|
||||
const [open, setOpen] = useState(false)
|
||||
const [view, setView] = useState<'config' | 'status'>('status')
|
||||
const [showBack, setShowBack] = useState(false)
|
||||
const [draft, setDraft] = useState<AccessControlDraft | null>(null)
|
||||
const [savedDraft, setSavedDraft] = useState<AccessControlDraft | null>(null)
|
||||
const [enabled, setEnabled] = useState(true)
|
||||
|
||||
if (deploymentEdition !== 'CLOUD' || (!isSandbox && !isPaid)) return null
|
||||
const bindingErrorStatus = getNetworkAccessErrorStatus(bindingQuery.error)
|
||||
const hideForUnsupportedApp =
|
||||
canFetchNetworkAccess &&
|
||||
Boolean(appId) &&
|
||||
(bindingErrorStatus === 400 || bindingErrorStatus === 403 || bindingErrorStatus === 404)
|
||||
|
||||
if (deploymentEdition !== 'CLOUD' || !isManager) return null
|
||||
if (hideForUnsupportedApp) return null
|
||||
if (groupsQuery.isPending || (appId && bindingQuery.isPending)) return null
|
||||
|
||||
const label = t(($) => $['studio.accessControl.entryLabel'], { ns: 'deployments' })
|
||||
const workflowState = appInfo ? getPublishedWorkflowState(appInfo, workflow) : undefined
|
||||
const availability = getAccessControlScopeAvailability({
|
||||
const triggerAvailable = getAccessControlScopeAvailability({
|
||||
mode: appInfo?.mode,
|
||||
hasTriggerNode: Boolean(workflowState?.hasTriggerNode),
|
||||
isUnpublished: Boolean(workflowState?.isUnpublished),
|
||||
})
|
||||
const policies: readonly AccessControlPolicy[] = []
|
||||
const resolvedDraft = draft ?? savedDraft ?? createDefaultAccessControlDraft(availability)
|
||||
const assignment: AccessControlAssignment | null = savedDraft?.selectedPolicyId
|
||||
}).trigger
|
||||
const availability = availabilityFromAccessPoints(
|
||||
bindingQuery.data?.available_access_points ?? [],
|
||||
triggerAvailable,
|
||||
)
|
||||
const groups = groupsQuery.data?.groups ?? []
|
||||
const binding = bindingQuery.data?.binding
|
||||
const policies = groups.map((group) => ({
|
||||
id: group.id,
|
||||
name: group.name,
|
||||
allowed_cidrs: group.allowed_cidrs,
|
||||
}))
|
||||
const baseline = draftFromBinding(binding, availability)
|
||||
const resolvedDraft = draft ?? baseline
|
||||
const assignment: AccessControlAssignment | null = binding?.group_id
|
||||
? {
|
||||
policyId: savedDraft.selectedPolicyId,
|
||||
policyName:
|
||||
policies.find((policy) => policy.id === savedDraft.selectedPolicyId)?.name ??
|
||||
savedDraft.selectedPolicyId,
|
||||
scopes: savedDraft.scopes,
|
||||
enabled,
|
||||
policyId: binding.group_id,
|
||||
policyName: groups.find((group) => group.id === binding.group_id)?.name ?? binding.group_id,
|
||||
scopes: scopesFromAccessPoints(binding.access_points, availability),
|
||||
enabled: binding.enabled,
|
||||
}
|
||||
: null
|
||||
const chip = getAccessControlChipState({ plan, assignment, availability })
|
||||
const entitled = bindingQuery.data?.entitled ?? groupsQuery.data?.entitled
|
||||
const canMutate = entitled === true
|
||||
const dirty = !isAccessControlDraftEqual(resolvedDraft, baseline)
|
||||
const canSave = canSaveAccessControl({
|
||||
draft: resolvedDraft,
|
||||
availability,
|
||||
baseline,
|
||||
})
|
||||
const chip = getAccessControlChipState({ entitled, assignment, availability })
|
||||
const showPaywall = chip.kind === 'pro'
|
||||
const showStatus = Boolean(assignment) && view === 'status'
|
||||
const showStatus = Boolean(assignment) && (view === 'status' || !canMutate)
|
||||
|
||||
const tooltip =
|
||||
chip.kind === 'pro'
|
||||
@@ -101,37 +155,109 @@ export function AccessControlEntry() {
|
||||
: t(($) => $['studio.accessControl.tooltipOff'], { ns: 'deployments' })
|
||||
|
||||
const handleTurnOn = () => {
|
||||
setShowPricingModal()
|
||||
void setPricing('open')
|
||||
const gtag = (window as Window & { gtag?: GtagHandler }).gtag
|
||||
if (gtag) gtag('event', 'click_upgrade_btn', { loc: 'access-control-paywall' })
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
setDraft(null)
|
||||
setShowBack(false)
|
||||
if (assignment) {
|
||||
setView('status')
|
||||
setShowBack(false)
|
||||
return
|
||||
}
|
||||
setOpen(false)
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
setShowBack(false)
|
||||
setView('status')
|
||||
}
|
||||
|
||||
const handleCreatePolicy = () => {
|
||||
setOpen(false)
|
||||
void setSettingsDestination('ip-policies')
|
||||
}
|
||||
|
||||
const persistBinding = (
|
||||
{
|
||||
enabled,
|
||||
groupId,
|
||||
accessPoints,
|
||||
}: {
|
||||
enabled: boolean
|
||||
groupId: string | null
|
||||
accessPoints: ReturnType<typeof accessPointsFromScopes>
|
||||
},
|
||||
onSuccess?: () => void,
|
||||
) => {
|
||||
if (!appId) return
|
||||
|
||||
updateBinding.mutate(
|
||||
{
|
||||
params: { app_id: appId },
|
||||
body: {
|
||||
enabled,
|
||||
group_id: groupId,
|
||||
access_points: accessPoints,
|
||||
expected_version: binding?.version ?? 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
onSuccess,
|
||||
onError: (error) => {
|
||||
if (getNetworkAccessErrorStatus(error) !== 409) return
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.apps.byAppId.networkAccessGroup.get.queryKey({
|
||||
input: { params: { app_id: appId } },
|
||||
}),
|
||||
})
|
||||
void queryClient.invalidateQueries({
|
||||
queryKey: consoleQuery.workspaces.current.networkAccessGroups.get.queryKey(),
|
||||
})
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const handleSave = () => {
|
||||
setSavedDraft(resolvedDraft)
|
||||
setEnabled(true)
|
||||
setDraft(null)
|
||||
setView('status')
|
||||
setShowBack(false)
|
||||
if (!canMutate || !canSave || !resolvedDraft.selectedPolicyId) return
|
||||
|
||||
persistBinding(
|
||||
{
|
||||
enabled: resolvedDraft.enabled,
|
||||
groupId: resolvedDraft.selectedPolicyId,
|
||||
accessPoints: accessPointsFromScopes(resolvedDraft.scopes, availability),
|
||||
},
|
||||
() => {
|
||||
setDraft(null)
|
||||
setView('status')
|
||||
setShowBack(false)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const handleEnabledChange = (enabled: boolean) => {
|
||||
if (!canMutate) return
|
||||
setDraft({ ...resolvedDraft, enabled })
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<Popover
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
setOpen(nextOpen)
|
||||
if (!nextOpen) {
|
||||
setDraft(null)
|
||||
setShowBack(false)
|
||||
return
|
||||
}
|
||||
setView(assignment || !canMutate ? 'status' : 'config')
|
||||
setShowBack(false)
|
||||
}}
|
||||
>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<PopoverTrigger className="flex h-8 shrink-0 items-center gap-1.5 rounded-md border-[0.5px] border-divider-deep px-2.5 shadow-xs outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid" />
|
||||
@@ -151,15 +277,23 @@ export function AccessControlEntry() {
|
||||
>
|
||||
{showPaywall ? (
|
||||
<AccessControlFreePaywall onTurnOn={handleTurnOn} />
|
||||
) : showStatus && savedDraft ? (
|
||||
) : showStatus && assignment ? (
|
||||
<AccessControlStatusPanel
|
||||
draft={savedDraft}
|
||||
draft={resolvedDraft}
|
||||
policies={policies}
|
||||
enabled={enabled}
|
||||
enabled={resolvedDraft.enabled}
|
||||
availability={availability}
|
||||
onEnabledChange={setEnabled}
|
||||
updating={updateBinding.isPending}
|
||||
dirty={dirty}
|
||||
canSave={canSave}
|
||||
readOnly={!canMutate}
|
||||
onUpgrade={handleTurnOn}
|
||||
onEnabledChange={handleEnabledChange}
|
||||
onCancel={handleCancel}
|
||||
onSave={handleSave}
|
||||
onEdit={() => {
|
||||
setDraft(savedDraft)
|
||||
if (!canMutate) return
|
||||
setDraft(resolvedDraft)
|
||||
setShowBack(true)
|
||||
setView('config')
|
||||
}}
|
||||
@@ -169,8 +303,10 @@ export function AccessControlEntry() {
|
||||
draft={resolvedDraft}
|
||||
policies={policies}
|
||||
availability={availability}
|
||||
baseline={baseline}
|
||||
showBack={showBack}
|
||||
onBack={handleCancel}
|
||||
saving={updateBinding.isPending}
|
||||
onBack={handleBack}
|
||||
onCancel={handleCancel}
|
||||
onCreatePolicy={handleCreatePolicy}
|
||||
onManagePolicies={handleCreatePolicy}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import type {
|
||||
AppNetworkAccessGroupBindingResponse,
|
||||
AppNetworkAccessGroupResponse,
|
||||
} from '@dify/contracts/api/console/apps/types.gen'
|
||||
import type { AccessControlDraft, AccessControlScopeAvailability } from './draft'
|
||||
import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { createDefaultAccessControlDraft } from './draft'
|
||||
|
||||
export type NetworkAccessPoint = AppNetworkAccessGroupResponse['available_access_points'][number]
|
||||
|
||||
const ACCESS_POINT_TO_API = {
|
||||
webApp: 'webapp',
|
||||
serviceApi: 'service_api',
|
||||
mcp: 'mcp',
|
||||
trigger: 'trigger',
|
||||
} as const satisfies Record<AccessPoint, NetworkAccessPoint>
|
||||
|
||||
const API_TO_ACCESS_POINT = {
|
||||
webapp: 'webApp',
|
||||
service_api: 'serviceApi',
|
||||
mcp: 'mcp',
|
||||
trigger: 'trigger',
|
||||
} as const satisfies Record<NetworkAccessPoint, AccessPoint>
|
||||
|
||||
export function toApiAccessPoint(accessPoint: AccessPoint): NetworkAccessPoint {
|
||||
return ACCESS_POINT_TO_API[accessPoint]
|
||||
}
|
||||
|
||||
export function toUiAccessPoint(accessPoint: NetworkAccessPoint): AccessPoint {
|
||||
return API_TO_ACCESS_POINT[accessPoint]
|
||||
}
|
||||
|
||||
export function availabilityFromAccessPoints(
|
||||
availableAccessPoints: readonly string[],
|
||||
triggerAvailable: boolean,
|
||||
): AccessControlScopeAvailability {
|
||||
const allowed = new Set(
|
||||
availableAccessPoints.flatMap((accessPoint) => {
|
||||
if (accessPoint in API_TO_ACCESS_POINT)
|
||||
return [API_TO_ACCESS_POINT[accessPoint as NetworkAccessPoint]]
|
||||
return []
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
webApp: allowed.has('webApp'),
|
||||
serviceApi: allowed.has('serviceApi'),
|
||||
mcp: allowed.has('mcp'),
|
||||
trigger: allowed.has('trigger') && triggerAvailable,
|
||||
}
|
||||
}
|
||||
|
||||
export function getNetworkAccessErrorStatus(error: unknown): number | undefined {
|
||||
if (error instanceof Response) return error.status
|
||||
if (typeof error === 'object' && error !== null) {
|
||||
if ('status' in error && typeof error.status === 'number') return error.status
|
||||
if (
|
||||
'response' in error &&
|
||||
typeof error.response === 'object' &&
|
||||
error.response !== null &&
|
||||
'status' in error.response &&
|
||||
typeof error.response.status === 'number'
|
||||
)
|
||||
return error.response.status
|
||||
}
|
||||
}
|
||||
|
||||
export function scopesFromAccessPoints(
|
||||
accessPoints: readonly string[],
|
||||
availability: AccessControlScopeAvailability,
|
||||
): AccessControlDraft['scopes'] {
|
||||
const selected = new Set(
|
||||
accessPoints.flatMap((accessPoint) => {
|
||||
if (accessPoint in API_TO_ACCESS_POINT)
|
||||
return [API_TO_ACCESS_POINT[accessPoint as NetworkAccessPoint]]
|
||||
return []
|
||||
}),
|
||||
)
|
||||
|
||||
return {
|
||||
webApp: availability.webApp && selected.has('webApp'),
|
||||
serviceApi: availability.serviceApi && selected.has('serviceApi'),
|
||||
mcp: availability.mcp && selected.has('mcp'),
|
||||
trigger: availability.trigger && selected.has('trigger'),
|
||||
}
|
||||
}
|
||||
|
||||
export function accessPointsFromScopes(
|
||||
scopes: AccessControlDraft['scopes'],
|
||||
availability: AccessControlScopeAvailability,
|
||||
): NetworkAccessPoint[] {
|
||||
return ACCESS_POINT_ORDER.filter(
|
||||
(accessPoint) => availability[accessPoint] && scopes[accessPoint],
|
||||
).map(toApiAccessPoint)
|
||||
}
|
||||
|
||||
export function draftFromBinding(
|
||||
binding: AppNetworkAccessGroupBindingResponse | null | undefined,
|
||||
availability: AccessControlScopeAvailability,
|
||||
): AccessControlDraft {
|
||||
if (!binding?.group_id) return createDefaultAccessControlDraft(availability)
|
||||
|
||||
return {
|
||||
selectedPolicyId: binding.group_id,
|
||||
enabled: binding.enabled,
|
||||
scopes: scopesFromAccessPoints(binding.access_points, availability),
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,10 @@ import {
|
||||
SelectValue,
|
||||
} from '@langgenius/dify-ui/select'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { policyIncludesIp, splitPolicySummary } from './draft'
|
||||
import {
|
||||
policyIncludesIp,
|
||||
splitPolicySummary,
|
||||
} from '@/app/components/header/account-setting/ip-policies-page/validate-ip-entry'
|
||||
|
||||
const MANAGE_POLICIES_VALUE = '__manage-ip-policies__'
|
||||
|
||||
@@ -38,12 +41,12 @@ export function AccessControlPolicyField({
|
||||
}: AccessControlPolicyFieldProps) {
|
||||
const { t } = useTranslation()
|
||||
const selectedPolicy = policies.find((policy) => policy.id === selectedPolicyId)
|
||||
const summary = selectedPolicy ? splitPolicySummary(selectedPolicy.addresses) : undefined
|
||||
const summary = selectedPolicy ? splitPolicySummary(selectedPolicy.allowed_cidrs) : undefined
|
||||
const showLockout =
|
||||
Boolean(selectedPolicy && currentIp) &&
|
||||
selectedPolicy !== undefined &&
|
||||
currentIp !== undefined &&
|
||||
!policyIncludesIp(selectedPolicy.addresses, currentIp)
|
||||
!policyIncludesIp(selectedPolicy.allowed_cidrs, currentIp)
|
||||
const selectLabel = t(($) => $['studio.accessControl.ipPolicy'], { ns: 'deployments' })
|
||||
const placeholder = t(($) => $['studio.accessControl.selectPolicy'], { ns: 'deployments' })
|
||||
|
||||
@@ -73,7 +76,7 @@ export function AccessControlPolicyField({
|
||||
<span className="shrink-0 system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['studio.accessControl.addressCount'], {
|
||||
ns: 'deployments',
|
||||
count: policy.addresses.length,
|
||||
count: policy.allowed_cidrs.length,
|
||||
})}
|
||||
</span>
|
||||
<SelectItemIndicator />
|
||||
@@ -132,7 +135,7 @@ export function AccessControlPolicyField({
|
||||
<span className="shrink-0 system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['studio.accessControl.addressCount'], {
|
||||
ns: 'deployments',
|
||||
count: policy.addresses.length,
|
||||
count: policy.allowed_cidrs.length,
|
||||
})}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
@@ -24,8 +24,9 @@ import { useTranslation } from 'react-i18next'
|
||||
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { useStore as useAppStore } from '@/app/components/app/store'
|
||||
import AppIcon from '@/app/components/base/app-icon'
|
||||
import { splitPolicySummary } from '@/app/components/header/account-setting/ip-policies-page/validate-ip-entry'
|
||||
import { getInServiceCoverage } from './chip-status'
|
||||
import { isProtectableAccessPoint, splitPolicySummary } from './draft'
|
||||
import { isProtectableAccessPoint } from './draft'
|
||||
|
||||
const SCOPE_ICONS: Record<Exclude<AccessPoint, 'webApp'>, string> = {
|
||||
serviceApi: 'i-custom-vender-knowledge-api-aggregate',
|
||||
@@ -39,6 +40,13 @@ type AccessControlStatusPanelProps = {
|
||||
enabled: boolean
|
||||
availability: AccessControlScopeAvailability
|
||||
onEdit: () => void
|
||||
updating?: boolean
|
||||
dirty?: boolean
|
||||
canSave?: boolean
|
||||
readOnly?: boolean
|
||||
onUpgrade?: () => void
|
||||
onCancel?: () => void
|
||||
onSave?: () => void
|
||||
onEnabledChange: (enabled: boolean) => void
|
||||
}
|
||||
|
||||
@@ -48,13 +56,20 @@ export function AccessControlStatusPanel({
|
||||
enabled,
|
||||
availability,
|
||||
onEdit,
|
||||
updating = false,
|
||||
dirty = false,
|
||||
canSave = false,
|
||||
readOnly = false,
|
||||
onUpgrade,
|
||||
onCancel,
|
||||
onSave,
|
||||
onEnabledChange,
|
||||
}: AccessControlStatusPanelProps) {
|
||||
const { t } = useTranslation()
|
||||
const appInfo = useAppStore((state) => state.appDetail)
|
||||
const [confirmPause, setConfirmPause] = useState(false)
|
||||
const selectedPolicy = policies.find((policy) => policy.id === draft.selectedPolicyId)
|
||||
const summary = selectedPolicy ? splitPolicySummary(selectedPolicy.addresses) : undefined
|
||||
const summary = selectedPolicy ? splitPolicySummary(selectedPolicy.allowed_cidrs) : undefined
|
||||
const coverage = getInServiceCoverage(draft.scopes, availability)
|
||||
const labels: Record<AccessPoint, string> = {
|
||||
webApp: t(($) => $['overview.appInfo.title'], { ns: 'appOverview' }),
|
||||
@@ -78,9 +93,15 @@ export function AccessControlStatusPanel({
|
||||
})
|
||||
: t(($) => $['studio.accessControl.entryLabel'], { ns: 'deployments' })}
|
||||
</PopoverTitle>
|
||||
<Button type="button" variant="ghost" size="small" onClick={onEdit}>
|
||||
{t(($) => $['operation.edit'], { ns: 'common' })}
|
||||
</Button>
|
||||
{readOnly ? (
|
||||
<Button type="button" variant="ghost" size="small" onClick={onUpgrade}>
|
||||
{t(($) => $['studio.accessControl.turnOn'], { ns: 'deployments' })}
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" variant="ghost" size="small" onClick={onEdit}>
|
||||
{t(($) => $['operation.edit'], { ns: 'common' })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-5 overflow-hidden px-4 pt-2 pb-4">
|
||||
@@ -104,6 +125,7 @@ export function AccessControlStatusPanel({
|
||||
</div>
|
||||
<Switch
|
||||
checked={enabled}
|
||||
disabled={updating || readOnly}
|
||||
aria-label={t(($) => $['studio.accessControl.restrictByIp'], { ns: 'deployments' })}
|
||||
onCheckedChange={(next) => {
|
||||
if (next) {
|
||||
@@ -202,6 +224,22 @@ export function AccessControlStatusPanel({
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
{dirty && !readOnly && (
|
||||
<div className="flex items-center justify-end gap-2 pt-5">
|
||||
<Button type="button" variant="secondary" onClick={onCancel}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={!canSave || updating}
|
||||
loading={updating}
|
||||
onClick={onSave}
|
||||
>
|
||||
{t(($) => $['operation.save'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AlertDialog open={confirmPause} onOpenChange={setConfirmPause}>
|
||||
|
||||
@@ -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