This is an automated email from the ASF dual-hosted git repository.
jerryshao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new d7d5095c05 feat(web): support system access-control policies (#14570)
d7d5095c05 is described below
commit d7d5095c05ec9d1b129216b95d56030630e9d7bd
Author: Abhijeet Singh <[email protected]>
AuthorDate: Wed Nov 18 13:50:23 2026 +0530
feat(web): support system access-control policies (#14570)
### What changes were proposed in this pull request?
* Add System Access Control as a policy type.
* Require at least one applicable role and one permitted privilege.
* Update label in policy list page
### Why are the changes needed?
Users need to manage tag-based access-control policies through the web
UI. These policies must be associated with tags, so direct
metadata-object assignment must be prevented.
Fixes #14569
### Does this PR introduce _any_ user-facing change?
Yes. Users can select System Access Control when creating a policy,
choose applicable roles and privileges, and view or edit its content.
Policy forms also show a loading state and retain input when saving
fails.
### How was this patch tested?
by running it locally and testing it out
creating policy:
<img width="847" height="778" alt="Screenshot 2026-11-03 at 2 18 49 PM"
src="https://github.com/user-attachments/assets/49234527-1652-4f49-b838-421e4e39fb24"
/>
listing page:
<img width="521" height="183" alt="Screenshot 2026-11-17 at 10 12 17 AM"
src="https://github.com/user-attachments/assets/ee43c869-5dd1-4e9f-b57c-99dd302178a4"
/>
---------
Co-authored-by: Abhijeet Singh <[email protected]>
---
.../app/compliance/policies/CreatePolicyDialog.js | 375 ++++++++++++---------
.../policies/CreatePolicyDialog.test.jsx | 216 ++++++++++++
.../web/src/app/compliance/policies/constants.js | 38 +++
web-v2/web/src/app/compliance/policies/page.js | 163 +++++----
web-v2/web/src/components/PolicyTag.test.jsx | 37 +-
web-v2/web/src/lib/utils/index.js | 6 +-
6 files changed, 601 insertions(+), 234 deletions(-)
diff --git a/web-v2/web/src/app/compliance/policies/CreatePolicyDialog.js
b/web-v2/web/src/app/compliance/policies/CreatePolicyDialog.js
index 5787979e20..14720d7e20 100644
--- a/web-v2/web/src/app/compliance/policies/CreatePolicyDialog.js
+++ b/web-v2/web/src/app/compliance/policies/CreatePolicyDialog.js
@@ -17,18 +17,19 @@
* under the License.
*/
-import React, { useEffect, useState, useRef } from 'react'
+import React, { useEffect, useState } from 'react'
import { PlusOutlined } from '@ant-design/icons'
-import { Button, Flex, Form, Input, Modal, Select, Switch, Typography } from
'antd'
+import { Button, Flex, Form, Input, Modal, Select, Spin, Switch, Typography }
from 'antd'
import Icons from '@/components/Icons'
import RenderPropertiesFormItem from '@/components/EntityPropertiesFormItem'
import { validateMessages, supportedObjectTypesMap, mismatchName } from
'@/config'
import { nameRegex } from '@/lib/utils/regex'
import { useResetFormOnCloseModal } from '@/lib/hooks/use-reset'
import { genUpdates } from '@/lib/utils'
-import { cn } from '@/lib/utils/tailwind'
-import { useAppDispatch } from '@/lib/hooks/useStore'
+import { useAppDispatch, useAppSelector } from '@/lib/hooks/useStore'
import { getPolicyDetails, createPolicy, updatePolicy } from
'@/lib/store/policies'
+import { fetchRoles } from '@/lib/store/roles'
+import { accessControlPrivilegeOptions, policyTypeLabels } from './constants'
const { Paragraph } = Typography
const { TextArea } = Input
@@ -38,6 +39,8 @@ const defaultValues = {
comment: '',
enabled: true,
policyType: 'custom',
+ privileges: [],
+ applicableRoles: [],
supportedObjectTypes: [],
rules: [],
properties: []
@@ -46,11 +49,14 @@ const defaultValues = {
export default function CreatePolicyDialog({ ...props }) {
const { open, setOpen, metalake, editPolicy } = props
const [confirmLoading, setConfirmLoading] = useState(false)
+ const [isLoading, setIsLoading] = useState(false)
const [cacheData, setCacheData] = useState()
- const loadedRef = useRef(false)
const [form] = Form.useForm()
const values = Form.useWatch([], form)
const dispatch = useAppDispatch()
+ const roles = useAppSelector(state => state.roles)
+ const anthEnable = useAppSelector(state => state.auth.anthEnable)
+ const isAccessControl = values?.policyType === 'system_access_control'
useResetFormOnCloseModal({
form,
@@ -58,87 +64,86 @@ export default function CreatePolicyDialog({ ...props }) {
})
useEffect(() => {
- if (open && editPolicy && !loadedRef.current) {
- loadedRef.current = true
+ setCacheData(undefined)
+ setIsLoading(open && !!editPolicy)
+ if (!open || !editPolicy) return
+ let cancelled = false
- const init = async () => {
- const { payload: policy } = await dispatch(getPolicyDetails({
metalake, policy: editPolicy }))
- setCacheData(policy)
- form.setFieldValue('name', policy.name)
- form.setFieldValue('enabled', policy.enabled)
- form.setFieldValue('comment', policy.comment)
- form.setFieldValue('policyType', policy.policyType)
- form.setFieldValue('supportedObjectTypes',
policy.content?.supportedObjectTypes || [])
- let ruleIndex = 0
- Object.entries(policy.content?.customRules || {}).forEach(([key,
value]) => {
- if (key !== 'color') {
- form.setFieldValue(['rules', ruleIndex, 'ruleName'], key)
- form.setFieldValue(['rules', ruleIndex, 'ruleContent'], value)
- ruleIndex++
- }
- })
- let index = 0
- Object.entries(policy.content?.properties || {}).forEach(([key,
value]) => {
- if (key !== 'color') {
- form.setFieldValue(['properties', index, 'key'], key)
- form.setFieldValue(['properties', index, 'value'], value)
- index++
- }
- })
- }
- init()
+ const init = async () => {
+ const { payload: policy } = await dispatch(getPolicyDetails({ metalake,
policy: editPolicy }))
+ if (cancelled) return
+ setIsLoading(false)
+ if (!policy) return
+ setCacheData(policy)
+ form.setFieldsValue({
+ name: policy.name,
+ enabled: policy.enabled,
+ comment: policy.comment,
+ policyType: policy.policyType,
+ privileges: policy.content?.privileges || [],
+ applicableRoles: policy.content?.applicableRoles || [],
+ supportedObjectTypes: policy.content?.supportedObjectTypes || [],
+ rules: Object.entries(policy.content?.customRules || {})
+ .filter(([key]) => key !== 'color')
+ .map(([ruleName, ruleContent]) => ({ ruleName, ruleContent })),
+ properties: Object.entries(policy.content?.properties || {})
+ .filter(([key]) => key !== 'color')
+ .map(([key, value]) => ({ key, value }))
+ })
}
+ init()
- // Reset loadedRef when dialog closes
- if (!open) {
- loadedRef.current = false
+ return () => {
+ cancelled = true
}
- }, [open, editPolicy, metalake])
+ }, [open, editPolicy, metalake, dispatch, form])
+
+ useEffect(() => {
+ if (open && isAccessControl && anthEnable) dispatch(fetchRoles({ metalake
}))
+ }, [open, isAccessControl, anthEnable, metalake, dispatch])
- const handleSubmit = e => {
+ const handleSubmit = async e => {
e.preventDefault()
- form
- .validateFields()
- .then(async () => {
- setConfirmLoading(true)
+ try {
+ const values = await form.validateFields()
+ setConfirmLoading(true)
- const submitData = {
- name: values.name.trim(),
- comment: values.comment,
- enabled: values.enabled,
- policyType: values.policyType,
- content: {
- customRules: values.rules.reduce((acc, item) => {
- if (item.ruleName) {
- acc[item.ruleName] = item.ruleContent
- }
+ const submitData = {
+ name: values.name.trim(),
+ comment: values.comment,
+ enabled: values.enabled,
+ policyType: values.policyType,
+ content:
+ values.policyType === 'system_access_control'
+ ? { privileges: values.privileges, applicableRoles:
values.applicableRoles }
+ : {
+ customRules: values.rules.reduce((acc, item) => {
+ if (item.ruleName) acc[item.ruleName] = item.ruleContent
- return acc
- }, {}),
- supportedObjectTypes: values.supportedObjectTypes,
- properties: values.properties.reduce((acc, item) => {
- acc[item.key] = values[item.key] || item.value
+ return acc
+ }, {}),
+ supportedObjectTypes: values.supportedObjectTypes,
+ properties: values.properties.reduce((acc, item) => {
+ acc[item.key] = values[item.key] || item.value
- return acc
- }, {})
- }
- }
- if (editPolicy) {
- // update policy
- const reqData = { updates: genUpdates(cacheData, submitData) }
- if (reqData.updates.length) {
- await dispatch(updatePolicy({ metalake, policy: editPolicy, data:
reqData }))
- }
- } else {
- await dispatch(createPolicy({ metalake, data: submitData }))
+ return acc
+ }, {})
+ }
+ }
+ if (editPolicy) {
+ const reqData = { updates: genUpdates(cacheData, submitData) }
+ if (reqData.updates.length) {
+ await dispatch(updatePolicy({ metalake, policy: editPolicy, data:
reqData })).unwrap()
}
- setConfirmLoading(false)
- setOpen(false)
- })
- .catch(info => {
- console.error(info)
- form.scrollToField(info?.errorFields?.[0]?.name?.[0])
- })
+ } else {
+ await dispatch(createPolicy({ metalake, data: submitData })).unwrap()
+ }
+ setOpen(false)
+ } catch (info) {
+ if (info?.errorFields?.length)
form.scrollToField(info.errorFields[0].name)
+ } finally {
+ setConfirmLoading(false)
+ }
}
const handleCancel = () => {
@@ -156,97 +161,145 @@ export default function CreatePolicyDialog({ ...props })
{
keyboard={false}
width={800}
confirmLoading={confirmLoading}
+ okButtonProps={{ disabled: !!editPolicy && !cacheData }}
onCancel={handleCancel}
>
<Paragraph type='secondary'>{!editPolicy ? 'Create a new policy' :
`Edit the policy ${editPolicy}.`}</Paragraph>
- <Form
- form={form}
- initialValues={defaultValues}
- layout='vertical'
- name='policyForm'
- validateMessages={validateMessages}
- >
- <Form.Item
- name='name'
- label='Policy Name'
- rules={[{ required: true }, { type: 'string', max: 64 }, {
pattern: new RegExp(nameRegex) }]}
- messageVariables={{ label: 'policy name' }}
- >
- <Input placeholder={mismatchName} />
- </Form.Item>
- <Form.Item name='enabled' label='Enabled'>
- <Switch disabled={!!editPolicy} />
- </Form.Item>
- <Form.Item name='policyType' label='Policy Type'>
- <Select>
- <Select.Option value='custom'>Custom</Select.Option>
- </Select>
- </Form.Item>
- <Form.Item
- name='supportedObjectTypes'
- rules={[{ required: true, message: 'Please select supported object
types!' }]}
- label='Supported Object Types'
+ <Spin spinning={isLoading}>
+ <Form
+ disabled={!!editPolicy && !cacheData}
+ form={form}
+ initialValues={defaultValues}
+ layout='vertical'
+ name='policyForm'
+ validateMessages={validateMessages}
>
- <Select mode='multiple'>
- {Object.values(supportedObjectTypesMap).map(item => (
- <Select.Option key={item} value={item}>
- {item}
+ <Form.Item
+ name='name'
+ label='Policy Name'
+ rules={[{ required: true }, { type: 'string', max: 64 }, {
pattern: new RegExp(nameRegex) }]}
+ messageVariables={{ label: 'policy name' }}
+ >
+ <Input placeholder={mismatchName} />
+ </Form.Item>
+ <Form.Item name='enabled' label='Enabled'>
+ <Switch disabled={!!editPolicy} />
+ </Form.Item>
+ <Form.Item name='policyType' label='Policy Type'>
+ <Select disabled={!!editPolicy}>
+ <Select.Option
value='custom'>{policyTypeLabels.custom}</Select.Option>
+ <Select.Option value='system_access_control'
disabled={!anthEnable}>
+ {policyTypeLabels.system_access_control}
</Select.Option>
- ))}
- </Select>
- </Form.Item>
- <Form.Item label='Rule(s)'>
- <div className='flex flex-col gap-2'>
- <Form.List name='rules'>
- {(fields, { add, remove }) => (
- <>
- {fields.map(({ key, name, ...restField }) => (
- <Form.Item label={null} className='align-items-center
mb-1' key={key}>
- <Flex gap='small' align='start'>
- <Form.Item
- {...restField}
- name={[name, 'ruleName']}
- rules={[{ required: true, message: 'Please enter
the rule name!' }]}
- className='mb-0 w-full grow'
- >
- <Input placeholder='Rule Name' />
- </Form.Item>
- <Form.Item
- {...restField}
- name={[name, 'ruleContent']}
- rules={[{ required: true, message: 'Please enter
the rule content!' }]}
- className='mb-0 w-full grow'
- >
- <Input placeholder='Rule Content' />
- </Form.Item>
- <Form.Item className='mb-0 grow-0'>
- <Icons.Minus
- className='size-8 cursor-pointer text-gray-400
hover:text-defaultPrimary'
- onClick={() => remove(name)}
- />
- </Form.Item>
- </Flex>
- </Form.Item>
+ </Select>
+ </Form.Item>
+ {isAccessControl ? (
+ <>
+ <Paragraph type='secondary'>
+ Grants the selected privileges when any applicable role
matches. Associate this policy with a tag; it
+ cannot be assigned directly to a table, schema, or other
metadata object. Users still need USE_CATALOG
+ and USE_SCHEMA, and an RBAC deny overrides this policy.
+ </Paragraph>
+ <Form.Item
+ name='applicableRoles'
+ label='Applicable Roles'
+ rules={[{ type: 'array', required: true, min: 1, message:
'Please select at least one role.' }]}
+ >
+ <Select
+ mode='multiple'
+ showSearch
+ optionFilterProp='label'
+ loading={roles.rolesLoading}
+ placeholder='Select roles'
+ options={roles.rolesData?.map(role => ({ value: role,
label: role }))}
+ />
+ </Form.Item>
+ <Form.Item
+ name='privileges'
+ label='Privileges'
+ rules={[{ type: 'array', required: true, min: 1, message:
'Please select at least one privilege.' }]}
+ >
+ <Select
+ mode='multiple'
+ showSearch
+ optionFilterProp='label'
+ placeholder='Select privileges'
+ options={accessControlPrivilegeOptions}
+ />
+ </Form.Item>
+ </>
+ ) : (
+ <>
+ <Form.Item
+ name='supportedObjectTypes'
+ rules={[{ required: true, message: 'Please select supported
object types!' }]}
+ label='Supported Object Types'
+ >
+ <Select mode='multiple'>
+ {Object.values(supportedObjectTypesMap).map(item => (
+ <Select.Option key={item} value={item}>
+ {item}
+ </Select.Option>
))}
- <Button className='w-fit' type='dashed' onClick={() =>
add()} icon={<PlusOutlined />}>
- Add Rule
- </Button>
- </>
- )}
- </Form.List>
- </div>
- </Form.Item>
- <Form.Item name='comment' label='Comment'>
- <TextArea />
- </Form.Item>
- <Form.Item label='Properties'>
- <Form.List name='properties'>
- {(fields, subOpt) => (
- <RenderPropertiesFormItem fields={fields} subOpt={subOpt}
form={form} isEdit={!!editPolicy} />
- )}
- </Form.List>
- </Form.Item>
- </Form>
+ </Select>
+ </Form.Item>
+ <Form.Item label='Rule(s)'>
+ <div className='flex flex-col gap-2'>
+ <Form.List name='rules'>
+ {(fields, { add, remove }) => (
+ <>
+ {fields.map(({ key, name, ...restField }) => (
+ <Form.Item label={null}
className='align-items-center mb-1' key={key}>
+ <Flex gap='small' align='start'>
+ <Form.Item
+ {...restField}
+ name={[name, 'ruleName']}
+ rules={[{ required: true, message: 'Please
enter the rule name!' }]}
+ className='mb-0 w-full grow'
+ >
+ <Input placeholder='Rule Name' />
+ </Form.Item>
+ <Form.Item
+ {...restField}
+ name={[name, 'ruleContent']}
+ rules={[{ required: true, message: 'Please
enter the rule content!' }]}
+ className='mb-0 w-full grow'
+ >
+ <Input placeholder='Rule Content' />
+ </Form.Item>
+ <Form.Item className='mb-0 grow-0'>
+ <Icons.Minus
+ className='size-8 cursor-pointer
text-gray-400 hover:text-defaultPrimary'
+ onClick={() => remove(name)}
+ />
+ </Form.Item>
+ </Flex>
+ </Form.Item>
+ ))}
+ <Button className='w-fit' type='dashed' onClick={()
=> add()} icon={<PlusOutlined />}>
+ Add Rule
+ </Button>
+ </>
+ )}
+ </Form.List>
+ </div>
+ </Form.Item>
+ </>
+ )}
+ <Form.Item name='comment' label='Comment'>
+ <TextArea />
+ </Form.Item>
+ {!isAccessControl && (
+ <Form.Item label='Properties'>
+ <Form.List name='properties'>
+ {(fields, subOpt) => (
+ <RenderPropertiesFormItem fields={fields} subOpt={subOpt}
form={form} isEdit={!!editPolicy} />
+ )}
+ </Form.List>
+ </Form.Item>
+ )}
+ </Form>
+ </Spin>
</Modal>
</>
)
diff --git a/web-v2/web/src/app/compliance/policies/CreatePolicyDialog.test.jsx
b/web-v2/web/src/app/compliance/policies/CreatePolicyDialog.test.jsx
new file mode 100644
index 0000000000..fb84be2c22
--- /dev/null
+++ b/web-v2/web/src/app/compliance/policies/CreatePolicyDialog.test.jsx
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { Simulate } from 'react-dom/test-utils'
+import { Provider } from 'react-redux'
+import { configureStore } from '@reduxjs/toolkit'
+import { defHttp } from '@/lib/utils/axios'
+import policies from '@/lib/store/policies'
+import roles from '@/lib/store/roles'
+import CreatePolicyDialog from './CreatePolicyDialog'
+
+vi.mock('@/lib/utils/axios', () => ({ defHttp: { get: vi.fn(), post: vi.fn(),
put: vi.fn() } }))
+vi.mock('react-hot-toast', () => ({ default: { error: vi.fn() } }))
+
+const policy = {
+ name: 'read_sales',
+ comment: 'Sales access',
+ enabled: true,
+ policyType: 'system_access_control',
+ content: { privileges: ['select_table'], applicableRoles: ['analyst'] }
+}
+let root
+let container
+let close
+
+beforeEach(() => {
+ vi.resetAllMocks()
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ const getComputedStyle = window.getComputedStyle
+
+ // jsdom has no pseudo-element layout; Ant Design uses this to measure
scrollbars.
+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element =>
getComputedStyle(element))
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ )
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: vi.fn(() => ({ matches: false, addListener() {}, removeListener()
{} }))
+ })
+ defHttp.get.mockImplementation(({ url }) => {
+ if (url.endsWith('/read_sales')) return Promise.resolve({ policy })
+ if (url.endsWith('/roles')) return Promise.resolve({ names: ['analyst',
'writer'] })
+
+ return Promise.resolve({ policies: [] })
+ })
+ container = document.createElement('div')
+ document.body.appendChild(container)
+ root = createRoot(container)
+ close = vi.fn()
+})
+
+afterEach(async () => {
+ await act(async () => root.unmount())
+ container.remove()
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+})
+
+const input = name => document.querySelector(`#policyForm_${name}`)
+const button = () => document.querySelector('.ant-modal-footer
.ant-btn-primary')
+
+const fill = async (name, value) => {
+ await act(async () => Simulate.change(input(name), { target: { value } }))
+}
+
+const openSelect = async name => {
+ if (input(name).getAttribute('aria-expanded') !== 'true') {
+ await act(async () =>
Simulate.mouseDown(input(name).closest('.ant-select').querySelector('.ant-select-selector')))
+ }
+}
+
+const select = async (name, label) => {
+ await openSelect(name)
+
+ const option = [
+
...document.querySelectorAll('.ant-select-dropdown:not(.ant-select-dropdown-hidden)
.ant-select-item-option')
+ ].find(item => item.textContent === label)
+ expect(option).toBeTruthy()
+ await act(async () => option.click())
+}
+
+const submit = async () => {
+ await act(async () => button().click())
+
+ // Ant Design debounces rendering field validation errors.
+ await act(async () => new Promise(resolve => setTimeout(resolve, 100)))
+}
+
+const renderDialog = async ({ edit = false, anthEnable = true } = {}) => {
+ const store = configureStore({ reducer: { policies, roles, auth: () => ({
anthEnable }) } })
+ await act(async () =>
+ root.render(
+ <Provider store={store}>
+ <CreatePolicyDialog open setOpen={close} metalake='demo'
editPolicy={edit ? 'read_sales' : undefined} />
+ </Provider>
+ )
+ )
+}
+
+const fillAccessPolicy = async () => {
+ await fill('name', 'read_sales')
+ await fill('comment', 'Sales access')
+ await select('policyType', 'System Access Control')
+ await select('applicableRoles', 'analyst')
+ await select('privileges', 'Select Table')
+}
+
+describe('access-control policy editor', () => {
+ it.each([false, null])('disables access-control creation when authorization
is %s', async anthEnable => {
+ await renderDialog({ anthEnable })
+ await openSelect('policyType')
+
+ const option =
[...document.querySelectorAll('.ant-select-item-option')].find(
+ item => item.textContent === 'System Access Control'
+ )
+
expect(option.classList.contains('ant-select-item-option-disabled')).toBe(true)
+ await act(async () => option.click())
+ expect(input('applicableRoles')).toBeNull()
+ expect(defHttp.get).not.toHaveBeenCalled()
+ })
+
+ it('does not fetch roles for an existing policy when authorization is
disabled', async () => {
+ await renderDialog({ edit: true, anthEnable: false })
+ expect(input('name').value).toBe('read_sales')
+ expect(defHttp.get.mock.calls.map(([request]) =>
request.url)).toEqual(['/api/metalakes/demo/policies/read_sales'])
+ })
+
+ it.each([
+ ['applicableRoles', 'privileges', 'Select Table', 'Please select at least
one role.'],
+ ['privileges', 'applicableRoles', 'analyst', 'Please select at least one
privilege.']
+ ])('rejects empty %s before sending a request', async (missing, field,
label, message) => {
+ await renderDialog()
+ await fill('name', 'read_sales')
+ await select('policyType', 'System Access Control')
+ await select(field, label)
+ await submit()
+ expect(document.body.textContent).toContain(message)
+ expect(defHttp.post).not.toHaveBeenCalled()
+ expect(close).not.toHaveBeenCalled()
+ })
+
+ it('creates an access-control policy with only privileges and applicable
roles in its content', async () => {
+ defHttp.post.mockResolvedValue({ policy })
+ await renderDialog()
+ await fillAccessPolicy()
+ await submit()
+ expect(defHttp.post).toHaveBeenCalledExactlyOnceWith({ url:
'/api/metalakes/demo/policies', data: policy })
+ expect(close).toHaveBeenCalledWith(false)
+ })
+
+ it('edits access-control content with the correct updateContent policy
type', async () => {
+ defHttp.put.mockResolvedValue({ policy })
+ await renderDialog({ edit: true })
+ await select('privileges', 'Modify Table')
+ await select('applicableRoles', 'writer')
+ await submit()
+ expect(defHttp.put).toHaveBeenCalledExactlyOnceWith({
+ url: '/api/metalakes/demo/policies/read_sales',
+ data: {
+ updates: [
+ {
+ '@type': 'updateContent',
+ policyType: 'system_access_control',
+ newContent: { privileges: ['select_table', 'modify_table'],
applicableRoles: ['analyst', 'writer'] }
+ }
+ ]
+ }
+ })
+ expect(close).toHaveBeenCalledWith(false)
+ })
+
+ it.each([false, true])('retains input after a failed save and allows retry
(edit=%s)', async edit => {
+ const write = edit ? defHttp.put : defHttp.post
+ write.mockRejectedValueOnce(new Error('Save failed')).mockResolvedValue({
policy })
+ await renderDialog({ edit })
+ if (!edit) await fillAccessPolicy()
+ await fill('comment', 'Unsaved comment')
+ await select('privileges', 'Modify Table')
+ await submit()
+ expect(write).toHaveBeenCalledTimes(1)
+ expect(close).not.toHaveBeenCalled()
+ expect(input('name').value).toBe('read_sales')
+ expect(input('comment').value).toBe('Unsaved comment')
+
expect(input('applicableRoles').closest('.ant-select').textContent).toContain('analyst')
+
expect(input('privileges').closest('.ant-select').textContent).toContain('Modify
Table')
+ expect(button().classList.contains('ant-btn-loading')).toBe(false)
+ await submit()
+ expect(write).toHaveBeenCalledTimes(2)
+ expect(write.mock.calls[1][0]).toEqual(write.mock.calls[0][0])
+ expect(close).toHaveBeenCalledWith(false)
+ })
+})
diff --git a/web-v2/web/src/app/compliance/policies/constants.js
b/web-v2/web/src/app/compliance/policies/constants.js
new file mode 100644
index 0000000000..17ed1615fa
--- /dev/null
+++ b/web-v2/web/src/app/compliance/policies/constants.js
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+export const policyTypeLabels = {
+ custom: 'Custom',
+ system_access_control: 'System Access Control'
+}
+
+// Keep in sync with AccessControlContent.PERMITTED_PRIVILEGES and the OpenAPI
enum.
+export const accessControlPrivilegeOptions = [
+ { label: 'Select Table', value: 'select_table' },
+ { label: 'Modify Table', value: 'modify_table' },
+ { label: 'Probe Table Like', value: 'probe_table_like' },
+ { label: 'Select View', value: 'select_view' },
+ { label: 'Read Fileset', value: 'read_fileset' },
+ { label: 'Write Fileset', value: 'write_fileset' },
+ { label: 'Consume Topic', value: 'consume_topic' },
+ { label: 'Produce Topic', value: 'produce_topic' },
+ { label: 'Use Model', value: 'use_model' },
+ { label: 'Execute Function', value: 'execute_function' },
+ { label: 'Use Semantic Model', value: 'use_semantic_model' }
+]
diff --git a/web-v2/web/src/app/compliance/policies/page.js
b/web-v2/web/src/app/compliance/policies/page.js
index 399830190c..2f8a861966 100644
--- a/web-v2/web/src/app/compliance/policies/page.js
+++ b/web-v2/web/src/app/compliance/policies/page.js
@@ -46,6 +46,7 @@ import Icons from '@/components/Icons'
import SectionContainer from '@/components/SectionContainer'
import AssociatedTable from '@/components/AssociatedTable'
import CreatePolicyDialog from './CreatePolicyDialog'
+import { accessControlPrivilegeOptions, policyTypeLabels } from './constants'
import { formatToDateTime } from '@/lib/utils'
import { useAppSelector, useAppDispatch } from '@/lib/hooks/useStore'
import { use } from 'react'
@@ -181,7 +182,7 @@ export default function PoliciesPage() {
key: 'policyType',
ellipsis: true,
width: 150,
- render: (_, record) => <>{record.policyType}</>
+ render: (_, record) => <>{policyTypeLabels[record.policyType] ||
record.policyType}</>
},
{
title: 'Comment',
@@ -289,14 +290,32 @@ export default function PoliciesPage() {
<Descriptions.Item label='Enabled'>
<Switch checked={currentPolicy?.enabled} disabled size='small' />
</Descriptions.Item>
- <Descriptions.Item label='Policy
Type'>{currentPolicy?.policyType}</Descriptions.Item>
- <Descriptions.Item label='Supported Object Types'>
- {currentPolicy?.content?.supportedObjectTypes?.length === 1
- ? currentPolicy?.content?.supportedObjectTypes[0]
- : currentPolicy?.content?.supportedObjectTypes?.length
- ? currentPolicy?.content?.supportedObjectTypes.join(', ')
- : '-'}
+ <Descriptions.Item label='Policy Type'>
+ {policyTypeLabels[currentPolicy?.policyType] ||
currentPolicy?.policyType}
</Descriptions.Item>
+ {currentPolicy?.policyType === 'system_access_control' ? (
+ <>
+ <Descriptions.Item label='Applicable Roles'>
+ {currentPolicy.content?.applicableRoles?.join(', ') || '-'}
+ </Descriptions.Item>
+ <Descriptions.Item label='Privileges'>
+ {currentPolicy.content?.privileges
+ ?.map(
+ privilege =>
+ accessControlPrivilegeOptions.find(option =>
option.value === privilege)?.label || privilege
+ )
+ .join(', ') || '-'}
+ </Descriptions.Item>
+ </>
+ ) : (
+ <Descriptions.Item label='Supported Object Types'>
+ {currentPolicy?.content?.supportedObjectTypes?.length === 1
+ ? currentPolicy?.content?.supportedObjectTypes[0]
+ : currentPolicy?.content?.supportedObjectTypes?.length
+ ? currentPolicy?.content?.supportedObjectTypes.join(', ')
+ : '-'}
+ </Descriptions.Item>
+ )}
<Descriptions.Item label='Comment'>{currentPolicy?.comment ||
'-'}</Descriptions.Item>
<Descriptions.Item label='Creator'>{currentPolicy?.audit?.creator
|| '-'}</Descriptions.Item>
<Descriptions.Item label='Created At'>
@@ -307,68 +326,72 @@ export default function PoliciesPage() {
</Descriptions.Item>
<Descriptions.Item label='Last
Modifier'>{currentPolicy?.audit?.lastModifier || '-'}</Descriptions.Item>
</Descriptions>
- <Title level={5} className='mt-4 mb-2'>
- Rule(s)
- </Title>
- <Table
- size='small'
- pagination={false}
- rowKey='name'
- dataSource={
- currentPolicy?.content?.customRules &&
Object.keys(currentPolicy.content.customRules).length > 0
- ?
Object.entries(currentPolicy.content.customRules).map(([name, content]) => ({
- name,
- content
- }))
- : []
- }
- columns={[
- {
- title: 'Rule Name',
- dataIndex: 'name',
- key: 'name',
- ellipsis: true
- },
- {
- title: 'Rule Content',
- dataIndex: 'content',
- key: 'content',
- ellipsis: true,
- render: value => value || '-'
- }
- ]}
- />
- <Title level={5} className='mt-4 mb-2'>
- Properties
- </Title>
- <Table
- size='small'
- pagination={false}
- rowKey='key'
- dataSource={
- currentPolicy?.content?.properties &&
Object.keys(currentPolicy.content.properties).length > 0
- ? Object.entries(currentPolicy.content.properties).map(([key,
value]) => ({
- key,
- value
- }))
- : []
- }
- columns={[
- {
- title: 'Key',
- dataIndex: 'key',
- key: 'key',
- ellipsis: true
- },
- {
- title: 'Value',
- dataIndex: 'value',
- key: 'value',
- ellipsis: true,
- render: value => value || '-'
- }
- ]}
- />
+ {currentPolicy?.policyType !== 'system_access_control' && (
+ <>
+ <Title level={5} className='mt-4 mb-2'>
+ Rule(s)
+ </Title>
+ <Table
+ size='small'
+ pagination={false}
+ rowKey='name'
+ dataSource={
+ currentPolicy?.content?.customRules &&
Object.keys(currentPolicy.content.customRules).length > 0
+ ?
Object.entries(currentPolicy.content.customRules).map(([name, content]) => ({
+ name,
+ content
+ }))
+ : []
+ }
+ columns={[
+ {
+ title: 'Rule Name',
+ dataIndex: 'name',
+ key: 'name',
+ ellipsis: true
+ },
+ {
+ title: 'Rule Content',
+ dataIndex: 'content',
+ key: 'content',
+ ellipsis: true,
+ render: value => value || '-'
+ }
+ ]}
+ />
+ <Title level={5} className='mt-4 mb-2'>
+ Properties
+ </Title>
+ <Table
+ size='small'
+ pagination={false}
+ rowKey='key'
+ dataSource={
+ currentPolicy?.content?.properties &&
Object.keys(currentPolicy.content.properties).length > 0
+ ?
Object.entries(currentPolicy.content.properties).map(([key, value]) => ({
+ key,
+ value
+ }))
+ : []
+ }
+ columns={[
+ {
+ title: 'Key',
+ dataIndex: 'key',
+ key: 'key',
+ ellipsis: true
+ },
+ {
+ title: 'Value',
+ dataIndex: 'value',
+ key: 'value',
+ ellipsis: true,
+ render: value => value || '-'
+ }
+ ]}
+ />
+ </>
+ )}
{anthEnable && (
<>
<Title level={5} className='mt-4 mb-2'>
diff --git a/web-v2/web/src/components/PolicyTag.test.jsx
b/web-v2/web/src/components/PolicyTag.test.jsx
index b4856eface..73f4ca7bca 100644
--- a/web-v2/web/src/components/PolicyTag.test.jsx
+++ b/web-v2/web/src/components/PolicyTag.test.jsx
@@ -93,11 +93,29 @@ it.each([true, false])('respects readOnly=%s while
retaining policy navigation',
if (readOnly) expect(defHttp.post).not.toHaveBeenCalled()
})
-const renderTagPolicies = async () => {
+it.each(['table', 'schema', 'catalog'])('keeps policy associations read-only
on %s', async metadataObjectType => {
+ defHttp.get.mockResolvedValue({ policies: [{ name: 'access', enabled: true,
policyType: 'system_access_control' }] })
+ const store = configureStore({ reducer: { metalakes, policies } })
+ await act(async () =>
+ root.render(
+ <Provider store={store}>
+ <PolicyTag metadataObjectType={metadataObjectType}
metadataObjectFullName='sales.mart.orders' />
+ </Provider>
+ )
+ )
+
+ expect(container.textContent).toContain('access')
+ expect(container.textContent).not.toContain('Associate Policy')
+ expect(container.querySelector('.ant-tag-close-icon')).toBeNull()
+ expect(defHttp.post).not.toHaveBeenCalled()
+ expect(defHttp.delete).not.toHaveBeenCalled()
+})
+
+const renderTagPolicies = async (options = [{ name: 'masking', enabled: true
}]) => {
const store = configureStore({
reducer: { metalakes, policies },
preloadedState: {
- policies: { policiesData: [{ name: 'masking', enabled: true }],
policiesLoading: false, error: null }
+ policies: { policiesData: options, policiesLoading: false, error: null }
}
})
await act(async () =>
@@ -194,3 +212,18 @@ it('handles a rejected tag policy removal request', async
() => {
expect(defHttp.delete).toHaveBeenCalledExactlyOnceWith({ url:
`${tagPoliciesUrl}/masking` })
expect(container.textContent).toContain('masking')
})
+
+it('offers access-control policies for tag association', async () => {
+ defHttp.get.mockResolvedValue({ associations: [] })
+ defHttp.post.mockResolvedValue({})
+ await renderTagPolicies([{ name: 'access', enabled: true, policyType:
'system_access_control' }])
+ await act(async () =>
+ [...container.querySelectorAll('.ant-tag')].find(tag => tag.textContent
=== 'Associate Policy').click()
+ )
+ await selectPolicy('access')
+
+ expect(defHttp.post).toHaveBeenCalledExactlyOnceWith({
+ url: `${tagPoliciesUrl}/access`,
+ data: { selector: { type: 'ALL_VALUES' } }
+ })
+})
diff --git a/web-v2/web/src/lib/utils/index.js
b/web-v2/web/src/lib/utils/index.js
index 1c847cf344..aa5d787869 100644
--- a/web-v2/web/src/lib/utils/index.js
+++ b/web-v2/web/src/lib/utils/index.js
@@ -117,7 +117,11 @@ export const genUpdates = (originalData, newData,
disableUpdate = false) => {
const newContent = newData.content || {}
if (JSON.stringify(originalContent) !== JSON.stringify(newContent)) {
- updates.push({ '@type': 'updateContent', policyType: 'custom', newContent:
newContent })
+ updates.push({
+ '@type': 'updateContent',
+ policyType: newData.policyType || originalData.policyType || 'custom',
+ newContent: newContent
+ })
}
const originalProperties = originalData.properties || {}