mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
fix(web): align IP access controls with app capabilities and Agent access
This commit is contained in:
1 parent
892c6ee1c0
commit
e4d98dddd9
17 files changed
+1010
-193
No files matched your search
@@ -1,3 +1,4 @@
|
||||
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { getAccessControlChipState, getInServiceCoverage } from '../chip-status'
|
||||
|
||||
const assignment = {
|
||||
@@ -15,7 +16,10 @@ const assignment = {
|
||||
describe('getInServiceCoverage', () => {
|
||||
it('counts selected access points against every configured access point', () => {
|
||||
expect(
|
||||
getInServiceCoverage({ webApp: true, serviceApi: true, mcp: false, trigger: true }),
|
||||
getInServiceCoverage(
|
||||
{ webApp: true, serviceApi: true, mcp: false, trigger: true },
|
||||
ACCESS_POINT_ORDER,
|
||||
),
|
||||
).toEqual({ coveredCount: 3, inServiceCount: 4 })
|
||||
})
|
||||
})
|
||||
@@ -24,6 +28,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns pro when the workspace is not entitled and has no assignment', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
entitled: false,
|
||||
assignment: null,
|
||||
}).kind,
|
||||
@@ -33,6 +38,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('keeps the saved assignment visible when the workspace is not entitled', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
entitled: false,
|
||||
assignment,
|
||||
}).kind,
|
||||
@@ -42,6 +48,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns off when the app has never been configured', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
entitled: true,
|
||||
assignment: null,
|
||||
}),
|
||||
@@ -51,6 +58,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns paused when a saved policy is not enforcing', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
entitled: true,
|
||||
assignment: { ...assignment, enabled: false },
|
||||
}),
|
||||
@@ -65,6 +73,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns on when every access point is covered', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
entitled: true,
|
||||
assignment,
|
||||
}),
|
||||
@@ -79,6 +88,7 @@ describe('getAccessControlChipState', () => {
|
||||
it('returns partial when some access points are excluded', () => {
|
||||
expect(
|
||||
getAccessControlChipState({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
entitled: true,
|
||||
assignment: {
|
||||
...assignment,
|
||||
@@ -93,3 +103,14 @@ describe('getAccessControlChipState', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('app capability coverage', () => {
|
||||
it.each([
|
||||
{ available: ['webApp', 'serviceApi', 'mcp'] as const, count: 3 },
|
||||
{ available: ['webApp', 'serviceApi'] as const, count: 2 },
|
||||
])('counts full coverage as $count of $count', ({ available, count }) => {
|
||||
expect(
|
||||
getAccessControlChipState({ assignment, entitled: true, availableAccessPoints: available }),
|
||||
).toMatchObject({ kind: 'on', coveredCount: count, inServiceCount: count })
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/pop
|
||||
import { screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { render } from '@/test/console/render'
|
||||
import { AccessControlConfigPanel } from '../config-panel'
|
||||
import { createDefaultAccessControlDraft } from '../draft'
|
||||
@@ -50,7 +51,7 @@ vi.mock('react-i18next', async () => {
|
||||
|
||||
function PanelHarness({
|
||||
currentIp,
|
||||
initialDraft = createDefaultAccessControlDraft(),
|
||||
initialDraft = createDefaultAccessControlDraft(ACCESS_POINT_ORDER),
|
||||
onSave = vi.fn(),
|
||||
}: {
|
||||
currentIp?: string
|
||||
@@ -68,6 +69,9 @@ function PanelHarness({
|
||||
<PopoverContent>
|
||||
<AccessControlConfigPanel
|
||||
draft={draft}
|
||||
availableAccessPoints={ACCESS_POINT_ORDER}
|
||||
appIcon={{}}
|
||||
canManagePolicies
|
||||
policies={policies}
|
||||
currentIp={currentIp}
|
||||
onCancel={onCancel}
|
||||
@@ -156,7 +160,7 @@ describe('AccessControlConfigPanel', () => {
|
||||
render(
|
||||
<PanelHarness
|
||||
initialDraft={{
|
||||
...createDefaultAccessControlDraft(),
|
||||
...createDefaultAccessControlDraft(ACCESS_POINT_ORDER),
|
||||
selectedPolicyId: 'internal-network',
|
||||
enabled: true,
|
||||
}}
|
||||
|
||||
@@ -1,22 +1,33 @@
|
||||
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
|
||||
import {
|
||||
policyIncludesIp,
|
||||
splitPolicySummary,
|
||||
} from '@/app/components/header/account-setting/ip-policies-page/validate-ip-entry'
|
||||
import { canSaveAccessControl, createDefaultAccessControlDraft } from '../draft'
|
||||
import {
|
||||
canSaveAccessControl,
|
||||
createDefaultAccessControlDraft,
|
||||
isAccessControlDraftEqual,
|
||||
} from '../draft'
|
||||
|
||||
const selectedDraft = {
|
||||
...createDefaultAccessControlDraft(),
|
||||
...createDefaultAccessControlDraft(ACCESS_POINT_ORDER),
|
||||
selectedPolicyId: 'policy-1',
|
||||
}
|
||||
|
||||
describe('canSaveAccessControl', () => {
|
||||
it('disables save when no policy is selected', () => {
|
||||
expect(canSaveAccessControl({ draft: createDefaultAccessControlDraft() })).toBe(false)
|
||||
expect(
|
||||
canSaveAccessControl({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
draft: createDefaultAccessControlDraft(ACCESS_POINT_ORDER),
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('disables save when every access point is off', () => {
|
||||
expect(
|
||||
canSaveAccessControl({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
draft: {
|
||||
selectedPolicyId: 'policy-1',
|
||||
enabled: true,
|
||||
@@ -32,12 +43,15 @@ describe('canSaveAccessControl', () => {
|
||||
})
|
||||
|
||||
it('enables save when a policy is selected and at least one access point is on', () => {
|
||||
expect(canSaveAccessControl({ draft: selectedDraft })).toBe(true)
|
||||
expect(
|
||||
canSaveAccessControl({ availableAccessPoints: ACCESS_POINT_ORDER, draft: selectedDraft }),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('counts trigger as a selectable access point', () => {
|
||||
expect(
|
||||
canSaveAccessControl({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
draft: {
|
||||
selectedPolicyId: 'policy-1',
|
||||
enabled: true,
|
||||
@@ -58,14 +72,9 @@ describe('canSaveAccessControl', () => {
|
||||
draft: {
|
||||
selectedPolicyId: 'policy-1',
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: false,
|
||||
serviceApi: false,
|
||||
mcp: false,
|
||||
trigger: true,
|
||||
},
|
||||
scopes: { webApp: false, serviceApi: false, mcp: false, trigger: true },
|
||||
},
|
||||
persistableAccessPoints: [],
|
||||
availableAccessPoints: [],
|
||||
}),
|
||||
).toBe(false)
|
||||
})
|
||||
@@ -73,6 +82,7 @@ describe('canSaveAccessControl', () => {
|
||||
it('disables save when the draft matches the saved baseline', () => {
|
||||
expect(
|
||||
canSaveAccessControl({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
draft: selectedDraft,
|
||||
baseline: selectedDraft,
|
||||
}),
|
||||
@@ -82,6 +92,7 @@ describe('canSaveAccessControl', () => {
|
||||
it('allows saving a pause when a policy is already selected', () => {
|
||||
expect(
|
||||
canSaveAccessControl({
|
||||
availableAccessPoints: ACCESS_POINT_ORDER,
|
||||
draft: { ...selectedDraft, enabled: false },
|
||||
baseline: selectedDraft,
|
||||
}),
|
||||
@@ -121,3 +132,39 @@ describe('policyIncludesIp', () => {
|
||||
expect(policyIncludesIp(['198.51.100.0/24'], '203.0.113.42')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('available access points', () => {
|
||||
it.each([
|
||||
{ available: ['webApp', 'serviceApi', 'mcp', 'trigger'] as const, selected: 4 },
|
||||
{ available: ['webApp', 'serviceApi', 'mcp'] as const, selected: 3 },
|
||||
{ available: ['webApp', 'serviceApi'] as const, selected: 2 },
|
||||
])('defaults to $selected supported scopes', ({ available, selected }) => {
|
||||
const draft = createDefaultAccessControlDraft(available)
|
||||
expect(Object.values(draft.scopes).filter(Boolean)).toHaveLength(selected)
|
||||
available.forEach((scope) => expect(draft.scopes[scope]).toBe(true))
|
||||
})
|
||||
|
||||
it('ignores unsupported scope differences when checking for edits', () => {
|
||||
const baseline = createDefaultAccessControlDraft(['webApp', 'serviceApi'])
|
||||
expect(
|
||||
isAccessControlDraftEqual(
|
||||
baseline,
|
||||
{
|
||||
...baseline,
|
||||
scopes: { ...baseline.scopes, mcp: true, trigger: true },
|
||||
},
|
||||
['webApp', 'serviceApi'],
|
||||
),
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('does not count an unsupported trigger selection toward a valid binding', () => {
|
||||
const draft = {
|
||||
...selectedDraft,
|
||||
scopes: { webApp: false, serviceApi: false, mcp: false, trigger: true },
|
||||
}
|
||||
expect(
|
||||
canSaveAccessControl({ draft, availableAccessPoints: ['webApp', 'serviceApi', 'mcp'] }),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,8 +1,15 @@
|
||||
import type { AppNetworkAccessGroupBindingResponse } from '@dify/contracts/api/console/apps/types.gen'
|
||||
import type {
|
||||
AppNetworkAccessGroupBindingResponse,
|
||||
AppNetworkAccessGroupResponse,
|
||||
} 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 type {
|
||||
GetWorkspacesCurrentSummaryResponse,
|
||||
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 { consoleQuery } from '@/service/console'
|
||||
import {
|
||||
createNetworkAccessGroupFixture,
|
||||
seedAppNetworkAccessGroup,
|
||||
@@ -74,16 +81,6 @@ const accessControlTranslations = vi.hoisted(() => ({
|
||||
'studio.accessControl.turnOffConfirm': 'Turn off',
|
||||
}))
|
||||
|
||||
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 {
|
||||
@@ -105,28 +102,42 @@ const renderEntry = ({
|
||||
deploymentEdition = 'CLOUD',
|
||||
groups = [],
|
||||
binding = null,
|
||||
availableAccessPoints = ['webapp', 'service_api', 'mcp'],
|
||||
role = 'owner',
|
||||
canEditBinding = true,
|
||||
}: {
|
||||
plan?: CloudPlan
|
||||
deploymentEdition?: 'CLOUD' | 'COMMUNITY' | 'ENTERPRISE'
|
||||
groups?: NetworkAccessGroupResponse[]
|
||||
binding?: AppNetworkAccessGroupBindingResponse | null
|
||||
availableAccessPoints?: AppNetworkAccessGroupResponse['available_access_points']
|
||||
role?: GetWorkspacesCurrentSummaryResponse['role']
|
||||
canEditBinding?: boolean
|
||||
} = {}) => {
|
||||
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
|
||||
? {
|
||||
billing: {
|
||||
subscription: { interval: 'month', plan },
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
seedAppNetworkAccessGroup(queryClient, 'app-1', {
|
||||
entitled,
|
||||
binding,
|
||||
available_access_points: availableAccessPoints,
|
||||
})
|
||||
|
||||
return renderWithConsoleQuery(
|
||||
<AccessControlEntry appId="app-1" appIcon={{}} canEditBinding={canEditBinding} />,
|
||||
{
|
||||
queryClient,
|
||||
currentWorkspace: { role },
|
||||
systemFeatures: { deployment_edition: deploymentEdition },
|
||||
features: plan
|
||||
? {
|
||||
billing: {
|
||||
subscription: { interval: 'month', plan },
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
const getChip = () => screen.getByRole('button', { name: /Access Control/ })
|
||||
@@ -166,13 +177,13 @@ describe('AccessControlEntry', () => {
|
||||
},
|
||||
})
|
||||
|
||||
expect(within(getChip()).getByText('3 of 4')).toBeInTheDocument()
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
await user.click(getChip())
|
||||
expect(screen.getByText('This app is no longer protected')).toBeInTheDocument()
|
||||
expect(screen.getByText('Access control needs the Pro plan.')).toBeInTheDocument()
|
||||
expect(screen.getByText('Ready to resume')).toBeInTheDocument()
|
||||
expect(screen.getByText('Internal Network')).toBeInTheDocument()
|
||||
expect(screen.getByText('Protects 3 of 4 access points')).toBeInTheDocument()
|
||||
expect(screen.getByText('Protects 3 of 3 access points')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Restricted to Internal Network')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('switch', { name: 'Restrict by IP address' })).not.toBeInTheDocument()
|
||||
@@ -264,10 +275,7 @@ describe('AccessControlEntry', () => {
|
||||
'aria-disabled',
|
||||
'true',
|
||||
)
|
||||
expect(screen.getByRole('switch', { name: 'Trigger' })).not.toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
)
|
||||
expect(screen.queryByRole('switch', { name: 'Trigger' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Not enabled')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
@@ -386,7 +394,7 @@ describe('AccessControlEntry', () => {
|
||||
},
|
||||
})
|
||||
|
||||
expect(within(getChip()).getByText('3 of 4')).toBeInTheDocument()
|
||||
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()
|
||||
@@ -415,7 +423,7 @@ describe('AccessControlEntry', () => {
|
||||
await user.click(screen.getByRole('button', { name: 'Turn off' }))
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
|
||||
expect(within(getChip()).getByText('3 of 4')).toBeInTheDocument()
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('discards an unsaved first-time draft on Cancel', async () => {
|
||||
@@ -423,7 +431,7 @@ describe('AccessControlEntry', () => {
|
||||
renderEntry({ plan: 'professional' })
|
||||
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('switch', { name: 'Trigger' }))
|
||||
await user.click(screen.getByRole('switch', { name: 'Web App' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -431,7 +439,7 @@ describe('AccessControlEntry', () => {
|
||||
})
|
||||
|
||||
await user.click(getChip())
|
||||
expect(screen.getByRole('switch', { name: 'Trigger' })).toBeChecked()
|
||||
expect(screen.getByRole('switch', { name: 'Web App' })).toBeChecked()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
})
|
||||
|
||||
@@ -440,8 +448,8 @@ describe('AccessControlEntry', () => {
|
||||
renderEntry({ plan: 'professional' })
|
||||
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('switch', { name: 'Trigger' }))
|
||||
expect(screen.getByRole('switch', { name: 'Trigger' })).not.toBeChecked()
|
||||
await user.click(screen.getByRole('switch', { name: 'Web App' }))
|
||||
expect(screen.getByRole('switch', { name: 'Web App' })).not.toBeChecked()
|
||||
|
||||
await user.keyboard('{Escape}')
|
||||
await waitFor(() => {
|
||||
@@ -450,7 +458,7 @@ describe('AccessControlEntry', () => {
|
||||
|
||||
await user.click(getChip())
|
||||
expect(screen.getByText('No IP policies in this workspace yet')).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Trigger' })).not.toBeChecked()
|
||||
expect(screen.getByRole('switch', { name: 'Web App' })).not.toBeChecked()
|
||||
expect(screen.queryByRole('button', { name: 'Back' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
})
|
||||
@@ -482,15 +490,15 @@ describe('AccessControlEntry', () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
})
|
||||
expect(within(getChip()).getByText('3 of 4')).toBeInTheDocument()
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
|
||||
await user.click(getChip())
|
||||
expect(screen.queryByText('Restricted to Internal Network')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'MCP Server' })).not.toBeChecked()
|
||||
expect(screen.getByRole('switch', { name: 'Trigger' })).not.toBeChecked()
|
||||
expect(screen.queryByRole('switch', { name: 'Trigger' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Back' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
|
||||
expect(within(getChip()).getByText('3 of 4')).toBeInTheDocument()
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('discards an unsaved edit on Cancel', async () => {
|
||||
@@ -626,12 +634,420 @@ describe('AccessControlEntry', () => {
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
})
|
||||
expect(within(getChip()).getByText('3 of 4')).toBeInTheDocument()
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
|
||||
await user.click(getChip())
|
||||
expect(screen.queryByText('Restricted to Internal Network')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Back' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
|
||||
expect(within(getChip()).getByText('3 of 4')).toBeInTheDocument()
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
const capabilityCases = [
|
||||
{
|
||||
name: 'workflow',
|
||||
points: ['webapp', 'service_api', 'mcp', 'trigger'],
|
||||
labels: ['Web App', 'Backend Service API', 'MCP Server', 'Trigger'],
|
||||
},
|
||||
{
|
||||
name: 'legacy and chatflow',
|
||||
points: ['webapp', 'service_api', 'mcp'],
|
||||
labels: ['Web App', 'Backend Service API', 'MCP Server'],
|
||||
},
|
||||
{ name: 'agent', points: ['webapp', 'service_api'], labels: ['Web App', 'Backend Service API'] },
|
||||
] satisfies {
|
||||
name: string
|
||||
points: AppNetworkAccessGroupResponse['available_access_points']
|
||||
labels: string[]
|
||||
}[]
|
||||
|
||||
const createBinding = (
|
||||
overrides: Partial<AppNetworkAccessGroupBindingResponse> = {},
|
||||
): AppNetworkAccessGroupBindingResponse => ({
|
||||
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',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('supported access points and binding permission', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it.each(capabilityCases)(
|
||||
'shows and saves exactly the $name capabilities',
|
||||
async ({ points, labels }) => {
|
||||
const user = userEvent.setup()
|
||||
const requests: Record<string, unknown>[] = []
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
if (request.method === 'PUT') {
|
||||
const payload = await request.json()
|
||||
requests.push(payload)
|
||||
return Response.json({
|
||||
binding: createBinding({ ...payload, version: 1 }),
|
||||
available_access_points: points,
|
||||
effective_enabled: true,
|
||||
})
|
||||
}
|
||||
return Response.json({
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'app-1',
|
||||
entitled: true,
|
||||
binding: createBinding({ access_points: points }),
|
||||
available_access_points: points,
|
||||
effective_enabled: true,
|
||||
})
|
||||
})
|
||||
try {
|
||||
renderEntry({
|
||||
plan: 'professional',
|
||||
availableAccessPoints: points,
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
})
|
||||
await user.click(getChip())
|
||||
expect(screen.getAllByRole('switch')).toHaveLength(labels.length)
|
||||
labels.forEach((label) => expect(screen.getByRole('switch', { name: label })).toBeChecked())
|
||||
await user.click(screen.getByRole('option', { name: /Internal Network/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() =>
|
||||
expect(requests).toEqual([
|
||||
{ enabled: true, group_id: 'group-1', access_points: points, expected_version: 0 },
|
||||
]),
|
||||
)
|
||||
} finally {
|
||||
fetchSpy.mockRestore()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
it.each(capabilityCases)(
|
||||
'shows full $name coverage in saved status',
|
||||
async ({ points, labels }) => {
|
||||
const user = userEvent.setup()
|
||||
renderEntry({
|
||||
plan: 'professional',
|
||||
availableAccessPoints: points,
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
binding: createBinding({ access_points: points }),
|
||||
})
|
||||
expect(within(getChip()).getByText('ON')).toBeInTheDocument()
|
||||
await user.click(getChip())
|
||||
expect(
|
||||
screen.getByText(`Protecting all ${points.length} access points in service.`),
|
||||
).toBeInTheDocument()
|
||||
labels.forEach((label) => expect(screen.getByText(label)).toBeInTheDocument())
|
||||
if (!points.includes('trigger')) expect(screen.queryByText('Trigger')).not.toBeInTheDocument()
|
||||
if (!points.includes('mcp')) expect(screen.queryByText('MCP Server')).not.toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it.each(capabilityCases)(
|
||||
'uses $name capabilities in the downgrade summary',
|
||||
async ({ points }) => {
|
||||
const user = userEvent.setup()
|
||||
renderEntry({
|
||||
plan: 'sandbox',
|
||||
availableAccessPoints: points,
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
binding: createBinding({ access_points: points }),
|
||||
})
|
||||
await user.click(getChip())
|
||||
expect(
|
||||
screen.getByText(`Protects ${points.length} of ${points.length} access points`),
|
||||
).toBeInTheDocument()
|
||||
},
|
||||
)
|
||||
|
||||
it('lets editors select and save an existing policy without allowing policy creation', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { unmount } = renderEntry({ plan: 'professional', role: 'editor' })
|
||||
await user.click(getChip())
|
||||
expect(screen.queryByRole('button', { name: 'Create an IP policy' })).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Manage IP policies' }))
|
||||
expect(mockSetSettingsDestination).toHaveBeenCalledWith('ip-policies')
|
||||
unmount()
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
|
||||
Response.json({
|
||||
binding: createBinding(),
|
||||
available_access_points: ['webapp', 'service_api', 'mcp'],
|
||||
effective_enabled: true,
|
||||
}),
|
||||
)
|
||||
try {
|
||||
renderEntry({
|
||||
plan: 'professional',
|
||||
role: 'editor',
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
})
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('option', { name: /Internal Network/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(fetchSpy).toHaveBeenCalled())
|
||||
const [input, init] = fetchSpy.mock.calls[0]!
|
||||
expect(new Request(input, init).method).toBe('PUT')
|
||||
} finally {
|
||||
fetchSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves selected scopes and versions when pausing and resuming a binding', async () => {
|
||||
const user = userEvent.setup()
|
||||
const availableAccessPoints = ['webapp', 'service_api', 'mcp'] as const
|
||||
let binding = createBinding({ access_points: ['webapp', 'mcp'] })
|
||||
const payloads: unknown[] = []
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
|
||||
const request = new Request(input, init)
|
||||
if (request.url.endsWith('/workspaces/current/network-access-groups'))
|
||||
return Response.json({
|
||||
tenant_id: 'workspace-1',
|
||||
entitled: true,
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
})
|
||||
if (request.method === 'PUT') {
|
||||
const payload = await request.json()
|
||||
payloads.push(payload)
|
||||
binding = createBinding({ ...payload, version: binding.version + 1 })
|
||||
return Response.json({
|
||||
binding,
|
||||
available_access_points: availableAccessPoints,
|
||||
effective_enabled: binding.enabled,
|
||||
})
|
||||
}
|
||||
return Response.json({
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'app-1',
|
||||
entitled: true,
|
||||
binding,
|
||||
available_access_points: availableAccessPoints,
|
||||
effective_enabled: binding.enabled,
|
||||
})
|
||||
})
|
||||
try {
|
||||
renderEntry({ plan: 'professional', groups: [createNetworkAccessGroupFixture()], binding })
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('switch', { name: 'Restrict by IP address' }))
|
||||
expect(screen.getByRole('alertdialog')).toHaveTextContent(
|
||||
'Web App, MCP Server will be reachable from any IP.',
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: 'Turn off' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() =>
|
||||
expect(payloads).toEqual([
|
||||
{
|
||||
enabled: false,
|
||||
group_id: 'group-1',
|
||||
access_points: ['webapp', 'mcp'],
|
||||
expected_version: 2,
|
||||
},
|
||||
]),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(),
|
||||
)
|
||||
expect(screen.getByRole('switch', { name: 'Restrict by IP address' })).not.toBeChecked()
|
||||
await user.click(screen.getByRole('switch', { name: 'Restrict by IP address' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
await waitFor(() => expect(payloads).toHaveLength(2))
|
||||
expect(payloads[1]).toEqual({
|
||||
enabled: true,
|
||||
group_id: 'group-1',
|
||||
access_points: ['webapp', 'mcp'],
|
||||
expected_version: 3,
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(),
|
||||
)
|
||||
} finally {
|
||||
fetchSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('shows a paid read-only binding without a downgrade or editing controls', async () => {
|
||||
const user = userEvent.setup()
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch')
|
||||
try {
|
||||
renderEntry({
|
||||
plan: 'professional',
|
||||
canEditBinding: false,
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
binding: createBinding(),
|
||||
})
|
||||
await user.click(getChip())
|
||||
expect(screen.getByText('Restricted to Internal Network')).toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Restrict by IP address' })).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('This app is no longer protected')).not.toBeInTheDocument()
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Turn on Access Control' }),
|
||||
).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('switch', { name: 'Restrict by IP address' }))
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
fetchSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('discards unsaved policy and scope edits when binding permission is revoked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const rendered = renderEntry({
|
||||
plan: 'professional',
|
||||
groups: [
|
||||
createNetworkAccessGroupFixture(),
|
||||
createNetworkAccessGroupFixture({ id: 'group-2', name: 'Office' }),
|
||||
],
|
||||
binding: createBinding(),
|
||||
})
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
await user.click(screen.getByRole('combobox', { name: 'IP Policy' }))
|
||||
await user.click(screen.getByRole('option', { name: /Office/ }))
|
||||
await user.click(screen.getByRole('switch', { name: 'MCP Server' }))
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
|
||||
|
||||
rendered.rerender(<AccessControlEntry appId="app-1" appIcon={{}} canEditBinding={false} />)
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
await user.click(getChip())
|
||||
expect(screen.getByText('Restricted to Internal Network')).toBeInTheDocument()
|
||||
expect(screen.getByText('Protecting all 3 access points in service.')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Office')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Restrict by IP address' })).toHaveAttribute(
|
||||
'aria-disabled',
|
||||
'true',
|
||||
)
|
||||
|
||||
rendered.rerender(<AccessControlEntry appId="app-1" appIcon={{}} canEditBinding />)
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
|
||||
await user.click(getChip())
|
||||
expect(screen.getByText('Restricted to Internal Network')).toBeInTheDocument()
|
||||
await user.click(screen.getByRole('button', { name: 'Edit' }))
|
||||
expect(screen.getByRole('combobox', { name: 'IP Policy' })).toHaveTextContent(
|
||||
'Internal Network',
|
||||
)
|
||||
expect(screen.getByRole('switch', { name: 'MCP Server' })).toBeChecked()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
})
|
||||
|
||||
it('closes an outstanding pause confirmation when binding permission is revoked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const rendered = renderEntry({
|
||||
plan: 'professional',
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
binding: createBinding(),
|
||||
})
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('switch', { name: 'Restrict by IP address' }))
|
||||
expect(screen.getByRole('alertdialog')).toBeInTheDocument()
|
||||
|
||||
rendered.rerender(<AccessControlEntry appId="app-1" appIcon={{}} canEditBinding={false} />)
|
||||
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
|
||||
await user.click(getChip())
|
||||
expect(screen.getByRole('switch', { name: 'Restrict by IP address' })).toBeChecked()
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
|
||||
rendered.rerender(<AccessControlEntry appId="app-1" appIcon={{}} canEditBinding />)
|
||||
await user.click(getChip())
|
||||
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('switch', { name: 'Restrict by IP address' })).toBeChecked()
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps first-time binding controls read-only when app edits are forbidden', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderEntry({
|
||||
plan: 'professional',
|
||||
canEditBinding: false,
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
})
|
||||
await user.click(getChip())
|
||||
expect(screen.getByRole('option', { name: /Internal Network/ })).toBeDisabled()
|
||||
expect(screen.getByRole('switch', { name: 'Web App' })).toHaveAttribute('aria-disabled', 'true')
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each(['normal', 'dataset_operator'] as const)('hides the entry from workspace %s', (role) => {
|
||||
renderEntry({ plan: 'professional', role })
|
||||
expect(screen.queryByRole('button', { name: /Access Control/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not create an editable fallback when available access points are empty', () => {
|
||||
renderEntry({ plan: 'professional', availableAccessPoints: [] })
|
||||
expect(screen.queryByRole('button', { name: /Access Control/ })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('discards the previous app draft when the App ID changes', async () => {
|
||||
const user = userEvent.setup()
|
||||
const rendered = renderEntry({
|
||||
plan: 'professional',
|
||||
groups: [createNetworkAccessGroupFixture()],
|
||||
})
|
||||
seedAppNetworkAccessGroup(rendered.queryClient, 'app-2', {
|
||||
available_access_points: ['webapp', 'service_api'],
|
||||
})
|
||||
await user.click(getChip())
|
||||
await user.click(screen.getByRole('option', { name: /Internal Network/ }))
|
||||
await user.click(screen.getByRole('switch', { name: 'Web App' }))
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
|
||||
rendered.rerender(<AccessControlEntry appId="app-2" appIcon={{}} canEditBinding />)
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
await user.click(getChip())
|
||||
expect(screen.getByRole('switch', { name: 'Web App' })).toBeChecked()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
expect(screen.queryByRole('switch', { name: 'MCP Server' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: 'failed binding query',
|
||||
response: () => Response.json({ message: 'Service unavailable' }, { status: 503 }),
|
||||
status: 'error',
|
||||
},
|
||||
{
|
||||
name: 'missing capability field',
|
||||
response: () =>
|
||||
Response.json({
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'app-1',
|
||||
entitled: true,
|
||||
binding: null,
|
||||
effective_enabled: false,
|
||||
}),
|
||||
status: 'success',
|
||||
},
|
||||
])('does not enable editing after $name', async ({ response, status }) => {
|
||||
const queryClient = createConsoleQueryClient()
|
||||
seedNetworkAccessGroups(queryClient, { entitled: true })
|
||||
const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => response())
|
||||
try {
|
||||
renderWithConsoleQuery(<AccessControlEntry appId="app-1" appIcon={{}} canEditBinding />, {
|
||||
queryClient,
|
||||
systemFeatures: { deployment_edition: 'CLOUD' },
|
||||
})
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
queryClient.getQueryState(
|
||||
consoleQuery.apps.byAppId.networkAccessGroup.get.queryKey({
|
||||
input: { params: { app_id: 'app-1' } },
|
||||
}),
|
||||
)?.status,
|
||||
).toBe(status),
|
||||
)
|
||||
expect(screen.queryByRole('button', { name: /Access Control/ })).not.toBeInTheDocument()
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
fetchSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
+43
-19
@@ -1,6 +1,8 @@
|
||||
import { ACCESS_POINT_ORDER } from '@/app/components/app/deploy/utils/access-point'
|
||||
import {
|
||||
accessPointsFromScopes,
|
||||
draftFromBinding,
|
||||
getAvailableAccessPoints,
|
||||
getNetworkAccessErrorStatus,
|
||||
scopesFromAccessPoints,
|
||||
toApiAccessPoint,
|
||||
@@ -31,12 +33,15 @@ describe('network access mappers', () => {
|
||||
|
||||
it('includes every selected access point in the PUT payload', () => {
|
||||
expect(
|
||||
accessPointsFromScopes({
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: true,
|
||||
trigger: true,
|
||||
}),
|
||||
accessPointsFromScopes(
|
||||
{
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: true,
|
||||
trigger: true,
|
||||
},
|
||||
ACCESS_POINT_ORDER,
|
||||
),
|
||||
).toEqual(['webapp', 'service_api', 'mcp', 'trigger'])
|
||||
})
|
||||
|
||||
@@ -49,13 +54,13 @@ describe('network access mappers', () => {
|
||||
mcp: true,
|
||||
trigger: true,
|
||||
},
|
||||
['webapp', 'service_api', 'mcp'],
|
||||
['webApp', 'serviceApi', 'mcp'],
|
||||
),
|
||||
).toEqual(['webapp', 'service_api', 'mcp'])
|
||||
})
|
||||
|
||||
it('creates an empty draft when the app has no binding', () => {
|
||||
expect(draftFromBinding(null)).toEqual({
|
||||
expect(draftFromBinding(null, ACCESS_POINT_ORDER)).toEqual({
|
||||
selectedPolicyId: null,
|
||||
enabled: true,
|
||||
scopes: {
|
||||
@@ -69,17 +74,20 @@ describe('network access mappers', () => {
|
||||
|
||||
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',
|
||||
}),
|
||||
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',
|
||||
},
|
||||
['webApp', 'serviceApi'],
|
||||
),
|
||||
).toEqual({
|
||||
selectedPolicyId: 'group-1',
|
||||
enabled: true,
|
||||
@@ -92,3 +100,19 @@ describe('network access mappers', () => {
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('available scope mapping', () => {
|
||||
it('orders supported access points independently of response order', () => {
|
||||
expect(getAvailableAccessPoints(['mcp', 'webapp', 'service_api'])).toEqual([
|
||||
'webApp',
|
||||
'serviceApi',
|
||||
'mcp',
|
||||
])
|
||||
})
|
||||
it('keeps an explicit empty capability list empty', () => {
|
||||
expect(getAvailableAccessPoints([])).toEqual([])
|
||||
expect(
|
||||
accessPointsFromScopes({ webApp: true, serviceApi: true, mcp: true, trigger: true }, []),
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { AccessControlDraft } 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'
|
||||
|
||||
export type AccessControlAssignment = {
|
||||
policyId: string
|
||||
@@ -18,28 +17,33 @@ export type AccessControlChipState = {
|
||||
policyName?: string
|
||||
}
|
||||
|
||||
export function getInServiceCoverage(scopes: Record<AccessPoint, boolean>) {
|
||||
const covered = ACCESS_POINT_ORDER.filter((scope) => scopes[scope])
|
||||
export function getInServiceCoverage(
|
||||
scopes: Record<AccessPoint, boolean>,
|
||||
availableAccessPoints: readonly AccessPoint[],
|
||||
) {
|
||||
const covered = availableAccessPoints.filter((scope) => scopes[scope])
|
||||
|
||||
return {
|
||||
coveredCount: covered.length,
|
||||
inServiceCount: ACCESS_POINT_ORDER.length,
|
||||
inServiceCount: availableAccessPoints.length,
|
||||
}
|
||||
}
|
||||
|
||||
export function getAccessControlChipState({
|
||||
entitled,
|
||||
assignment,
|
||||
availableAccessPoints,
|
||||
}: {
|
||||
entitled?: boolean
|
||||
assignment: AccessControlAssignment | null
|
||||
availableAccessPoints: readonly AccessPoint[]
|
||||
}): AccessControlChipState {
|
||||
if (!assignment) {
|
||||
if (entitled === false) return { kind: 'pro', coveredCount: 0, inServiceCount: 0 }
|
||||
return { kind: 'off', coveredCount: 0, inServiceCount: 0 }
|
||||
}
|
||||
|
||||
const coverage = getInServiceCoverage(assignment.scopes)
|
||||
const coverage = getInServiceCoverage(assignment.scopes, availableAccessPoints)
|
||||
|
||||
if (!assignment.enabled) {
|
||||
return {
|
||||
@@ -50,7 +54,10 @@ export function getAccessControlChipState({
|
||||
}
|
||||
|
||||
return {
|
||||
kind: coverage.coveredCount === coverage.inServiceCount ? 'on' : 'partial',
|
||||
kind:
|
||||
coverage.inServiceCount > 0 && coverage.coveredCount === coverage.inServiceCount
|
||||
? 'on'
|
||||
: 'partial',
|
||||
policyName: assignment.policyName,
|
||||
...coverage,
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
import type { FormEvent } from 'react'
|
||||
import type { AccessControlDraft, AccessControlPolicy } from './draft'
|
||||
import type { AccessControlAppIcon } from './index'
|
||||
import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Fieldset, FieldsetLegend } from '@langgenius/dify-ui/fieldset'
|
||||
@@ -16,7 +18,10 @@ type AccessControlConfigPanelProps = {
|
||||
draft: AccessControlDraft
|
||||
policies: readonly AccessControlPolicy[]
|
||||
currentIp?: string
|
||||
persistableAccessPoints?: readonly string[]
|
||||
availableAccessPoints: readonly AccessPoint[]
|
||||
appIcon: AccessControlAppIcon
|
||||
readOnly?: boolean
|
||||
canManagePolicies: boolean
|
||||
baseline?: AccessControlDraft
|
||||
showBack?: boolean
|
||||
saving?: boolean
|
||||
@@ -32,7 +37,10 @@ export function AccessControlConfigPanel({
|
||||
draft,
|
||||
policies,
|
||||
currentIp,
|
||||
persistableAccessPoints,
|
||||
availableAccessPoints,
|
||||
appIcon,
|
||||
readOnly = false,
|
||||
canManagePolicies,
|
||||
baseline,
|
||||
showBack = false,
|
||||
saving = false,
|
||||
@@ -46,10 +54,8 @@ export function AccessControlConfigPanel({
|
||||
const { t } = useTranslation()
|
||||
const title = t(($) => $['studio.accessControl.entryLabel'], { ns: 'deployments' })
|
||||
const hasSelectedPolicy = Boolean(draft.selectedPolicyId)
|
||||
const hasPersistableSelection = persistableAccessPoints
|
||||
? persistableAccessPoints.length > 0
|
||||
: hasSelectedAccessPoint(draft)
|
||||
const canSave = canSaveAccessControl({ draft, baseline, persistableAccessPoints })
|
||||
const hasPersistableSelection = hasSelectedAccessPoint(draft, availableAccessPoints)
|
||||
const canSave = !readOnly && canSaveAccessControl({ draft, baseline, availableAccessPoints })
|
||||
|
||||
const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
@@ -90,9 +96,12 @@ export function AccessControlConfigPanel({
|
||||
policies={policies}
|
||||
selectedPolicyId={draft.selectedPolicyId}
|
||||
currentIp={currentIp}
|
||||
readOnly={readOnly}
|
||||
canManagePolicies={canManagePolicies}
|
||||
onCreatePolicy={onCreatePolicy}
|
||||
onManagePolicies={onManagePolicies}
|
||||
onSelectPolicy={(policyId) => {
|
||||
if (readOnly) return
|
||||
onDraftChange({ ...draft, selectedPolicyId: policyId })
|
||||
}}
|
||||
/>
|
||||
@@ -107,7 +116,13 @@ export function AccessControlConfigPanel({
|
||||
? t(($) => $['studio.accessControl.applyToHelpSelected'], { ns: 'deployments' })
|
||||
: t(($) => $['studio.accessControl.applyToHelp'], { ns: 'deployments' })}
|
||||
</p>
|
||||
<AccessControlScopeList draft={draft} onDraftChange={onDraftChange} />
|
||||
<AccessControlScopeList
|
||||
draft={draft}
|
||||
appIcon={appIcon}
|
||||
availableAccessPoints={availableAccessPoints}
|
||||
readOnly={readOnly}
|
||||
onDraftChange={onDraftChange}
|
||||
/>
|
||||
{hasSelectedPolicy && draft.enabled && !hasPersistableSelection && (
|
||||
<p className="system-xs-regular text-text-warning">
|
||||
{t(($) => $['studio.accessControl.selectAccessPoint'], { ns: 'deployments' })}
|
||||
@@ -119,9 +134,11 @@ export function AccessControlConfigPanel({
|
||||
<Button type="button" variant="secondary" onClick={onCancel}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" disabled={!canSave || saving} loading={saving}>
|
||||
{t(($) => $['operation.save'], { ns: 'common' })}
|
||||
</Button>
|
||||
{!readOnly && (
|
||||
<Button type="submit" variant="primary" disabled={!canSave || saving} loading={saving}>
|
||||
{t(($) => $['operation.save'], { ns: 'common' })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
'use client'
|
||||
|
||||
import type { AccessControlAssignment } from './chip-status'
|
||||
import type { AccessControlAppIcon } from './index'
|
||||
import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { PopoverDescription, PopoverTitle } from '@langgenius/dify-ui/popover'
|
||||
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 { getInServiceCoverage } from './chip-status'
|
||||
|
||||
@@ -19,17 +18,20 @@ const SCOPE_ICONS: Record<Exclude<AccessPoint, 'webApp'>, string> = {
|
||||
|
||||
type AccessControlDowngradePanelProps = {
|
||||
assignment: AccessControlAssignment
|
||||
appIcon: AccessControlAppIcon
|
||||
availableAccessPoints: readonly AccessPoint[]
|
||||
onTurnOn: () => void
|
||||
}
|
||||
|
||||
export function AccessControlDowngradePanel({
|
||||
assignment,
|
||||
appIcon,
|
||||
availableAccessPoints,
|
||||
onTurnOn,
|
||||
}: AccessControlDowngradePanelProps) {
|
||||
const { t } = useTranslation()
|
||||
const appInfo = useAppStore((state) => state.appDetail)
|
||||
const coverage = getInServiceCoverage(assignment.scopes)
|
||||
const protectedScopes = ACCESS_POINT_ORDER.filter((scope) => assignment.scopes[scope])
|
||||
const coverage = getInServiceCoverage(assignment.scopes, availableAccessPoints)
|
||||
const protectedScopes = availableAccessPoints.filter((scope) => assignment.scopes[scope])
|
||||
const title = t(($) => $['studio.accessControl.entryLabel'], { ns: 'deployments' })
|
||||
const turnOn = t(($) => $['studio.accessControl.turnOn'], { ns: 'deployments' })
|
||||
const pro = t(($) => $['studio.accessControl.proBadge'], { ns: 'deployments' })
|
||||
@@ -64,10 +66,7 @@ export function AccessControlDowngradePanel({
|
||||
key={scope}
|
||||
size="tiny"
|
||||
decorative
|
||||
iconType={appInfo?.icon_type}
|
||||
icon={appInfo?.icon}
|
||||
background={appInfo?.icon_background ?? undefined}
|
||||
imageUrl={appInfo?.icon_url}
|
||||
{...appIcon}
|
||||
className="rounded-sm bg-util-colors-orange-orange-100"
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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'
|
||||
|
||||
export type AccessControlPolicy = Pick<NetworkAccessGroupResponse, 'id' | 'name' | 'allowed_cidrs'>
|
||||
|
||||
@@ -10,40 +9,49 @@ export type AccessControlDraft = {
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export const createDefaultAccessControlDraft = (): AccessControlDraft => ({
|
||||
export const createDefaultAccessControlDraft = (
|
||||
availableAccessPoints: readonly AccessPoint[],
|
||||
): AccessControlDraft => ({
|
||||
selectedPolicyId: null,
|
||||
enabled: true,
|
||||
scopes: {
|
||||
webApp: true,
|
||||
serviceApi: true,
|
||||
mcp: true,
|
||||
trigger: true,
|
||||
webApp: availableAccessPoints.includes('webApp'),
|
||||
serviceApi: availableAccessPoints.includes('serviceApi'),
|
||||
mcp: availableAccessPoints.includes('mcp'),
|
||||
trigger: availableAccessPoints.includes('trigger'),
|
||||
},
|
||||
})
|
||||
|
||||
export function isAccessControlDraftEqual(left: AccessControlDraft, right: AccessControlDraft) {
|
||||
export function isAccessControlDraftEqual(
|
||||
left: AccessControlDraft,
|
||||
right: AccessControlDraft,
|
||||
availableAccessPoints: readonly AccessPoint[],
|
||||
) {
|
||||
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])
|
||||
return availableAccessPoints.every((scope) => left.scopes[scope] === right.scopes[scope])
|
||||
}
|
||||
|
||||
export function hasSelectedAccessPoint(draft: AccessControlDraft) {
|
||||
return ACCESS_POINT_ORDER.some((scope) => draft.scopes[scope])
|
||||
export function hasSelectedAccessPoint(
|
||||
draft: AccessControlDraft,
|
||||
availableAccessPoints: readonly AccessPoint[],
|
||||
) {
|
||||
return availableAccessPoints.some((scope) => draft.scopes[scope])
|
||||
}
|
||||
|
||||
export function canSaveAccessControl({
|
||||
draft,
|
||||
baseline,
|
||||
persistableAccessPoints,
|
||||
availableAccessPoints,
|
||||
}: {
|
||||
draft: AccessControlDraft
|
||||
baseline?: AccessControlDraft
|
||||
persistableAccessPoints?: readonly string[]
|
||||
availableAccessPoints: readonly AccessPoint[]
|
||||
}) {
|
||||
if (baseline && isAccessControlDraftEqual(draft, baseline)) return false
|
||||
if (!availableAccessPoints.length) return false
|
||||
if (baseline && isAccessControlDraftEqual(draft, baseline, availableAccessPoints)) return false
|
||||
if (!draft.enabled) return Boolean(draft.selectedPolicyId)
|
||||
if (!draft.selectedPolicyId) return false
|
||||
if (persistableAccessPoints) return persistableAccessPoints.length > 0
|
||||
return hasSelectedAccessPoint(draft)
|
||||
return hasSelectedAccessPoint(draft, availableAccessPoints)
|
||||
}
|
||||
@@ -1,15 +1,16 @@
|
||||
'use client'
|
||||
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { AccessControlAssignment } from './chip-status'
|
||||
import type { AccessControlDraft } from './draft'
|
||||
import type AppIcon from '@/app/components/base/app-icon'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { 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,
|
||||
@@ -19,8 +20,10 @@ import {
|
||||
settingsQueryParamName,
|
||||
settingsQueryParser,
|
||||
} from '@/app/components/header/account-setting/query-params'
|
||||
import { isCurrentWorkspaceManagerAtom } from '@/context/workspace-state'
|
||||
import { deploymentEditionAtom } from '@/features/system-features/state'
|
||||
import {
|
||||
canManageNetworkAccessPoliciesAtom,
|
||||
canReadNetworkAccessAtom,
|
||||
} from '@/features/network-access/permissions'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { AccessControlChipAffix } from './chip-affix'
|
||||
import { getAccessControlChipState } from './chip-status'
|
||||
@@ -31,26 +34,39 @@ import { AccessControlFreePaywall } from './free-paywall'
|
||||
import {
|
||||
accessPointsFromScopes,
|
||||
draftFromBinding,
|
||||
getAvailableAccessPoints,
|
||||
getNetworkAccessErrorStatus,
|
||||
scopesFromAccessPoints,
|
||||
} from './network-access'
|
||||
import { AccessControlStatusPanel } from './status-panel'
|
||||
|
||||
export type AccessControlAppIcon = Pick<
|
||||
ComponentProps<typeof AppIcon>,
|
||||
'iconType' | 'icon' | 'background' | 'imageUrl'
|
||||
>
|
||||
|
||||
type AccessControlEntryProps = {
|
||||
appId: string
|
||||
appIcon: AccessControlAppIcon
|
||||
canEditBinding: boolean
|
||||
}
|
||||
|
||||
type GtagHandler = (command: 'event', action: 'click_upgrade_btn', payload: { loc: string }) => void
|
||||
|
||||
export function AccessControlEntry() {
|
||||
export function AccessControlEntry(props: AccessControlEntryProps) {
|
||||
return <AccessControlSession key={`${props.appId}:${props.canEditBinding}`} {...props} />
|
||||
}
|
||||
|
||||
function AccessControlSession({ appId, appIcon, canEditBinding }: AccessControlEntryProps) {
|
||||
const { t } = useTranslation()
|
||||
const queryClient = useQueryClient()
|
||||
const deploymentEdition = useAtomValue(deploymentEditionAtom)
|
||||
const isManager = useAtomValue(isCurrentWorkspaceManagerAtom)
|
||||
const canRead = useAtomValue(canReadNetworkAccessAtom)
|
||||
const canManagePolicies = useAtomValue(canManageNetworkAccessPoliciesAtom)
|
||||
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 canFetchNetworkAccess = canRead && Boolean(appId)
|
||||
const groupsQuery = useQuery(
|
||||
consoleQuery.workspaces.current.networkAccessGroups.get.queryOptions({
|
||||
enabled: canFetchNetworkAccess,
|
||||
@@ -59,7 +75,7 @@ export function AccessControlEntry() {
|
||||
)
|
||||
const bindingQuery = useQuery(
|
||||
consoleQuery.apps.byAppId.networkAccessGroup.get.queryOptions({
|
||||
input: appId ? { params: { app_id: appId } } : skipToken,
|
||||
input: { params: { app_id: appId } },
|
||||
context: { silent: true },
|
||||
retry: false,
|
||||
enabled: canFetchNetworkAccess && Boolean(appId),
|
||||
@@ -83,44 +99,49 @@ export function AccessControlEntry() {
|
||||
Boolean(appId) &&
|
||||
(bindingErrorStatus === 400 || bindingErrorStatus === 403 || bindingErrorStatus === 404)
|
||||
|
||||
if (deploymentEdition !== 'CLOUD' || !isManager) return null
|
||||
if (!canFetchNetworkAccess) return null
|
||||
if (hideForUnsupportedApp) return null
|
||||
if (groupsQuery.isPending || (appId && bindingQuery.isPending)) return null
|
||||
if (groupsQuery.isPending || bindingQuery.isPending) return null
|
||||
if (groupsQuery.isError || bindingQuery.isError || !groupsQuery.data || !bindingQuery.data)
|
||||
return null
|
||||
if (!Array.isArray(bindingQuery.data.available_access_points)) return null
|
||||
const availableAccessPoints = getAvailableAccessPoints(bindingQuery.data.available_access_points)
|
||||
if (!availableAccessPoints.length) return null
|
||||
|
||||
const label = t(($) => $['studio.accessControl.entryLabel'], { ns: 'deployments' })
|
||||
const groups = groupsQuery.data?.groups ?? []
|
||||
const binding = bindingQuery.data?.binding
|
||||
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)
|
||||
const resolvedDraft = draft ?? baseline
|
||||
const baseline = draftFromBinding(binding, availableAccessPoints)
|
||||
const entitled = bindingQuery.data.entitled
|
||||
const canMutate = canRead && canEditBinding && entitled
|
||||
const resolvedDraft = canMutate ? (draft ?? baseline) : baseline
|
||||
const assignment: AccessControlAssignment | null = binding?.group_id
|
||||
? {
|
||||
policyId: binding.group_id,
|
||||
policyName: groups.find((group) => group.id === binding.group_id)?.name ?? binding.group_id,
|
||||
scopes: scopesFromAccessPoints(binding.access_points),
|
||||
scopes: baseline.scopes,
|
||||
enabled: binding.enabled,
|
||||
}
|
||||
: null
|
||||
const entitled = bindingQuery.data?.entitled ?? groupsQuery.data?.entitled
|
||||
const canMutate = entitled === true
|
||||
const dirty = !isAccessControlDraftEqual(resolvedDraft, baseline)
|
||||
const dirty = !isAccessControlDraftEqual(resolvedDraft, baseline, availableAccessPoints)
|
||||
const persistableAccessPoints = accessPointsFromScopes(
|
||||
resolvedDraft.scopes,
|
||||
bindingQuery.data?.available_access_points,
|
||||
availableAccessPoints,
|
||||
)
|
||||
const canSave = canSaveAccessControl({
|
||||
draft: resolvedDraft,
|
||||
baseline,
|
||||
persistableAccessPoints,
|
||||
availableAccessPoints,
|
||||
})
|
||||
const chip = getAccessControlChipState({ entitled, assignment })
|
||||
const chip = getAccessControlChipState({ entitled, assignment, availableAccessPoints })
|
||||
const showPaywall = chip.kind === 'pro'
|
||||
const showDowngrade = Boolean(assignment) && !canMutate
|
||||
const showStatus = Boolean(assignment) && canMutate && view === 'status'
|
||||
const showDowngrade = Boolean(assignment) && !entitled
|
||||
const showStatus = Boolean(assignment) && entitled && (!canMutate || view === 'status')
|
||||
|
||||
const tooltip =
|
||||
chip.kind === 'pro'
|
||||
@@ -170,6 +191,7 @@ export function AccessControlEntry() {
|
||||
}
|
||||
|
||||
const handleCreatePolicy = () => {
|
||||
if (!canMutate || !canManagePolicies) return
|
||||
setOpen(false)
|
||||
setCreatePolicyOpen(true)
|
||||
}
|
||||
@@ -197,7 +219,7 @@ export function AccessControlEntry() {
|
||||
},
|
||||
onSuccess?: () => void,
|
||||
) => {
|
||||
if (!appId) return
|
||||
if (!canMutate) return
|
||||
|
||||
updateBinding.mutate(
|
||||
{
|
||||
@@ -287,17 +309,23 @@ export function AccessControlEntry() {
|
||||
{showPaywall ? (
|
||||
<AccessControlFreePaywall onTurnOn={handleTurnOn} />
|
||||
) : showDowngrade && assignment ? (
|
||||
<AccessControlDowngradePanel assignment={assignment} onTurnOn={handleTurnOn} />
|
||||
<AccessControlDowngradePanel
|
||||
assignment={assignment}
|
||||
appIcon={appIcon}
|
||||
availableAccessPoints={availableAccessPoints}
|
||||
onTurnOn={handleTurnOn}
|
||||
/>
|
||||
) : showStatus && assignment ? (
|
||||
<AccessControlStatusPanel
|
||||
draft={resolvedDraft}
|
||||
appIcon={appIcon}
|
||||
availableAccessPoints={availableAccessPoints}
|
||||
policies={policies}
|
||||
enabled={resolvedDraft.enabled}
|
||||
updating={updateBinding.isPending}
|
||||
dirty={dirty}
|
||||
canSave={canSave}
|
||||
readOnly={!canMutate}
|
||||
onUpgrade={handleTurnOn}
|
||||
onEnabledChange={handleEnabledChange}
|
||||
onCancel={handleCancel}
|
||||
onSave={handleSave}
|
||||
@@ -311,8 +339,11 @@ export function AccessControlEntry() {
|
||||
) : (
|
||||
<AccessControlConfigPanel
|
||||
draft={resolvedDraft}
|
||||
appIcon={appIcon}
|
||||
availableAccessPoints={availableAccessPoints}
|
||||
policies={policies}
|
||||
persistableAccessPoints={persistableAccessPoints}
|
||||
readOnly={!canMutate}
|
||||
canManagePolicies={canManagePolicies}
|
||||
baseline={baseline}
|
||||
showBack={showBack}
|
||||
saving={updateBinding.isPending}
|
||||
@@ -320,7 +351,9 @@ export function AccessControlEntry() {
|
||||
onCancel={handleCancel}
|
||||
onCreatePolicy={handleCreatePolicy}
|
||||
onManagePolicies={handleManagePolicies}
|
||||
onDraftChange={setDraft}
|
||||
onDraftChange={(nextDraft) => {
|
||||
if (canMutate) setDraft(nextDraft)
|
||||
}}
|
||||
onSave={handleSave}
|
||||
/>
|
||||
)}
|
||||
@@ -328,13 +361,14 @@ export function AccessControlEntry() {
|
||||
</Popover>
|
||||
<TooltipContent>{tooltip}</TooltipContent>
|
||||
</Tooltip>
|
||||
{createPolicyOpen && (
|
||||
{createPolicyOpen && canMutate && canManagePolicies && (
|
||||
<IpPolicyDialog
|
||||
mode="create"
|
||||
open
|
||||
isPending={createGroup.isPending}
|
||||
onOpenChange={handlePolicyDialogOpenChange}
|
||||
onSubmit={(payload) => {
|
||||
if (!canMutate || !canManagePolicies) return
|
||||
createGroup.mutate(
|
||||
{
|
||||
body: {
|
||||
|
||||
@@ -65,27 +65,31 @@ export function scopesFromAccessPoints(
|
||||
}
|
||||
}
|
||||
|
||||
export function getAvailableAccessPoints(
|
||||
accessPoints: readonly NetworkAccessPoint[],
|
||||
): AccessPoint[] {
|
||||
const available = new Set(accessPoints)
|
||||
return ACCESS_POINT_ORDER.filter((accessPoint) => available.has(toApiAccessPoint(accessPoint)))
|
||||
}
|
||||
|
||||
export function accessPointsFromScopes(
|
||||
scopes: AccessControlDraft['scopes'],
|
||||
availableAccessPoints?: readonly string[],
|
||||
availableAccessPoints: readonly AccessPoint[],
|
||||
): NetworkAccessPoint[] {
|
||||
const allowed = availableAccessPoints ? new Set(availableAccessPoints) : null
|
||||
|
||||
return ACCESS_POINT_ORDER.filter((accessPoint) => {
|
||||
if (!scopes[accessPoint]) return false
|
||||
if (!allowed) return true
|
||||
return allowed.has(toApiAccessPoint(accessPoint))
|
||||
}).map(toApiAccessPoint)
|
||||
return availableAccessPoints.filter((accessPoint) => scopes[accessPoint]).map(toApiAccessPoint)
|
||||
}
|
||||
|
||||
export function draftFromBinding(
|
||||
binding: AppNetworkAccessGroupBindingResponse | null | undefined,
|
||||
binding: AppNetworkAccessGroupBindingResponse | null,
|
||||
availableAccessPoints: readonly AccessPoint[],
|
||||
): AccessControlDraft {
|
||||
if (!binding?.group_id) return createDefaultAccessControlDraft()
|
||||
if (!binding?.group_id) return createDefaultAccessControlDraft(availableAccessPoints)
|
||||
|
||||
return {
|
||||
selectedPolicyId: binding.group_id,
|
||||
enabled: binding.enabled,
|
||||
scopes: scopesFromAccessPoints(binding.access_points),
|
||||
scopes: scopesFromAccessPoints(
|
||||
accessPointsFromScopes(scopesFromAccessPoints(binding.access_points), availableAccessPoints),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ type AccessControlPolicyFieldProps = {
|
||||
policies: readonly AccessControlPolicy[]
|
||||
selectedPolicyId: string | null
|
||||
currentIp?: string
|
||||
readOnly?: boolean
|
||||
canManagePolicies: boolean
|
||||
onCreatePolicy: () => void
|
||||
onManagePolicies: () => void
|
||||
onSelectPolicy: (policyId: string) => void
|
||||
@@ -35,6 +37,8 @@ export function AccessControlPolicyField({
|
||||
policies,
|
||||
selectedPolicyId,
|
||||
currentIp,
|
||||
readOnly = false,
|
||||
canManagePolicies,
|
||||
onCreatePolicy,
|
||||
onManagePolicies,
|
||||
onSelectPolicy,
|
||||
@@ -56,9 +60,15 @@ export function AccessControlPolicyField({
|
||||
<p className="w-full text-center system-sm-medium text-text-secondary">
|
||||
{t(($) => $['studio.accessControl.emptyPoliciesTitle'], { ns: 'deployments' })}
|
||||
</p>
|
||||
<Button type="button" variant="secondary-accent" onClick={onCreatePolicy}>
|
||||
{t(($) => $['studio.accessControl.createIpPolicy'], { ns: 'deployments' })}
|
||||
</Button>
|
||||
{canManagePolicies && !readOnly ? (
|
||||
<Button type="button" variant="secondary-accent" onClick={onCreatePolicy}>
|
||||
{t(($) => $['studio.accessControl.createIpPolicy'], { ns: 'deployments' })}
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="button" variant="secondary" onClick={onManagePolicies}>
|
||||
{t(($) => $['studio.accessControl.manageIpPolicies'], { ns: 'deployments' })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -123,8 +133,11 @@ export function AccessControlPolicyField({
|
||||
type="button"
|
||||
role="option"
|
||||
aria-selected={false}
|
||||
disabled={readOnly}
|
||||
className="flex h-8 w-full cursor-pointer items-center rounded-lg px-2 text-left system-sm-medium text-text-secondary outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid"
|
||||
onClick={() => onSelectPolicy(policy.id)}
|
||||
onClick={() => {
|
||||
if (!readOnly) onSelectPolicy(policy.id)
|
||||
}}
|
||||
>
|
||||
<span className="min-w-0 flex-1 truncate px-1">{policy.name}</span>
|
||||
<span className="shrink-0 system-xs-regular text-text-tertiary">
|
||||
@@ -155,7 +168,9 @@ export function AccessControlPolicyField({
|
||||
<div className="flex w-full items-center gap-1">
|
||||
<Select
|
||||
value={selectedPolicyId}
|
||||
disabled={readOnly}
|
||||
onValueChange={(value) => {
|
||||
if (readOnly) return
|
||||
if (value === MANAGE_POLICIES_VALUE) {
|
||||
onManagePolicies()
|
||||
return
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
'use client'
|
||||
|
||||
import type { AccessControlDraft } from './draft'
|
||||
import type { AccessControlAppIcon } from './index'
|
||||
import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Switch } from '@langgenius/dify-ui/switch'
|
||||
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'
|
||||
|
||||
const SCOPE_ICONS: Record<Exclude<AccessPoint, 'webApp'>, string> = {
|
||||
@@ -17,12 +16,20 @@ const SCOPE_ICONS: Record<Exclude<AccessPoint, 'webApp'>, string> = {
|
||||
|
||||
type AccessControlScopeListProps = {
|
||||
draft: AccessControlDraft
|
||||
appIcon: AccessControlAppIcon
|
||||
availableAccessPoints: readonly AccessPoint[]
|
||||
readOnly?: boolean
|
||||
onDraftChange: (draft: AccessControlDraft) => void
|
||||
}
|
||||
|
||||
export function AccessControlScopeList({ draft, onDraftChange }: AccessControlScopeListProps) {
|
||||
export function AccessControlScopeList({
|
||||
draft,
|
||||
appIcon,
|
||||
availableAccessPoints,
|
||||
readOnly = false,
|
||||
onDraftChange,
|
||||
}: AccessControlScopeListProps) {
|
||||
const { t } = useTranslation()
|
||||
const appInfo = useAppStore((state) => state.appDetail)
|
||||
|
||||
const labels: Record<AccessPoint, string> = {
|
||||
webApp: t(($) => $['overview.appInfo.title'], { ns: 'appOverview' }),
|
||||
@@ -33,7 +40,7 @@ export function AccessControlScopeList({ draft, onDraftChange }: AccessControlSc
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-0.5">
|
||||
{ACCESS_POINT_ORDER.map((scope) => {
|
||||
{availableAccessPoints.map((scope) => {
|
||||
const label = labels[scope]
|
||||
|
||||
return (
|
||||
@@ -42,10 +49,7 @@ export function AccessControlScopeList({ draft, onDraftChange }: AccessControlSc
|
||||
<AppIcon
|
||||
size="tiny"
|
||||
decorative
|
||||
iconType={appInfo?.icon_type}
|
||||
icon={appInfo?.icon}
|
||||
background={appInfo?.icon_background ?? undefined}
|
||||
imageUrl={appInfo?.icon_url}
|
||||
{...appIcon}
|
||||
className="rounded-sm bg-util-colors-orange-orange-100"
|
||||
/>
|
||||
) : (
|
||||
@@ -59,8 +63,10 @@ export function AccessControlScopeList({ draft, onDraftChange }: AccessControlSc
|
||||
<span className="min-w-0 flex-1 system-sm-medium text-text-secondary">{label}</span>
|
||||
<Switch
|
||||
checked={draft.scopes[scope]}
|
||||
disabled={readOnly}
|
||||
aria-label={label}
|
||||
onCheckedChange={(checked) => {
|
||||
if (readOnly) return
|
||||
onDraftChange({
|
||||
...draft,
|
||||
scopes: {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import type { AccessControlDraft, AccessControlPolicy } from './draft'
|
||||
import type { AccessControlAppIcon } from './index'
|
||||
import type { AccessPoint } from '@/app/components/app/deploy/utils/access-point'
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -17,8 +18,6 @@ import { PopoverTitle } from '@langgenius/dify-ui/popover'
|
||||
import { Switch } from '@langgenius/dify-ui/switch'
|
||||
import { useState } from 'react'
|
||||
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'
|
||||
@@ -31,6 +30,8 @@ const SCOPE_ICONS: Record<Exclude<AccessPoint, 'webApp'>, string> = {
|
||||
|
||||
type AccessControlStatusPanelProps = {
|
||||
draft: AccessControlDraft
|
||||
appIcon: AccessControlAppIcon
|
||||
availableAccessPoints: readonly AccessPoint[]
|
||||
policies: readonly AccessControlPolicy[]
|
||||
enabled: boolean
|
||||
onEdit: () => void
|
||||
@@ -38,7 +39,6 @@ type AccessControlStatusPanelProps = {
|
||||
dirty?: boolean
|
||||
canSave?: boolean
|
||||
readOnly?: boolean
|
||||
onUpgrade?: () => void
|
||||
onCancel?: () => void
|
||||
onSave?: () => void
|
||||
onEnabledChange: (enabled: boolean) => void
|
||||
@@ -46,6 +46,8 @@ type AccessControlStatusPanelProps = {
|
||||
|
||||
export function AccessControlStatusPanel({
|
||||
draft,
|
||||
appIcon,
|
||||
availableAccessPoints,
|
||||
policies,
|
||||
enabled,
|
||||
onEdit,
|
||||
@@ -53,26 +55,24 @@ export function AccessControlStatusPanel({
|
||||
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.allowed_cidrs) : undefined
|
||||
const coverage = getInServiceCoverage(draft.scopes)
|
||||
const coverage = getInServiceCoverage(draft.scopes, availableAccessPoints)
|
||||
const labels: Record<AccessPoint, string> = {
|
||||
webApp: t(($) => $['overview.appInfo.title'], { ns: 'appOverview' }),
|
||||
serviceApi: t(($) => $['overview.apiInfo.title'], { ns: 'appOverview' }),
|
||||
mcp: t(($) => $['mcp.server.title'], { ns: 'tools' }),
|
||||
trigger: t(($) => $['settings.trigger'], { ns: 'common' }),
|
||||
}
|
||||
const exposedNames = ACCESS_POINT_ORDER.filter((scope) => draft.scopes[scope]).map(
|
||||
(scope) => labels[scope],
|
||||
)
|
||||
const exposedNames = availableAccessPoints
|
||||
.filter((scope) => draft.scopes[scope])
|
||||
.map((scope) => labels[scope])
|
||||
const policyName = selectedPolicy?.name
|
||||
|
||||
return (
|
||||
@@ -86,11 +86,7 @@ export function AccessControlStatusPanel({
|
||||
})
|
||||
: t(($) => $['studio.accessControl.entryLabel'], { ns: 'deployments' })}
|
||||
</PopoverTitle>
|
||||
{readOnly ? (
|
||||
<Button type="button" variant="ghost" size="small" onClick={onUpgrade}>
|
||||
{t(($) => $['studio.accessControl.turnOn'], { ns: 'deployments' })}
|
||||
</Button>
|
||||
) : (
|
||||
{!readOnly && (
|
||||
<Button type="button" variant="ghost" size="small" onClick={onEdit}>
|
||||
{t(($) => $['operation.edit'], { ns: 'common' })}
|
||||
</Button>
|
||||
@@ -121,6 +117,7 @@ export function AccessControlStatusPanel({
|
||||
disabled={updating || readOnly}
|
||||
aria-label={t(($) => $['studio.accessControl.restrictByIp'], { ns: 'deployments' })}
|
||||
onCheckedChange={(next) => {
|
||||
if (readOnly || updating) return
|
||||
if (next) {
|
||||
onEnabledChange(true)
|
||||
return
|
||||
@@ -163,7 +160,7 @@ export function AccessControlStatusPanel({
|
||||
<p className="system-sm-medium text-text-secondary">
|
||||
{t(($) => $['studio.accessControl.applyTo'], { ns: 'deployments' })}
|
||||
</p>
|
||||
{ACCESS_POINT_ORDER.map((scope) => {
|
||||
{availableAccessPoints.map((scope) => {
|
||||
const excluded = !draft.scopes[scope]
|
||||
const label = labels[scope]
|
||||
|
||||
@@ -173,10 +170,7 @@ export function AccessControlStatusPanel({
|
||||
<AppIcon
|
||||
size="tiny"
|
||||
decorative
|
||||
iconType={appInfo?.icon_type}
|
||||
icon={appInfo?.icon}
|
||||
background={appInfo?.icon_background ?? undefined}
|
||||
imageUrl={appInfo?.icon_url}
|
||||
{...appIcon}
|
||||
className="rounded-sm bg-util-colors-orange-orange-100"
|
||||
/>
|
||||
) : (
|
||||
@@ -245,7 +239,9 @@ export function AccessControlStatusPanel({
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</AlertDialogCancelButton>
|
||||
<AlertDialogConfirmButton
|
||||
disabled={readOnly || updating}
|
||||
onClick={() => {
|
||||
if (readOnly || updating) return
|
||||
onEnabledChange(false)
|
||||
setConfirmPause(false)
|
||||
}}
|
||||
|
||||
@@ -55,6 +55,7 @@ function AccessPointContent({
|
||||
showEnvironmentTabs,
|
||||
}: AccessPointContentProps) {
|
||||
const { t } = useTranslation()
|
||||
const appInfo = useAppStore((state) => state.appDetail)
|
||||
const environments = useAtomValue(inUseAppEnvironmentsAtom)
|
||||
const [queryStates, setQueryStates] = useQueryStates(accessPointQueryStates)
|
||||
const { accessPoint: highlightedAccessPoint, environment } = queryStates
|
||||
@@ -75,7 +76,16 @@ function AccessPointContent({
|
||||
<h1 id="access-point-title" className="title-xl-semi-bold text-text-primary">
|
||||
{t(($) => $['appMenus.accessPoint'], { ns: 'common' })}
|
||||
</h1>
|
||||
<AccessControlEntry />
|
||||
<AccessControlEntry
|
||||
appId={appId}
|
||||
appIcon={{
|
||||
iconType: appInfo?.icon_type,
|
||||
icon: appInfo?.icon,
|
||||
background: appInfo?.icon_background,
|
||||
imageUrl: appInfo?.icon_url,
|
||||
}}
|
||||
canEditBinding={canManageAccessPoint}
|
||||
/>
|
||||
</div>
|
||||
<p className="system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['studio.accessPoint.description'], { ns: 'deployments' })}
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import type { AgentAppDetailWithSite } from '@dify/contracts/api/console/agent/types.gen'
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing'
|
||||
import { AgentPermission } from '@/features/agent-v2/acl'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import {
|
||||
createNetworkAccessGroupFixture,
|
||||
seedAppNetworkAccessGroup,
|
||||
seedNetworkAccessGroups,
|
||||
} from '@/test/console/network-access'
|
||||
import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { createAgentFixture } from '@/test/fixtures/agent'
|
||||
import { AgentAccessPage } from '../page'
|
||||
|
||||
vi.mock('@/context/i18n', () => ({
|
||||
useDocLink: () => (path: string) => `https://docs.example.test${path}`,
|
||||
}))
|
||||
|
||||
// These cards own independent publishing and API-key workflows.
|
||||
vi.mock('../components/web-app-access-card', () => ({ WebAppAccessCard: () => null }))
|
||||
vi.mock('../components/service-api-access-card', () => ({ ServiceApiAccessCard: () => null }))
|
||||
vi.mock('../components/workflow-references-table', () => ({ WorkflowReferencesTable: () => null }))
|
||||
|
||||
vi.mock('react-i18next', async () => {
|
||||
const { createReactI18nextMock } = await import('@/test/i18n-mock')
|
||||
return createReactI18nextMock({
|
||||
'studio.accessControl.entryLabel': 'Access Control',
|
||||
'studio.accessControl.chipOff': 'Off',
|
||||
'studio.accessControl.chipOn': 'ON',
|
||||
'studio.accessControl.chipPartial': '{{n}} of {{m}}',
|
||||
'studio.accessControl.restrictByIp': 'Restrict by IP address',
|
||||
'studio.accessControl.protectingAll': 'Protecting all {{count}} access points.',
|
||||
'studio.accessControl.selectPolicy': 'Select a policy',
|
||||
'studio.accessControl.ipPolicy': 'IP Policy',
|
||||
'studio.accessControl.manageIpPolicies': 'Manage IP policies',
|
||||
'overview.appInfo.title': 'Web App',
|
||||
'overview.apiInfo.title': 'Backend Service API',
|
||||
'mcp.server.title': 'MCP Server',
|
||||
'settings.trigger': 'Trigger',
|
||||
'operation.save': 'Save',
|
||||
'operation.edit': 'Edit',
|
||||
'operation.cancel': 'Cancel',
|
||||
})
|
||||
})
|
||||
|
||||
function setup(overrides: Partial<AgentAppDetailWithSite> = {}, configured = false) {
|
||||
const queryClient = createConsoleQueryClient()
|
||||
const agent = createAgentFixture({
|
||||
app_id: 'public-app',
|
||||
backing_app_id: 'runtime-app',
|
||||
hidden_app_backed: false,
|
||||
...overrides,
|
||||
})
|
||||
queryClient.setQueryData(
|
||||
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: agent.id } } }),
|
||||
agent,
|
||||
)
|
||||
const policy = createNetworkAccessGroupFixture()
|
||||
seedNetworkAccessGroups(queryClient, { groups: [policy] })
|
||||
const binding = configured
|
||||
? {
|
||||
id: 'binding-1',
|
||||
tenant_id: 'workspace-1',
|
||||
app_id: 'public-app',
|
||||
enabled: true,
|
||||
group_id: policy.id,
|
||||
access_points: ['webapp', 'service_api'] as const,
|
||||
version: 1,
|
||||
updated_by_account_id: null,
|
||||
created_at: policy.created_at,
|
||||
updated_at: policy.updated_at,
|
||||
}
|
||||
: null
|
||||
const appBinding = seedAppNetworkAccessGroup(queryClient, 'public-app', {
|
||||
available_access_points: ['webapp', 'service_api'],
|
||||
binding: binding ? { ...binding, access_points: [...binding.access_points] } : null,
|
||||
effective_enabled: configured,
|
||||
})
|
||||
const renderPage = (agentId: string) => (
|
||||
<NuqsTestingAdapter>
|
||||
<AgentAccessPage agentId={agentId} />
|
||||
</NuqsTestingAdapter>
|
||||
)
|
||||
const rendered = renderWithConsoleQuery(renderPage(agent.id), {
|
||||
queryClient,
|
||||
currentWorkspace: { id: 'workspace-1', role: 'editor' },
|
||||
systemFeatures: { deployment_edition: 'CLOUD' },
|
||||
})
|
||||
return { ...rendered, agent, policy, appBinding, renderPage }
|
||||
}
|
||||
|
||||
describe('Agent IP access configuration', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('lets an Editor configure the public App ID with exactly two access points', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { appBinding, policy } = setup({
|
||||
access_ready: false,
|
||||
enable_site: false,
|
||||
enable_api: false,
|
||||
})
|
||||
const writes: Array<{ url: string; body: unknown }> = []
|
||||
vi.mocked(globalThis.fetch).mockImplementation(async (input, init) => {
|
||||
const request = input instanceof Request ? input : new Request(String(input), init)
|
||||
if (request.method === 'PUT') {
|
||||
const body = await request.json()
|
||||
writes.push({ url: request.url, body })
|
||||
}
|
||||
if (request.url.includes('/workspaces/current/network-access-groups'))
|
||||
return Response.json({ tenant_id: 'workspace-1', entitled: true, groups: [policy] })
|
||||
return Response.json(appBinding)
|
||||
})
|
||||
|
||||
await user.click(await screen.findByRole('button', { name: /Access Control/ }))
|
||||
expect(screen.getByRole('switch', { name: 'Web App' })).toBeChecked()
|
||||
expect(screen.getByRole('switch', { name: 'Backend Service API' })).toBeChecked()
|
||||
expect(screen.queryByRole('switch', { name: 'MCP Server' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('switch', { name: 'Trigger' })).not.toBeInTheDocument()
|
||||
await user.click(screen.getByRole('option', { name: /Internal Network/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Save' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(writes).toEqual([
|
||||
{
|
||||
url: 'http://localhost:5001/console/api/apps/public-app/network-access-group',
|
||||
body: {
|
||||
enabled: true,
|
||||
group_id: 'group-1',
|
||||
access_points: ['webapp', 'service_api'],
|
||||
expected_version: 0,
|
||||
},
|
||||
},
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it.each([{ app_id: null }, { hidden_app_backed: true }, { permission_keys: [] }])(
|
||||
'does not offer an independent IP binding for an ineligible Agent: %o',
|
||||
(overrides) => {
|
||||
setup(overrides)
|
||||
expect(screen.queryByRole('button', { name: /Access Control/ })).not.toBeInTheDocument()
|
||||
expect(globalThis.fetch).not.toHaveBeenCalled()
|
||||
},
|
||||
)
|
||||
|
||||
it('shows both protected endpoints as complete coverage for a read-only Agent', async () => {
|
||||
const user = userEvent.setup()
|
||||
setup({ permission_keys: [AgentPermission.AccessPointView] }, true)
|
||||
const chip = await screen.findByRole('button', { name: /Access Control/ })
|
||||
expect(chip).toHaveTextContent('ON')
|
||||
await user.click(chip)
|
||||
expect(screen.getByText('Protecting all 2 access points.')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
|
||||
const toggle = screen.getByRole('switch', { name: 'Restrict by IP address' })
|
||||
expect(toggle).toHaveAttribute('aria-disabled', 'true')
|
||||
await user.click(toggle)
|
||||
expect(toggle).toBeChecked()
|
||||
expect(
|
||||
vi
|
||||
.mocked(globalThis.fetch)
|
||||
.mock.calls.filter(([input]) => input instanceof Request && input.method !== 'GET'),
|
||||
).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('closes an unsaved policy draft when switching Agents', async () => {
|
||||
const user = userEvent.setup()
|
||||
const { queryClient, rerender, renderPage } = setup()
|
||||
await user.click(await screen.findByRole('button', { name: /Access Control/ }))
|
||||
await user.click(screen.getByRole('option', { name: /Internal Network/ }))
|
||||
await user.click(screen.getByRole('switch', { name: 'Backend Service API' }))
|
||||
|
||||
const second = createAgentFixture({ id: 'agent-2', app_id: 'second-app' })
|
||||
queryClient.setQueryData(
|
||||
consoleQuery.agent.byAgentId.get.queryKey({ input: { params: { agent_id: second.id } } }),
|
||||
second,
|
||||
)
|
||||
seedAppNetworkAccessGroup(queryClient, 'second-app', {
|
||||
available_access_points: ['webapp', 'service_api'],
|
||||
})
|
||||
rerender(renderPage(second.id))
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument(),
|
||||
)
|
||||
await user.click(screen.getByRole('button', { name: /Access Control/ }))
|
||||
expect(screen.getByRole('switch', { name: 'Backend Service API' })).toBeChecked()
|
||||
expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,9 @@ import {
|
||||
} from '@langgenius/dify-ui/scroll-area'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { AccessControlEntry } from '@/app/components/app/access-point/access-control'
|
||||
import { useDocLink } from '@/context/i18n'
|
||||
import { getAgentACLCapabilities } from '@/features/agent-v2/acl'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { AgentDetailSectionSurface } from '../section-surface'
|
||||
import { ServiceApiAccessCard } from './components/service-api-access-card'
|
||||
@@ -32,10 +34,12 @@ export function AgentAccessPage({ agentId }: AgentAccessPageProps) {
|
||||
},
|
||||
}),
|
||||
)
|
||||
const agent = agentQuery.data
|
||||
const capabilities = getAgentACLCapabilities(agent?.permission_keys)
|
||||
|
||||
return (
|
||||
<AgentDetailSectionSurface label={t(($) => $['agentDetail.sections.access'])}>
|
||||
<header className="h-15.5 shrink-0 px-6 pt-3 pb-2">
|
||||
<header className="flex shrink-0 flex-wrap items-start justify-between gap-3 px-6 pt-3 pb-2">
|
||||
<div className="min-w-0">
|
||||
<h2 className="system-xl-semibold text-text-primary">
|
||||
{t(($) => $['agentDetail.access.title'])}
|
||||
@@ -53,6 +57,19 @@ export function AgentAccessPage({ agentId }: AgentAccessPageProps) {
|
||||
</a>
|
||||
</p>
|
||||
</div>
|
||||
{agent?.app_id && !agent.hidden_app_backed && capabilities.canViewAccessPoint && (
|
||||
<AccessControlEntry
|
||||
appId={agent.app_id}
|
||||
appIcon={{
|
||||
iconType:
|
||||
agent.icon_type === 'image' || agent.icon_type === 'link' ? 'image' : 'emoji',
|
||||
icon: agent.icon ?? undefined,
|
||||
background: agent.icon_background,
|
||||
imageUrl: agent.icon_url,
|
||||
}}
|
||||
canEditBinding={capabilities.canManageAccessPoint}
|
||||
/>
|
||||
)}
|
||||
</header>
|
||||
|
||||
<ScrollArea className="min-h-0 flex-1 overflow-hidden">
|
||||
|
||||
Reference in new issue
Block a user