You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ranger.apache.org by dh...@apache.org on 2026/07/20 10:13:14 UTC
(ranger) 01/01: RANGER-5570 : Ranger: New Enhanced Policy Creation Interface
This is an automated email from the ASF dual-hosted git repository.
dhavaljrajpara pushed a commit to branch RANGER-5570-final
in repository https://gitbox.apache.org/repos/asf/ranger.git
commit 143c75e019e971fc9165d392ecd56a1f2577c077
Author: Dhaval Rajpara <dh...@gmail.com>
AuthorDate: Mon Jul 20 07:24:45 2026 +0530
RANGER-5570 : Ranger: New Enhanced Policy Creation Interface
---
.../src/main/webapp/react-webapp/src/App.jsx | 148 +-
.../src/components/StepperFormComponents.jsx | 301 ++++
.../react-webapp/src/images/sidebar/plus.svg | 1 +
.../src/main/webapp/react-webapp/src/index.jsx | 1 +
.../webapp/react-webapp/src/styles/StepperForm.css | 241 +++
.../main/webapp/react-webapp/src/styles/style.css | 91 +-
.../main/webapp/react-webapp/src/utils/XAEnums.js | 14 +-
.../main/webapp/react-webapp/src/utils/XAUtils.js | 215 ++-
.../react-webapp/src/utils/policyConditionUtils.js | 46 +-
.../views/PolicyListing/AddUpdatePolicyForm.jsx | 1666 +++++++++-----------
.../NewPolicyForm/CreateNewPolicyForm.jsx | 661 ++++++++
.../EditNewPolicyForm/EditPolicyForm.jsx | 954 +++++++++++
.../AccessRulesStep.jsx | 329 ++++
.../PolicyDetailsStep.jsx | 518 ++++++
.../PolicyPermissionItemVertical.jsx | 923 +++++++++++
.../PolicyValidityPeriodModal.jsx | 240 +++
.../PolicyCreateStepperStepComp/ResourcesStep.jsx | 121 ++
.../ReviewConfirmStep.jsx | 681 ++++++++
.../PolicyCreateStepperStepComp/ServiceStep.jsx | 451 ++++++
.../UsersGroupsAndRolesSelectionComponent.jsx | 495 ++++++
.../NewPolicyForm/policyFormValidation.js | 263 +++
.../src/views/PolicyListing/PolicyFormContext.jsx | 280 ++++
.../src/views/PolicyListing/PolicyListing.jsx | 2 +-
.../views/PolicyListing/TagBasePermissionItem.jsx | 156 +-
.../src/views/Resources/ResourceComp.jsx | 26 +-
.../src/views/Resources/ResourceSelectComp.jsx | 8 +-
.../react-webapp/src/views/SideBar/SideBar.jsx | 22 +-
27 files changed, 7792 insertions(+), 1062 deletions(-)
diff --git a/security-admin/src/main/webapp/react-webapp/src/App.jsx b/security-admin/src/main/webapp/react-webapp/src/App.jsx
index 3ca9e886f..520dba6df 100755
--- a/security-admin/src/main/webapp/react-webapp/src/App.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/App.jsx
@@ -40,99 +40,109 @@ const HomeComp = lazy(() => import("Views/Home"));
const ServiceFormComp = lazy(() => import("Views/ServiceManager/ServiceForm"));
const UserProfileComp = lazy(() => import("Views/UserProfile"));
const ZoneListingComp = lazy(() => import("Views/SecurityZone/ZoneListing"));
-const SecurityZoneFormComp = lazy(() =>
- import("Views/SecurityZone/SecurityZoneForm")
+const SecurityZoneFormComp = lazy(
+ () => import("Views/SecurityZone/SecurityZoneForm")
);
-const UserGroupRoleListing = lazy(() =>
- import("Views/UserGroupRoleListing/UserGroupRoleListing")
+const UserGroupRoleListing = lazy(
+ () => import("Views/UserGroupRoleListing/UserGroupRoleListing")
);
-const UserListingComp = lazy(() =>
- import("Views/UserGroupRoleListing/users_details/UserListing")
+const UserListingComp = lazy(
+ () => import("Views/UserGroupRoleListing/users_details/UserListing")
);
-const GroupListingComp = lazy(() =>
- import("Views/UserGroupRoleListing/groups_details/GroupListing")
+const GroupListingComp = lazy(
+ () => import("Views/UserGroupRoleListing/groups_details/GroupListing")
);
-const RoleListingComp = lazy(() =>
- import("Views/UserGroupRoleListing/role_details/RoleListing")
+const RoleListingComp = lazy(
+ () => import("Views/UserGroupRoleListing/role_details/RoleListing")
);
-const UserForm = lazy(() =>
- import("Views/UserGroupRoleListing/users_details/AddUserView")
+const UserForm = lazy(
+ () => import("Views/UserGroupRoleListing/users_details/AddUserView")
);
-const EditUserView = lazy(() =>
- import("Views/UserGroupRoleListing/users_details/EditUserView")
+const EditUserView = lazy(
+ () => import("Views/UserGroupRoleListing/users_details/EditUserView")
);
-const GroupForm = lazy(() =>
- import("Views/UserGroupRoleListing/groups_details/GroupForm")
+const GroupForm = lazy(
+ () => import("Views/UserGroupRoleListing/groups_details/GroupForm")
);
-const RoleForm = lazy(() =>
- import("Views/UserGroupRoleListing/role_details/RoleForm")
+const RoleForm = lazy(
+ () => import("Views/UserGroupRoleListing/role_details/RoleForm")
);
const Permissions = lazy(() => import("Views/PermissionsModule/Permissions"));
-const EditPermissionComp = lazy(() =>
- import("Views/PermissionsModule/EditPermission")
+const EditPermissionComp = lazy(
+ () => import("Views/PermissionsModule/EditPermission")
);
const AuditLayout = lazy(() => import("Views/AuditEvent/AuditLayout"));
const AccessLogs = lazy(() => import("Views/AuditEvent/Access/AccessLogs"));
const AdminLogs = lazy(() => import("Views/AuditEvent/Admin/AdminLogs"));
-const LoginSessionsLogs = lazy(() =>
- import("Views/AuditEvent/LoginSessions/LoginSessionsLogs")
+const LoginSessionsLogs = lazy(
+ () => import("Views/AuditEvent/LoginSessions/LoginSessionsLogs")
);
const PluginsLogs = lazy(() => import("Views/AuditEvent/Plugins/PluginsLogs"));
-const PluginStatusLogs = lazy(() =>
- import("Views/AuditEvent/PluginStatus/PluginStatusLogs")
+const PluginStatusLogs = lazy(
+ () => import("Views/AuditEvent/PluginStatus/PluginStatusLogs")
);
-const UserSyncLogs = lazy(() =>
- import("Views/AuditEvent/UserSync/UserSyncLogs")
+const UserSyncLogs = lazy(
+ () => import("Views/AuditEvent/UserSync/UserSyncLogs")
);
-const PolicyListingTabView = lazy(() =>
- import("Views/PolicyListing/PolicyListingTabView")
+const PolicyListingTabView = lazy(
+ () => import("Views/PolicyListing/PolicyListingTabView")
);
-const AddUpdatePolicyForm = lazy(() =>
- import("Views/PolicyListing/AddUpdatePolicyForm")
+const AddUpdatePolicyForm = lazy(
+ () => import("Views/PolicyListing/AddUpdatePolicyForm")
);
const EncryptionComp = lazy(() => import("Views/Encryption/KeyManager"));
const KeyCreateComp = lazy(() => import("Views/Encryption/KeyCreate"));
-const AccessLogDetailComp = lazy(() =>
- import("Views/AuditEvent/Access/AccessLogDetail")
+const AccessLogDetailComp = lazy(
+ () => import("Views/AuditEvent/Access/AccessLogDetail")
);
-const UserAccessLayoutComp = lazy(() =>
- import("Views/Reports/UserAccessLayout")
+const UserAccessLayoutComp = lazy(
+ () => import("Views/Reports/UserAccessLayout")
);
-const MyDatasetListingComp = lazy(() =>
- import("Views/GovernedData/Dataset/MyDatasetListing")
+const MyDatasetListingComp = lazy(
+ () => import("Views/GovernedData/Dataset/MyDatasetListing")
);
-const CreateDatasetComp = lazy(() =>
- import("Views/GovernedData/Dataset/AddDatasetView")
+const CreateDatasetComp = lazy(
+ () => import("Views/GovernedData/Dataset/AddDatasetView")
);
-const DatasetDetailLayoutComp = lazy(() =>
- import("Views/GovernedData/Dataset/DatasetDetailLayout")
+const DatasetDetailLayoutComp = lazy(
+ () => import("Views/GovernedData/Dataset/DatasetDetailLayout")
);
-const DatasetDetailFullViewComp = lazy(() =>
- import("Views/GovernedData/Dataset/DatasetDetailFullView")
+const DatasetDetailFullViewComp = lazy(
+ () => import("Views/GovernedData/Dataset/DatasetDetailFullView")
);
-const AccessGrantFormComp = lazy(() =>
- import("Views/GovernedData/Dataset/AccessGrantForm")
+const AccessGrantFormComp = lazy(
+ () => import("Views/GovernedData/Dataset/AccessGrantForm")
);
-const MyDatashareListingComp = lazy(() =>
- import("Views/GovernedData/Datashare/MyDatashareListing")
+const MyDatashareListingComp = lazy(
+ () => import("Views/GovernedData/Datashare/MyDatashareListing")
);
-const CreateDatashareComp = lazy(() =>
- import("Views/GovernedData/Datashare/AddDatashareView")
+const CreateDatashareComp = lazy(
+ () => import("Views/GovernedData/Datashare/AddDatashareView")
);
-const DatashareDetailLayoutComp = lazy(() =>
- import("Views/GovernedData/Datashare/DatashareDetailLayout")
+const DatashareDetailLayoutComp = lazy(
+ () => import("Views/GovernedData/Datashare/DatashareDetailLayout")
);
-const DatashareDetailFullView = lazy(() =>
- import("Views/GovernedData/Datashare/DatashareDetailFullView")
+const DatashareDetailFullView = lazy(
+ () => import("Views/GovernedData/Datashare/DatashareDetailFullView")
);
-const DatashareAddSharedResourceComp = lazy(() =>
- import("Views/GovernedData/Datashare/AddSharedResourceComp")
+const DatashareAddSharedResourceComp = lazy(
+ () => import("Views/GovernedData/Datashare/AddSharedResourceComp")
);
-const GDSRequestListingComp = lazy(() =>
- import("Views/GovernedData/Request/RequestListing")
+const GDSRequestListingComp = lazy(
+ () => import("Views/GovernedData/Request/RequestListing")
);
-const GDSRequestDetailComp = lazy(() =>
- import("Views/GovernedData/Request/RequestDetailView")
+const GDSRequestDetailComp = lazy(
+ () => import("Views/GovernedData/Request/RequestDetailView")
+);
+const CreatePolicyComp = lazy(
+ () => import("Views/PolicyListing/NewPolicyForm/CreateNewPolicyForm")
+);
+const EditPolicyComp = lazy(
+ () =>
+ import("Views/PolicyListing/NewPolicyForm/EditNewPolicyForm/EditPolicyForm")
+);
+const PolicyFormContextComp = lazy(
+ () => import("Views/PolicyListing/PolicyFormContext")
);
export default class App extends Component {
@@ -193,8 +203,8 @@ export default class App extends Component {
let serviceDefUrl = hasAccessToTab("Resource Based Policies")
? "plugins/definitions"
: hasAccessToTab("Tag Based Policies") && isUser()
- ? "plugins/definitions/name/tag"
- : "plugins/definitions";
+ ? "plugins/definitions/name/tag"
+ : "plugins/definitions";
try {
getServiceDefData = await fetchApi({
@@ -265,6 +275,10 @@ export default class App extends Component {
path="tag"
element={<HomeComp isTagView={true} key="tagHomeComp" />}
/>
+ <Route
+ path="create-policy"
+ element={<CreatePolicyComp />}
+ />
</Route>
<Route
path="/reports/userAccess"
@@ -292,18 +306,28 @@ export default class App extends Component {
element={<PolicyListingTabView />}
/>
{/* POLICY CREATE */}
- <Route path="create">
+ <Route
+ path="create"
+ element={<PolicyFormContextComp />}
+ >
<Route
path=":policyType"
element={<AddUpdatePolicyForm />}
/>
</Route>
{/* POLICY EDIT */}
- <Route path=":policyId">
+ <Route
+ path=":policyId"
+ element={<PolicyFormContextComp />}
+ >
<Route
path="edit"
element={<AddUpdatePolicyForm />}
/>
+ <Route
+ path="new-policy-form-edit"
+ element={<EditPolicyComp />}
+ />
</Route>
</Route>
</Route>
diff --git a/security-admin/src/main/webapp/react-webapp/src/components/StepperFormComponents.jsx b/security-admin/src/main/webapp/react-webapp/src/components/StepperFormComponents.jsx
new file mode 100644
index 000000000..f027e0960
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/components/StepperFormComponents.jsx
@@ -0,0 +1,301 @@
+/*
+ * 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 React, { useState, useRef } from "react";
+import { Form } from "react-final-form";
+import arrayMutators from "final-form-arrays";
+import { Button } from "react-bootstrap";
+import usePrompt from "Hooks/usePrompt";
+
+const PromptDialog = ({ isDirtyField, isUnblock }) => {
+ usePrompt(
+ "Are you sure you want to leave? You have unsaved changes.",
+ isDirtyField && !isUnblock
+ );
+ return null;
+};
+
+const StepperForm = ({
+ steps,
+ onSubmit,
+ initialValues = {},
+ blockUI,
+ preventUnBlock = false,
+ /** Called when navigating away (Next, jump to review, or header step click) so the parent
+ * can sync form state (e.g. prune access types after resources change in step 1). */
+ onBeforeNavigate
+}) => {
+ const [currentStep, setCurrentStep] = useState(0);
+ const formRef = useRef(null);
+ const [formValues, setFormValues] = useState(initialValues);
+ const [formKey, setFormKey] = useState(0);
+ const [hasUserStarted, setHasUserStarted] = useState(false);
+
+ // True once the user reaches the last step via "Next".
+ // Enables clicking step numbers in the header to jump freely.
+ const [hasVisitedLastStep, setHasVisitedLastStep] = useState(false);
+
+ // True once the user advances past the Service step (e.g. to Resources).
+ // ServiceStep uses this to confirm resets when later-step data may exist.
+ const [hasProgressedPastService, setHasProgressedPastService] =
+ useState(false);
+
+ const lastStepIndex = steps.length - 1;
+ const isLastStep = currentStep === lastStepIndex;
+ const currentStepConfig = steps[currentStep];
+
+ // ─── Navigation handlers ──────────────────────────────────────────────────
+
+ const runBeforeNavigateAndGetValues = (toStep) => {
+ const form = formRef.current;
+ if (onBeforeNavigate && form) {
+ onBeforeNavigate({
+ fromStep: currentStep,
+ toStep,
+ form
+ });
+ return form.getState().values;
+ }
+ return null;
+ };
+
+ const handleNext = (values) => {
+ const toStep = isLastStep ? lastStepIndex : currentStep + 1;
+ const afterNavigate = runBeforeNavigateAndGetValues(toStep);
+ const resolved = afterNavigate !== null ? afterNavigate : values;
+ const merged = { ...formValues, ...resolved };
+ setFormValues(merged);
+
+ if (isLastStep) {
+ setHasUserStarted(false);
+ return onSubmit(merged);
+ }
+
+ const next = currentStep + 1;
+ if (currentStep === 0) {
+ setHasProgressedPastService(true);
+ }
+ if (next === lastStepIndex) {
+ setHasVisitedLastStep(true);
+ }
+
+ setHasUserStarted(true);
+
+ setCurrentStep(next);
+ };
+
+ const handlePrevious = (values, form) => {
+ // If user has visited last step, validate current step before going back
+ if (hasVisitedLastStep) {
+ const currentStepErrors = validate(values);
+
+ // Check if there are validation errors
+ if (currentStepErrors && Object.keys(currentStepErrors).length > 0) {
+ // Force react-final-form to show validation errors
+ if (form) {
+ form.getRegisteredFields().forEach((fieldName) => {
+ form.blur(fieldName);
+ });
+ }
+
+ // Show user-friendly message
+ alert("Please fill in all required fields before proceeding.");
+ return false;
+ }
+ }
+
+ // If validation passes or user hasn't visited last step, proceed
+ setCurrentStep(Math.max(0, currentStep - 1));
+ return true;
+ };
+
+ // Jump directly to ReviewConfirmStep, but validate current step first.
+ const handleJumpToReview = (values, form) => {
+ // Validate current step before jumping
+ const currentStepErrors = validate(values);
+
+ // Check if there are validation errors
+ if (currentStepErrors && Object.keys(currentStepErrors).length > 0) {
+ // Force react-final-form to show validation errors
+ if (form) {
+ form.getRegisteredFields().forEach((fieldName) => {
+ form.blur(fieldName);
+ });
+ }
+
+ // Show user-friendly message
+ alert("Please fill in all required fields before proceeding to review.");
+ return false;
+ }
+
+ // If validation passes, proceed with jump
+ const afterNavigate = runBeforeNavigateAndGetValues(lastStepIndex);
+ const resolved = afterNavigate !== null ? afterNavigate : values;
+ const merged = { ...formValues, ...resolved };
+ setFormValues(merged);
+ setCurrentStep(lastStepIndex);
+ return true;
+ };
+
+ // Called when user clicks a step number in the header.
+ // Only active after the user has visited the last step at least once.
+ const handleStepClick = (index) => {
+ if (!hasVisitedLastStep) return;
+ if (index === currentStep) return;
+ const afterNavigate = runBeforeNavigateAndGetValues(index);
+ if (afterNavigate !== null) {
+ setFormValues({ ...formValues, ...afterNavigate });
+ }
+ setCurrentStep(index);
+ };
+
+ // Exposed to step components so they can reinitialize the wizard.
+ // serviceFieldSnapshot: fields from the Service step to keep after reset
+ // (merged on top of initialValues); clears Resources and later-step data.
+ const handleResetForm = (serviceFieldSnapshot = {}) => {
+ setFormValues({ ...initialValues, ...serviceFieldSnapshot });
+ setFormKey((k) => k + 1); // force react-final-form to fully reinitialize
+ setCurrentStep(0);
+ setHasVisitedLastStep(false);
+ setHasProgressedPastService(false);
+ setHasUserStarted(false);
+ };
+
+ // ─── Validation ───────────────────────────────────────────────────────────
+
+ const validate = (values) => {
+ if (currentStepConfig.validate) {
+ return currentStepConfig.validate(values);
+ }
+ return {};
+ };
+
+ // ─── Render ───────────────────────────────────────────────────────────────
+
+ return (
+ <div className="stepper-form-container">
+ {/* ── Stepper Header ── */}
+ <div className="stepper-header">
+ {steps.map((step, index) => {
+ const isActive = index === currentStep;
+ const isCompleted = index < currentStep;
+ const isClickable = hasVisitedLastStep && index !== currentStep;
+
+ return (
+ <React.Fragment key={index}>
+ <div
+ className={`stepper-item${isActive ? " active" : ""}${isCompleted ? " completed" : ""}${isClickable ? " clickable" : ""}`}
+ onClick={() => handleStepClick(index)}
+ title={isClickable ? `Jump to ${step.title}` : undefined}
+ >
+ <div className="stepper-number">{index + 1}</div>
+ <div className="stepper-content">
+ <div className="stepper-title">
+ <h6 className="mb-0">{step.title}</h6>
+ </div>
+ <div className="stepper-subtitle">
+ <span className="font-13">{step.subtitle}</span>
+ </div>
+ </div>
+ </div>
+
+ {index < lastStepIndex && (
+ <div
+ className={`stepper-arrow${isCompleted ? " completed" : ""}`}
+ >
+ ›
+ </div>
+ )}
+ </React.Fragment>
+ );
+ })}
+ </div>
+ <hr />
+
+ {/* ── Form Content ── */}
+ <Form
+ key={formKey}
+ initialValues={formValues}
+ validate={validate}
+ onSubmit={handleNext}
+ mutators={{ ...arrayMutators }}
+ keepDirtyOnReinitialize
+ render={({ handleSubmit, submitting, values, form, dirty }) => {
+ formRef.current = form;
+ return (
+ <form onSubmit={handleSubmit}>
+ <PromptDialog
+ isDirtyField={hasUserStarted || dirty}
+ isUnblock={preventUnBlock}
+ />
+ <div className="stepper-body">
+ {currentStepConfig.component &&
+ React.createElement(currentStepConfig.component, {
+ values,
+ // react-final-form API (change, reset, batch, etc.) — required by
+ // steps that call form.change(...) outside of Field render props.
+ form,
+ hasProgressedPastService,
+ onResetForm: handleResetForm,
+ ...currentStepConfig.componentProps
+ })}
+ </div>
+
+ {/* ── Navigation Buttons ── */}
+ <div className="stepper-footer">
+ <Button
+ variant="outline-secondary"
+ onClick={() => handlePrevious(values, form)}
+ disabled={currentStep === 0 || submitting || blockUI}
+ >
+ Previous
+ </Button>
+
+ <div className="d-flex gap-2">
+ {/* "Jump to Review" — shown when user has visited the last step
+ and is on any intermediate step */}
+ {hasVisitedLastStep && !isLastStep && (
+ <Button
+ variant="outline-primary"
+ onClick={() => handleJumpToReview(values, form)}
+ disabled={submitting || blockUI}
+ >
+ <i className="fa fa-forward me-1"></i>
+ Jump to Review (Step {lastStepIndex + 1})
+ </Button>
+ )}
+
+ <Button
+ variant="primary"
+ type="submit"
+ disabled={submitting || blockUI}
+ >
+ {isLastStep ? "Submit" : "Next"}
+ </Button>
+ </div>
+ </div>
+ </form>
+ );
+ }}
+ />
+ </div>
+ );
+};
+
+export default StepperForm;
diff --git a/security-admin/src/main/webapp/react-webapp/src/images/sidebar/plus.svg b/security-admin/src/main/webapp/react-webapp/src/images/sidebar/plus.svg
new file mode 100644
index 000000000..871c92616
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/images/sidebar/plus.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#FFFFFF"><path d="M440-280h80v-160h160v-80H520v-160h-80v160H280v80h160v160Zm40 200q-83 0-156-31.5T197-197q-54-54-85.5-127T80-480q0-83 31.5-156T197-763q54-54 127-85.5T480-880q83 0 156 31.5T763-763q54 54 85.5 127T880-480q0 83-31.5 156T763-197q-54 54-127 85.5T480-80Zm0-80q134 0 227-93t93-227q0-134-93-227t-227-93q-134 0-227 93t-93 227q0 134 93 227t227 93Zm0-320Z"/></svg>
\ No newline at end of file
diff --git a/security-admin/src/main/webapp/react-webapp/src/index.jsx b/security-admin/src/main/webapp/react-webapp/src/index.jsx
index 0d5d2949a..adc43efc7 100644
--- a/security-admin/src/main/webapp/react-webapp/src/index.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/index.jsx
@@ -26,6 +26,7 @@ import "font-awesome/css/font-awesome.min.css";
import "react-toastify/dist/ReactToastify.css";
import "react-datetime/css/react-datetime.css";
import "./styles/style.css";
+import "./styles/StepperForm.css";
const container = document.getElementById("app");
diff --git a/security-admin/src/main/webapp/react-webapp/src/styles/StepperForm.css b/security-admin/src/main/webapp/react-webapp/src/styles/StepperForm.css
new file mode 100644
index 000000000..d4c6c3c78
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/styles/StepperForm.css
@@ -0,0 +1,241 @@
+/*
+ * 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.
+ */
+
+.stepper-form-container {
+ background: #fff;
+ border-radius: 4px;
+}
+
+/* Stepper Header Styles */
+.stepper-header {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+}
+
+.stepper-item {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ position: relative;
+}
+
+.stepper-number {
+ width: 44px;
+ height: 44px;
+ border-radius: 4px;
+ background: #c4c4c4;
+ color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-weight: 600;
+ font-size: 16px;
+ transition: all 0.3s ease;
+}
+
+.stepper-item.active .stepper-number {
+ background: #0b7fad;
+}
+
+.stepper-item.completed .stepper-number {
+ background: #6c757d;
+}
+
+.stepper-item.clickable {
+ cursor: pointer;
+}
+
+.stepper-item.clickable:hover .stepper-number {
+ background: #0b7fad;
+ opacity: 0.8;
+}
+
+.stepper-item.clickable:hover .stepper-title {
+ color: #0b7fad;
+}
+
+
+.stepper-content {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.stepper-title {
+ color: #333;
+}
+
+.stepper-title h6 {
+ line-height: 22px;
+}
+
+.stepper-item.active .stepper-title {
+ color: #0b7fad;
+}
+
+.stepper-subtitle {
+ color: #6c757d;
+ line-height: 18px;
+}
+
+.stepper-arrow {
+ font-size: 24px;
+ color: #c4c4c4;
+ margin: 0 32px;
+ transition: color 0.3s ease;
+}
+
+.stepper-arrow.completed {
+ color: #6c757d;
+}
+
+/* Body and Footer */
+.stepper-body {
+ padding: 8px 0;
+ background: #fff;
+ margin-bottom: 20px;
+}
+
+.stepper-instruction-text {
+ font-size: 15px;
+ color: #6c757d;
+ margin-bottom: 32px;
+}
+
+.stepper-footer {
+ display: flex;
+ justify-content: space-between;
+}
+
+.stepper-footer .btn {
+ min-width: 100px;
+ padding: 0.5rem 1rem;
+}
+
+/* Responsive Design */
+@media (max-width: 768px) {
+ .stepper-header {
+ flex-direction: column;
+ gap: 20px;
+ }
+
+ .stepper-arrow {
+ transform: rotate(90deg);
+ margin: 10px 0;
+ }
+
+ .stepper-item {
+ width: 100%;
+ }
+}
+
+.w-33 {
+ width: 33.33% !important;
+}
+
+.btn-link {
+ text-decoration: none;
+}
+
+.accordion-button :not(.collapsed) {
+ border-radius: 0.375rem;
+}
+
+:not(.collapsed) .policy-permission-items-accordion .accordion-header button,
+:not(.collapsed)
+ .policy-permission-items-accordion
+ .accordion-header
+ button:focus
+ :not(.collapsed)
+ .policy-permission-items-accordion
+ .accordion-header
+ button:active {
+ border-bottom-left-radius: 0 !important;
+ border-bottom-right-radius: 0 !important;
+ padding: 1rem !important;
+}
+
+.policy-permission-items-accordion .accordion-header button.collapsed {
+ padding: 1rem !important;
+ border-radius: 0.375rem !important;
+}
+
+.policy-permission-items-accordion .accordion-item {
+ margin-bottom: 1rem;
+ border: 1px solid #dde2e6 !important;
+ border-radius: 0.375rem;
+}
+
+.labels-select-input [class$="placeholder"] {
+ color: #5f5f5f;
+}
+
+.labels-select-input [class$="ValueContainer"] {
+ padding-left: 12px;
+ padding-right: 12px;
+}
+
+.form-select {
+ font-size: 0.875rem;
+}
+
+.permissions-checkboxes {
+ display: grid;
+ grid-template-columns: 1fr 1fr 1fr 1fr;
+ row-gap: 0.5rem;
+ column-gap: 2rem;
+ flex-wrap: wrap;
+}
+
+.required-mark {
+ display: inline-block;
+ width: 10px;
+ color: red;
+ text-align: right;
+}
+
+.policy-permission-items-accordion .accordion-button:not(.collapsed) {
+ background: #f3f8f9 !important;
+ color: #333333;
+}
+
+.policy-permission-items-accordion .accordion-button.collapsed {
+ background: #f3f8f9 !important;
+ color: #333333;
+}
+
+@media (max-width: 1366px) {
+ .permissions-checkboxes {
+ grid-template-columns: 1fr 1fr 1fr;
+ }
+}
+
+.policy-form-toggle-switch .switch-handle{
+ border-radius: 4px !important;
+}
+.policy-form-toggle-switch .switch-on:hover{
+background-color: #0b7fad !important;
+color:#ffffff !important;
+}
+
+.policy-form-toggle-switch .switch-off:hover{
+ background-color: white !important;
+ color: #0b7fad !important;
+}
\ No newline at end of file
diff --git a/security-admin/src/main/webapp/react-webapp/src/styles/style.css b/security-admin/src/main/webapp/react-webapp/src/styles/style.css
index e273bd3e7..dfe685078 100644
--- a/security-admin/src/main/webapp/react-webapp/src/styles/style.css
+++ b/security-admin/src/main/webapp/react-webapp/src/styles/style.css
@@ -20,7 +20,7 @@
body {
background: #ffffff;
font-family: "Roboto", "Helvetica Neue", "Helvetica", "Arial", "sans-serif";
- font-size: 13px;
+ font-size: 14px;
}
a {
@@ -166,6 +166,35 @@ a:active {
color: #495057;
}
+.column-1-fixed {
+ flex: 0 0 244px;
+ max-width: 244px;
+}
+
+.policy-permission-items-accordion .column-1-fixed {
+ flex: 0 0 216px;
+ max-width: 216px;
+}
+
+.column-3-fixed {
+ flex: 0 0 280px;
+ max-width: 280px;
+}
+
+.policy-permission-items-accordion .column-3-fixed {
+ flex: 0 0 150px;
+ max-width: 150px;
+}
+
+.resource-block .column-3-fixed {
+ flex: 0 0 280px;
+ max-width: 280px;
+}
+
+.mw-50 {
+ max-width: 50%;
+}
+
.searchbox-border {
border: 1px solid #d6d6d6;
padding: 20px;
@@ -178,7 +207,7 @@ a:active {
/* Badge */
.badge {
padding: 4px 6px;
- font-size: 12px;
+ font-size: 13px;
margin-bottom: 2px;
}
@@ -201,6 +230,8 @@ a:active {
color: #424242;
background-image: none;
background-color: white;
+ font-size: 14px;
+ line-height: 20px;
}
.btn:hover {
@@ -217,6 +248,32 @@ a:active {
box-shadow: 0 0 0 0.2rem rgb(38 143 255 / 50%);
}
+.btn-outline-primary {
+ color: #0b7fad;
+ border-color: #0b7fad;
+ background: #ffffff;
+ font-size: 14px;
+ line-height: 20px;
+}
+
+.btn-outline-primary:hover {
+ color: #ffffff;
+ background-color: #0b7fad;
+ border-color: #0b7fad;
+}
+
+.btn-outline-primary:focus {
+ color: #ffffff !important;
+ background-color: #0b7fad !important;
+ border-color: #0b7fad !important;
+}
+
+.btn-outline-primary:active {
+ color: #ffffff !important;
+ background-color: #0b7fad !important;
+ border-color: #0b7fad !important;
+}
+
.btn-mini {
padding: 4px 8px;
font-size: 11.05px;
@@ -268,6 +325,14 @@ a:active {
background-color: #f8f9fa;
border-color: #007bff;
}
+
+.span-bg-primary {
+ background-color: #0b7fad;
+ background-image: none;
+ color: #fff;
+ border-color: #0b7fad;
+}
+
.user-name {
overflow: hidden;
display: -webkit-box !important;
@@ -606,7 +671,7 @@ table.no-bg-color thead tr th:first-child {
.position-relative .table th,
.table td {
padding: 8px;
- font-size: 13px;
+ font-size: 14px;
}
.policy-manager .policy-title {
@@ -1642,6 +1707,18 @@ header {
border-radius: 15px;
}
+.resource-toggle-switch .btn-group-xs > .btn,
+.btn-xs {
+ padding: 2px 8px !important;
+ font-size: 14px;
+ line-height: 1.2 !important;
+}
+
+.resource-toggle-switch .btn-xs {
+ padding: 2px 8px !important;
+ font-size: 14px;
+ line-height: 1.2 !important;
+}
.switch-handle {
width: 35px !important;
border-radius: 15px;
@@ -1655,8 +1732,9 @@ header {
padding-left: 20px !important;
}
-.policy-search-info {
+.font-13 {
font-size: 13px;
+ line-height: 18px;
}
.ranger-navbar .dropdown-item.active,
@@ -2977,11 +3055,6 @@ textarea.gds-placeholder::placeholder,
cursor: pointer;
}
-.resource-block {
- padding: 0.5rem 0;
- border-bottom: 1px solid #dddddd;
-}
-
.gds-shared-resource div.row:last-child {
margin-bottom: 0 !important;
}
diff --git a/security-admin/src/main/webapp/react-webapp/src/utils/XAEnums.js b/security-admin/src/main/webapp/react-webapp/src/utils/XAEnums.js
index 744f7bf82..34df921d4 100755
--- a/security-admin/src/main/webapp/react-webapp/src/utils/XAEnums.js
+++ b/security-admin/src/main/webapp/react-webapp/src/utils/XAEnums.js
@@ -598,7 +598,7 @@ export const RegexValidation = {
characters.
<br />
2. Allowed special character ,._-+/@= and space. <br />
- 3. Name length should be greater than one."
+ 3. Name length should be greater than one.
</>
),
regexForNameValidationMessage:
@@ -610,7 +610,7 @@ export const RegexValidation = {
<br />
2. Allowed special character ._-@ and space.
<br />
- 3. Name length should be greater than one."
+ 3. Name length should be greater than one.
</>
)
},
@@ -692,7 +692,11 @@ export const PathAssociateWithModule = {
PageNotFound: ["/pageNotFound"],
localLogin: ["/locallogin"],
slashPath: ["/"],
- Forbidden: ["/forbidden"]
+ Forbidden: ["/forbidden"],
+ CreateNewPolicyForm: ["/policymanager/create-policy"],
+ EditNewPolicyForm: [
+ "/service/:serviceId/policies/:policyId/new-policy-form-edit"
+ ]
};
/* Access */
@@ -701,13 +705,13 @@ export const DefStatus = {
RecursiveStatus: {
STATUS_RECURSIVE: {
value: true,
- label: "recursive",
+ label: "Recursive",
rbkey: "xa.enum.RecursiveStatus.RECURSIVE",
tt: "lbl.RecursiveStatus_RECURSIVE"
},
STATUS_NONRECURSIVE: {
value: false,
- label: "nonrecursive",
+ label: "Non-recursive",
rbkey: "xa.enum.RecursiveStatus.NONRECURSIVE",
tt: "lbl.RecursiveStatus_NONRECURSIVE"
}
diff --git a/security-admin/src/main/webapp/react-webapp/src/utils/XAUtils.js b/security-admin/src/main/webapp/react-webapp/src/utils/XAUtils.js
index 382305c7f..438caaf52 100644
--- a/security-admin/src/main/webapp/react-webapp/src/utils/XAUtils.js
+++ b/security-admin/src/main/webapp/react-webapp/src/utils/XAUtils.js
@@ -18,7 +18,7 @@
*/
import React, { useState } from "react";
-import { getUserProfile } from "Utils/appState";
+import { getUserProfile, getServiceDef } from "Utils/appState";
import {
UserRoles,
PathAssociateWithModule,
@@ -43,6 +43,9 @@ import {
some,
has,
sortBy,
+ cloneDeep,
+ toUpper,
+ groupBy,
isArray
} from "lodash";
import { matchRoutes } from "react-router-dom";
@@ -169,6 +172,10 @@ export const hasAccessToPath = (pathName) => {
if (isSystemAdmin() || isAuditor()) {
moduleNames.push("Permission");
}
+ if (isSystemAdmin() || isKeyAdmin() || isUser()) {
+ moduleNames.push("CreateNewPolicyForm");
+ moduleNames.push("EditNewPolicyForm");
+ }
let allRouter = [],
returnFlag = true;
for (const key in PathAssociateWithModule) {
@@ -1605,6 +1612,208 @@ export const safeJsonParse = (value, fallback) => {
}
};
+// Common function to get service definition type
+export const getServiceDefType = () => {
+ const { allServiceDefs } = cloneDeep(getServiceDef());
+ let serviceDefType = [];
+
+ serviceDefType = sortBy(
+ map(allServiceDefs, function (serviceDef) {
+ return {
+ label: toUpper(serviceDef.displayName),
+ value: serviceDef.name
+ };
+ }),
+ ["label"] // Sorts by the 'label' property in ascending order
+ );
+
+ return serviceDefType;
+};
+
+// Common function to get service names by service type
+export const getServiceNameByServiceType = async (serviceType) => {
+ let serviceNames = [];
+ let params = { serviceType: serviceType };
+ try {
+ const response = await fetchApi({
+ url: "public/v2/api/service-headers",
+ params: params
+ });
+ serviceNames =
+ sortBy(
+ map(response?.data, function ({ name, displayName, id }) {
+ return { label: displayName, value: name, serviceId: id };
+ }),
+ "label"
+ ) || [];
+ } catch (error) {
+ console.error(
+ `Error occurred while fetching Services names by service type or CSRF headers! ${error}`
+ );
+ }
+ return serviceNames;
+};
+
+// Common function to get zone names by service ID
+export const getZoneNameByServiceID = async (
+ serviceID,
+ selectedServiceComponentDef
+) => {
+ let zoneNames = [];
+ let params = {
+ isTagService: selectedServiceComponentDef?.name == "tag" ? true : false
+ };
+ try {
+ const response = await fetchApi({
+ url: `public/v2/api/zones/zone-headers/for-service/${serviceID}`,
+ params: params
+ });
+ zoneNames =
+ sortBy(
+ map(response?.data, function ({ name, id }) {
+ return { label: name, value: name, zoneId: id };
+ }),
+ "label"
+ ) || [];
+ } catch (error) {
+ console.error(
+ `Error occurred while fetching Zone names by service ID or CSRF headers! ${error}`
+ );
+ }
+ return zoneNames;
+};
+
+//Common function for select box colour change on error
+export const getSelectBoxErrorStyles = (meta) => ({
+ control: (provided) => ({
+ ...provided,
+ borderColor: meta.touched && meta.error ? "#dc3545" : provided.borderColor,
+ boxShadow:
+ meta.touched && meta.error
+ ? "0 0 0 0.2rem rgba(220,53,69,.25)"
+ : provided.boxShadow
+ })
+});
+
+//Common function to get AccessType base on resources
+export const getResourceLevelKeysSorted = (serviceCompDetails) => {
+ if (!serviceCompDetails) {
+ return [];
+ }
+ const { resources = [] } = serviceCompDetails;
+ const grpResources = groupBy(resources, "level");
+ const grpResourcesKeys = [];
+ for (const resourceKey in grpResources) {
+ grpResourcesKeys.push(+resourceKey);
+ }
+ grpResourcesKeys.sort();
+ return grpResourcesKeys;
+};
+
+export const getAccessTypesByResource = (formValues, serviceCompDetails) => {
+ if (!formValues || !serviceCompDetails) {
+ return [];
+ }
+ const grpResourcesKeys = getResourceLevelKeysSorted(serviceCompDetails);
+ const accessTypeNoneOption = {
+ label: "None",
+ value: "none"
+ };
+ let srcOp = [],
+ multiplePermissionItem = [];
+ if (
+ RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value == formValues.policyType
+ ) {
+ srcOp = serviceCompDetails.dataMaskDef?.accessTypes || [];
+ } else if (
+ RangerPolicyType.RANGER_ROW_FILTER_POLICY_TYPE.value ==
+ formValues.policyType
+ ) {
+ srcOp = serviceCompDetails.rowFilterDef?.accessTypes || [];
+ } else {
+ srcOp = serviceCompDetails.accessTypes;
+ }
+
+ map(formValues.additionalResources, (resourceObj) => {
+ for (let i = grpResourcesKeys.length - 1; i >= 0; i--) {
+ let selectedResource = `resourceName-${grpResourcesKeys[i]}`;
+ if (
+ resourceObj[selectedResource] &&
+ resourceObj[selectedResource].value !== accessTypeNoneOption.value
+ ) {
+ if (resourceObj[selectedResource].accessTypeRestrictions?.length > 0) {
+ let op = [];
+ for (const name of resourceObj[selectedResource]
+ .accessTypeRestrictions) {
+ let typeOp = find(srcOp, { name });
+ if (typeOp) {
+ op.push(typeOp);
+ }
+ }
+ multiplePermissionItem = [...multiplePermissionItem, ...op];
+ } else {
+ multiplePermissionItem = [...srcOp];
+ }
+ break;
+ }
+ }
+ });
+ srcOp = [...new Set(multiplePermissionItem)];
+ return sortBy(
+ srcOp.map(({ label, name: value }) => ({ label, value })),
+ [(o) => o.label.toLowerCase()]
+ );
+};
+
+export const prunePolicyItemAccessesToAllowedTypes = (
+ form,
+ selectedServiceComponentDef
+) => {
+ const formValues = form.getState().values;
+
+ const isNotAccessPolicy =
+ formValues?.policyType !== RangerPolicyType.RANGER_ACCESS_POLICY_TYPE.value;
+
+ const isTagService = selectedServiceComponentDef.name === "tag";
+
+ if (isNotAccessPolicy || isTagService) {
+ return;
+ }
+
+ const options = getAccessTypesByResource(
+ formValues,
+ selectedServiceComponentDef
+ );
+ const allowedSet = new Set(
+ (options || []).map((o) => o && o.value).filter(Boolean)
+ );
+
+ const pruneAccessArrays = (attrName) => {
+ const arr = formValues?.[attrName];
+ if (!Array.isArray(arr)) {
+ return;
+ }
+ for (let i = 0; i < arr.length; i++) {
+ const item = arr[i];
+ if (!item || !Array.isArray(item.accesses)) {
+ continue;
+ }
+
+ const selectedAccesses = item.accesses.filter((a) => {
+ return a.type && allowedSet.has(a.type);
+ });
+ form.change(`${attrName}[${i}].accesses`, selectedAccesses);
+ }
+ };
+
+ pruneAccessArrays("policyItems");
+ pruneAccessArrays("allowExceptions");
+ if (formValues?.isDenyAllElse !== true) {
+ pruneAccessArrays("denyPolicyItems");
+ pruneAccessArrays("denyExceptions");
+ }
+};
+
//CommonFunction to get display label for policy permission item
export const getPolicyPermissionItemDisplayLbl = (
serviceDef,
@@ -1630,8 +1839,8 @@ export const getPolicyPermissionItemDisplayLbl = (
if (accessType.length == accessTypeDefVal.length) {
return sortBy(accessTypeDefVal, "label");
} else {
- const accessTypeDisplayLblObj = filter(accessTypeDefVal, (item) =>
- includes(accesTypeKeys, { type: item.name })
+ const accessTypeDisplayLblObj = filter(accessTypeDefVal, (obj) =>
+ includes(accesTypeKeys, obj.name)
);
return sortBy(accessTypeDisplayLblObj, "label");
}
diff --git a/security-admin/src/main/webapp/react-webapp/src/utils/policyConditionUtils.js b/security-admin/src/main/webapp/react-webapp/src/utils/policyConditionUtils.js
index e8c1c3c00..aef63af18 100644
--- a/security-admin/src/main/webapp/react-webapp/src/utils/policyConditionUtils.js
+++ b/security-admin/src/main/webapp/react-webapp/src/utils/policyConditionUtils.js
@@ -170,7 +170,10 @@ export const getSelectedAccessTypesForRow = (formValues, attrName, index) => {
return [];
}
return accesses
- .map((a) => (typeof a?.value === "string" ? a.value.trim() : ""))
+ .map((a) => {
+ const raw = a?.value ?? a?.type;
+ return typeof raw === "string" ? raw.trim() : "";
+ })
.filter((v) => v.length > 0);
};
@@ -240,15 +243,19 @@ export const sortPolicyConditions = (conditions) => {
* @param {object} formValues - Form state (may contain additionalResources for multi-resource policies).
* @returns {Set<string>} Set of leaf resource type names currently in use.
*/
-export const getSelectedLeafResourceTypes = (serviceCompDetails, formValues) => {
+export const getSelectedLeafResourceTypes = (
+ serviceCompDetails,
+ formValues
+) => {
const result = new Set();
const resources = serviceCompDetails?.resources;
if (!Array.isArray(resources) || resources.length === 0) {
return result;
}
- const levels = [...new Set(resources.map((r) => r?.level).filter(Number.isFinite))]
- .sort((a, b) => a - b);
+ const levels = [
+ ...new Set(resources.map((r) => r?.level).filter(Number.isFinite))
+ ].sort((a, b) => a - b);
const blocks = Array.isArray(formValues?.additionalResources)
? formValues.additionalResources
@@ -581,7 +588,34 @@ const getActionMatchesOptions = ({
};
/**
- * Returns a new object with any null or empty string values removed.
+ * Returns true when a condition value should be treated as unset (removed from state).
+ */
+const isEmptyConditionValue = (value) => {
+ if (value == null || value === "") {
+ return true;
+ }
+ if (!Array.isArray(value)) {
+ return false;
+ }
+ if (value.length === 0) {
+ return true;
+ }
+ return value.every((item) => {
+ if (item == null || item === "") {
+ return true;
+ }
+ if (typeof item === "object" && item?.value != null) {
+ return String(item.value).trim().length === 0;
+ }
+ if (typeof item === "string") {
+ return item.trim().length === 0;
+ }
+ return false;
+ });
+};
+
+/**
+ * Returns a new object with null, empty string, and empty multi-value entries removed.
* Useful to prevent React state mutation and to get accurate keys count.
*/
export const getCleanConditions = (conditions) => {
@@ -590,7 +624,7 @@ export const getCleanConditions = (conditions) => {
}
const cleaned = { ...conditions };
for (const key in cleaned) {
- if (cleaned[key] == null || cleaned[key] === "") {
+ if (isEmptyConditionValue(cleaned[key])) {
delete cleaned[key];
}
}
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/AddUpdatePolicyForm.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/AddUpdatePolicyForm.jsx
index 5957f7658..de3a2bf1d 100644
--- a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/AddUpdatePolicyForm.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/AddUpdatePolicyForm.jsx
@@ -36,7 +36,6 @@ import {
groupBy,
find,
isEmpty,
- pick,
isArray,
isEqual,
forIn,
@@ -45,8 +44,7 @@ import {
map,
isUndefined,
forEach,
- reject,
- cloneDeep
+ reject
} from "lodash";
import { toast } from "react-toastify";
import {
@@ -60,14 +58,18 @@ import { fetchApi } from "Utils/fetchAPI";
import { RangerPolicyType, getEnumElementByValue } from "Utils/XAEnums";
import ResourceComp from "../Resources/ResourceComp";
import PolicyPermissionItem from "../PolicyListing/PolicyPermissionItem";
-import { useParams, useNavigate, useLocation } from "react-router-dom";
+import {
+ useParams,
+ useNavigate,
+ useLocation,
+ useOutletContext
+} from "react-router-dom";
import PolicyValidityPeriodComp from "./PolicyValidityPeriodComp";
import PolicyConditionsComp from "./PolicyConditionsComp";
import { isPerRowCondition } from "Utils/policyConditionUtils";
import moment from "moment";
import {
InfoIcon,
- commonBreadcrumb,
isPolicyExpired,
getResourcesDefVal,
getAllTimeZoneList,
@@ -79,7 +81,6 @@ import { useAccordionButton } from "react-bootstrap/AccordionButton";
import AccordionContext from "react-bootstrap/AccordionContext";
import usePrompt from "Hooks/usePrompt";
import { RegexMessage } from "Utils/XAMessages";
-import { getServiceDef } from "Utils/appState";
import { FieldArray } from "react-final-form-arrays";
const noneOptions = {
@@ -129,10 +130,13 @@ export default function AddUpdatePolicyForm() {
let { serviceId, policyType, policyId } = useParams();
const navigate = useNavigate();
const { state } = useLocation();
- const serviceDefs = cloneDeep(getServiceDef());
+
+ // Get data from PolicyFormContext
+ const contextData = useOutletContext();
+ const { serviceDetails, serviceCompDetails, policyData } = contextData;
+
const [policyState, dispatch] = useReducer(reducer, initialState);
- const { loader, serviceDetails, serviceCompDetails, policyData, formData } =
- policyState;
+ const { loader, formData } = policyState;
const [defaultPolicyLabelOptions, setDefaultPolicyLabelOptions] = useState(
[]
);
@@ -147,8 +151,20 @@ export default function AddUpdatePolicyForm() {
useState(false);
useEffect(() => {
- fetchInitialData();
- }, [serviceId, policyType, policyId]);
+ if (serviceCompDetails) {
+ const generatedFormData = generateFormData(
+ policyData,
+ serviceCompDetails
+ );
+ dispatch({
+ type: "SET_DATA",
+ serviceDetails,
+ serviceCompDetails,
+ policyData,
+ formData: generatedFormData
+ });
+ }
+ }, [serviceDetails, serviceCompDetails, policyData]);
const showDeleteModal = () => {
setShowDelete(true);
@@ -231,66 +247,6 @@ export default function AddUpdatePolicyForm() {
}));
};
- const fetchInitialData = async () => {
- let serviceData = await fetchServiceDetails();
-
- let serviceCompData = serviceDefs?.allServiceDefs?.find((serviceDef) => {
- return serviceDef.name == serviceData.type;
- });
- if (serviceCompData) {
- let serviceDefPolicyType = 0;
- if (
- serviceCompData?.dataMaskDef &&
- Object.keys(serviceCompData.dataMaskDef).length != 0
- )
- serviceDefPolicyType++;
- if (
- serviceCompData?.rowFilterDef &&
- Object.keys(serviceCompData.rowFilterDef).length != 0
- )
- serviceDefPolicyType++;
- if (+policyType > serviceDefPolicyType) navigate("/pageNotFound");
- }
- let policyData = null;
- if (policyId) {
- policyData = await fetchPolicyData();
- }
-
- dispatch({
- type: "SET_DATA",
- serviceDetails: serviceData,
- serviceCompDetails: serviceCompData,
- policyData: policyData || null,
- formData: generateFormData(policyData, serviceCompData)
- });
- };
-
- const fetchServiceDetails = async () => {
- let data = null;
- try {
- const resp = await fetchApi({
- url: `plugins/services/${serviceId}`
- });
- data = resp.data || null;
- } catch (error) {
- console.error(`Error occurred while fetching policy details ! ${error}`);
- }
- return data;
- };
-
- const fetchPolicyData = async () => {
- let data = null;
- try {
- const resp = await fetchApi({
- url: `plugins/policies/${policyId}`
- });
- data = resp.data || null;
- } catch (error) {
- console.error(`Error occurred while fetching service details ! ${error}`);
- }
- return data;
- };
-
const fetchPolicyLabel = async (inputValue) => {
let params = {};
if (inputValue) {
@@ -997,13 +953,14 @@ export default function AddUpdatePolicyForm() {
navigate(`/service/${serviceId}/policies/${polType}`);
};
- const CustomToggle = ({ children, eventKey, callback }) => {
+ const CustomToggle = ({ eventKey, callback }) => {
const currentEventKey = useContext(AccordionContext);
const decoratedOnClick = useAccordionButton(
eventKey,
() => callback && callback(eventKey)
);
+
const isCurrentEventKey = currentEventKey?.activeEventKey === eventKey;
return (
@@ -1062,645 +1019,669 @@ export default function AddUpdatePolicyForm() {
}
};
- const policyBreadcrumb = () => {
- let policyDetails = {};
- policyDetails["serviceId"] = serviceId;
- policyDetails["policyType"] = policyId
- ? policyData?.policyType
- : policyType;
- policyDetails["serviceName"] = serviceDetails?.displayName;
- policyDetails["selectedZone"] = JSON.parse(
- localStorage.getItem("zoneDetails")
- );
- if (serviceCompDetails?.name === "tag") {
- if (policyDetails?.selectedZone) {
- return commonBreadcrumb(
- [
- "TagBasedServiceManager",
- "ManagePolicies",
- policyId ? "PolicyEdit" : "PolicyCreate"
- ],
- policyDetails
- );
- } else {
- return commonBreadcrumb(
- [
- "TagBasedServiceManager",
- "ManagePolicies",
- policyId ? "PolicyEdit" : "PolicyCreate"
- ],
- pick(policyDetails, ["serviceId", "policyType", "serviceName"])
- );
- }
- } else {
- if (policyDetails?.selectedZone) {
- return commonBreadcrumb(
- [
- "ServiceManager",
- "ManagePolicies",
- policyId ? "PolicyEdit" : "PolicyCreate"
- ],
- policyDetails
- );
- } else {
- return commonBreadcrumb(
- [
- "ServiceManager",
- "ManagePolicies",
- policyId ? "PolicyEdit" : "PolicyCreate"
- ],
- pick(policyDetails, ["serviceId", "policyType", "serviceName"])
- );
- }
- }
- };
-
return (
<>
{loader ? (
<Loader />
) : (
- <div>
- <div className="header-wraper">
- <h3 className="wrap-header bold">{`${
- policyId ? "Edit" : "Create"
- } Policy`}</h3>
- {policyBreadcrumb()}
- </div>
-
- <div className="wrap">
- <Form
- onSubmit={handleSubmit}
- mutators={{
- ...arrayMutators
- }}
- initialValues={formData}
- validate={(values) => {
- const errors = {};
- if (!values.policyName) {
- errors.policyName = {
- required: true,
- text: "Required"
- };
- }
+ <div className="wrap">
+ <Form
+ onSubmit={handleSubmit}
+ mutators={{
+ ...arrayMutators
+ }}
+ initialValues={formData}
+ validate={(values) => {
+ const errors = {};
+ if (!values.policyName) {
+ errors.policyName = {
+ required: true,
+ text: "Required"
+ };
+ }
- return errors;
- }}
- render={({
- handleSubmit,
- values,
- invalid,
- errors,
- dirty,
- form: {
- mutators: { push: addPolicyItem }
- },
- dirtyFields,
- modified,
- initialValues
- }) => (
- <>
- <PromptDialog
- isDirtyField={
- dirty == true || !isEqual(initialValues, values)
- ? isDirtyFieldCheck(
- dirtyFields,
- modified,
- values,
- initialValues
- )
- : false
+ return errors;
+ }}
+ render={({
+ handleSubmit,
+ values,
+ invalid,
+ errors,
+ dirty,
+ form: {
+ mutators: { push: addPolicyItem }
+ },
+ dirtyFields,
+ modified,
+ initialValues
+ }) => (
+ <>
+ <PromptDialog
+ isDirtyField={
+ dirty == true || !isEqual(initialValues, values)
+ ? isDirtyFieldCheck(
+ dirtyFields,
+ modified,
+ values,
+ initialValues
+ )
+ : false
+ }
+ isUnblock={preventUnBlock}
+ />
+ <form
+ onSubmit={(event) => {
+ if (invalid) {
+ forIn(errors, function (value, key) {
+ if (
+ has(errors, "policyName") ||
+ resourceErrorCheck(errors, values)
+ ) {
+ let selector =
+ document.getElementById("isError") ||
+ document.getElementById(key) ||
+ document.querySelector(`input[name=${key}]`) ||
+ document.querySelector(`input[id=${key}]`) ||
+ document.querySelector(
+ `span[className="invalid-field"]`
+ );
+ scrollToError(selector);
+ } else {
+ getValidatePolicyItems(errors?.[key]);
+ }
+ });
}
- isUnblock={preventUnBlock}
- />
- <form
- onSubmit={(event) => {
- if (invalid) {
- forIn(errors, function (value, key) {
- if (
- has(errors, "policyName") ||
- resourceErrorCheck(errors, values)
- ) {
- let selector =
- document.getElementById("isError") ||
- document.getElementById(key) ||
- document.querySelector(`input[name=${key}]`) ||
- document.querySelector(`input[id=${key}]`) ||
- document.querySelector(
- `span[className="invalid-field"]`
- );
- scrollToError(selector);
- } else {
- getValidatePolicyItems(errors?.[key]);
- }
- });
- }
- handleSubmit(event);
- }}
- >
- {(values.policyType ==
- RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value ||
- values.policyType ==
- RangerPolicyType.RANGER_ROW_FILTER_POLICY_TYPE.value) &&
- show && (
- <Alert
- variant="warning"
- onClose={() => setShow(false)}
- dismissible
- data-js="policyInfoAlert"
- data-cy="policyInfoAlert"
- >
- <i className="fa-fw fa fa-info-circle d-inline text-dark"></i>
- {policyInfo(
- values.policyType,
- serviceCompDetails.name
- )}
- </Alert>
- )}
- {policyId &&
- !isEmpty(policyData.validitySchedules) &&
- isPolicyExpired(policyData) &&
- showPolicyExpire && (
- <Alert
- variant="danger"
- onClose={() => setShowPolicyExpire(false)}
- dismissible
- >
- <i className="fa fa-clock-o fa-fw fa-lg time-clock"></i>
- <p className="pd-l-6 d-inline"> Policy Expired</p>
- </Alert>
- )}
- <fieldset>
- <p className="formHeader">Policy Details : </p>
- </fieldset>
- <Row className="user-role-grp-form">
- <Col md={8}>
- <FormB.Group as={Row} className="mb-3">
- <Field
- className="form-control"
- name="policyType"
- render={({ input }) => (
- <>
- <FormB.Label column sm={3}>
- <span className="float-end fnt-14">
- Policy Type
- </span>
- </FormB.Label>
- <Col sm={5}>
- <h6 className="d-inline me-1">
- <Badge
- bg="primary"
- style={{ verticalAlign: "sub" }}
- >
- {
- getEnumElementByValue(
- RangerPolicyType,
- +input.value
- )?.label
- }
- </Badge>
- </h6>
- </Col>
- </>
- )}
- />
- </FormB.Group>
- {policyId && (
- <FormB.Group as={Row} className="mb-3">
- <FormB.Label column sm={3}>
- <span className="float-end fnt-14">
- Policy ID*
- </span>
- </FormB.Label>
- <Col sm={5}>
- <h6 className="d-inline me-1">
- <span style={{ verticalAlign: "sub" }}>
- <Badge bg="primary">{policyData.id}</Badge>
- </span>
- </h6>
- </Col>
- </FormB.Group>
- )}
- <FormB.Group as={Row} className="mb-3">
- <Field
- className="form-control"
- name="policyName"
- render={({ input, meta }) => (
- <>
- <FormB.Label column sm={3}>
- <span className="float-end fnt-14">
- Policy Name*
- </span>
- </FormB.Label>
- <>
- <Col sm={5} className={"position-relative"}>
- <FormB.Control
- {...input}
- placeholder="Policy Name"
- id={
- meta.error && meta.touched
- ? "isError"
- : "name"
- }
- className={
- meta.error && meta.touched
- ? "form-control border-danger"
- : "form-control"
- }
- data-cy="policyName"
- onBlur={(e) => trimInputValue(e, input)}
- />
- <InfoIcon
- css="input-box-info-icon"
- position="right"
- message={
- <p
- className="pd-10"
- style={{ fontSize: "small" }}
- >
- {
- RegexMessage.MESSAGE
- .policyNameInfoIconMessage
- }
- </p>
- }
- />
- {meta.touched && meta.error && (
- <span className="invalid-field">
- {meta.error.text}
- </span>
- )}
- </Col>
- </>
- </>
- )}
- />
- <Col sm={4}>
- <Row>
- <Col sm={5}>
- <Field
- className="form-control"
- name="isEnabled"
- render={({ input }) => (
- <BootstrapSwitchButton
- {...input}
- className="abcd"
- checked={!(input.value === false)}
- onlabel="Enabled"
- onstyle="primary"
- offlabel="Disabled"
- offstyle="outline-secondary"
- style="w-100"
- size="xs"
- key="isEnabled"
- />
- )}
- />
- </Col>
- <Col sm={5}>
- <Field
- className="form-control"
- name="policyPriority"
- render={({ input }) => (
- <BootstrapSwitchButton
- {...input}
- checked={input.value}
- onlabel="Override"
- onstyle="primary"
- offlabel="Normal"
- offstyle="outline-secondary"
- style="w-100"
- size="xs"
- key="policyPriority"
- />
- )}
- />
- </Col>
- </Row>
- </Col>
- </FormB.Group>
+ handleSubmit(event);
+ }}
+ >
+ {(values.policyType ==
+ RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value ||
+ values.policyType ==
+ RangerPolicyType.RANGER_ROW_FILTER_POLICY_TYPE.value) &&
+ show && (
+ <Alert
+ variant="warning"
+ onClose={() => setShow(false)}
+ dismissible
+ data-js="policyInfoAlert"
+ data-cy="policyInfoAlert"
+ >
+ <i className="fa-fw fa fa-info-circle d-inline text-dark"></i>
+ {policyInfo(values.policyType, serviceCompDetails.name)}
+ </Alert>
+ )}
+ {policyId &&
+ !isEmpty(policyData.validitySchedules) &&
+ isPolicyExpired(policyData) &&
+ showPolicyExpire && (
+ <Alert
+ variant="danger"
+ onClose={() => setShowPolicyExpire(false)}
+ dismissible
+ >
+ <i className="fa fa-clock-o fa-fw fa-lg time-clock"></i>
+ <p className="pd-l-6 d-inline"> Policy Expired</p>
+ </Alert>
+ )}
+ <fieldset>
+ <p className="formHeader">Policy Details : </p>
+ </fieldset>
+ <Row className="user-role-grp-form">
+ <Col md={8}>
+ <FormB.Group as={Row} className="mb-3">
<Field
className="form-control"
- name="policyLabel"
+ name="policyType"
render={({ input }) => (
- <FormB.Group as={Row} className="mb-3">
+ <>
<FormB.Label column sm={3}>
<span className="float-end fnt-14">
- Policy Label
+ Policy Type
</span>
</FormB.Label>
<Col sm={5}>
- <AsyncCreatableSelect
- {...input}
- isMulti
- loadOptions={fetchPolicyLabel}
- onFocus={() => {
- onFocusPolicyLabel();
- }}
- defaultOptions={defaultPolicyLabelOptions}
- styles={selectInputCustomStyles}
- // Add this prop to trim the visual "Create" label
- formatCreateLabel={(inputValue) =>
- `Create "${inputValue.trim()}"`
- }
- // Add this prop to trim the value when a tag is created
- onCreateOption={(inputValue) => {
- const policyLabelVal = inputValue.trim();
- if (policyLabelVal) {
- input.onChange([
- ...input.value,
- {
- label: policyLabelVal,
- value: policyLabelVal
- }
- ]);
+ <h6 className="d-inline me-1">
+ <Badge
+ bg="primary"
+ style={{ verticalAlign: "sub" }}
+ >
+ {
+ getEnumElementByValue(
+ RangerPolicyType,
+ +input.value
+ )?.label
}
- }}
- tabSelectsValue={false}
- placeholder="Add Policy Labels"
- />
+ </Badge>
+ </h6>
</Col>
- </FormB.Group>
+ </>
)}
/>
- {!isMultiResources && (
- <ResourceComp
- serviceDetails={serviceDetails}
- serviceCompDetails={serviceCompDetails}
- formValues={values}
- policyType={
- policyId ? policyData.policyType : policyType
- }
- policyId={policyId}
- />
- )}
+ </FormB.Group>
+ {policyId && (
+ <FormB.Group as={Row} className="mb-3">
+ <FormB.Label column sm={3}>
+ <span className="float-end fnt-14">Policy ID*</span>
+ </FormB.Label>
+ <Col sm={5}>
+ <h6 className="d-inline me-1">
+ <span style={{ verticalAlign: "sub" }}>
+ <Badge bg="primary">{policyData.id}</Badge>
+ </span>
+ </h6>
+ </Col>
+ </FormB.Group>
+ )}
+ <FormB.Group as={Row} className="mb-3">
<Field
className="form-control"
- name="description"
- render={({ input }) => (
- <FormB.Group as={Row} className="mb-3">
+ name="policyName"
+ render={({ input, meta }) => (
+ <>
<FormB.Label column sm={3}>
<span className="float-end fnt-14">
- Description
+ Policy Name*
</span>
</FormB.Label>
- <Col sm={5}>
- <FormB.Control
- {...input}
- as="textarea"
- rows={3}
- data-cy="description"
- onBlur={(e) => trimInputValue(e, input)}
- />
- </Col>
- </FormB.Group>
+ <>
+ <Col sm={5} className={"position-relative"}>
+ <FormB.Control
+ {...input}
+ placeholder="Policy Name"
+ id={
+ meta.error && meta.touched
+ ? "isError"
+ : "name"
+ }
+ className={
+ meta.error && meta.touched
+ ? "form-control border-danger"
+ : "form-control"
+ }
+ data-cy="policyName"
+ onBlur={(e) => trimInputValue(e, input)}
+ />
+ <InfoIcon
+ css="input-box-info-icon"
+ position="right"
+ message={
+ <p
+ className="pd-10"
+ style={{ fontSize: "small" }}
+ >
+ {
+ RegexMessage.MESSAGE
+ .policyNameInfoIconMessage
+ }
+ </p>
+ }
+ />
+ {meta.touched && meta.error && (
+ <span className="invalid-field">
+ {meta.error.text}
+ </span>
+ )}
+ </Col>
+ </>
+ </>
)}
/>
- <Field
- className="form-control"
- name="isAuditEnabled"
- render={({ input }) => (
- <FormB.Group as={Row} className="mb-3">
- <FormB.Label column sm={3}>
- <span className="float-end fnt-14">
- Audit Logging*
- </span>
- </FormB.Label>
- <Col sm={5}>
- <span style={{ verticalAlign: "sub" }}>
+ <Col sm={4}>
+ <Row>
+ <Col sm={5}>
+ <Field
+ className="form-control"
+ name="isEnabled"
+ render={({ input }) => (
<BootstrapSwitchButton
{...input}
+ className="abcd"
checked={!(input.value === false)}
- onlabel="Yes"
+ onlabel="Enabled"
onstyle="primary"
- offlabel="No"
+ offlabel="Disabled"
offstyle="outline-secondary"
+ style="w-100"
size="xs"
- key="isAuditEnabled"
+ key="isEnabled"
/>
- </span>
- </Col>
- </FormB.Group>
- )}
+ )}
+ />
+ </Col>
+ <Col sm={5}>
+ <Field
+ className="form-control"
+ name="policyPriority"
+ render={({ input }) => (
+ <BootstrapSwitchButton
+ {...input}
+ checked={input.value}
+ onlabel="Override"
+ onstyle="primary"
+ offlabel="Normal"
+ offstyle="outline-secondary"
+ style="w-100"
+ size="xs"
+ key="policyPriority"
+ />
+ )}
+ />
+ </Col>
+ </Row>
+ </Col>
+ </FormB.Group>
+ <Field
+ className="form-control"
+ name="policyLabel"
+ render={({ input }) => (
+ <FormB.Group as={Row} className="mb-3">
+ <FormB.Label column sm={3}>
+ <span className="float-end fnt-14">
+ Policy Label
+ </span>
+ </FormB.Label>
+ <Col sm={5}>
+ <AsyncCreatableSelect
+ {...input}
+ isMulti
+ loadOptions={fetchPolicyLabel}
+ onFocus={() => {
+ onFocusPolicyLabel();
+ }}
+ defaultOptions={defaultPolicyLabelOptions}
+ styles={selectInputCustomStyles}
+ // Add this prop to trim the visual "Create" label
+ formatCreateLabel={(inputValue) =>
+ `Create "${inputValue.trim()}"`
+ }
+ // Add this prop to trim the value when a tag is created
+ onCreateOption={(inputValue) => {
+ const policyLabelVal = inputValue.trim();
+ if (policyLabelVal) {
+ input.onChange([
+ ...input.value,
+ {
+ label: policyLabelVal,
+ value: policyLabelVal
+ }
+ ]);
+ }
+ }}
+ tabSelectsValue={false}
+ placeholder="Add Policy Labels"
+ />
+ </Col>
+ </FormB.Group>
+ )}
+ />
+ {!isMultiResources && (
+ <ResourceComp
+ serviceDetails={serviceDetails}
+ serviceCompDetails={serviceCompDetails}
+ formValues={values}
+ policyType={
+ policyId ? policyData.policyType : policyType
+ }
+ policyId={policyId}
/>
- </Col>
- {/* -------------------------------------------------------------- */}
- <Col md={4}>
- <div className="mb-4">
- <PolicyValidityPeriodComp
- addPolicyItem={addPolicyItem}
- />
- </div>
- <br />
- {serviceCompDetails?.policyConditions?.length > 0 && (
- <div className="table-responsive">
- <table className="table table-bordered condition-group-table">
- <thead>
- <tr>
- <th colSpan="2">
- Policy Conditions :
- {showModal && (
- <Field
- className="form-control"
- name="conditions"
- render={({ input }) => (
- <PolicyConditionsComp
- policyConditionDetails={policyConditionUpdatedJSON(
- serviceCompDetails.policyConditions
- )}
- inputVal={input}
- showModal={showModal}
- handleCloseModal={
- policyConditionState
- }
- modalHeader="Policy Conditions"
- />
- )}
- />
- )}
- <Button
- className="float-end btn btn-mini"
- onClick={() => {
- policyConditionState(true);
- }}
- data-js="customPolicyConditions"
- data-cy="customPolicyConditions"
- >
- <i className="fa-fw fa fa-plus"></i>
- </Button>
- </th>
- </tr>
- </thead>
- <tbody data-id="conditionData">
- <>
- {values?.conditions &&
- !isEmpty(values.conditions) ? (
- Object.keys(values.conditions).map(
- (keyName) => {
- if (isPerRowCondition(keyName)) {
- return null;
- }
- if (
- values.conditions[keyName] != "" &&
- values.conditions[keyName] != null
- ) {
- let conditionObj = find(
- serviceCompDetails?.policyConditions,
- function (m) {
- if (m.name == keyName) {
- return m;
- }
+ )}
+ <Field
+ className="form-control"
+ name="description"
+ render={({ input }) => (
+ <FormB.Group as={Row} className="mb-3">
+ <FormB.Label column sm={3}>
+ <span className="float-end fnt-14">
+ Description
+ </span>
+ </FormB.Label>
+ <Col sm={5}>
+ <FormB.Control
+ {...input}
+ as="textarea"
+ rows={3}
+ data-cy="description"
+ onBlur={(e) => trimInputValue(e, input)}
+ />
+ </Col>
+ </FormB.Group>
+ )}
+ />
+ <Field
+ className="form-control"
+ name="isAuditEnabled"
+ render={({ input }) => (
+ <FormB.Group as={Row} className="mb-3">
+ <FormB.Label column sm={3}>
+ <span className="float-end fnt-14">
+ Audit Logging*
+ </span>
+ </FormB.Label>
+ <Col sm={5}>
+ <span style={{ verticalAlign: "sub" }}>
+ <BootstrapSwitchButton
+ {...input}
+ checked={!(input.value === false)}
+ onlabel="Yes"
+ onstyle="primary"
+ offlabel="No"
+ offstyle="outline-secondary"
+ size="xs"
+ key="isAuditEnabled"
+ />
+ </span>
+ </Col>
+ </FormB.Group>
+ )}
+ />
+ </Col>
+ {/* -------------------------------------------------------------- */}
+ <Col md={4}>
+ <div className="mb-4">
+ <PolicyValidityPeriodComp
+ addPolicyItem={addPolicyItem}
+ />
+ </div>
+ <br />
+ {serviceCompDetails?.policyConditions?.length > 0 && (
+ <div className="table-responsive">
+ <table className="table table-bordered condition-group-table">
+ <thead>
+ <tr>
+ <th colSpan="2">
+ Policy Conditions :
+ {showModal && (
+ <Field
+ className="form-control"
+ name="conditions"
+ render={({ input }) => (
+ <PolicyConditionsComp
+ policyConditionDetails={policyConditionUpdatedJSON(
+ serviceCompDetails.policyConditions
+ )}
+ inputVal={input}
+ showModal={showModal}
+ handleCloseModal={
+ policyConditionState
+ }
+ modalHeader="Policy Conditions"
+ />
+ )}
+ />
+ )}
+ <Button
+ className="float-end btn btn-mini"
+ onClick={() => {
+ policyConditionState(true);
+ }}
+ data-js="customPolicyConditions"
+ data-cy="customPolicyConditions"
+ >
+ <i className="fa-fw fa fa-plus"></i>
+ </Button>
+ </th>
+ </tr>
+ </thead>
+ <tbody data-id="conditionData">
+ <>
+ {values?.conditions &&
+ !isEmpty(values.conditions) ? (
+ Object.keys(values.conditions).map(
+ (keyName) => {
+ if (isPerRowCondition(keyName)) {
+ return null;
+ }
+ if (
+ values.conditions[keyName] != "" &&
+ values.conditions[keyName] != null
+ ) {
+ let conditionObj = find(
+ serviceCompDetails?.policyConditions,
+ function (m) {
+ if (m.name == keyName) {
+ return m;
}
- );
- return (
- <tr key={keyName}>
- <td>
- <span>
- {getPolicyConditionDisplayLbl(
- conditionObj.label
- )}
- </span>
- </td>
- <td>
- {isArray(
- values?.conditions[keyName]
- ) ? (
- <span className="line-clamp line-clamp-3">
- {values.conditions[
- keyName
- ].join(", ")}
- </span>
- ) : (
- <span className="line-clamp line-clamp-3">
- {values.conditions[keyName]}
- </span>
+ }
+ );
+ return (
+ <tr key={keyName}>
+ <td>
+ <span>
+ {getPolicyConditionDisplayLbl(
+ conditionObj.label
)}
- </td>
- </tr>
- );
- }
+ </span>
+ </td>
+ <td>
+ {isArray(
+ values?.conditions[keyName]
+ ) ? (
+ <span className="line-clamp line-clamp-3">
+ {values.conditions[
+ keyName
+ ].join(", ")}
+ </span>
+ ) : (
+ <span className="line-clamp line-clamp-3">
+ {values.conditions[keyName]}
+ </span>
+ )}
+ </td>
+ </tr>
+ );
}
- )
- ) : (
- <tr>
- <td>
- <center className="text-muted">
- No Conditions
- </center>
- </td>
- </tr>
- )}
- </>
- </tbody>
- </table>
- </div>
- )}
- </Col>
- </Row>
- {/* --------------------- Multiple Resources ---------------------------- */}
- {isMultiResources && (
+ }
+ )
+ ) : (
+ <tr>
+ <td>
+ <center className="text-muted">
+ No Conditions
+ </center>
+ </td>
+ </tr>
+ )}
+ </>
+ </tbody>
+ </table>
+ </div>
+ )}
+ </Col>
+ </Row>
+ {/* --------------------- Multiple Resources ---------------------------- */}
+ {isMultiResources && (
+ <>
+ <fieldset>
+ <p className="formHeader">
+ {serviceCompDetails.name == "tag"
+ ? "Tags :"
+ : "Resources :"}
+ </p>
+ </fieldset>
<>
- <fieldset>
- <p className="formHeader">
- {serviceCompDetails.name == "tag"
- ? "Tags :"
- : "Resources :"}
- </p>
- </fieldset>
- <>
- <FieldArray name="additionalResources">
- {({ fields }) =>
- fields.map((name, index) => (
- <Row
- className="resource-block"
- key={`${name}-${index}`}
- >
- <Col md={8}>
- <ResourceComp
- serviceDetails={serviceDetails}
- serviceCompDetails={serviceCompDetails}
- formValues={
- values.additionalResources[index]
- }
- policyType={
- policyId
- ? policyData.policyType
- : policyType
- }
- name={name}
- isMultiResources={isMultiResources}
- />
+ <FieldArray name="additionalResources">
+ {({ fields }) =>
+ fields.map((name, index) => (
+ <Row
+ className="resource-block"
+ key={`${name}-${index}`}
+ >
+ <Col md={8}>
+ <ResourceComp
+ serviceDetails={serviceDetails}
+ serviceCompDetails={serviceCompDetails}
+ formValues={
+ values.additionalResources[index]
+ }
+ policyType={
+ policyId
+ ? policyData.policyType
+ : policyType
+ }
+ name={name}
+ isMultiResources={isMultiResources}
+ />
+ </Col>
+ {values.additionalResources.length > 1 && (
+ <Col md={4}>
+ <Button
+ variant="danger"
+ size="sm"
+ title="Remove"
+ onClick={() => fields.remove(index)}
+ data-action="delete"
+ data-cy="delete"
+ >
+ <i className="fa-fw fa fa-remove"></i>
+ </Button>
</Col>
- {values.additionalResources.length > 1 && (
- <Col md={4}>
- <Button
- variant="danger"
- size="sm"
- title="Remove"
- onClick={() => fields.remove(index)}
- data-action="delete"
- data-cy="delete"
- >
- <i className="fa-fw fa fa-remove"></i>
- </Button>
- </Col>
- )}
- </Row>
- ))
+ )}
+ </Row>
+ ))
+ }
+ </FieldArray>
+ <div className="wrap">
+ <Button
+ type="button"
+ className="btn-mini"
+ onClick={() =>
+ addPolicyItem("additionalResources", {})
}
- </FieldArray>
- <div className="wrap">
- <Button
- type="button"
- className="btn-mini"
- onClick={() =>
- addPolicyItem("additionalResources", {})
- }
- data-action="addTime"
- data-cy="addTime"
- >
- <i className="fa-fw fa fa-plus"></i> Add Resource
- </Button>
- </div>
- </>
+ data-action="addTime"
+ data-cy="addTime"
+ >
+ <i className="fa-fw fa fa-plus"></i> Add Resource
+ </Button>
+ </div>
</>
- )}
- {/*----------------------- Policy Item --------------------------- */}
- {values.policyType == 0 ? (
+ </>
+ )}
+ {/*----------------------- Policy Item --------------------------- */}
+ {values.policyType == 0 ? (
+ <div>
<div>
- <div>
- <Accordion defaultActiveKey="0">
- <>
- <p className="formHeader">
- Allow Rules:{" "}
- <CustomToggle eventKey="0"></CustomToggle>
- </p>
- <Accordion.Collapse eventKey="0">
- <>
- <div className="wrap">
- <PolicyPermissionItem
- serviceDetails={serviceDetails}
- serviceCompDetails={serviceCompDetails}
- formValues={values}
- addPolicyItem={addPolicyItem}
- attrName="policyItems"
- fetchUsersData={fetchUsersData}
- fetchGroupsData={fetchGroupsData}
- fetchRolesData={fetchRolesData}
- changePolicyItemPermissions={
- changePolicyItemPermissions
- }
- isMultiResources={isMultiResources}
+ <Accordion defaultActiveKey="0">
+ <>
+ <p className="formHeader">
+ Allow Rules:{" "}
+ <CustomToggle eventKey="0"></CustomToggle>
+ </p>
+ <Accordion.Collapse eventKey="0">
+ <>
+ <div className="wrap">
+ <PolicyPermissionItem
+ serviceDetails={serviceDetails}
+ serviceCompDetails={serviceCompDetails}
+ formValues={values}
+ addPolicyItem={addPolicyItem}
+ attrName="policyItems"
+ fetchUsersData={fetchUsersData}
+ fetchGroupsData={fetchGroupsData}
+ fetchRolesData={fetchRolesData}
+ changePolicyItemPermissions={
+ changePolicyItemPermissions
+ }
+ isMultiResources={isMultiResources}
+ />
+ </div>
+ {serviceCompDetails?.options
+ ?.enableDenyAndExceptionsInPolicies ==
+ "true" && (
+ <>
+ <fieldset>
+ <p className="wrap-header search-header">
+ <i className="fa-fw fa fa-exclamation-triangle fa-fw fa fa-1 text-color-red"></i>
+ Exclude from Allow Rules:
+ </p>
+ </fieldset>
+ <div className="wrap">
+ <PolicyPermissionItem
+ serviceDetails={serviceDetails}
+ serviceCompDetails={serviceCompDetails}
+ formValues={values}
+ addPolicyItem={addPolicyItem}
+ attrName="allowExceptions"
+ fetchUsersData={fetchUsersData}
+ fetchGroupsData={fetchGroupsData}
+ fetchRolesData={fetchRolesData}
+ changePolicyItemPermissions={
+ changePolicyItemPermissions
+ }
+ isMultiResources={isMultiResources}
+ />
+ </div>
+ </>
+ )}
+ </>
+ </Accordion.Collapse>
+ </>
+ </Accordion>
+ </div>
+ {serviceCompDetails?.options
+ ?.enableDenyAndExceptionsInPolicies == "true" && (
+ <>
+ <Field
+ className="form-control"
+ name="isDenyAllElse"
+ render={({ input }) => (
+ <FormB.Group
+ as={Row}
+ className="mb-3"
+ controlId="isDenyAllElse"
+ >
+ <FormB.Label column sm={2}>
+ Deny All Other Accesses: *
+ </FormB.Label>
+ <Col sm={1}>
+ <span style={{ verticalAlign: "sub" }}>
+ <BootstrapSwitchButton
+ {...input}
+ checked={input.value}
+ onlabel="True"
+ onstyle="primary"
+ offlabel="False"
+ offstyle="outline-secondary"
+ size="xs"
+ style="w-100"
+ key="isDenyAllElse"
/>
- </div>
- {serviceCompDetails?.options
- ?.enableDenyAndExceptionsInPolicies ==
- "true" && (
+ </span>
+ </Col>
+ </FormB.Group>
+ )}
+ />
+ <Condition when="isDenyAllElse" is={false}>
+ <div>
+ <Accordion defaultActiveKey="0">
+ <>
+ <p className="formHeader">
+ Deny Rules:
+ <CustomToggle eventKey="0"></CustomToggle>
+ </p>
+ <Accordion.Collapse eventKey="0">
<>
+ <div className="wrap">
+ <PolicyPermissionItem
+ serviceDetails={serviceDetails}
+ serviceCompDetails={
+ serviceCompDetails
+ }
+ formValues={values}
+ addPolicyItem={addPolicyItem}
+ attrName="denyPolicyItems"
+ fetchUsersData={fetchUsersData}
+ fetchGroupsData={fetchGroupsData}
+ fetchRolesData={fetchRolesData}
+ changePolicyItemPermissions={
+ changePolicyItemPermissions
+ }
+ isMultiResources={isMultiResources}
+ />
+ </div>
<fieldset>
<p className="wrap-header search-header">
<i className="fa-fw fa fa-exclamation-triangle fa-fw fa fa-1 text-color-red"></i>
- Exclude from Allow Rules:
+ Exclude from Deny Rules:
</p>
</fieldset>
<div className="wrap">
@@ -1711,7 +1692,7 @@ export default function AddUpdatePolicyForm() {
}
formValues={values}
addPolicyItem={addPolicyItem}
- attrName="allowExceptions"
+ attrName="denyExceptions"
fetchUsersData={fetchUsersData}
fetchGroupsData={fetchGroupsData}
fetchRolesData={fetchRolesData}
@@ -1722,112 +1703,52 @@ export default function AddUpdatePolicyForm() {
/>
</div>
</>
- )}
+ </Accordion.Collapse>
</>
- </Accordion.Collapse>
- </>
- </Accordion>
- </div>
- {serviceCompDetails?.options
- ?.enableDenyAndExceptionsInPolicies == "true" && (
- <>
- <Field
- className="form-control"
- name="isDenyAllElse"
- render={({ input }) => (
- <FormB.Group
- as={Row}
- className="mb-3"
- controlId="isDenyAllElse"
- >
- <FormB.Label column sm={2}>
- Deny All Other Accesses: *
- </FormB.Label>
- <Col sm={1}>
- <span style={{ verticalAlign: "sub" }}>
- <BootstrapSwitchButton
- {...input}
- checked={input.value}
- onlabel="True"
- onstyle="primary"
- offlabel="False"
- offstyle="outline-secondary"
- size="xs"
- style="w-100"
- key="isDenyAllElse"
- />
- </span>
- </Col>
- </FormB.Group>
- )}
- />
- <Condition when="isDenyAllElse" is={false}>
- <div>
- <Accordion defaultActiveKey="0">
- <>
- <p className="formHeader">
- Deny Rules:
- <CustomToggle eventKey="0"></CustomToggle>
- </p>
- <Accordion.Collapse eventKey="0">
- <>
- <div className="wrap">
- <PolicyPermissionItem
- serviceDetails={serviceDetails}
- serviceCompDetails={
- serviceCompDetails
- }
- formValues={values}
- addPolicyItem={addPolicyItem}
- attrName="denyPolicyItems"
- fetchUsersData={fetchUsersData}
- fetchGroupsData={fetchGroupsData}
- fetchRolesData={fetchRolesData}
- changePolicyItemPermissions={
- changePolicyItemPermissions
- }
- isMultiResources={isMultiResources}
- />
- </div>
- <fieldset>
- <p className="wrap-header search-header">
- <i className="fa-fw fa fa-exclamation-triangle fa-fw fa fa-1 text-color-red"></i>
- Exclude from Deny Rules:
- </p>
- </fieldset>
- <div className="wrap">
- <PolicyPermissionItem
- serviceDetails={serviceDetails}
- serviceCompDetails={
- serviceCompDetails
- }
- formValues={values}
- addPolicyItem={addPolicyItem}
- attrName="denyExceptions"
- fetchUsersData={fetchUsersData}
- fetchGroupsData={fetchGroupsData}
- fetchRolesData={fetchRolesData}
- changePolicyItemPermissions={
- changePolicyItemPermissions
- }
- isMultiResources={isMultiResources}
- />
- </div>
- </>
- </Accordion.Collapse>
- </>
- </Accordion>
+ </Accordion>
+ </div>
+ </Condition>
+ </>
+ )}
+ </div>
+ ) : values.policyType == 1 ? (
+ <div>
+ <Accordion defaultActiveKey="0">
+ <>
+ <p className="formHeader">
+ Mask Rules:
+ <CustomToggle eventKey="0"></CustomToggle>
+ </p>
+ <Accordion.Collapse eventKey="0">
+ <>
+ <div className="wrap">
+ <PolicyPermissionItem
+ serviceDetails={serviceDetails}
+ serviceCompDetails={serviceCompDetails}
+ formValues={values}
+ addPolicyItem={addPolicyItem}
+ attrName="dataMaskPolicyItems"
+ fetchUsersData={fetchUsersData}
+ fetchGroupsData={fetchGroupsData}
+ fetchRolesData={fetchRolesData}
+ changePolicyItemPermissions={
+ changePolicyItemPermissions
+ }
+ isMultiResources={isMultiResources}
+ />
</div>
- </Condition>
- </>
- )}
- </div>
- ) : values.policyType == 1 ? (
+ </>
+ </Accordion.Collapse>
+ </>
+ </Accordion>
+ </div>
+ ) : (
+ <div>
<div>
<Accordion defaultActiveKey="0">
<>
- <p className="formHeader">
- Mask Rules:
+ <p className="wrap-header search-header">
+ Row Filter Rules:
<CustomToggle eventKey="0"></CustomToggle>
</p>
<Accordion.Collapse eventKey="0">
@@ -1838,7 +1759,7 @@ export default function AddUpdatePolicyForm() {
serviceCompDetails={serviceCompDetails}
formValues={values}
addPolicyItem={addPolicyItem}
- attrName="dataMaskPolicyItems"
+ attrName="rowFilterPolicyItems"
fetchUsersData={fetchUsersData}
fetchGroupsData={fetchGroupsData}
fetchRolesData={fetchRolesData}
@@ -1853,142 +1774,107 @@ export default function AddUpdatePolicyForm() {
</>
</Accordion>
</div>
- ) : (
- <div>
- <div>
- <Accordion defaultActiveKey="0">
- <>
- <p className="wrap-header search-header">
- Row Filter Rules:
- <CustomToggle eventKey="0"></CustomToggle>
- </p>
- <Accordion.Collapse eventKey="0">
- <>
- <div className="wrap">
- <PolicyPermissionItem
- serviceDetails={serviceDetails}
- serviceCompDetails={serviceCompDetails}
- formValues={values}
- addPolicyItem={addPolicyItem}
- attrName="rowFilterPolicyItems"
- fetchUsersData={fetchUsersData}
- fetchGroupsData={fetchGroupsData}
- fetchRolesData={fetchRolesData}
- changePolicyItemPermissions={
- changePolicyItemPermissions
- }
- isMultiResources={isMultiResources}
- />
- </div>
- </>
- </Accordion.Collapse>
- </>
- </Accordion>
- </div>
- </div>
- )}
- <div className="row form-actions">
- <div className="col-md-9 offset-md-3">
- <Button
- onClick={(event) => {
- if (invalid) {
- forIn(errors, function (value, key) {
- if (
- has(errors, "policyName") ||
- resourceErrorCheck(errors, values)
- ) {
- let selector =
- document?.getElementById("isError") ||
- document?.getElementById(key) ||
- document?.querySelector(
- `input[name=${key}]`
- ) ||
- document?.querySelector(
- `input[id=${key}]`
- ) ||
- document?.querySelector(
- `span[className="invalid-field"]`
- );
- scrollToError(selector);
- } else {
- getValidatePolicyItems(errors?.[key]);
- }
- });
- }
- handleSubmit(event);
- }}
- variant="primary"
- size="sm"
- data-id="save"
- data-cy="save"
- >
- Save
- </Button>
+ </div>
+ )}
+ <div className="row form-actions">
+ <div className="col-md-9 offset-md-3">
+ <Button
+ onClick={(event) => {
+ if (invalid) {
+ forIn(errors, function (value, key) {
+ if (
+ has(errors, "policyName") ||
+ resourceErrorCheck(errors, values)
+ ) {
+ let selector =
+ document?.getElementById("isError") ||
+ document?.getElementById(key) ||
+ document?.querySelector(
+ `input[name=${key}]`
+ ) ||
+ document?.querySelector(`input[id=${key}]`) ||
+ document?.querySelector(
+ `span[className="invalid-field"]`
+ );
+ scrollToError(selector);
+ } else {
+ getValidatePolicyItems(errors?.[key]);
+ }
+ });
+ }
+ handleSubmit(event);
+ }}
+ variant="primary"
+ size="sm"
+ data-id="save"
+ data-cy="save"
+ >
+ Save
+ </Button>
+ <Button
+ variant="secondary"
+ type="button"
+ size="sm"
+ onClick={() => {
+ closeForm();
+ }}
+ data-id="cancel"
+ data-cy="cancel"
+ >
+ Cancel
+ </Button>
+
+ {policyId !== undefined && (
<Button
- variant="secondary"
+ variant="danger"
type="button"
+ className="btn-sm"
size="sm"
onClick={() => {
- closeForm();
+ showDeleteModal();
}}
- data-id="cancel"
- data-cy="cancel"
>
- Cancel
+ Delete
</Button>
+ )}
+ </div>
+ {policyId !== undefined && (
+ <Modal show={showDelete} onHide={hideDeleteModal}>
+ <Modal.Header closeButton>
+ <span className="text-word-break">
+ Are you sure want to delete policy "
+ <b>{`${values?.policyName}`}</b>" ?
+ </span>
+ </Modal.Header>
- {policyId !== undefined && (
+ <Modal.Footer>
<Button
- variant="danger"
- type="button"
- className="btn-sm"
+ variant="secondary"
size="sm"
- onClick={() => {
- showDeleteModal();
- }}
+ title="Cancel"
+ onClick={hideDeleteModal}
>
- Delete
+ Cancel
</Button>
- )}
- </div>
- {policyId !== undefined && (
- <Modal show={showDelete} onHide={hideDeleteModal}>
- <Modal.Header closeButton>
- <span className="text-word-break">
- Are you sure want to delete policy "
- <b>{`${values?.policyName}`}</b>" ?
- </span>
- </Modal.Header>
-
- <Modal.Footer>
- <Button
- variant="secondary"
- size="sm"
- title="Cancel"
- onClick={hideDeleteModal}
- >
- Cancel
- </Button>
- <Button
- variant="primary"
- size="sm"
- title="Yes"
- onClick={() =>
- handleDeleteClick(policyId, serviceId)
- }
- >
- Yes
- </Button>
- </Modal.Footer>
- </Modal>
- )}
- </div>
- </form>
- </>
- )}
- />
- <BlockUi isUiBlock={blockUI} />
- </div>
+ <Button
+ variant="primary"
+ size="sm"
+ title="Yes"
+ onClick={() =>
+ handleDeleteClick(policyId, serviceId)
+ }
+ >
+ Yes
+ </Button>
+ </Modal.Footer>
+ </Modal>
+ )}
+ </div>
+ </form>
+ </>
+ )}
+ />
+ <BlockUi isUiBlock={blockUI} />
</div>
)}
</>
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/CreateNewPolicyForm.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/CreateNewPolicyForm.jsx
new file mode 100644
index 000000000..44abb6324
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/CreateNewPolicyForm.jsx
@@ -0,0 +1,661 @@
+/*
+ * 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 React, { useState } from "react";
+import { useNavigate } from "react-router-dom";
+import { toast } from "react-toastify";
+import { getServiceDef } from "Utils/appState";
+import { fetchApi } from "Utils/fetchAPI";
+import {
+ getResourcesDefVal,
+ prunePolicyItemAccessesToAllowedTypes
+} from "Utils/XAUtils";
+import { isEmpty, isArray, map, reject, groupBy } from "lodash";
+import moment from "moment";
+import StepperForm from "../../../components/StepperFormComponents";
+import CustomBreadcrumb from "../../CustomBreadcrumb";
+import { BlockUi } from "Components/CommonComponents";
+import { RangerPolicyType } from "Utils/XAEnums";
+import {
+ validatePolicyItems,
+ validatePolicyDetails,
+ hasMissingAccessPermissionOnPolicyItems
+} from "./policyFormValidation";
+import ServiceStep from "./PolicyCreateStepperStepComp/ServiceStep";
+import ResourcesStep from "./PolicyCreateStepperStepComp/ResourcesStep";
+import AccessRulesStep from "./PolicyCreateStepperStepComp/AccessRulesStep";
+import PolicyDetailsStep from "./PolicyCreateStepperStepComp/PolicyDetailsStep";
+import ReviewConfirmStep from "./PolicyCreateStepperStepComp/ReviewConfirmStep";
+
+const CreateNewPolicyForm = () => {
+ const navigate = useNavigate();
+ const [selectedServiceComponentDef, setSelectedServiceComponentDef] =
+ useState({});
+ const [blockUI, setBlockUI] = useState(false);
+ const [preventUnBlock, setPreventUnBlock] = useState(false);
+
+ // Function to get service def by service type
+ const handleServiceTypeChange = (serviceType) => {
+ if (serviceType) {
+ const { allServiceDefs } = getServiceDef();
+ const serviceDef = allServiceDefs.find(
+ (def) => def.name === serviceType.value
+ );
+ setSelectedServiceComponentDef(serviceDef || {});
+ } else {
+ setSelectedServiceComponentDef({});
+ }
+ };
+
+ // Transform policy items to API format
+ const getPolicyItemsVal = (formData, name) => {
+ if (!formData[name] || formData[name].length === 0) {
+ return [];
+ }
+
+ const policyResourceItem = [];
+ for (let key of formData[name]) {
+ if (!isEmpty(key) && Object.entries(key).length > 0) {
+ let obj = {};
+
+ // Delegate Admin
+ if (key.delegateAdmin != "undefined" && key.delegateAdmin != null) {
+ obj.delegateAdmin = key.delegateAdmin;
+ } else {
+ if (
+ RangerPolicyType.RANGER_ACCESS_POLICY_TYPE.value ==
+ formData?.policyType &&
+ formData?.serviceType?.value != "tag"
+ ) {
+ obj.delegateAdmin = false;
+ }
+ }
+
+ // Accesses (permissions) - handle both regular and tag-based
+ if (key?.accesses) {
+ // For tag-based policies with tableList structure
+ if (key.accesses.tableList && isArray(key.accesses.tableList)) {
+ obj.accesses = key.accesses.tableList.flatMap((tableItem) => {
+ if (tableItem.permission && isArray(tableItem.permission)) {
+ return tableItem.permission.map((perm) => ({
+ type: perm,
+ isAllowed: true
+ }));
+ }
+ return [];
+ });
+ }
+ // For regular policies with array of accesses
+ else if (isArray(key.accesses) && key.accesses.length > 0) {
+ obj.accesses = key.accesses.map((access) => {
+ // Handle if access is already in correct format {type: "read", isAllowed: true}
+ if (access.type && access.isAllowed !== undefined) {
+ return {
+ type: access.type,
+ isAllowed: access.isAllowed
+ };
+ }
+ // Handle if access is object with value property
+ return {
+ type:
+ typeof access === "object" && access.value
+ ? access.value
+ : access.type || access,
+ isAllowed: true
+ };
+ });
+ }
+ }
+
+ // Resolve a stored principal object to its plain name string.
+ // Items are stored as { value: "USER:admin", name: "admin", type: "USER" }.
+ // We always prefer .name; fall back to stripping the "TYPE:" prefix from .value.
+ const principalName = (p) => {
+ if (typeof p !== "object") return p;
+ if (p.name) return p.name;
+ if (p.value) {
+ const colonIdx = p.value.indexOf(":");
+ return colonIdx !== -1 ? p.value.slice(colonIdx + 1) : p.value;
+ }
+ return p;
+ };
+
+ // Users
+ if (key.users) {
+ if (isArray(key.users)) {
+ obj.users = key.users.map(principalName);
+ } else if (key.users.users && isArray(key.users.users)) {
+ obj.users = key.users.users.map(principalName);
+ }
+ }
+
+ // Groups
+ if (
+ key.users?.groups &&
+ isArray(key.users.groups) &&
+ key.users.groups.length > 0
+ ) {
+ obj.groups = key.users.groups.map(principalName);
+ } else if (key.groups && isArray(key.groups) && key.groups.length > 0) {
+ obj.groups = key.groups.map(principalName);
+ }
+
+ // Roles
+ if (
+ key.users?.roles &&
+ isArray(key.users.roles) &&
+ key.users.roles.length > 0
+ ) {
+ obj.roles = key.users.roles.map(principalName);
+ } else if (key.roles && isArray(key.roles) && key.roles.length > 0) {
+ obj.roles = key.roles.map(principalName);
+ }
+
+ // Row Filter Info (for row filter policies)
+ if (
+ key.rowFilterInfo != "undefined" &&
+ key.rowFilterInfo != null &&
+ key.rowFilterInfo !== ""
+ ) {
+ obj.rowFilterInfo = {};
+ // If it's already an object with filterExpr
+ if (
+ typeof key.rowFilterInfo === "object" &&
+ key.rowFilterInfo.filterExpr
+ ) {
+ obj.rowFilterInfo.filterExpr = key.rowFilterInfo.filterExpr;
+ } else {
+ // If it's a string, use it directly as filterExpr
+ obj.rowFilterInfo.filterExpr = key.rowFilterInfo;
+ }
+ }
+
+ // Data Mask Info (for masking policies)
+ if (
+ key.dataMaskInfo != "undefined" &&
+ key.dataMaskInfo != null &&
+ !isEmpty(key.dataMaskInfo)
+ ) {
+ obj.dataMaskInfo = {};
+
+ // Handle if dataMaskInfo is an object with value property
+ if (typeof key.dataMaskInfo === "object") {
+ obj.dataMaskInfo.dataMaskType =
+ key.dataMaskInfo.value || key.dataMaskInfo.dataMaskType;
+
+ // Include valueExpr for custom masking
+ if (key.dataMaskInfo.valueExpr) {
+ obj.dataMaskInfo.valueExpr = key.dataMaskInfo.valueExpr;
+ }
+ } else {
+ // Handle if dataMaskInfo is a string
+ obj.dataMaskInfo.dataMaskType = key.dataMaskInfo;
+ }
+ }
+
+ // Conditions (rule-level conditions)
+ if (key?.conditions && !isEmpty(key.conditions)) {
+ obj.conditions = [];
+ Object.entries(key.conditions).map(
+ ([conditionKey, conditionValue]) => {
+ if (conditionValue != "" && conditionValue != null) {
+ return obj.conditions.push({
+ type: conditionKey,
+ values: isArray(conditionValue)
+ ? conditionValue.map((m) =>
+ typeof m === "object" && m.value ? m.value : m
+ )
+ : [conditionValue]
+ });
+ }
+ return null;
+ }
+ );
+ }
+
+ policyResourceItem.push(obj);
+ }
+ }
+
+ return policyResourceItem;
+ };
+
+ const handleSubmit = async (values) => {
+ if (hasMissingAccessPermissionOnPolicyItems(values)) {
+ toast.error(
+ "Please select a policy permission for each access rule in the Access Rule step. This is required to assign permissions to the specified resources."
+ );
+ return;
+ }
+ try {
+ setBlockUI(true);
+ let data = {};
+
+ // Policy Items (Allow Conditions)
+ data.policyItems = getPolicyItemsVal(values, "policyItems");
+ data.allowExceptions = getPolicyItemsVal(values, "allowExceptions");
+
+ // Deny Policy Items
+ if (values?.isDenyAllElse) {
+ data.denyPolicyItems = [];
+ data.denyExceptions = [];
+ } else {
+ data.denyPolicyItems = getPolicyItemsVal(values, "denyPolicyItems");
+ data.denyExceptions = getPolicyItemsVal(values, "denyExceptions");
+ }
+
+ // Masking and Row Filter Policy Items
+ data.dataMaskPolicyItems = getPolicyItemsVal(
+ values,
+ "dataMaskPolicyItems"
+ );
+ data.rowFilterPolicyItems = getPolicyItemsVal(
+ values,
+ "rowFilterPolicyItems"
+ );
+
+ // Basic policy fields
+ data.name = values.policyName;
+ data.description = values.description || "";
+ data.isAuditEnabled =
+ values.isAuditEnabled !== false ? true : values.isAuditEnabled;
+ data.isEnabled = values.isEnabled !== false ? true : values.isEnabled;
+ data.isDenyAllElse = values.isDenyAllElse || false;
+ data.policyPriority = values.policyPriority === 1 ? 1 : 0;
+ data.policyType = values.policyType || 0;
+
+ // Service name - extract from serviceName object
+ data.service = values?.serviceName?.value;
+
+ // Policy Labels
+ if (values.policyLabels && isArray(values.policyLabels)) {
+ data.policyLabels = values.policyLabels.map((label) =>
+ typeof label === "object" ? label.value || label.label : label
+ );
+ }
+
+ // Get resource definitions
+ let serviceCompRes;
+ if (values.policyType != null) {
+ serviceCompRes = getResourcesDefVal(
+ selectedServiceComponentDef,
+ values.policyType
+ );
+ }
+
+ const grpResources = groupBy(serviceCompRes || [], "level");
+ let grpResourcesKeys = [];
+ for (const resourceKey in grpResources) {
+ grpResourcesKeys.push(+resourceKey);
+ }
+ grpResourcesKeys = grpResourcesKeys.sort();
+
+ // Process resources (multi-resource support)
+ data.resources = {};
+ data.additionalResources = [];
+
+ if (values.additionalResources && values.additionalResources.length > 0) {
+ map(values.additionalResources, (resourceValue) => {
+ let additionalResourcesObj = {};
+ for (const level of grpResourcesKeys) {
+ if (
+ resourceValue[`resourceName-${level}`] &&
+ resourceValue[`value-${level}`] &&
+ !isEmpty(resourceValue[`value-${level}`])
+ ) {
+ let defObj = serviceCompRes.find(function (m) {
+ return m.name == resourceValue[`resourceName-${level}`].name;
+ });
+
+ if (defObj) {
+ additionalResourcesObj[
+ resourceValue[`resourceName-${level}`].name
+ ] = {
+ values: isArray(resourceValue[`value-${level}`])
+ ? resourceValue[`value-${level}`].map((v) => v.value || v)
+ : [
+ resourceValue[`value-${level}`].value ||
+ resourceValue[`value-${level}`]
+ ]
+ };
+
+ if (defObj?.excludesSupported) {
+ additionalResourcesObj[
+ resourceValue[`resourceName-${level}`].name
+ ]["isExcludes"] =
+ defObj.excludesSupported &&
+ resourceValue[`isExcludesSupport-${level}`] == false;
+ }
+ if (defObj?.recursiveSupported) {
+ additionalResourcesObj[
+ resourceValue[`resourceName-${level}`].name
+ ]["isRecursive"] =
+ defObj.recursiveSupported &&
+ !(resourceValue[`isRecursiveSupport-${level}`] === false);
+ }
+ }
+ }
+ }
+ if (!isEmpty(additionalResourcesObj)) {
+ data.additionalResources.push(additionalResourcesObj);
+ }
+ });
+ }
+
+ // Move first resource to data.resources
+ if (data?.additionalResources?.length > 0) {
+ data.additionalResources = reject(data.additionalResources, isEmpty);
+ data.resources = data.additionalResources[0];
+ data.additionalResources.shift();
+ }
+
+ // Remove empty resources
+ if (isEmpty(data.resources)) {
+ delete data.resources;
+ }
+
+ // Validity Schedules
+ if (values?.validitySchedules && values.validitySchedules.length > 0) {
+ data.validitySchedules = [];
+ values.validitySchedules.filter((val) => {
+ if (val) {
+ let timeObj = {};
+ if (val.startTime) {
+ timeObj.startTime = moment(val.startTime).format(
+ "YYYY/MM/DD HH:mm:ss"
+ );
+ }
+ if (val.endTime) {
+ timeObj.endTime = moment(val.endTime).format(
+ "YYYY/MM/DD HH:mm:ss"
+ );
+ }
+ if (val.timeZone) {
+ timeObj.timeZone = val.timeZone.id;
+ }
+ if (!isEmpty(timeObj)) {
+ data.validitySchedules.push(timeObj);
+ }
+ }
+ return null;
+ });
+ }
+
+ // Policy Conditions
+ if (values?.conditions && !isEmpty(values.conditions)) {
+ data.conditions = [];
+ Object.entries(values.conditions).map(([key, value]) => {
+ if (value != "" && value != null) {
+ return data.conditions.push({
+ type: key,
+ values: isArray(value) ? value : [value]
+ });
+ }
+ return null;
+ });
+ } else {
+ data.conditions = [];
+ }
+
+ // For zone policy
+ if (values?.zoneName?.value) {
+ data.zoneName = values?.zoneName?.label;
+ let zoneDetails = {};
+ zoneDetails["label"] = values?.zoneName?.value;
+ zoneDetails["value"] = values?.zoneName?.zoneId;
+ localStorage.setItem("zoneDetails", JSON.stringify(zoneDetails));
+ } else {
+ localStorage.removeItem("zoneDetails");
+ }
+
+ const getPolicyCount = await fetchApi({
+ url: "plugins/policies/count",
+ method: "GET",
+ params: {
+ serviceName: data.service,
+ policyType: data.policyType
+ }
+ });
+
+ // Create new policy
+ await fetchApi({
+ url: "plugins/policies",
+ method: "POST",
+ data: data
+ });
+
+ toast.success("Policy created successfully!");
+
+ // Navigate to policy listing page using service ID
+ const serviceId = values.serviceName?.serviceId;
+ const policyType = values.policyType || 0;
+ let tablePageData = {};
+ tablePageData["pageRecords"] = getPolicyCount.data;
+ tablePageData["pageSize"] = 25;
+ if (getPolicyCount.data % 25 == 0) {
+ tablePageData["totalPage"] = Math.ceil(getPolicyCount.data / 25) + 1;
+ } else {
+ tablePageData["totalPage"] = Math.ceil(getPolicyCount.data / 25);
+ }
+ setBlockUI(false);
+ setPreventUnBlock(true);
+ navigate(`/service/${serviceId}/policies/${policyType}`, {
+ state: { showLastPage: true, addPageData: tablePageData }
+ });
+ } catch (error) {
+ setBlockUI(false);
+ console.error("Error creating policy:", error);
+ let errorMsg = "Failed to create policy";
+ if (error?.response?.data?.msgDesc) {
+ errorMsg = `Error! ${error.response.data.msgDesc}`;
+ }
+ toast.error(errorMsg);
+ }
+ };
+
+ // Define the steps configuration
+ const steps = [
+ {
+ title: "Service",
+ subtitle: "Add service details",
+ component: (props) => (
+ <ServiceStep
+ {...props}
+ selectedServiceComponentDef={selectedServiceComponentDef}
+ onServiceTypeChange={handleServiceTypeChange}
+ />
+ ),
+ validate: (values) => {
+ const errors = {};
+ if (!values.serviceType) {
+ errors.serviceType = "Service Type is required";
+ }
+ if (!values.serviceName) {
+ errors.serviceName = "Service Name is required";
+ }
+ return errors;
+ }
+ },
+ {
+ title: "Resources",
+ subtitle: "Add resource details",
+ component: (props) => (
+ <ResourcesStep
+ {...props}
+ selectedServiceComponentDef={selectedServiceComponentDef}
+ />
+ ),
+ validate: (values) => {
+ const errors = {};
+
+ // Check if additionalResources array exists
+ if (
+ !values.additionalResources ||
+ values.additionalResources.length === 0
+ ) {
+ return errors; // Let the form handle this naturally
+ }
+
+ // Get resource definitions to know which fields are required
+ if (
+ !selectedServiceComponentDef ||
+ !selectedServiceComponentDef.resources
+ ) {
+ return errors;
+ }
+
+ const serviceCompRes = getResourcesDefVal(
+ selectedServiceComponentDef,
+ values.policyType || 0
+ );
+
+ const grpResources = groupBy(serviceCompRes || [], "level");
+ let grpResourcesKeys = [];
+ for (const resourceKey in grpResources) {
+ grpResourcesKeys.push(+resourceKey);
+ }
+ grpResourcesKeys = grpResourcesKeys.sort();
+
+ // Initialize errors for additionalResources array
+ errors.additionalResources = [];
+
+ // Validate each resource
+ values.additionalResources.forEach((resource, resourceIndex) => {
+ const resourceErrors = {};
+
+ if (!resource || typeof resource !== "object") {
+ return; // Skip invalid resources
+ }
+
+ // Check each resource level
+ grpResourcesKeys.forEach((levelKey) => {
+ const resourceNameKey = `resourceName-${levelKey}`;
+ const resourceValueKey = `value-${levelKey}`;
+
+ const resourceName = resource[resourceNameKey];
+ const resourceValue = resource[resourceValueKey];
+
+ // If resourceName is selected, check if value is required and provided
+ if (resourceName && resourceName.mandatory) {
+ if (!resourceValue || isEmpty(resourceValue)) {
+ resourceErrors[resourceValueKey] =
+ `${resourceName.label || "Resource"} value is required`;
+ }
+ }
+ });
+
+ // Add errors for this resource if any exist
+ if (Object.keys(resourceErrors).length > 0) {
+ errors.additionalResources[resourceIndex] = resourceErrors;
+ }
+ });
+
+ // Clean up empty error arrays
+ if (
+ errors.additionalResources &&
+ errors.additionalResources.every((item) => !item)
+ ) {
+ delete errors.additionalResources;
+ }
+
+ return errors;
+ }
+ },
+ {
+ title: "Access Rules",
+ subtitle: "Configure access rules",
+ component: (props) => (
+ <AccessRulesStep
+ {...props}
+ selectedServiceComponentDef={selectedServiceComponentDef}
+ />
+ ),
+ validate: validatePolicyItems
+ },
+ {
+ title: "Policy Details",
+ subtitle: "Add policy details",
+ component: PolicyDetailsStep,
+ componentProps: {
+ selectedServiceComponentDef
+ },
+ validate: validatePolicyDetails
+ },
+ {
+ title: "Review & Confirm",
+ subtitle: "Verify details",
+ component: ReviewConfirmStep,
+ componentProps: {
+ selectedServiceComponentDef
+ }
+ }
+ ];
+
+ return (
+ <>
+ <div className="header-wraper">
+ <h3 className="wrap-header bold">Policy Editor</h3>
+ <CustomBreadcrumb />
+ </div>
+ <div className="container-fluid p-xxl-4 p-xl-3 p-lg-2">
+ <div className="row">
+ <div className="col-md-12">
+ <div className="card">
+ <div className="card-body">
+ <h5 className="mb-3 mt-2">Create policy</h5>
+ <hr />
+ <StepperForm
+ steps={steps}
+ onSubmit={handleSubmit}
+ onBeforeNavigate={({ fromStep, form }) => {
+ if (fromStep === 1) {
+ prunePolicyItemAccessesToAllowedTypes(
+ form,
+ selectedServiceComponentDef
+ );
+ }
+ }}
+ initialValues={{
+ policyType: 0,
+ additionalResources: [{}], // Initialize with one empty resource
+ policyItems: [{}], // For allow conditions
+ allowExceptions: [{}], // For allow exceptions
+ denyPolicyItems: [{}], // For deny conditions
+ denyExceptions: [{}], // For deny exceptions
+ dataMaskPolicyItems: [{}], // For masking rules
+ rowFilterPolicyItems: [{}], // For row filter rules
+ isDenyAllElse: false, // For deny all toggle
+ isEnabled: true, // Policy enabled by default
+ isAuditEnabled: true, // Audit enabled by default
+ policyPriority: 0 // Normal priority by default
+ }}
+ blockUI={blockUI}
+ preventUnBlock={preventUnBlock}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ <BlockUi isUiBlock={blockUI} />
+ </div>
+ </>
+ );
+};
+
+export default CreateNewPolicyForm;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/EditNewPolicyForm/EditPolicyForm.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/EditNewPolicyForm/EditPolicyForm.jsx
new file mode 100644
index 000000000..fe3d1aadf
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/EditNewPolicyForm/EditPolicyForm.jsx
@@ -0,0 +1,954 @@
+/*
+ * 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 React, { useState, useEffect } from "react";
+import { useParams, useNavigate, useOutletContext } from "react-router-dom";
+import { Form } from "react-final-form";
+import arrayMutators from "final-form-arrays";
+import { toast } from "react-toastify";
+import { Loader, BlockUi, scrollToError } from "Components/CommonComponents";
+import { fetchApi } from "Utils/fetchAPI";
+import usePrompt from "Hooks/usePrompt";
+import {
+ getResourcesDefVal,
+ getAllTimeZoneList,
+ policyConditionUpdatedJSON,
+ isPolicyExpired,
+ policyInfo,
+ getAccessTypesByResource
+} from "Utils/XAUtils";
+import { RangerPolicyType } from "Utils/XAEnums";
+import {
+ isEmpty,
+ isArray,
+ find,
+ map,
+ groupBy,
+ has,
+ maxBy,
+ forIn,
+ includes
+} from "lodash";
+import moment from "moment";
+import {
+ Accordion,
+ Alert,
+ Badge,
+ Button,
+ Col,
+ Row,
+ Modal
+} from "react-bootstrap";
+import { validatePolicyForm } from "../policyFormValidation";
+import ResourcesStep from "../PolicyCreateStepperStepComp/ResourcesStep";
+import AccessRulesStep from "../PolicyCreateStepperStepComp/AccessRulesStep";
+import PolicyDetailsStep from "../PolicyCreateStepperStepComp/PolicyDetailsStep";
+
+// ─── helpers ─────────────────────────────────────────────────────────────────
+
+const PromptDialog = (props) => {
+ const { isDirtyField, isUnblock } = props;
+ usePrompt("Are you sure you want to leave", isDirtyField && !isUnblock);
+ return null;
+};
+
+const noneOptions = { label: "None", value: "none" };
+
+/** Convert API policy items into form state compatible with the new components */
+const setPolicyItemVal = (
+ formData,
+ accessTypes,
+ maskTypes,
+ serviceType,
+ serviceData,
+ finalAccessTypes
+) => {
+ return formData.map((val) => {
+ let obj = {};
+
+ if (has(val, "delegateAdmin")) {
+ obj.delegateAdmin = val.delegateAdmin;
+ }
+
+ // Accesses
+ if (serviceType === "tag") {
+ let accessTypesObj = [];
+ for (let i = 0; val.accesses.length > i; i++) {
+ accessTypes.map((opt) => {
+ if (val.accesses[i].type === opt.name) accessTypesObj.push(opt.name);
+ });
+ }
+ let tableList = [];
+ let tagAccessType = groupBy(accessTypesObj, (m) =>
+ m.substr(0, m.indexOf(":"))
+ );
+ for (let tagObjData in tagAccessType) {
+ tableList.push({
+ serviceName: tagObjData,
+ permission: tagAccessType[tagObjData]
+ });
+ }
+ obj.accesses = { tableList };
+ } else {
+ // New format: {type, isAllowed}
+ let accessTypesObj = [];
+ for (let i = 0; val?.accesses?.length > i; i++) {
+ finalAccessTypes.map((opt) => {
+ if (val.accesses[i].type === opt.value) {
+ accessTypesObj.push({ type: opt.value, isAllowed: true });
+ }
+ });
+ }
+ obj.accesses = accessTypesObj;
+ }
+
+ // Users / Groups / Roles – merge into UsersGroupsAndRolesSelectionComponent format
+ const toNormalisedPrincipal = (name, type) => ({
+ value: `${type}:${name}`,
+ name: name,
+ type: type
+ });
+
+ obj.users = {
+ users: (val?.users || []).map((u) => toNormalisedPrincipal(u, "USER")),
+ groups: (val?.groups || []).map((g) => toNormalisedPrincipal(g, "GROUP")),
+ roles: (val?.roles || []).map((r) => toNormalisedPrincipal(r, "ROLE"))
+ };
+
+ // Row filter
+ if (val?.rowFilterInfo?.filterExpr) {
+ obj.rowFilterInfo = val.rowFilterInfo.filterExpr;
+ }
+
+ // Data mask
+ if (val?.dataMaskInfo?.dataMaskType) {
+ obj.dataMaskInfo = {};
+ let maskDataType = maskTypes?.find(
+ (m) => m.name === val.dataMaskInfo.dataMaskType
+ );
+ if (maskDataType) {
+ obj.dataMaskInfo.label = maskDataType.label;
+ obj.dataMaskInfo.value = maskDataType.name;
+ }
+ if (val?.dataMaskInfo?.valueExpr)
+ obj.dataMaskInfo.valueExpr = val.dataMaskInfo.valueExpr;
+ }
+
+ // Conditions
+ if (val?.conditions?.length > 0) {
+ obj.conditions = {};
+ for (let data of val.conditions) {
+ let conditionObj = find(
+ policyConditionUpdatedJSON(serviceData?.policyConditions),
+ (m) => m.name === data.type
+ );
+ if (conditionObj && !isEmpty(conditionObj.uiHint)) {
+ obj.conditions[data.type] = JSON.parse(conditionObj.uiHint)
+ .isMultiValue
+ ? data.values
+ : data.values.toString().trim();
+ }
+ }
+ }
+
+ return obj;
+ });
+};
+
+/** Transform API response into React Final Form initial values */
+const generateFormData = (policyData, serviceCompData) => {
+ const data = {};
+ data.policyType = policyData?.policyType ?? 0;
+ // Basic fields
+ data.policyName = policyData?.name;
+ data.isEnabled = policyData?.isEnabled ?? true;
+ data.policyPriority = policyData?.policyPriority === 1 ? 1 : 0;
+ data.description = policyData?.description?.trim() ?? "";
+ data.isAuditEnabled = policyData?.isAuditEnabled ?? true;
+ data.isDenyAllElse = policyData?.isDenyAllElse ?? false;
+ data.policyLabels = (policyData?.policyLabels || []).map((v) => ({
+ label: v.trim(),
+ value: v.trim()
+ }));
+
+ // Resources (multi-resource)
+ let serviceCompResourcesDetails = getResourcesDefVal(
+ serviceCompData,
+ data.policyType
+ );
+ if (policyData.additionalResources || policyData.resources) {
+ policyData.additionalResources = [
+ policyData.resources,
+ ...(policyData.additionalResources || [])
+ ];
+ data.additionalResources = [];
+ map(policyData.additionalResources, function (resourceObj) {
+ let lastResourceLevel = [],
+ additionalResourcesObj = {};
+ Object.entries(resourceObj).map(([key, value]) => {
+ let setResources = find(serviceCompResourcesDetails, ["name", key]);
+ additionalResourcesObj[`resourceName-${setResources?.level}`] =
+ setResources;
+ additionalResourcesObj[`value-${setResources?.level}`] =
+ value.values.map((m) => {
+ return { label: m?.trim(), value: m?.trim() };
+ });
+ if (setResources?.excludesSupported) {
+ additionalResourcesObj[`isExcludesSupport-${setResources?.level}`] =
+ value.isExcludes == false;
+ }
+ if (setResources?.recursiveSupported) {
+ additionalResourcesObj[`isRecursiveSupport-${setResources?.level}`] =
+ value?.isRecursive;
+ }
+ lastResourceLevel.push({
+ level: setResources.level,
+ name: setResources.name
+ });
+ });
+ lastResourceLevel = maxBy(lastResourceLevel, "level");
+ let setLastResources = find(serviceCompResourcesDetails, [
+ "parent",
+ lastResourceLevel.name
+ ]);
+ if (setLastResources && setLastResources?.isValidLeaf) {
+ additionalResourcesObj[`resourceName-${setLastResources.level}`] = {
+ label: "None",
+ value: "none"
+ };
+ }
+ data.additionalResources.push(additionalResourcesObj);
+ });
+ }
+
+ // Validity schedules
+ if (policyData?.validitySchedules) {
+ data.validitySchedules = policyData.validitySchedules.map((val) => {
+ const obj = {};
+ if (val.startTime)
+ obj.startTime = moment(val.startTime, "YYYY/MM/DD HH:mm:ss");
+ if (val.endTime) obj.endTime = moment(val.endTime, "YYYY/MM/DD HH:mm:ss");
+ if (val.timeZone)
+ obj.timeZone = getAllTimeZoneList().find(
+ (tz) => tz.id === val.timeZone
+ );
+ return obj;
+ });
+ }
+
+ // Policy conditions
+ if (policyData?.conditions?.length > 0) {
+ data.conditions = {};
+ for (const val of policyData.conditions) {
+ const conditionObj = find(
+ policyConditionUpdatedJSON(serviceCompData?.policyConditions),
+ (m) => m.name === val.type
+ );
+ if (conditionObj && !isEmpty(conditionObj.uiHint)) {
+ data.conditions[val.type] = JSON.parse(conditionObj.uiHint).isMultiValue
+ ? val?.values
+ : val.values.toString().trim();
+ }
+ }
+ }
+
+ //permissions Item
+ const finalAccessTypes = getAccessTypesByResource(data, serviceCompData);
+
+ const policyItemOpts = (arr, accTypes, maskTypes, finalAccessTypes) =>
+ arr?.length > 0
+ ? setPolicyItemVal(
+ arr,
+ accTypes,
+ maskTypes,
+ serviceCompData?.name,
+ serviceCompData,
+ finalAccessTypes
+ )
+ : [{}];
+
+ data.policyItems = policyItemOpts(
+ policyData?.policyItems,
+ serviceCompData?.accessTypes,
+ null,
+ finalAccessTypes
+ );
+ data.allowExceptions = policyItemOpts(
+ policyData?.allowExceptions,
+ serviceCompData?.accessTypes,
+ null,
+ finalAccessTypes
+ );
+ data.denyPolicyItems = policyItemOpts(
+ policyData?.denyPolicyItems,
+ serviceCompData?.accessTypes,
+ null,
+ finalAccessTypes
+ );
+ data.denyExceptions = policyItemOpts(
+ policyData?.denyExceptions,
+ serviceCompData?.accessTypes,
+ null,
+ finalAccessTypes
+ );
+ data.dataMaskPolicyItems = policyItemOpts(
+ policyData?.dataMaskPolicyItems,
+ serviceCompData?.dataMaskDef?.accessTypes,
+ serviceCompData?.dataMaskDef?.maskTypes,
+ finalAccessTypes
+ );
+ data.rowFilterPolicyItems = policyItemOpts(
+ policyData?.rowFilterPolicyItems,
+ serviceCompData?.rowFilterDef?.accessTypes,
+ null,
+ finalAccessTypes
+ );
+
+ return data;
+};
+
+/** Resolve a stored principal object to its plain name */
+const principalName = (p) => {
+ if (typeof p !== "object") return p;
+ if (p.name) return p.name;
+ if (p.value) {
+ const idx = p.value.indexOf(":");
+ return idx !== -1 ? p.value.slice(idx + 1) : p.value;
+ }
+ return p;
+};
+
+/** Transform form policy items back to API format */
+const getPolicyItemsVal = (formData, name, finalAccessTypes) => {
+ if (!formData[name] || formData[name].length === 0) return [];
+ const result = [];
+
+ for (const key of formData[name]) {
+ if (!isEmpty(key) && Object.entries(key).length > 0) {
+ const obj = {};
+
+ if (key.delegateAdmin != null && key.delegateAdmin !== "undefined") {
+ obj.delegateAdmin = key.delegateAdmin;
+ }
+
+ // Accesses
+ if (key?.accesses?.tableList && isArray(key.accesses.tableList)) {
+ obj.accesses = key.accesses.tableList.flatMap((t) =>
+ (t.permission || []).map((p) => ({ type: p, isAllowed: true }))
+ );
+ } else if (isArray(key.accesses) && key.accesses.length > 0) {
+ const validValues = map(finalAccessTypes, "value");
+ const result = _.filter(key.accesses, (item) =>
+ includes(validValues, item.type)
+ );
+ obj.accesses = result.map((a) => {
+ return { type: a.type, isAllowed: a.isAllowed === true };
+ });
+ }
+
+ // Users / Groups / Roles (combined field from UsersGroupsAndRolesSelectionComponent)
+ if (key.users) {
+ if (isArray(key.users)) {
+ obj.users = key.users.map(principalName);
+ } else if (key.users.users && isArray(key.users.users)) {
+ obj.users = key.users.users.map(principalName);
+ if (key.users.groups?.length)
+ obj.groups = key.users.groups.map(principalName);
+ if (key.users.roles?.length)
+ obj.roles = key.users.roles.map(principalName);
+ }
+ }
+ if (!obj.groups && key.groups?.length)
+ obj.groups = key.groups.map(principalName);
+ if (!obj.roles && key.roles?.length)
+ obj.roles = key.roles.map(principalName);
+
+ // Row filter
+ if (
+ key.rowFilterInfo != null &&
+ key.rowFilterInfo !== "" &&
+ key.rowFilterInfo !== "undefined"
+ ) {
+ obj.rowFilterInfo = {
+ filterExpr:
+ typeof key.rowFilterInfo === "object"
+ ? key.rowFilterInfo.filterExpr
+ : key.rowFilterInfo
+ };
+ }
+
+ // Data mask
+ if (
+ key.dataMaskInfo != null &&
+ !isEmpty(key.dataMaskInfo) &&
+ key.dataMaskInfo !== "undefined"
+ ) {
+ obj.dataMaskInfo = {
+ dataMaskType: key.dataMaskInfo.value || key.dataMaskInfo.dataMaskType
+ };
+ if (key.dataMaskInfo.valueExpr)
+ obj.dataMaskInfo.valueExpr = key.dataMaskInfo.valueExpr;
+ }
+
+ // Rule conditions
+ if (key.conditions && !isEmpty(key.conditions)) {
+ obj.conditions = Object.entries(key.conditions)
+ .filter(([, v]) => v !== "" && v != null)
+ .map(([k, v]) => ({
+ type: k,
+ values: isArray(v)
+ ? v.map((m) => (typeof m === "object" ? m.value : m))
+ : [v]
+ }));
+ }
+
+ if (!isEmpty(obj)) result.push(obj);
+ }
+ }
+ return result;
+};
+
+// ─── main component ──────────────────────────────────────────────────────────
+
+export default function EditPolicyForm() {
+ const { serviceId, policyId } = useParams();
+ const navigate = useNavigate();
+
+ // Get data from PolicyFormContext
+ const contextData = useOutletContext();
+ const {
+ serviceDetails,
+ serviceCompDetails: serviceCompDef,
+ policyData
+ } = contextData;
+
+ const [blockUI, setBlockUI] = useState(false);
+ const [formData, setFormData] = useState({});
+ const [showDelete, setShowDelete] = useState(false);
+ const [preventUnBlock, setPreventUnblock] = useState(false);
+ const [showPolicyExpire, setShowPolicyExpire] = useState(true);
+ const [show, setShow] = useState(true);
+
+ useEffect(() => {
+ if (policyData && serviceCompDef) {
+ initializeFormData();
+ }
+ }, [policyData, serviceCompDef]);
+
+ const initializeFormData = () => {
+ try {
+ const fd = generateFormData(policyData, serviceCompDef);
+ // ResourcesStep reads values.serviceName; pass the plain name so it works without the stepper's service selector
+ fd.serviceName = serviceDetails.name;
+ setFormData(fd);
+ } catch (err) {
+ console.error("Error initializing edit policy form:", err);
+ toast.error("Failed to initialize policy data.");
+ }
+ };
+
+ // Helper functions for error handling and delete functionality
+ const showDeleteModal = () => {
+ setShowDelete(true);
+ };
+
+ const hideDeleteModal = () => {
+ setShowDelete(false);
+ };
+
+ const getValidatePolicyItems = (errors) => {
+ let errorField;
+ errors?.find((value) => {
+ if (value !== undefined) {
+ return (errorField = value);
+ }
+ });
+
+ return errorField !== undefined && errorField?.accesses
+ ? toast.error(errorField?.accesses, { toastId: "error1" })
+ : toast.error(errorField?.delegateAdmin, { toastId: "error1" });
+ };
+
+ const resourceErrorCheck = (errors) => {
+ if (errors?.additionalResources?.length > 0) {
+ return true;
+ }
+
+ return false;
+ };
+
+ const handleDeleteClick = async (policyID, serviceId) => {
+ hideDeleteModal();
+ try {
+ setPreventUnblock(true);
+ setBlockUI(true);
+ await fetchApi({
+ url: `plugins/policies/${policyID}`,
+ method: "DELETE"
+ });
+ setBlockUI(false);
+ toast.success("Success! Policy deleted successfully");
+ navigate(`/service/${serviceId}/policies/${policyData?.policyType || 0}`);
+ } catch (error) {
+ setBlockUI(false);
+ let errorMsg = `Error occurred during deleting policy`;
+ if (error?.response?.data?.msgDesc) {
+ errorMsg = error.response.data.msgDesc;
+ }
+ toast.error(errorMsg);
+ console.error(`Error occurred during deleting policy! ${error}`);
+ }
+ };
+
+ const handleSubmit = async (values) => {
+ try {
+ setPreventUnblock(true);
+ setBlockUI(true);
+
+ const data = {};
+ const finalAccessTypes = getAccessTypesByResource(values, serviceCompDef);
+ data.policyItems = getPolicyItemsVal(
+ values,
+ "policyItems",
+ finalAccessTypes
+ );
+ data.allowExceptions = getPolicyItemsVal(
+ values,
+ "allowExceptions",
+ finalAccessTypes
+ );
+ data.denyPolicyItems = values.isDenyAllElse
+ ? []
+ : getPolicyItemsVal(values, "denyPolicyItems", finalAccessTypes);
+ data.denyExceptions = values.isDenyAllElse
+ ? []
+ : getPolicyItemsVal(values, "denyExceptions", finalAccessTypes);
+ data.dataMaskPolicyItems = getPolicyItemsVal(
+ values,
+ "dataMaskPolicyItems",
+ finalAccessTypes
+ );
+ data.rowFilterPolicyItems = getPolicyItemsVal(
+ values,
+ "rowFilterPolicyItems",
+ finalAccessTypes
+ );
+
+ data.id = policyId;
+ data.name = values.policyName;
+ data.description = values.description || "";
+ data.isEnabled = values.isEnabled !== false;
+ data.isAuditEnabled = values.isAuditEnabled !== false;
+ data.isDenyAllElse = values.isDenyAllElse || false;
+ data.policyPriority = values.policyPriority === 1 ? 1 : 0;
+ data.policyType = values.policyType ?? 0;
+ data.service = serviceDetails?.name;
+ data.policyLabels = (values.policyLabels || []).map((l) =>
+ typeof l === "object" ? l.value || l.label : l
+ );
+
+ // Resources
+ const serviceCompRes =
+ getResourcesDefVal(serviceCompDef, data.policyType) || [];
+ const levels = [...new Set(serviceCompRes.map((r) => r.level))].sort(
+ (a, b) => a - b
+ );
+
+ data.additionalResources = [];
+ map(values.additionalResources || [], (resourceValue) => {
+ const obj = {};
+ for (const level of levels) {
+ const nameObj = resourceValue[`resourceName-${level}`];
+ const valArr = resourceValue[`value-${level}`];
+ if (
+ !nameObj ||
+ nameObj.value === noneOptions.value ||
+ !valArr ||
+ isEmpty(valArr)
+ )
+ continue;
+
+ const defObj = find(
+ serviceCompRes,
+ (m) => m.name === (nameObj.name || nameObj.value)
+ );
+ const resName = nameObj.name || nameObj.value;
+ obj[resName] = {
+ values: isArray(valArr)
+ ? valArr.map((v) => v.value || v)
+ : [valArr.value || valArr]
+ };
+ if (defObj?.excludesSupported) {
+ obj[resName].isExcludes =
+ defObj.excludesSupported &&
+ resourceValue[`isExcludesSupport-${level}`] === false;
+ }
+ if (defObj?.recursiveSupported) {
+ obj[resName].isRecursive =
+ defObj.recursiveSupported &&
+ resourceValue[`isRecursiveSupport-${level}`] !== false;
+ }
+ }
+ if (!isEmpty(obj)) data.additionalResources.push(obj);
+ });
+
+ if (data.additionalResources.length > 0) {
+ data.resources = data.additionalResources[0];
+ data.additionalResources = data.additionalResources.slice(1);
+ }
+
+ // Validity schedules
+ if (values.validitySchedules?.length > 0) {
+ data.validitySchedules = values.validitySchedules
+ .filter(Boolean)
+ .map((s) => ({
+ startTime: s.startTime
+ ? moment(s.startTime).format("YYYY/MM/DD HH:mm:ss")
+ : "",
+ endTime: s.endTime
+ ? moment(s.endTime).format("YYYY/MM/DD HH:mm:ss")
+ : "",
+ timeZone: s.timeZone?.id || ""
+ }));
+ } else {
+ data["validitySchedules"] = [];
+ }
+
+ // Policy conditions
+ if (values.conditions && !isEmpty(values.conditions)) {
+ data.conditions = Object.entries(values.conditions)
+ .filter(([, v]) => v !== "" && v != null)
+ .map(([k, v]) => ({
+ type: k,
+ values: isArray(v)
+ ? v.map((m) => (typeof m === "object" ? m.value : m))
+ : [v]
+ }));
+ } else {
+ data["conditions"] = [];
+ }
+
+ /* For create zone policy */
+ if (localStorage.getItem("zoneDetails") != null) {
+ data["zoneName"] = JSON.parse(
+ localStorage.getItem("zoneDetails")
+ ).label;
+ }
+
+ const mergeFormData = {
+ ...policyData,
+ ...data
+ };
+
+ await fetchApi({
+ url: `plugins/policies/${policyId}`,
+ method: "PUT",
+ data: mergeFormData
+ });
+
+ toast.success("Policy updated successfully!");
+ setBlockUI(false);
+ navigate(`/service/${serviceId}/policies/${formData.policyType ?? 0}`);
+ } catch (err) {
+ setBlockUI(false);
+ const msg = err?.response?.data?.msgDesc || "Failed to update policy.";
+ toast.error(`Error! ${msg}`);
+ }
+ };
+
+ const handleCancel = () => {
+ navigate(`/service/${serviceId}/policies/${formData.policyType ?? 0}`);
+ };
+
+ if (
+ !serviceDetails ||
+ !serviceCompDef ||
+ !policyData ||
+ !formData.policyName
+ ) {
+ return <Loader />;
+ }
+
+ const policyTypeLabel =
+ formData.policyType === 1
+ ? "Masking"
+ : formData.policyType === 2
+ ? "Row Filter"
+ : "Access";
+ const policyTypeBg =
+ formData.policyType === 1
+ ? "warning"
+ : formData.policyType === 2
+ ? "info"
+ : "primary";
+
+ return (
+ <>
+ <div className="wrap">
+ <Form
+ onSubmit={handleSubmit}
+ mutators={{ ...arrayMutators }}
+ initialValues={formData}
+ validate={validatePolicyForm}
+ render={({
+ handleSubmit: submitForm,
+ values,
+ form,
+ invalid,
+ errors,
+ dirty,
+ pristine
+ }) => (
+ <form onSubmit={submitForm} noValidate>
+ <PromptDialog
+ isDirtyField={dirty && !pristine}
+ isUnblock={preventUnBlock}
+ />
+
+ {(values.policyType ==
+ RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value ||
+ values.policyType ==
+ RangerPolicyType.RANGER_ROW_FILTER_POLICY_TYPE.value) &&
+ show && (
+ <Alert
+ variant="warning"
+ onClose={() => setShow(false)}
+ dismissible
+ data-js="policyInfoAlert"
+ data-cy="policyInfoAlert"
+ >
+ <i className="fa-fw fa fa-info-circle d-inline text-dark"></i>
+ {policyInfo(values.policyType, serviceCompDef.name)}
+ </Alert>
+ )}
+
+ {policyId &&
+ !isEmpty(policyData?.validitySchedules) &&
+ isPolicyExpired(policyData) &&
+ showPolicyExpire && (
+ <Alert
+ variant="danger"
+ onClose={() => setShowPolicyExpire(false)}
+ dismissible
+ >
+ <i className="fa fa-clock-o fa-fw fa-lg time-clock" />
+ <p className="pd-l-6 d-inline"> Policy Expired</p>
+ </Alert>
+ )}
+
+ {/* Policy name + type badge */}
+ <fieldset>
+ <p className="formHeader" style={{ fontSize: "16px" }}>
+ {values.policyName}
+ <span
+ className="text-muted"
+ style={{ fontSize: "16px", fontWeight: "normal" }}
+ >
+ (id: {policyId})
+ </span>
+ </p>
+ </fieldset>
+
+ <Accordion
+ defaultActiveKey={["service", "resources", "access", "details"]}
+ alwaysOpen
+ className="policy-permission-items-accordion"
+ >
+ {/* ── Service ──────────────────────────────────── */}
+ <Accordion.Item eventKey="service">
+ <Accordion.Header>Service</Accordion.Header>
+ <Accordion.Body>
+ <Row className="user-role-grp-form">
+ <Col md={5}>
+ <Row className="mb-2">
+ <Col sm={4} className="text-end fnt-14">
+ Service :
+ </Col>
+ <Col sm={8}>{serviceDetails?.name}</Col>
+ </Row>
+ <Row className="mb-2">
+ <Col sm={4} className="text-end fnt-14">
+ Service Type :
+ </Col>
+ <Col sm={8}>{serviceDetails?.type}</Col>
+ </Row>
+ {serviceDetails?.zoneName && (
+ <Row className="mb-2">
+ <Col sm={4} className="text-end fnt-14">
+ Security Zone :
+ </Col>
+ <Col sm={8}>{serviceDetails.zoneName}</Col>
+ </Row>
+ )}
+ <Row className="mb-2">
+ <Col sm={4} className="text-end fnt-14">
+ policy Type :
+ </Col>
+ <Col sm={8}>
+ <Badge
+ bg={policyTypeBg}
+ text={
+ formData.policyType === 1 ? "dark" : undefined
+ }
+ >
+ {policyTypeLabel}
+ </Badge>
+ </Col>
+ </Row>
+ </Col>
+ </Row>
+ </Accordion.Body>
+ </Accordion.Item>
+
+ {/* ── Resources ────────────────────────────────── */}
+ <Accordion.Item eventKey="resources">
+ <Accordion.Header>Resources</Accordion.Header>
+ <Accordion.Body>
+ <ResourcesStep
+ values={values}
+ form={form}
+ selectedServiceComponentDef={serviceCompDef}
+ />
+ </Accordion.Body>
+ </Accordion.Item>
+
+ {/* ── Access Rules ─────────────────────────────── */}
+ <Accordion.Item eventKey="access">
+ <Accordion.Header>Access rules</Accordion.Header>
+ <Accordion.Body>
+ <AccessRulesStep
+ values={values}
+ form={form}
+ selectedServiceComponentDef={serviceCompDef}
+ />
+ </Accordion.Body>
+ </Accordion.Item>
+
+ {/* ── Policy Details ───────────────────────────── */}
+ <Accordion.Item eventKey="details">
+ <Accordion.Header>Policy details</Accordion.Header>
+ <Accordion.Body>
+ <PolicyDetailsStep
+ values={values}
+ form={form}
+ selectedServiceComponentDef={serviceCompDef}
+ />
+ </Accordion.Body>
+ </Accordion.Item>
+ </Accordion>
+
+ {/* Footer */}
+ <div className="row form-actions">
+ <div className="col-md-9 offset-md-3">
+ <Button
+ onClick={(event) => {
+ if (invalid) {
+ forIn(errors, function (value, key) {
+ if (
+ has(errors, "policyName") ||
+ resourceErrorCheck(errors)
+ ) {
+ let selector =
+ document?.getElementById("isError") ||
+ document?.getElementById(key) ||
+ document?.querySelector(`input[name=${key}]`) ||
+ document?.querySelector(`input[id=${key}]`) ||
+ document?.querySelector(
+ `span[className="invalid-field"]`
+ );
+ scrollToError(selector);
+ } else {
+ getValidatePolicyItems(errors?.[key]);
+ }
+ });
+ }
+ submitForm(event);
+ }}
+ variant="primary"
+ size="sm"
+ disabled={blockUI}
+ data-id="save"
+ data-cy="save"
+ >
+ Save
+ </Button>
+ <Button
+ variant="secondary"
+ type="button"
+ size="sm"
+ onClick={handleCancel}
+ disabled={blockUI}
+ data-id="cancel"
+ data-cy="cancel"
+ >
+ Cancel
+ </Button>
+
+ {policyId && (
+ <Button
+ variant="danger"
+ type="button"
+ className="btn-sm"
+ size="sm"
+ onClick={showDeleteModal}
+ disabled={blockUI}
+ >
+ Delete
+ </Button>
+ )}
+ </div>
+
+ {/* Delete confirmation modal */}
+ {policyId && (
+ <Modal show={showDelete} onHide={hideDeleteModal}>
+ <Modal.Header closeButton>
+ <span className="text-word-break">
+ Are you sure want to delete policy "
+ <b>{`${values?.policyName}`}</b>" ?
+ </span>
+ </Modal.Header>
+ <Modal.Footer>
+ <Button
+ variant="secondary"
+ size="sm"
+ title="Cancel"
+ onClick={hideDeleteModal}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ size="sm"
+ title="Yes"
+ onClick={() => handleDeleteClick(policyId, serviceId)}
+ >
+ Yes
+ </Button>
+ </Modal.Footer>
+ </Modal>
+ )}
+ </div>
+ </form>
+ )}
+ />
+ <BlockUi isUiBlock={blockUI} />
+ </div>
+ </>
+ );
+}
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/AccessRulesStep.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/AccessRulesStep.jsx
new file mode 100644
index 000000000..686ca47ac
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/AccessRulesStep.jsx
@@ -0,0 +1,329 @@
+/*
+ * 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 React from "react";
+import { Tab, Tabs, Accordion, Row, Col } from "react-bootstrap";
+import { Field } from "react-final-form";
+import BootstrapSwitchButton from "bootstrap-switch-button-react";
+import PolicyPermissionItemVertical from "./PolicyPermissionItemVertical";
+import { isEmpty } from "lodash";
+
+const hasItems = (arr) =>
+ Array.isArray(arr) && arr.some((item) => !isItemEmpty(item));
+
+const isItemEmpty = (item) => {
+ if (!item || typeof item !== "object") return true;
+
+ // Check if object is completely empty
+ if (Object.keys(item).length === 0) return true;
+
+ // Check if users/groups/roles have actual content
+ const hasUsers =
+ item.users?.users?.length > 0 ||
+ item.users?.groups?.length > 0 ||
+ item.users?.roles?.length > 0 ||
+ (Array.isArray(item.users) && item.users.length > 0) ||
+ (Array.isArray(item.groups) && item.groups.length > 0) ||
+ (Array.isArray(item.roles) && item.roles.length > 0);
+
+ // Check if accesses have content (handle both regular and tag-based policies)
+ const hasAccesses =
+ // Regular policy: accesses is an array
+ (Array.isArray(item.accesses) && item.accesses.length > 0) ||
+ // Tag-based policy: accesses is an object with tableList
+ (item.accesses?.tableList &&
+ Array.isArray(item.accesses.tableList) &&
+ item.accesses.tableList.some(
+ (table) =>
+ Array.isArray(table.permission) && table.permission.length > 0
+ ));
+
+ // Check if other meaningful fields exist (for different policy types)
+ // delegateAdmin should only count as content when it's true (checkbox checked)
+ const hasOtherContent =
+ item.dataMaskInfo ||
+ item.rowFilterInfo ||
+ item.delegateAdmin === true ||
+ (item.conditions &&
+ typeof item.conditions === "object" &&
+ Object.keys(item.conditions).length > 0);
+
+ // Special case: if object only has delegateAdmin: false and nothing else, consider it empty
+ const onlyFalseDelegateAdmin =
+ Object.keys(item).length === 1 && item.delegateAdmin === false;
+
+ // Special case: if object only has empty conditions and nothing else, consider it empty
+ const onlyEmptyConditions =
+ Object.keys(item).length === 1 &&
+ item.conditions &&
+ typeof item.conditions === "object" &&
+ Object.keys(item.conditions).length === 0;
+
+ if (onlyFalseDelegateAdmin || onlyEmptyConditions) return true;
+
+ // An item is empty if it has no meaningful content
+ const isEmpty = !hasUsers && !hasAccesses && !hasOtherContent;
+
+ return isEmpty;
+};
+
+const AccessRulesStep = ({ values, selectedServiceComponentDef }) => {
+ const isDenyAllElseEnabled = values?.isDenyAllElse === true;
+ const enableDenyAndExceptions =
+ selectedServiceComponentDef?.options?.enableDenyAndExceptionsInPolicies ===
+ "true";
+ const policyPermissionItems = [];
+ const policyType = values.policyType;
+
+ // Count items in each category
+ const allowRulesCount = hasItems(values?.policyItems)
+ ? values.policyItems.filter((item) => !isEmpty(item)).length
+ : 0;
+
+ const allowExceptionsCount = hasItems(values?.allowExceptions)
+ ? values.allowExceptions.filter((item) => !isEmpty(item)).length
+ : 0;
+
+ const denyRulesCount = hasItems(values?.denyPolicyItems)
+ ? values.denyPolicyItems.filter((item) => !isEmpty(item)).length
+ : 0;
+
+ const denyExceptionsCount = hasItems(values?.denyExceptions)
+ ? values.denyExceptions.filter((item) => !isEmpty(item)).length
+ : 0;
+
+ // Total counts for tab display
+ const allowTabTotal = allowRulesCount + allowExceptionsCount;
+ const denyTabTotal = denyRulesCount + denyExceptionsCount;
+
+ // Auto-open "Exclude from Allow Rules" accordion item if it has saved values
+ const hasAllowExceptions = hasItems(values?.allowExceptions);
+ const allowAccordionDefault = hasAllowExceptions ? ["0", "1"] : ["0"];
+
+ if (policyType == 1) {
+ policyPermissionItems.push({
+ attrName: "dataMaskPolicyItems",
+ title: "Mask Rules",
+ msg: "Mask rules grants access to resources when the specific criteria are met."
+ });
+ } else if (policyType == 2) {
+ policyPermissionItems.push({
+ attrName: "rowFilterPolicyItems",
+ title: "Row Filter Rules",
+ msg: "Row filter rules grants access to resources when the specific criteria are met."
+ });
+ } else if (policyType == 0 && !enableDenyAndExceptions) {
+ policyPermissionItems.push({
+ attrName: "policyItems",
+ title: "Allow Rules",
+ msg: "Allow rules grants access to resources when the specific criteria are met."
+ });
+ }
+
+ return (
+ <Row>
+ <Col xxl={12}>
+ <p className="stepper-instruction-text">
+ Configure access permissions by setting allow conditions to grant
+ access to specific users/groups/roles and deny conditions to
+ explicitly block access
+ </p>
+ {policyType == 0 && isEmpty(policyPermissionItems) && (
+ <>
+ <Tabs defaultActiveKey="allow" transition={false} className="mb-3">
+ <Tab
+ eventKey="allow"
+ title={
+ <span className="d-flex align-items-center gap-2">
+ Allow
+ {allowTabTotal > 0 && (
+ <span
+ className="badge bg-primary text-light"
+ style={{
+ fontSize: "0.75rem",
+ padding: "0.25rem 0.5rem",
+ borderRadius: "12px",
+ margin: "0px"
+ }}
+ >
+ {allowTabTotal}
+ </span>
+ )}
+ </span>
+ }
+ >
+ <Accordion
+ defaultActiveKey={allowAccordionDefault}
+ alwaysOpen
+ className="policy-permission-items-accordion"
+ >
+ <Accordion.Item eventKey="0">
+ <Accordion.Header>
+ <span className="d-flex align-items-center justify-content-between w-100">
+ <span>Allow Rules</span>
+ </span>
+ </Accordion.Header>
+ <Accordion.Body>
+ <PolicyPermissionItemVertical
+ serviceCompDetails={selectedServiceComponentDef}
+ formValues={values}
+ attrName="policyItems"
+ msg="Allow rules grants access to resources when the specific criteria are met."
+ />
+ </Accordion.Body>
+ </Accordion.Item>
+
+ <Accordion.Item eventKey="1">
+ <Accordion.Header>
+ <span className="d-flex align-items-center justify-content-between w-100">
+ <span>Exclude from Allow Rules</span>
+ </span>
+ </Accordion.Header>
+ <Accordion.Body>
+ <PolicyPermissionItemVertical
+ serviceCompDetails={selectedServiceComponentDef}
+ formValues={values}
+ attrName="allowExceptions"
+ msg="Exclude from Allow Rules grants access to resources when the specific criteria are met."
+ />
+ </Accordion.Body>
+ </Accordion.Item>
+
+ <Accordion.Item eventKey="2">
+ <Accordion.Header>Deny All Other Accesses</Accordion.Header>
+ <Accordion.Body>
+ <p className="stepper-instruction-text mb-3">
+ When enabled, this option denies all access types (read,
+ write, execute, etc.) to every user, group and role
+ except those explicitly allowed in this policy. Any
+ user/group/role not listed in the 'Allow'
+ section will automatically be blocked from accessing the
+ resource.
+ </p>
+
+ <Field name="isDenyAllElse">
+ {({ input }) => (
+ <Row>
+ <Col className="column-1-fixed">
+ <span>Deny all other accesses</span>
+ </Col>
+ <Col className="resource-toggle-switch">
+ <BootstrapSwitchButton
+ {...input}
+ checked={input.value || false}
+ onlabel="True"
+ onstyle="primary"
+ offlabel="False"
+ offstyle="outline-secondary"
+ size="xs"
+ width={100}
+ />
+ </Col>
+ </Row>
+ )}
+ </Field>
+ </Accordion.Body>
+ </Accordion.Item>
+ </Accordion>
+ </Tab>
+
+ <Tab
+ eventKey="deny"
+ disabled={isDenyAllElseEnabled}
+ title={
+ <span className="d-flex align-items-center gap-2">
+ Deny
+ {!isDenyAllElseEnabled && denyTabTotal > 0 && (
+ <span
+ className="badge bg-primary text-light"
+ style={{
+ fontSize: "0.75rem",
+ padding: "0.25rem 0.5rem",
+ borderRadius: "12px",
+ margin: "0px"
+ }}
+ >
+ {denyTabTotal}
+ </span>
+ )}
+ </span>
+ }
+ >
+ <Accordion
+ defaultActiveKey={["0"]}
+ alwaysOpen
+ className="policy-permission-items-accordion"
+ >
+ <Accordion.Item eventKey="0">
+ <Accordion.Header>
+ <span className="d-flex align-items-center justify-content-between w-100">
+ <span>Deny Rules</span>
+ </span>
+ </Accordion.Header>
+ <Accordion.Body>
+ <PolicyPermissionItemVertical
+ serviceCompDetails={selectedServiceComponentDef}
+ formValues={values}
+ attrName="denyPolicyItems"
+ msg="Deny rules explicitly block access to resources when the specific
+ criteria are met."
+ />
+ </Accordion.Body>
+ </Accordion.Item>
+
+ <Accordion.Item eventKey="1">
+ <Accordion.Header>
+ <span className="d-flex align-items-center justify-content-between w-100">
+ <span>Exclude from Deny Rules</span>
+ </span>
+ </Accordion.Header>
+ <Accordion.Body>
+ <PolicyPermissionItemVertical
+ serviceCompDetails={selectedServiceComponentDef}
+ formValues={values}
+ attrName="denyExceptions"
+ msg="Exclude from Deny Rules explicitly block access to resources when the specific
+ criteria are met."
+ />
+ </Accordion.Body>
+ </Accordion.Item>
+ </Accordion>
+ </Tab>
+ </Tabs>
+ </>
+ )}
+ {!isEmpty(policyPermissionItems) && (
+ <>
+ {policyPermissionItems.map((item) => (
+ <PolicyPermissionItemVertical
+ key={item.attrName}
+ serviceCompDetails={selectedServiceComponentDef}
+ formValues={values}
+ attrName={item.attrName}
+ msg={item.msg}
+ />
+ ))}
+ </>
+ )}
+ </Col>
+ </Row>
+ );
+};
+
+export default AccessRulesStep;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyDetailsStep.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyDetailsStep.jsx
new file mode 100644
index 000000000..36e97981b
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyDetailsStep.jsx
@@ -0,0 +1,518 @@
+/*
+ * 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 React, { useState, useCallback } from "react";
+import {
+ Form as FormB,
+ Row,
+ Col,
+ Container,
+ Button,
+ Table,
+ Collapse
+} from "react-bootstrap";
+import { Field } from "react-final-form";
+import { isEmpty, trim, find, isArray } from "lodash";
+import { fetchApi } from "Utils/fetchAPI";
+import {
+ selectInputCustomStyles,
+ trimInputValue
+} from "Components/CommonComponents";
+import AsyncCreatableSelect from "react-select/async-creatable";
+import BootstrapSwitchButton from "bootstrap-switch-button-react";
+import PolicyValidityPeriodModal from "./PolicyValidityPeriodModal";
+import PolicyConditionsComp from "../../PolicyConditionsComp";
+import {
+ policyConditionUpdatedJSON,
+ getPolicyConditionDisplayLbl
+} from "Utils/XAUtils";
+import moment from "moment";
+
+const PolicyDetailsStep = ({ values, form, selectedServiceComponentDef }) => {
+ const [defaultPolicyLabelOptions, setDefaultPolicyLabelOptions] = useState(
+ []
+ );
+ const [showConditionsModal, setShowConditionsModal] = useState(false);
+ const [showValidityPeriodModal, setShowValidityPeriodModal] = useState(false);
+ const [open, setOpen] = useState(false);
+
+ const required = (value) => (value ? undefined : "Required");
+
+ const handleToggleSetting = (e) => {
+ e.preventDefault(); // Prevents the "#" from jumping the page to the top
+ setOpen(!open);
+ };
+
+ // Fetch policy labels with lodash trim
+ const fetchPolicyLabel = useCallback(async (inputValue) => {
+ const params = {};
+ if (!isEmpty(inputValue)) {
+ params.policyLabel = trim(inputValue);
+ }
+
+ try {
+ const policyLabelResp = await fetchApi({
+ url: "plugins/policyLabels",
+ params
+ });
+
+ return policyLabelResp.data.map((name) => ({
+ label: trim(name),
+ value: trim(name)
+ }));
+ } catch (error) {
+ console.error("Error fetching policy labels:", error);
+ return [];
+ }
+ }, []);
+
+ // Load default options on focus
+ const onFocusPolicyLabel = useCallback(() => {
+ fetchPolicyLabel().then((opts) => {
+ setDefaultPolicyLabelOptions(opts);
+ });
+ }, [fetchPolicyLabel]);
+
+ return (
+ <Container fluid className="p-0">
+ <Row>
+ <Col lg={11}>
+ <p className="text-muted">Add policy details</p>
+
+ {/* Policy Name */}
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label
+ column
+ className="fnt-14 column-1-fixed text-end"
+ htmlFor="policyName"
+ >
+ Policy Name
+ <span className="required-mark">*</span>
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="policyName" validate={required}>
+ {({ input, meta }) => (
+ <>
+ <FormB.Control
+ {...input}
+ type="text"
+ placeholder="Enter policy name"
+ onBlur={(e) => trimInputValue(e, input)}
+ />
+ {meta.touched && meta.error && (
+ <span className="text-danger">{meta.error}</span>
+ )}
+ </>
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* Policy Labels */}
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label
+ column
+ className="fnt-14 column-1-fixed text-end"
+ htmlFor="policyLabels"
+ >
+ Policy Labels
+ </FormB.Label>
+ <Col className="mw-50 labels-select-input">
+ <Field name="policyLabels" className="">
+ {({ input }) => (
+ <AsyncCreatableSelect
+ {...input}
+ isMulti
+ loadOptions={fetchPolicyLabel}
+ onFocus={onFocusPolicyLabel}
+ defaultOptions={defaultPolicyLabelOptions}
+ styles={selectInputCustomStyles}
+ placeholder="Add Policy Labels"
+ tabSelectsValue={false}
+ formatCreateLabel={(inputValue) =>
+ `Create "${trim(inputValue)}"`
+ }
+ onCreateOption={(inputValue) => {
+ const policyLabelVal = trim(inputValue);
+ if (!isEmpty(policyLabelVal)) {
+ input.onChange([
+ ...(input.value || []),
+ {
+ label: policyLabelVal,
+ value: policyLabelVal
+ }
+ ]);
+ }
+ }}
+ />
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* Policy Description */}
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label
+ column
+ className="fnt-14 column-1-fixed text-end"
+ htmlFor="description"
+ >
+ Policy Description
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="description">
+ {({ input }) => (
+ <FormB.Control
+ {...input}
+ as="textarea"
+ rows={3}
+ placeholder="Enter policy description"
+ onBlur={(e) => trimInputValue(e, input)}
+ />
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* Policy Status */}
+ <FormB.Group as={Row} className="mb-4 align-items-center">
+ <FormB.Label
+ column
+ className="fnt-14 column-1-fixed text-end"
+ htmlFor="isEnabled"
+ >
+ Policy Status
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="isEnabled">
+ {({ input }) => (
+ <BootstrapSwitchButton
+ {...input}
+ checked={!(input.value === false)}
+ onlabel="Enabled"
+ onstyle="primary"
+ offlabel="Disabled"
+ offstyle="outline-secondary"
+ width={100}
+ size="xs"
+ key="isEnabled"
+ />
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* Policy Priority */}
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label
+ column
+ className="fnt-14 column-1-fixed text-end"
+ htmlFor="policyPriority"
+ >
+ Policy Priority
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="policyPriority">
+ {({ input }) => (
+ <div className="d-flex gap-5">
+ <FormB.Check
+ type="radio"
+ label="Normal"
+ name="policyPriority"
+ value={0}
+ checked={input.value === 0 || input.value === undefined}
+ onChange={(e) => input.onChange(Number(e.target.value))}
+ id="policyPriorityNormal"
+ />
+ <FormB.Check
+ type="radio"
+ label="Override"
+ name="policyPriority"
+ value={1}
+ checked={input.value === 1}
+ onChange={(e) => input.onChange(Number(e.target.value))}
+ id="policyPriorityOverride"
+ />
+ </div>
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* {Hide show advance setting} */}
+ <div className="mt-4">
+ <FormB.Group as={Row} className="mb-4">
+ <Col sm={12}>
+ <div className="d-flex align-items-center">
+ <p className="mb-0">
+ <a
+ href="#"
+ className="link-underline-light text-primary fw-bold d-flex align-items-center"
+ onClick={handleToggleSetting}
+ style={{ textDecoration: "none" }}
+ >
+ <span className="me-2">
+ {open
+ ? "Hide Advanced Settings"
+ : "Show Advanced Settings"}
+ </span>
+ <i
+ className={`fa-fw fa ${open ? "fa-angle-up" : "fa-angle-down"}`}
+ />
+ </a>
+ </p>
+ </div>
+ </Col>
+ </FormB.Group>
+
+ {/* The Collapse Component replaces Accordion.Collapse */}
+ <Collapse in={open}>
+ <div>
+ {/* Policy Validity Period */}
+ <Col xl={12} className="mb-4">
+ <Row>
+ <Col className="fnt-14 column-1-fixed text-end">
+ <FormB.Label>Policy Validity Period</FormB.Label>
+ </Col>
+ <Col>
+ {values?.validitySchedules &&
+ !isEmpty(values.validitySchedules) ? (
+ <Row>
+ <Col>
+ <div style={{ flex: 1 }}>
+ <Table
+ bordered
+ size="sm"
+ className="condition-group-table"
+ >
+ <thead>
+ <tr>
+ <th className="text-center">Start Date</th>
+ <th className="text-center">End Date</th>
+ <th className="text-center">Time Zone</th>
+ </tr>
+ </thead>
+ <tbody>
+ {values.validitySchedules
+ .filter((schedule) => schedule != null)
+ .map((schedule, idx) => (
+ <tr key={idx}>
+ <td className="text-center">
+ {schedule?.startTime
+ ? moment(schedule.startTime).format(
+ "MM-DD-YYYY HH:mm:ss"
+ )
+ : "-"}
+ </td>
+ <td className="text-center">
+ {schedule?.endTime
+ ? moment(schedule.endTime).format(
+ "MM-DD-YYYY HH:mm:ss"
+ )
+ : "-"}
+ </td>
+ <td className="text-center">
+ {schedule?.timeZone?.text || "-"}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </Table>
+ </div>
+ </Col>
+ <Col className="column-3-fixed">
+ <Button
+ variant="link"
+ onClick={() => setShowValidityPeriodModal(true)}
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Edit Validity Period
+ </Button>
+ </Col>
+ </Row>
+ ) : (
+ <Button
+ variant="link"
+ onClick={() => setShowValidityPeriodModal(true)}
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Add Validity Period
+ </Button>
+ )}
+
+ {/* Policy Validity Period Modal */}
+ {showValidityPeriodModal && (
+ <PolicyValidityPeriodModal
+ showModal={showValidityPeriodModal}
+ handleCloseModal={() =>
+ setShowValidityPeriodModal(false)
+ }
+ currentValues={values?.validitySchedules || []}
+ onSave={(newValues) => {
+ form.change("validitySchedules", newValues);
+ }}
+ />
+ )}
+ </Col>
+ </Row>
+ </Col>
+
+ {/* Policy Conditions */}
+ {selectedServiceComponentDef?.policyConditions?.length > 0 && (
+ <Col xl={12} className="mb-4">
+ <Row>
+ <Col className="fnt-14 column-1-fixed text-end">
+ <FormB.Label>Policy Conditions</FormB.Label>
+ </Col>
+ <Col>
+ {values?.conditions && !isEmpty(values.conditions) ? (
+ <Row>
+ <Col>
+ <div style={{ flex: 1 }}>
+ <Table
+ bordered
+ size="sm"
+ className="condition-group-table"
+ >
+ <thead>
+ <tr>
+ <th className="text-center">Condition</th>
+ <th className="text-center">Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ {Object.keys(values.conditions).map(
+ (keyName) => {
+ const conditionValue =
+ values.conditions[keyName];
+ if (
+ conditionValue != "" &&
+ conditionValue != null
+ ) {
+ let conditionObj = find(
+ selectedServiceComponentDef?.policyConditions,
+ (m) => m.name === keyName
+ );
+
+ return (
+ <tr key={keyName}>
+ <td className="white-space-nowrap">
+ {getPolicyConditionDisplayLbl(
+ conditionObj?.label
+ )}
+ </td>
+ <td className="text-word-break">
+ {isArray(conditionValue)
+ ? conditionValue.join(", ")
+ : conditionValue}
+ </td>
+ </tr>
+ );
+ }
+ return null;
+ }
+ )}
+ </tbody>
+ </Table>
+ </div>
+ </Col>
+ <Col className="column-3-fixed">
+ <Button
+ variant="link"
+ onClick={() => setShowConditionsModal(true)}
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Edit Conditions
+ </Button>
+ </Col>
+ </Row>
+ ) : (
+ <Button
+ variant="link"
+ onClick={() => setShowConditionsModal(true)}
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Add Conditions
+ </Button>
+ )}
+
+ {/* Policy Conditions Modal */}
+ {showConditionsModal && (
+ <PolicyConditionsComp
+ policyConditionDetails={policyConditionUpdatedJSON(
+ selectedServiceComponentDef.policyConditions
+ )}
+ inputVal={{
+ value: values?.conditions || {},
+ onChange: (newValue) => {
+ form.change("conditions", newValue);
+ }
+ }}
+ showModal={showConditionsModal}
+ handleCloseModal={() =>
+ setShowConditionsModal(false)
+ }
+ />
+ )}
+ </Col>
+ </Row>
+ </Col>
+ )}
+
+ {/* Audit Logging */}
+ <FormB.Group as={Row} className="mb-4 align-items-center">
+ <FormB.Label
+ column
+ className="fnt-14 column-1-fixed text-end"
+ htmlFor="isAuditEnabled"
+ >
+ Audit Logging
+ </FormB.Label>
+ <Col sm={2}>
+ <Field name="isAuditEnabled">
+ {({ input }) => (
+ <BootstrapSwitchButton
+ {...input}
+ checked={!!input.value}
+ onlabel="Yes"
+ onstyle="primary"
+ offlabel="No"
+ offstyle="outline-secondary"
+ width={100}
+ size="xs"
+ key="isAuditEnabled"
+ />
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+ </div>
+ </Collapse>
+ </div>
+ </Col>
+ </Row>
+ </Container>
+ );
+};
+
+export default PolicyDetailsStep;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyPermissionItemVertical.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyPermissionItemVertical.jsx
new file mode 100644
index 000000000..f961df92a
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyPermissionItemVertical.jsx
@@ -0,0 +1,923 @@
+/*
+ * 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 React, { useMemo, useState } from "react";
+import { FieldArray } from "react-final-form-arrays";
+import {
+ Row,
+ Col,
+ Button,
+ Form as FormB,
+ Table,
+ Container
+} from "react-bootstrap";
+import { Field, useForm } from "react-final-form";
+import { RangerPolicyType } from "Utils/XAEnums";
+import { find, isEmpty, isArray, toUpper, map } from "lodash";
+import PolicyConditionsComp from "../../PolicyConditionsComp";
+import { policyConditionUpdatedJSON } from "Utils/XAUtils";
+import UsersGroupsAndRolesSelectionComponent from "./UsersGroupsAndRolesSelectionComponent";
+import TagBasePermissionItem from "../../TagBasePermissionItem";
+import {
+ getAccessTypesByResource,
+ getPolicyConditionDisplayLbl
+} from "Utils/XAUtils";
+import { CustomTooltip } from "Components/CommonComponents";
+import {
+ getSelectedAccessTypesForRow,
+ getSelectedLeafResourceTypes,
+ buildActionReqsMapFromConditionDef
+} from "Utils/policyConditionUtils";
+import { usePruneStaleConditions } from "../../../../hooks/usePruneStaleConditions";
+
+export default function PolicyPermissionItemVertical({
+ attrName,
+ serviceCompDetails,
+ formValues
+}) {
+ const [showConditionsModalIndex, setShowConditionsModalIndex] =
+ useState(null);
+ const [showTagPermissionModalIndex, setShowTagPermissionModalIndex] =
+ useState(null);
+ const form = useForm(); // Get form instance
+
+ const conditionDefVal = useMemo(
+ () => policyConditionUpdatedJSON(serviceCompDetails?.policyConditions),
+ [serviceCompDetails?.policyConditions]
+ );
+
+ const actionReqsMap = useMemo(
+ () => buildActionReqsMapFromConditionDef(conditionDefVal),
+ [conditionDefVal]
+ );
+
+ const leafResourceTypes = useMemo(
+ () => getSelectedLeafResourceTypes(serviceCompDetails, formValues),
+ [serviceCompDetails, formValues]
+ );
+
+ usePruneStaleConditions({
+ formValues,
+ attrName,
+ form,
+ leafResourceTypes,
+ serviceCompDetails,
+ conditionDefVal,
+ actionReqsMap
+ });
+
+ const accessTypeOptions = getAccessTypesByResource(
+ formValues,
+ serviceCompDetails
+ );
+
+ const getMaskingAccessTypeOptions = (index) => {
+ if (serviceCompDetails?.dataMaskDef?.maskTypes?.length > 0) {
+ if (
+ formValues?.policyType ==
+ RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value &&
+ serviceCompDetails?.name == "tag"
+ ) {
+ const accessServices =
+ formValues?.dataMaskPolicyItems?.[index]?.accesses?.tableList?.[0]
+ ?.serviceName;
+ if (accessServices) {
+ const filterServiceDetails =
+ serviceCompDetails.dataMaskDef.maskTypes.filter((a) => {
+ return a.name.includes(accessServices);
+ });
+ return filterServiceDetails.map(({ label, name: value }) => ({
+ label,
+ value
+ }));
+ }
+ }
+ return serviceCompDetails.dataMaskDef.maskTypes.map(
+ ({ label, name: value }) => ({
+ label,
+ value
+ })
+ );
+ }
+ return [];
+ };
+
+ const displayTagPermissionItem = (permission) => {
+ let srcOp = [];
+ if (
+ RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value == formValues.policyType
+ ) {
+ srcOp = serviceCompDetails.dataMaskDef?.accessTypes || [];
+ } else if (
+ RangerPolicyType.RANGER_ROW_FILTER_POLICY_TYPE.value ==
+ formValues.policyType
+ ) {
+ srcOp = serviceCompDetails.rowFilterDef?.accessTypes || [];
+ } else {
+ srcOp = serviceCompDetails.accessTypes;
+ }
+ const labels = map(permission, (perm) => {
+ return find(srcOp, { name: perm })?.label;
+ });
+ return labels;
+ };
+
+ // Required field validation
+ const required = (value) => (value ? undefined : "Required");
+
+ // Helper function to clear all data from a permission item
+ const clearPermissionItem = (index) => {
+ // Reset the entire permission item to an empty object
+ form.change(`${attrName}[${index}]`, {});
+ };
+
+ // Handle delegate admin changes with auto-clear logic
+ const handleDelegateAdminChange = (input, index) => {
+ return (e) => {
+ const newValue = e.target.checked;
+
+ if (newValue) {
+ // User is checking delegate admin - just set it to true
+ input.onChange(true);
+ } else {
+ // User is unchecking delegate admin - check if this would be the only data
+ const currentItem = form.getState().values[attrName]?.[index] || {};
+
+ // Create a copy without delegateAdmin to check other fields
+ const itemWithoutDelegate = { ...currentItem };
+ delete itemWithoutDelegate.delegateAdmin;
+
+ // If no other meaningful data exists, clear the entire item instead of setting false
+ if (Object.keys(itemWithoutDelegate).length === 0) {
+ // Keep the item set empty by clearing it completely
+ form.change(`${attrName}[${index}]`, {});
+ } else {
+ // There's other data, so just set delegateAdmin to false
+ input.onChange(false);
+ }
+ }
+ };
+ };
+
+ return (
+ <div className="fnt-14">
+ <FieldArray name={attrName}>
+ {({ fields }) => (
+ <>
+ {fields.length === 0 && (
+ <Row>
+ <Col className="text-center text-muted py-4">
+ <p>
+ No rules added yet. Click "Add more rules" to
+ start.
+ </p>
+ </Col>
+ </Row>
+ )}
+
+ {fields.map((name, index) => (
+ <React.Fragment key={name}>
+ <Row key={name} className="py-3">
+ {/* Rule Header */}
+ <Col sm={11}>
+ {/* Permissions Section */}
+ <Col xs={12} className="mb-4">
+ <Row>
+ <Col className="column-1-fixed text-end">
+ <FormB.Label>Permissions</FormB.Label>
+ </Col>
+ <Col>
+ {/* Tag-based policy - use modal with table layout */}
+ {serviceCompDetails?.name === "tag" ? (
+ <Field name={`${name}.accesses`}>
+ {({ input, meta }) => (
+ <>
+ {/* Container with flex layout for table + button side by side */}
+ {input.value?.tableList?.length > 0 ? (
+ <Container fluid className="p-0">
+ <Row>
+ <Col>
+ <div style={{ flex: 1 }}>
+ <Table
+ bordered
+ size="sm"
+ className="condition-group-table"
+ >
+ <thead>
+ <tr>
+ <th className="text-center">
+ Service
+ </th>
+ <th className="text-center">
+ Permissions
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {input.value.tableList.map(
+ (tableItem, idx) => (
+ <tr
+ key={`${tableItem.serviceName}-${idx}`}
+ >
+ <td className="white-space-nowrap">
+ {toUpper(
+ tableItem.serviceName
+ )}
+ </td>
+ <td className="text-word-break">
+ {displayTagPermissionItem(
+ tableItem.permission
+ ).join(", ")}
+ </td>
+ </tr>
+ )
+ )}
+ </tbody>
+ </Table>
+ </div>
+ </Col>
+ <Col className="column-3-fixed">
+ <Button
+ variant="link"
+ onClick={() =>
+ setShowTagPermissionModalIndex(
+ index
+ )
+ }
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Edit Permissions
+ </Button>
+ </Col>
+ </Row>
+ </Container>
+ ) : (
+ <Col>
+ <Button
+ variant="link"
+ onClick={() =>
+ setShowTagPermissionModalIndex(index)
+ }
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Add Permissions
+ </Button>
+ </Col>
+ )}
+ {/* Tag Permission Modal */}
+ {showTagPermissionModalIndex === index && (
+ <TagBasePermissionItem
+ options={accessTypeOptions}
+ inputVal={{
+ ...input,
+ onChange: (value) => {
+ input.onChange(value);
+ // Don't close here, let the modal handle it via onClose
+ }
+ }}
+ formValues={formValues}
+ dataMaskIndex={index}
+ serviceCompDetails={serviceCompDetails}
+ attrName={attrName}
+ showModal={true}
+ handleCloseModal={() =>
+ setShowTagPermissionModalIndex(null)
+ }
+ />
+ )}
+ {meta.error && (
+ <div className="text-danger small mt-1">
+ <i className="fa fa-exclamation-circle me-1" />
+ {meta.error}
+ </div>
+ )}
+ </>
+ )}
+ </Field>
+ ) : (
+ /* Non-tag policy - use checkboxes */
+ <Field name={`${name}.accesses`}>
+ {({ input, meta }) => {
+ const currentValue = input.value || [];
+ const allSelected =
+ accessTypeOptions.length > 0 &&
+ accessTypeOptions.every((access) =>
+ currentValue.some(
+ (a) => a.type === access.value
+ )
+ );
+
+ const handleSelectAll = () => {
+ if (allSelected) {
+ // Deselect all
+ input.onChange([]);
+ } else {
+ // Select all
+ const allAccesses = accessTypeOptions.map(
+ (a) => ({
+ type: a.value,
+ isAllowed: true,
+ label: a.label
+ })
+ );
+ input.onChange(allAccesses);
+ }
+ };
+
+ return (
+ <div>
+ <Container fluid className="p-0">
+ <div className="gx-3 gy-1 permissions-checkboxes">
+ {/* Select All Link - Only show if more than 1 option */}
+ {accessTypeOptions.length > 1 && (
+ <div className="mb-1">
+ <FormB.Check
+ type="checkbox"
+ id={`${name}-selectAll`}
+ label="Select All"
+ checked={allSelected}
+ onChange={handleSelectAll}
+ className="text-nowrap text-primary"
+ />
+ </div>
+ )}
+ {accessTypeOptions.map((access) => {
+ const isChecked =
+ Array.isArray(input.value) &&
+ input.value.some(
+ (a) => a.type === access.value
+ );
+
+ return (
+ <div
+ className="mb-1"
+ key={access.value}
+ >
+ <FormB.Check
+ type="checkbox"
+ id={`${name}-${access.value}`}
+ label={access.label}
+ checked={isChecked}
+ onChange={(e) => {
+ const currentValue =
+ input.value || [];
+ if (e.target.checked) {
+ input.onChange([
+ ...currentValue,
+ {
+ type: access.value,
+ isAllowed: true,
+ label: access.label
+ }
+ ]);
+ } else {
+ input.onChange(
+ currentValue.filter(
+ (a) =>
+ a.type !==
+ access.value
+ )
+ );
+ }
+ }}
+ className="text-nowrap"
+ />
+ </div>
+ );
+ })}
+ </div>
+ </Container>
+ {meta.error && (
+ <div className="text-danger small mt-1">
+ <i className="fa fa-exclamation-circle me-1" />
+ {meta.error}
+ </div>
+ )}
+ </div>
+ );
+ }}
+ </Field>
+ )}
+ </Col>
+ </Row>
+ </Col>
+
+ {/* Users, Groups, Roles Selection */}
+ <Col xl={12} className="mb-4">
+ <Row>
+ <Col className="column-1-fixed text-end">
+ <FormB.Label>Users, Groups, Roles</FormB.Label>
+ </Col>
+ <Col>
+ <Field name={`${name}.users`}>
+ {({ input, meta }) => (
+ <>
+ <UsersGroupsAndRolesSelectionComponent
+ value={input.value}
+ onChange={input.onChange}
+ name={`${name}.users`}
+ placeholder="Select users, groups, roles..."
+ />
+ {meta.error && (
+ <div className="text-danger small mt-1">
+ <i className="fa fa-exclamation-circle me-1" />
+ {meta.error}
+ </div>
+ )}
+ </>
+ )}
+ </Field>
+ </Col>
+ </Row>
+ </Col>
+
+ {/* Rule Conditions */}
+ {serviceCompDetails?.policyConditions?.length > 0 && (
+ <Col xs={12} className="mb-4">
+ <Row>
+ <Col className="column-1-fixed text-end">
+ <FormB.Label>Rule Conditions</FormB.Label>
+ </Col>
+ {fields.value[index]?.conditions &&
+ !isEmpty(fields.value[index].conditions) ? (
+ <>
+ <Col>
+ <div style={{ flex: 1 }}>
+ <Table
+ bordered
+ size="sm"
+ className="condition-group-table"
+ >
+ <thead>
+ <tr>
+ <th className="text-center">
+ Condition
+ </th>
+ <th className="text-center">Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ {Object.keys(
+ fields.value[index].conditions
+ ).map((keyName) => {
+ const conditionValue =
+ fields.value[index].conditions[
+ keyName
+ ];
+
+ if (
+ conditionValue != "" &&
+ conditionValue != null
+ ) {
+ let conditionObj = find(
+ serviceCompDetails?.policyConditions,
+ function (m) {
+ return m.name == keyName;
+ }
+ );
+
+ return (
+ <tr key={keyName}>
+ <td className="white-space-nowrap">
+ {getPolicyConditionDisplayLbl(
+ conditionObj?.label
+ )}
+ </td>
+ <td className="text-word-break">
+ {isArray(conditionValue)
+ ? conditionValue
+ .map((m) =>
+ typeof m === "object" &&
+ m?.value != null
+ ? m.value
+ : m
+ )
+ .join(", ")
+ : conditionValue}
+ </td>
+ </tr>
+ );
+ }
+ return null;
+ })}
+ </tbody>
+ </Table>
+ </div>
+ </Col>
+ <Col className="column-3-fixed">
+ {/* Edit/Add Button - Always visible on the right */}
+ <Button
+ variant="link"
+ onClick={() =>
+ setShowConditionsModalIndex(index)
+ }
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Edit Conditions
+ </Button>
+ </Col>
+ </>
+ ) : (
+ <Col>
+ {/* Edit/Add Button - Always visible on the right */}
+ <Button
+ variant="link"
+ onClick={() =>
+ setShowConditionsModalIndex(index)
+ }
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ Add Conditions
+ </Button>
+ </Col>
+ )}
+ {showConditionsModalIndex === index && (
+ <PolicyConditionsComp
+ policyConditionDetails={conditionDefVal}
+ inputVal={{
+ value: fields.value[index]?.conditions || {},
+ onChange: (newValue) => {
+ form.change(`${name}.conditions`, newValue);
+ }
+ }}
+ showModal={true}
+ handleCloseModal={() =>
+ setShowConditionsModalIndex(null)
+ }
+ modalHeader="Rule Conditions"
+ scope="policyItem"
+ servicedefName={serviceCompDetails?.name}
+ actionReqsMap={actionReqsMap}
+ actionFilterContext={{
+ selectedAccessTypes:
+ getSelectedAccessTypesForRow(
+ formValues,
+ attrName,
+ index
+ ),
+ leafResourceTypes,
+ accessTypeDefs: serviceCompDetails?.accessTypes
+ }}
+ />
+ )}
+ </Row>
+ </Col>
+ )}
+
+ {/* Data Masking Option (for Masking policies) */}
+ {RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value ==
+ formValues?.policyType && (
+ <Col xs={12} className="mb-4">
+ <Row>
+ <Col className="column-1-fixed text-end">
+ <FormB.Label>Select Masking Option</FormB.Label>
+ </Col>
+ <Col>
+ {serviceCompDetails?.name !== "tag" ? (
+ <>
+ {" "}
+ <Field name={`${name}.dataMaskInfo`}>
+ {({ input, meta }) => {
+ const maskingOptions =
+ getMaskingAccessTypeOptions(index);
+ return (
+ <>
+ <Container fluid className="p-0">
+ <Row>
+ {/* Masking Type Radio Buttons */}
+ {maskingOptions.map((maskType) => (
+ <Col
+ xxl={3}
+ xl={4}
+ md={6}
+ sm={12}
+ className="mb-3"
+ key={maskType.value}
+ >
+ <FormB.Check
+ type="radio"
+ id={`${name}-mask-${maskType.value}`}
+ name={`${name}.dataMaskInfo`}
+ label={maskType.label}
+ checked={
+ input.value?.value ===
+ maskType.value
+ }
+ onChange={() =>
+ input.onChange({
+ label: maskType.label,
+ value: maskType.value
+ })
+ }
+ className="mb-2"
+ />
+ </Col>
+ ))}
+ </Row>
+ </Container>
+ {/* Custom Value Expression (shown when "Custom" is selected) */}
+ {input.value?.label === "Custom" && (
+ <div className="mt-2">
+ <Field
+ name={`${name}.dataMaskInfo.valueExpr`}
+ validate={required}
+ >
+ {({
+ input: exprInput,
+ meta: exprMeta
+ }) => (
+ <div>
+ <FormB.Control
+ {...exprInput}
+ type="text"
+ placeholder="Enter masked value or expression..."
+ isInvalid={
+ exprMeta.touched &&
+ exprMeta.error
+ }
+ />
+ {exprMeta.touched &&
+ exprMeta.error && (
+ <FormB.Control.Feedback type="invalid">
+ {exprMeta.error}
+ </FormB.Control.Feedback>
+ )}
+ </div>
+ )}
+ </Field>
+ </div>
+ )}
+ {/* Form-level validation error - only render if string (nested field errors bubble up as objects) */}
+ {typeof meta.error === "string" && (
+ <div className="text-danger small mt-1">
+ <i className="fa fa-exclamation-circle me-1" />
+ {meta.error}
+ </div>
+ )}
+ </>
+ );
+ }}
+ </Field>
+ </>
+ ) : formValues?.dataMaskPolicyItems?.[index]
+ ?.accesses?.tableList?.length > 0 ? (
+ <>
+ {" "}
+ <Field name={`${name}.dataMaskInfo`}>
+ {({ input, meta }) => {
+ const maskingOptions =
+ getMaskingAccessTypeOptions(index);
+ return (
+ <>
+ <Container fluid className="p-0">
+ <Row>
+ {/* Masking Type Radio Buttons */}
+ {maskingOptions.map((maskType) => (
+ <Col
+ xxl={3}
+ xl={4}
+ md={6}
+ sm={12}
+ className="mb-3"
+ key={maskType.value}
+ >
+ <FormB.Check
+ type="radio"
+ id={`${name}-mask-${maskType.value}`}
+ name={`${name}.dataMaskInfo`}
+ label={maskType.label}
+ checked={
+ input.value?.value ===
+ maskType.value
+ }
+ onChange={() =>
+ input.onChange({
+ label: maskType.label,
+ value: maskType.value
+ })
+ }
+ className="mb-2"
+ />
+ </Col>
+ ))}
+ </Row>
+ </Container>
+ {/* Custom Value Expression (shown when "Custom" is selected) */}
+ {input.value?.label === "Custom" && (
+ <div className="mt-2">
+ <Field
+ name={`${name}.dataMaskInfo.valueExpr`}
+ validate={required}
+ >
+ {({
+ input: exprInput,
+ meta: exprMeta
+ }) => (
+ <div>
+ <FormB.Control
+ {...exprInput}
+ type="text"
+ placeholder="Enter masked value or expression..."
+ isInvalid={
+ exprMeta.touched &&
+ exprMeta.error
+ }
+ />
+ {exprMeta.touched &&
+ exprMeta.error && (
+ <FormB.Control.Feedback type="invalid">
+ {exprMeta.error}
+ </FormB.Control.Feedback>
+ )}
+ </div>
+ )}
+ </Field>
+ </div>
+ )}
+ {/* Form-level validation error - only render if string (nested field errors bubble up as objects) */}
+ {typeof meta.error === "string" && (
+ <div className="text-danger small mt-1">
+ <i className="fa fa-exclamation-circle me-1" />
+ {meta.error}
+ </div>
+ )}
+ </>
+ );
+ }}
+ </Field>
+ </>
+ ) : (
+ <Col>
+ <div className="text-muted fst-italic">
+ Please add permissions to select masking
+ option.
+ </div>
+ </Col>
+ )}
+ </Col>
+ </Row>
+ </Col>
+ )}
+
+ {/* Row Level Filter (for Row Filter policies) */}
+ {RangerPolicyType.RANGER_ROW_FILTER_POLICY_TYPE.value ==
+ formValues?.policyType && (
+ <Col xs={12} className="mb-4">
+ <Row>
+ <Col className="column-1-fixed text-end">
+ <FormB.Label>Row Level Filter</FormB.Label>
+ </Col>
+ <Col>
+ <Field name={`${name}.rowFilterInfo`}>
+ {({ input, meta }) => (
+ <div>
+ <FormB.Control
+ {...input}
+ as="textarea"
+ rows={3}
+ placeholder="Enter filter expression (e.g., country = 'US')"
+ isInvalid={!!meta.error}
+ />
+ {meta.error && (
+ <FormB.Control.Feedback type="invalid">
+ {meta.error}
+ </FormB.Control.Feedback>
+ )}
+ </div>
+ )}
+ </Field>
+ </Col>
+ </Row>
+ </Col>
+ )}
+
+ {/* Delegate Admin (for Access policies only, non-tag) */}
+ {RangerPolicyType.RANGER_ACCESS_POLICY_TYPE.value ==
+ formValues?.policyType &&
+ serviceCompDetails?.name !== "tag" && (
+ <Col xs={12} className="mb-0">
+ <Row>
+ <Col className="column-1-fixed text-end">
+ <FormB.Label htmlFor={`${name}.delegateAdmin`}>
+ Delegate Admin
+ <span className="ps-2">
+ <CustomTooltip
+ placement="right"
+ content={
+ <p
+ className="pd-5"
+ style={{ fontSize: "small" }}
+ >
+ Delegate Admin grants users or groups or
+ roles the authority to create and manage
+ policies, but strictly within the
+ specific resource boundaries defined by
+ the original policy.
+ </p>
+ }
+ icon="fa-fw fa fa-info-circle"
+ />
+ </span>
+ </FormB.Label>
+ </Col>
+ <Col>
+ <Field
+ className="form-control"
+ name={`${name}.delegateAdmin`}
+ data-js="delegatedAdmin"
+ data-cy="delegatedAdmin"
+ type="checkbox"
+ >
+ {({ input }) => (
+ <div
+ className="d-flex align-items-center"
+ style={{ height: "21px" }}
+ >
+ <input
+ {...input}
+ type="checkbox"
+ onChange={handleDelegateAdminChange(
+ input,
+ index
+ )}
+ />{" "}
+ </div>
+ )}
+ </Field>
+ </Col>
+ </Row>
+ </Col>
+ )}
+ </Col>
+ <Col
+ sm={1}
+ className="mb-4 justify-content-end d-flex align-items-start"
+ >
+ {fields.length > 1 ? (
+ <Button
+ variant="danger"
+ size="sm"
+ title="Remove"
+ onClick={() => fields.remove(index)}
+ data-action="delete"
+ data-cy="delete"
+ >
+ <i className="fa-fw fa fa-remove"></i>
+ </Button>
+ ) : (
+ // Show clear button only when there's one item and it has data
+ <Button
+ variant="danger"
+ size="sm"
+ title="Clear item data"
+ onClick={() => clearPermissionItem(index)}
+ data-action="clear"
+ data-cy="clear"
+ >
+ <i className="fa-fw fa fa-remove"></i>
+ </Button>
+ )}
+ </Col>
+ </Row>
+ <hr />
+ </React.Fragment>
+ ))}
+
+ {/* Add More Rules Button */}
+ <Row className="my-3">
+ <Col>
+ <Button
+ variant="outline-primary"
+ onClick={() => fields.push({})}
+ >
+ <i className="fa-fw fa fa-plus me-1" />
+ {fields.length === 0 ? "Add Rule" : "Add more rules"}
+ </Button>
+ </Col>
+ </Row>
+ </>
+ )}
+ </FieldArray>
+ </div>
+ );
+}
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyValidityPeriodModal.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyValidityPeriodModal.jsx
new file mode 100644
index 000000000..193042912
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/PolicyValidityPeriodModal.jsx
@@ -0,0 +1,240 @@
+/*
+ * 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 React, { useState, useEffect } from "react";
+import { Button, Modal, Table, InputGroup, FormControl } from "react-bootstrap";
+import Select from "react-select";
+import Datetime from "react-datetime";
+import { getAllTimeZoneList } from "Utils/XAUtils";
+import { isEmpty, cloneDeep } from "lodash";
+import moment from "moment-timezone";
+import {
+ CustomTooltip,
+ selectInputCustomStyles
+} from "Components/CommonComponents";
+
+const PolicyValidityPeriodModal = ({
+ showModal,
+ handleCloseModal,
+ currentValues,
+ onSave
+}) => {
+ const [draftValues, setDraftValues] = useState([]);
+
+ // Initialize draft values when modal opens
+ useEffect(() => {
+ if (showModal) {
+ setDraftValues(
+ currentValues && currentValues.length > 0
+ ? cloneDeep(currentValues)
+ : []
+ );
+ }
+ }, [showModal, currentValues]);
+
+ const RenderInput = (props) => {
+ function clear() {
+ props.dateProps.onChange({ target: { value: "" } });
+ }
+ return (
+ <InputGroup className="mb-2">
+ <FormControl {...props.dateProps} readOnly />
+ <InputGroup.Text onClick={clear} className="cursor-pointer">
+ X
+ </InputGroup.Text>
+ </InputGroup>
+ );
+ };
+
+ const calEndDate = (sDate, currentDate) => {
+ if (sDate && sDate?.endTime) {
+ return currentDate.isBefore(sDate.endTime);
+ } else {
+ return true;
+ }
+ };
+
+ const calStartDate = (sDate, currentDate) => {
+ if (sDate && sDate?.startTime) {
+ return currentDate.isAfter(sDate.startTime);
+ } else {
+ let yesterday = moment().subtract(1, "day");
+ return currentDate.isAfter(yesterday);
+ }
+ };
+
+ const handleSave = () => {
+ // Save draft values to actual form
+ onSave(draftValues);
+ handleCloseModal();
+ };
+
+ const handleCancel = () => {
+ // Discard changes and close
+ setDraftValues([]);
+ handleCloseModal();
+ };
+
+ const handleAddTimePeriod = () => {
+ setDraftValues([...draftValues, {}]);
+ };
+
+ const handleRemoveTimePeriod = (index) => {
+ const newValues = [...draftValues];
+ newValues.splice(index, 1);
+ setDraftValues(newValues);
+ };
+
+ const handleFieldChange = (index, field, value) => {
+ const newValues = [...draftValues];
+ if (!newValues[index]) {
+ newValues[index] = {};
+ }
+ newValues[index][field] = value;
+ setDraftValues(newValues);
+ };
+
+ return (
+ <Modal show={showModal} size="lg" onHide={handleCancel} backdrop="static">
+ <Modal.Header closeButton>
+ <Modal.Title>Policy Validity Period</Modal.Title>
+ </Modal.Header>
+ <Modal.Body>
+ <Table bordered>
+ <thead>
+ <tr>
+ <th>Start Date</th>
+ <th>End Date</th>
+ <th>
+ Time Zone{" "}
+ <span>
+ <CustomTooltip
+ placement="right"
+ content={
+ <p className="pd-10" style={{ fontSize: "small" }}>
+ Please Select StartDate or EndDate to enable Time Zone
+ </p>
+ }
+ icon="fa-fw fa fa-info-circle"
+ />
+ </span>
+ </th>
+ <th>Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {draftValues.length > 0 ? (
+ draftValues.map((schedule, index) => (
+ <tr key={index}>
+ <td className="text-center">
+ <Datetime
+ value={schedule?.startTime || ""}
+ renderInput={(props) => <RenderInput dateProps={props} />}
+ dateFormat="MM-DD-YYYY"
+ timeFormat="HH:mm:ss"
+ closeOnSelect
+ isValidDate={(currentDate) =>
+ calEndDate(schedule, currentDate)
+ }
+ onChange={(value) =>
+ handleFieldChange(index, "startTime", value)
+ }
+ />
+ </td>
+ <td className="text-center">
+ <Datetime
+ value={schedule?.endTime || ""}
+ renderInput={(props) => <RenderInput dateProps={props} />}
+ dateFormat="MM-DD-YYYY"
+ timeFormat="HH:mm:ss"
+ closeOnSelect
+ isValidDate={(currentDate) =>
+ calStartDate(schedule, currentDate)
+ }
+ onChange={(value) =>
+ handleFieldChange(index, "endTime", value)
+ }
+ />
+ </td>
+ <td className="text-center">
+ <Select
+ value={schedule?.timeZone || null}
+ options={getAllTimeZoneList()}
+ getOptionLabel={(obj) => obj.text}
+ getOptionValue={(obj) => obj.id}
+ isClearable={true}
+ isDisabled={
+ isEmpty(schedule?.startTime) &&
+ isEmpty(schedule?.endTime)
+ }
+ styles={selectInputCustomStyles}
+ onChange={(value) =>
+ handleFieldChange(index, "timeZone", value)
+ }
+ />
+ </td>
+ <td className="text-center">
+ <Button
+ variant="danger"
+ size="sm"
+ className="btn-mini"
+ title="Remove"
+ onClick={() => handleRemoveTimePeriod(index)}
+ data-action="delete"
+ data-cy="delete"
+ >
+ <i className="fa-fw fa fa-remove"></i>
+ </Button>
+ </td>
+ </tr>
+ ))
+ ) : (
+ <tr>
+ <td colSpan="4" className="text-center text-muted">
+ No time periods added. Click Add Time "Period" to
+ get started.
+ </td>
+ </tr>
+ )}
+ </tbody>
+ </Table>
+ <Button
+ type="button"
+ variant="outline-primary"
+ className="btn-sm"
+ onClick={handleAddTimePeriod}
+ data-action="addTime"
+ data-cy="addTime"
+ >
+ <i className="fa-fw fa fa-plus"></i> Add Time Period
+ </Button>
+ </Modal.Body>
+ <Modal.Footer>
+ <Button variant="secondary" size="sm" onClick={handleCancel}>
+ Cancel
+ </Button>
+ <Button variant="primary" size="sm" onClick={handleSave}>
+ Save
+ </Button>
+ </Modal.Footer>
+ </Modal>
+ );
+};
+
+export default PolicyValidityPeriodModal;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ResourcesStep.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ResourcesStep.jsx
new file mode 100644
index 000000000..f3b0da297
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ResourcesStep.jsx
@@ -0,0 +1,121 @@
+/*
+ * 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 React from "react";
+import { Row, Col, Button } from "react-bootstrap";
+import { FieldArray } from "react-final-form-arrays";
+import ResourceComp from "../../../Resources/ResourceComp";
+
+const ResourcesStep = ({ values, form, selectedServiceComponentDef }) => {
+ // Get policyType from form values (defaults to 0 for Access policy)
+ const policyType = values?.policyType !== undefined ? values.policyType : 0;
+
+ // Ensure additionalResources exists
+ React.useEffect(() => {
+ if (
+ !values.additionalResources ||
+ values.additionalResources.length === 0
+ ) {
+ form.change("additionalResources", [{}]);
+ }
+ }, []);
+
+ // Add a new resource to the array
+ const addResource = () => {
+ const currentResources = values.additionalResources || [];
+ form.change("additionalResources", [...currentResources, {}]);
+ };
+
+ // serviceName can be a react-select option {value, label} (stepper) or a plain string (edit form)
+ const serviceDetails = {
+ name:
+ typeof values.serviceName === "object"
+ ? (values.serviceName?.value ?? "")
+ : (values.serviceName ?? "")
+ };
+
+ return (
+ <Row>
+ <Col xxl={12}>
+ <p className="stepper-instruction-text mb-4">
+ Define the resources for which this policy will apply
+ </p>
+
+ {/* Multiple Resources with FieldArray */}
+ <FieldArray name="additionalResources">
+ {({ fields }) => (
+ <>
+ {fields.map((name, index) => (
+ <Row className="resource-block mb-3" key={`${name}-${index}`}>
+ <Col md={11}>
+ {selectedServiceComponentDef && (
+ <ResourceComp
+ serviceDetails={serviceDetails}
+ serviceCompDetails={selectedServiceComponentDef}
+ formValues={values.additionalResources?.[index]}
+ policyType={policyType}
+ name={name}
+ isMultiResources={true}
+ />
+ )}
+ </Col>
+ <Col
+ md={1}
+ className="d-flex align-items-start justify-content-start"
+ >
+ {fields.length > 1 && (
+ <Button
+ variant="danger"
+ size="sm"
+ title="Remove Resource"
+ onClick={() => fields.remove(index)}
+ data-action="delete"
+ data-cy="delete"
+ >
+ <i className="fa-fw fa fa-remove"></i>
+ </Button>
+ )}
+ </Col>
+ {fields.length > 1 && index < fields.length - 1 && <hr />}
+ </Row>
+ ))}
+ </>
+ )}
+ </FieldArray>
+
+ {/* Add Resource Button */}
+ <Row className="mt-3">
+ <Col>
+ <Button
+ type="button"
+ variant="outline-primary"
+ onClick={addResource}
+ data-action="addResource"
+ data-cy="addResource"
+ >
+ <i className="fa-fw fa fa-plus"></i> Add Resource
+ </Button>
+ </Col>
+ </Row>
+ </Col>
+ </Row>
+ );
+};
+
+export default ResourcesStep;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ReviewConfirmStep.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ReviewConfirmStep.jsx
new file mode 100644
index 000000000..8f555c5dc
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ReviewConfirmStep.jsx
@@ -0,0 +1,681 @@
+/*
+ * 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 React from "react";
+import { Accordion, Badge, Table } from "react-bootstrap";
+import { isEmpty, isArray, find, map } from "lodash";
+import moment from "moment";
+import {
+ getResourcesDefVal,
+ getPolicyConditionDisplayLbl
+} from "Utils/XAUtils";
+import { DefStatus, RangerPolicyType } from "Utils/XAEnums";
+import userColourIcon from "Images/user-colour.svg";
+import groupColourIcon from "Images/group-colour.svg";
+import roleColourIcon from "Images/role-colour.svg";
+
+// ─── reusable building blocks ────────────────────────────────────────────────
+
+const Empty = () => <span className="text-muted fst-italic">—</span>;
+
+const StatusBadge = ({ on, onLabel = "Yes", offLabel = "No" }) => (
+ <Badge bg={on ? "success" : "secondary"}>{on ? onLabel : offLabel}</Badge>
+);
+
+/** Icon + name badges for users / groups / roles */
+const PrincipalRow = ({ icon, alt, items = [] }) =>
+ items.length === 0 ? null : (
+ <div className="d-flex align-items-center flex-wrap gap-1 mb-1">
+ <img src={icon} height="24" width="24" alt={alt} className="me-1" />
+ {items.map((p, i) => (
+ <Badge
+ key={i}
+ bg="light"
+ text="dark"
+ className="border"
+ style={{ fontSize: "13px", fontWeight: "400" }}
+ >
+ {p.name || p.value || p}
+ </Badge>
+ ))}
+ </div>
+ );
+
+/**
+ * One label + value row inside a section.
+ * label column is fixed at 190 px; value fills the rest.
+ * ✅ NEW: Accepts isLast prop to remove bottom border from last item
+ */
+const InfoRow = ({ label, children, isLast = false }) => (
+ <div
+ className="d-flex align-items-start py-2"
+ style={{
+ borderBottom: isLast ? "none" : "1px solid #dee2e6"
+ }}
+ >
+ <span className="me-3" style={{ minWidth: 210, fontSize: "14px" }}>
+ {label}
+ </span>
+ <div className="flex-grow-1" style={{ fontSize: "14px" }}>
+ {children ?? <Empty />}
+ </div>
+ </div>
+);
+
+/** Accordion section header with step number + icon */
+const SectionHeader = ({ title }) => (
+ <span className="d-flex align-items-center gap-2">{title}</span>
+);
+
+// ─── main component ──────────────────────────────────────────────────────────
+
+const ReviewConfirmStep = ({ values, selectedServiceComponentDef }) => {
+ const policyType = values.policyType;
+ const isMasking =
+ policyType == RangerPolicyType.RANGER_MASKING_POLICY_TYPE.value;
+ const isRowFilter =
+ policyType == RangerPolicyType.RANGER_ROW_FILTER_POLICY_TYPE.value;
+ const enableDenyAndExceptions =
+ selectedServiceComponentDef?.options?.enableDenyAndExceptionsInPolicies ===
+ "true";
+
+ const policyTypeLabel = isMasking
+ ? "Masking"
+ : isRowFilter
+ ? "Row Filter"
+ : "Access";
+
+ const displayTagPermissionItem = (permission) => {
+ let srcOp = [];
+ if (isMasking) {
+ srcOp = selectedServiceComponentDef.dataMaskDef?.accessTypes || [];
+ } else if (isRowFilter) {
+ srcOp = selectedServiceComponentDef.rowFilterDef?.accessTypes || [];
+ } else {
+ srcOp = selectedServiceComponentDef.accessTypes;
+ }
+ const labels = map(permission, (perm) => {
+ return find(srcOp, { name: perm })?.label;
+ });
+ return labels;
+ };
+
+ const resourcesArray = (values.additionalResources || []).filter(
+ (r) => r && !isEmpty(r)
+ );
+
+ const renderResources = () => {
+ if (resourcesArray.length === 0) return <Empty />;
+
+ const resourceDef =
+ getResourcesDefVal(selectedServiceComponentDef, policyType) || [];
+
+ // Collect all numeric levels present in the def
+ const levels = [...new Set(resourceDef.map((d) => d.level ?? 0))].sort(
+ (a, b) => a - b
+ );
+
+ return resourcesArray.map((resourceItem, ridx) => {
+ // Build rows by iterating levels
+ const rows = [];
+ for (const level of levels) {
+ const nameObj = resourceItem[`resourceName-${level}`];
+ const valueArr = resourceItem[`value-${level}`];
+ if (!nameObj || !valueArr) continue;
+
+ const resourceName = nameObj.name || nameObj;
+ const defItem = find(resourceDef, { name: resourceName });
+ if (!defItem) continue;
+
+ // Extract plain string values
+ const vals = isArray(valueArr)
+ ? valueArr
+ .map((v) => (typeof v === "object" ? (v.value ?? v.label) : v))
+ .filter(Boolean)
+ : valueArr
+ ? [
+ typeof valueArr === "object"
+ ? (valueArr.value ?? valueArr.label)
+ : valueArr
+ ]
+ : [];
+
+ rows.push({
+ label: defItem.label || resourceName,
+ level,
+ vals,
+ isExcludes: resourceItem[`isExcludesSupport-${level}`] === false,
+ isRecursive: resourceItem[`isRecursiveSupport-${level}`] !== false,
+ excludesSupported: defItem.excludesSupported,
+ recursiveSupported: defItem.recursiveSupported
+ });
+ }
+
+ if (rows.length === 0) return null;
+
+ return (
+ <div key={ridx}>
+ {resourcesArray.length > 1 && (
+ <p className="text-uppercase small mb-2 mt-3">#{ridx + 1}</p>
+ )}
+ <Table bordered size="sm" className="mb-3 align-middle">
+ <tbody>
+ {rows.map((r, i) => (
+ <tr key={i}>
+ <td style={{ width: 210 }}>{r.label}</td>
+ <td>
+ <div className="d-flex flex-wrap gap-1">
+ {r.vals.length > 0 ? (
+ r.vals.map((v, vi) => (
+ <Badge key={vi} bg="primary">
+ {v}
+ </Badge>
+ ))
+ ) : (
+ <Empty />
+ )}
+ </div>
+ </td>
+ <td style={{ width: 224 }}>
+ <div className="d-flex flex-wrap gap-1">
+ {r.excludesSupported && (
+ <Badge
+ bg={r.isExcludes ? "warning" : "success"}
+ text={r.isExcludes ? "dark" : undefined}
+ className="text-capitalize"
+ >
+ {r.isExcludes
+ ? DefStatus.ExcludeStatus.STATUS_EXCLUDE.label
+ : DefStatus.ExcludeStatus.STATUS_INCLUDE.label}
+ </Badge>
+ )}
+ {r.recursiveSupported && (
+ <Badge bg="secondary" className="text-capitalize">
+ {r.isRecursive
+ ? DefStatus.RecursiveStatus.STATUS_RECURSIVE.label
+ : DefStatus.RecursiveStatus.STATUS_NONRECURSIVE
+ .label}
+ </Badge>
+ )}
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </Table>
+ </div>
+ );
+ });
+ };
+
+ // ── single rule card ─────────────────────────────────────────────────────
+ const RuleCard = ({ item, idx, ruleLabel }) => {
+ if (!item || isEmpty(item)) return null;
+
+ const users = item.users?.users || (isArray(item.users) ? item.users : []);
+ const groups =
+ item.users?.groups || (isArray(item.groups) ? item.groups : []);
+ const roles = item.users?.roles || (isArray(item.roles) ? item.roles : []);
+ const hasPrincipal =
+ users.length > 0 || groups.length > 0 || roles.length > 0;
+ const isTagAccesses = !!item.accesses?.tableList;
+ const hasAccesses = isTagAccesses
+ ? item.accesses.tableList.length > 0
+ : isArray(item.accesses);
+ const hasConditions =
+ (item.conditions && !isEmpty(item.conditions)) ||
+ selectedServiceComponentDef?.policyConditions?.length > 0;
+ const hasDataMask = !!item.dataMaskInfo?.value;
+ const hasRowFilter = !!(
+ item.rowFilterInfo && String(item.rowFilterInfo).trim()
+ );
+ const hasDelegateAdmin = !isMasking && !isRowFilter && !isTagAccesses;
+
+ if (
+ !hasPrincipal &&
+ !hasAccesses &&
+ !hasConditions &&
+ !hasDataMask &&
+ !hasRowFilter &&
+ !hasDelegateAdmin
+ ) {
+ return null;
+ }
+
+ return (
+ <div className="border rounded mb-3 mt-2 overflow-hidden">
+ {/* rule header */}
+ <div className="px-3 py-2">
+ <span className="text-primary">
+ {ruleLabel} #{idx + 1}
+ </span>
+ </div>
+
+ {/* rule body */}
+ <div className="px-3 py-2">
+ {hasAccesses && (
+ <InfoRow label="Permissions">
+ {isTagAccesses ? (
+ <Table bordered size="sm" className="mb-0 align-middle">
+ <thead className="table-light">
+ <tr>
+ <th>Service</th>
+ <th>Permissions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {item.accesses.tableList.map((t, ti) => (
+ <tr key={ti}>
+ <td className="text-uppercase small">
+ {t.serviceName}
+ </td>
+ <td>
+ <div className="d-flex flex-wrap gap-1">
+ {(
+ displayTagPermissionItem(t.permission || []) || []
+ ).map((p, pi) => (
+ <Badge key={pi} bg="primary">
+ {p}
+ </Badge>
+ ))}
+ </div>
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </Table>
+ ) : item.accesses.length > 0 ? (
+ <div className="d-flex flex-wrap gap-1">
+ {item.accesses.map((a, ai) => (
+ <Badge key={ai} bg="primary">
+ {a?.label}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <Empty />
+ )}
+ </InfoRow>
+ )}
+
+ {/* Users / Groups / Roles - ONLY SHOW IF HAS PRINCIPAL */}
+ {hasPrincipal && (
+ <InfoRow label="Users / Groups / Roles">
+ <PrincipalRow icon={userColourIcon} alt="Users" items={users} />
+ <PrincipalRow
+ icon={groupColourIcon}
+ alt="Groups"
+ items={groups}
+ />
+ <PrincipalRow icon={roleColourIcon} alt="Roles" items={roles} />
+ </InfoRow>
+ )}
+
+ {/* Rule conditions - ONLY SHOW IF HAS CONDITIONS */}
+ {hasConditions && (
+ <InfoRow label="Rule Conditions">
+ {item?.conditions && !isEmpty(item?.conditions) ? (
+ <Table bordered size="sm" className="mb-0 align-middle">
+ <thead className="table-light">
+ <tr>
+ <th className="small p-2">Condition</th>
+ <th className="small p-2">Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ {Object.keys(item.conditions).map((k) => {
+ const v = item.conditions[k];
+ if (v === "" || v == null) return null;
+ const def = find(
+ selectedServiceComponentDef?.policyConditions,
+ (m) => m.name === k
+ );
+ return (
+ <tr key={k}>
+ <td style={{ minWidth: "210px" }}>
+ {getPolicyConditionDisplayLbl(def?.label)}
+ </td>
+ <td className="text-word-break">
+ {isArray(v) ? v.join(", ") : String(v)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </Table>
+ ) : (
+ <Empty />
+ )}
+ </InfoRow>
+ )}
+
+ {/* Masking option - ONLY SHOW IF HAS DATA MASK */}
+ {hasDataMask && (
+ <InfoRow label="Masking Option" isLast={true}>
+ <Badge bg="warning" text="dark">
+ {item.dataMaskInfo.label || item.dataMaskInfo.value}
+ </Badge>
+ {item.dataMaskInfo.valueExpr && (
+ <code className="ms-2 text-muted small">
+ {item.dataMaskInfo.valueExpr}
+ </code>
+ )}
+ </InfoRow>
+ )}
+
+ {/* Row filter - ONLY SHOW IF HAS ROW FILTER */}
+ {hasRowFilter && (
+ <InfoRow label="Row Level Filter" isLast={true}>
+ <code className="bg-light border rounded px-2 py-1 small d-inline-block">
+ {String(item.rowFilterInfo)}
+ </code>
+ </InfoRow>
+ )}
+
+ {/* Delegate Admin - ONLY SHOW IF HAS DELEGATE ADMIN */}
+ {hasDelegateAdmin && (
+ <InfoRow label="Delegate Admin" isLast={true}>
+ <Badge bg={item?.delegateAdmin ? "success" : "secondary"}>
+ {item?.delegateAdmin ? "Yes" : "No"}
+ </Badge>
+ </InfoRow>
+ )}
+ </div>
+ </div>
+ );
+ };
+
+ // ── rule group (e.g. "Allow Rules") ──────────────────────────────────────
+ const RuleGroup = ({ attrName, title }) => {
+ const items = values[attrName] || [];
+ const valid = items.filter((it) => it && !isEmpty(it));
+ const ruleLabel = title.replace(/ Rules$/, " Rule");
+ return (
+ <div className="mb-4">
+ <p
+ className="fw-bold m-0"
+ style={{
+ borderLeft: "4px solid #0d6efd",
+ paddingLeft: "0.6rem",
+ width: "226px",
+ display: valid.length === 0 ? "inline-block" : "block"
+ }}
+ >
+ {title}
+ </p>
+ {valid.length === 0 ? (
+ <p className="text-muted fst-italic ms-2 mb-0 d-inline-block">
+ No rules configured
+ </p>
+ ) : (
+ valid.map((item, idx) => (
+ <RuleCard
+ key={idx}
+ item={item}
+ idx={idx}
+ ruleLabel={ruleLabel}
+ className="d-block"
+ />
+ ))
+ )}
+ </div>
+ );
+ };
+
+ // ── access rules block ────────────────────────────────────────────────────
+ const renderAccessRules = () => {
+ if (isMasking)
+ return <RuleGroup attrName="dataMaskPolicyItems" title="Mask Rules" />;
+ if (isRowFilter)
+ return (
+ <RuleGroup attrName="rowFilterPolicyItems" title="Row Filter Rules" />
+ );
+
+ return (
+ <>
+ <RuleGroup attrName="policyItems" title="Allow Rules" />
+ <RuleGroup
+ attrName="allowExceptions"
+ title="Exclude from Allow Rules"
+ />
+
+ {/* Deny All */}
+ <div
+ className="d-flex align-items-center gap-2 rounded px-3 py-2 mb-4"
+ style={{
+ background: "#fff8e1",
+ border: "1px solid #ffe082",
+ fontSize: "0.85rem"
+ }}
+ >
+ <span style={{ width: 190 }}>Deny All Other Accesses</span>
+ <StatusBadge
+ on={values.isDenyAllElse}
+ onLabel="True"
+ offLabel="False"
+ />
+ </div>
+
+ {enableDenyAndExceptions && !values.isDenyAllElse && (
+ <>
+ <RuleGroup attrName="denyPolicyItems" title="Deny Rules" />
+ <RuleGroup
+ attrName="denyExceptions"
+ title="Exclude from Deny Rules"
+ />
+ </>
+ )}
+ </>
+ );
+ };
+
+ // ── policy conditions helper ──────────────────────────────────────────────
+ const renderPolicyConditions = () => {
+ if (!values.conditions || isEmpty(values.conditions)) return null;
+ const entries = Object.keys(values.conditions).filter(
+ (k) => values.conditions[k] !== "" && values.conditions[k] != null
+ );
+ if (entries.length === 0) return null;
+ return (
+ <Table bordered size="sm" className="mb-0 align-middle">
+ <thead className="table-light">
+ <tr>
+ <th className="small p-2">Condition</th>
+ <th className="small p-2">Value</th>
+ </tr>
+ </thead>
+ <tbody>
+ {entries.map((k) => {
+ const v = values.conditions[k];
+ const def = find(
+ selectedServiceComponentDef?.policyConditions,
+ (m) => m.name === k
+ );
+ return (
+ <tr key={k}>
+ <td style={{ minWidth: "210px" }}>
+ {getPolicyConditionDisplayLbl(def?.label)}
+ </td>
+ <td className="text-word-break">
+ {isArray(v) ? v.join(", ") : String(v)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </Table>
+ );
+ };
+
+ // ── validity schedules helper ──────────────────────────────────────────────
+ const renderValidity = () => {
+ const schedules = (values.validitySchedules || []).filter((s) => s != null);
+ if (schedules.length === 0) return null;
+ return (
+ <Table bordered size="sm" className="mb-0 align-middle">
+ <thead className="table-light">
+ <tr>
+ <th>Start Date</th>
+ <th>End Date</th>
+ <th>Time Zone</th>
+ </tr>
+ </thead>
+ <tbody>
+ {schedules.map((s, i) => (
+ <tr key={i}>
+ <td className="small">
+ {s?.startTime
+ ? moment(s.startTime).format("YYYY/MM/DD HH:mm:ss")
+ : "—"}
+ </td>
+ <td className="small">
+ {s?.endTime
+ ? moment(s.endTime).format("YYYY/MM/DD HH:mm:ss")
+ : "—"}
+ </td>
+ <td className="small">{s?.timeZone?.text || "—"}</td>
+ </tr>
+ ))}
+ </tbody>
+ </Table>
+ );
+ };
+
+ const policyConditionsContent = renderPolicyConditions();
+ const validityContent = renderValidity();
+
+ return (
+ <div>
+ <Accordion
+ defaultActiveKey={["1", "2", "3", "4"]}
+ alwaysOpen
+ className="policy-permission-items-accordion"
+ >
+ {/* Step 1 — Service */}
+ <Accordion.Item eventKey="1">
+ <Accordion.Header>
+ <SectionHeader title="Service" />
+ </Accordion.Header>
+ <Accordion.Body>
+ <InfoRow label="Service Type">
+ {values.serviceType?.label || <Empty />}
+ </InfoRow>
+ <InfoRow label="Service Name">
+ {values.serviceName?.label || values.serviceName || <Empty />}
+ </InfoRow>
+ <InfoRow label="Security Zone">
+ {values.zoneName?.label || <Empty />}
+ </InfoRow>
+ <InfoRow label="Policy Type" isLast={true}>
+ <Badge
+ bg={isMasking ? "warning" : isRowFilter ? "info" : "primary"}
+ text={isMasking ? "dark" : undefined}
+ >
+ {policyTypeLabel}
+ </Badge>
+ </InfoRow>
+ </Accordion.Body>
+ </Accordion.Item>
+
+ {/* Step 2 — Resources */}
+ <Accordion.Item eventKey="2">
+ <Accordion.Header>
+ <SectionHeader title="Policy Resources" />
+ </Accordion.Header>
+ <Accordion.Body>{renderResources()}</Accordion.Body>
+ </Accordion.Item>
+
+ {/* Step 3 — Access Rules */}
+ <Accordion.Item eventKey="3">
+ <Accordion.Header>
+ <SectionHeader title="Access Rules" />
+ </Accordion.Header>
+ <Accordion.Body>{renderAccessRules()}</Accordion.Body>
+ </Accordion.Item>
+
+ {/* Step 4 — Policy Details */}
+ <Accordion.Item eventKey="4">
+ <Accordion.Header>
+ <SectionHeader title="Policy Details" />
+ </Accordion.Header>
+ <Accordion.Body>
+ <InfoRow label="Policy Name">
+ {values.policyName || <Empty />}
+ </InfoRow>
+
+ <InfoRow label="Policy Labels">
+ {values.policyLabels?.length > 0 ? (
+ <div className="d-flex flex-wrap gap-1">
+ {values.policyLabels.map((l, i) => (
+ <Badge key={i} bg="secondary">
+ {l.label || l.value || l}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <Empty />
+ )}
+ </InfoRow>
+
+ {values.description && (
+ <InfoRow label="Description">{values.description}</InfoRow>
+ )}
+
+ <InfoRow label="Policy Status">
+ <StatusBadge
+ on={values.isEnabled !== false}
+ onLabel="Enabled"
+ offLabel="Disabled"
+ />
+ </InfoRow>
+
+ <InfoRow label="Policy Priority">
+ <Badge
+ bg={values.policyPriority === 1 ? "warning" : "info"}
+ text={values.policyPriority === 1 ? "dark" : undefined}
+ >
+ {values.policyPriority === 1 ? "Override" : "Normal"}
+ </Badge>
+ </InfoRow>
+
+ {validityContent && (
+ <InfoRow label="Policy Validity">{validityContent}</InfoRow>
+ )}
+
+ {policyConditionsContent && (
+ <InfoRow label="Policy Conditions">
+ {policyConditionsContent}
+ </InfoRow>
+ )}
+
+ <InfoRow label="Audit Logging" isLast={true}>
+ <StatusBadge
+ on={values.isAuditEnabled !== false}
+ onLabel="Enabled"
+ offLabel="Disabled"
+ />
+ </InfoRow>
+ </Accordion.Body>
+ </Accordion.Item>
+ </Accordion>
+ </div>
+ );
+};
+
+export default ReviewConfirmStep;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ServiceStep.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ServiceStep.jsx
new file mode 100644
index 000000000..215545f88
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/ServiceStep.jsx
@@ -0,0 +1,451 @@
+/*
+ * 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 React, { useState, useRef } from "react";
+import { Field } from "react-final-form";
+import { Form as FormB, Row, Col, Modal, Button } from "react-bootstrap";
+import Select from "react-select";
+import AsyncSelect from "react-select/async";
+import {
+ getServiceDefType,
+ getServiceNameByServiceType,
+ getZoneNameByServiceID,
+ isRenderMasking,
+ isRenderRowFilter,
+ getSelectBoxErrorStyles,
+ isKeyAdmin,
+ isKMSAuditor
+} from "Utils/XAUtils";
+
+const required = (value) => (value ? undefined : "Required");
+
+const ServiceStep = ({
+ values,
+ form,
+ selectedServiceComponentDef,
+ onServiceTypeChange,
+ hasProgressedPastService,
+ onResetForm
+}) => {
+ const [showResetModal, setShowResetModal] = useState(false);
+ const pendingServiceSnapshotRef = useRef(null);
+ const pendingAfterResetRef = useRef(null);
+
+ const needsConfirmReset = Boolean(hasProgressedPastService);
+ const isKeyAdminOrKMSAuditor = isKeyAdmin() || isKMSAuditor();
+
+ /**
+ * After the user has moved past the Service step, changing service details
+ * invalidates later wizard data. We ask for confirmation, then reinitialize
+ * the form from defaults plus the new service-field snapshot.
+ */
+ const requestChangeOrConfirmReset = (
+ applyChange,
+ getServiceSnapshot,
+ afterReset
+ ) => {
+ if (!needsConfirmReset) {
+ applyChange();
+ return;
+ }
+ pendingServiceSnapshotRef.current = getServiceSnapshot();
+ pendingAfterResetRef.current = afterReset || null;
+ setShowResetModal(true);
+ };
+
+ const handleServiceTypeChange = (input, newValue) => {
+ if (values?.serviceType?.value === newValue?.value) {
+ return;
+ }
+
+ requestChangeOrConfirmReset(
+ () => {
+ input.onChange(newValue);
+ form.change("serviceName", null);
+ if (onServiceTypeChange) {
+ onServiceTypeChange(newValue);
+ }
+ },
+ () => ({
+ serviceType: newValue,
+ serviceName: null,
+ zoneName: null,
+ policyType: 0
+ }),
+ () => onServiceTypeChange?.(newValue)
+ );
+ };
+
+ const handleServiceNameChange = (input, newValue) => {
+ if (values?.serviceName?.value === newValue?.value) {
+ return;
+ }
+
+ requestChangeOrConfirmReset(
+ () => {
+ input.onChange(newValue);
+ form.change("zoneName", null);
+ },
+ () => ({
+ serviceType: values.serviceType,
+ serviceName: newValue,
+ zoneName: null,
+ policyType: values.policyType !== undefined ? values.policyType : 0
+ })
+ );
+ };
+
+ const handleZoneNameChange = (input, newValue) => {
+ const prev = values?.zoneName;
+ const same =
+ prev === newValue ||
+ (prev?.value != null &&
+ newValue?.value != null &&
+ prev.value === newValue.value);
+ if (same) {
+ return;
+ }
+
+ requestChangeOrConfirmReset(
+ () => {
+ input.onChange(newValue);
+ },
+ () => ({
+ serviceType: values.serviceType,
+ serviceName: values.serviceName,
+ zoneName: newValue,
+ policyType: values.policyType !== undefined ? values.policyType : 0
+ })
+ );
+ };
+
+ const handlePolicyTypeChange = (input, newValue) => {
+ const cur = input.value === undefined ? 0 : input.value;
+ const next = newValue === undefined ? 0 : newValue;
+ if (cur === next) {
+ return;
+ }
+
+ requestChangeOrConfirmReset(
+ () => {
+ input.onChange(newValue);
+ },
+ () => ({
+ serviceType: values.serviceType,
+ serviceName: values.serviceName,
+ zoneName: values.zoneName,
+ policyType: newValue
+ })
+ );
+ };
+
+ const handleCancelReset = () => {
+ pendingServiceSnapshotRef.current = null;
+ pendingAfterResetRef.current = null;
+ setShowResetModal(false);
+ };
+
+ const handleConfirmReset = () => {
+ const snapshot = pendingServiceSnapshotRef.current;
+ const afterReset = pendingAfterResetRef.current;
+ pendingServiceSnapshotRef.current = null;
+ pendingAfterResetRef.current = null;
+ setShowResetModal(false);
+ afterReset?.();
+ if (onResetForm) {
+ onResetForm(snapshot || {});
+ }
+ };
+
+ const loadServiceNames = async () => {
+ if (!values?.serviceType) {
+ return [];
+ }
+ const serviceTypeValue = values.serviceType.value;
+ return await getServiceNameByServiceType(serviceTypeValue);
+ };
+
+ const loadZoneNames = async () => {
+ if (!values?.serviceName || !values?.serviceType) {
+ return [];
+ }
+ const serviceID = values.serviceName.serviceId;
+ return await getZoneNameByServiceID(serviceID, selectedServiceComponentDef);
+ };
+
+ return (
+ <Row>
+ <Col lg={11}>
+ <p className="stepper-instruction-text">
+ Pick the service to manage access rules for its resources
+ </p>
+ {/* Service Type */}
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label column className="fnt-14 column-1-fixed text-end">
+ Service Type
+ <span className="required-mark">*</span>
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="serviceType" validate={required}>
+ {({ input, meta }) => (
+ <>
+ <Select
+ {...input}
+ isClearable={true}
+ options={getServiceDefType()}
+ menuPlacement="auto"
+ placeholder="Select Service Type"
+ tabSelectsValue={false}
+ onChange={(value) => handleServiceTypeChange(input, value)}
+ styles={getSelectBoxErrorStyles(meta)}
+ />
+ {meta.touched && meta.error && (
+ <span className="text-danger">{meta.error}</span>
+ )}
+ </>
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* Service Name */}
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label column className="fnt-14 column-1-fixed text-end">
+ Service Name
+ <span className="required-mark">*</span>
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="serviceName" validate={required}>
+ {({ input, meta }) => (
+ <>
+ <AsyncSelect
+ {...input}
+ key={values?.serviceType?.value}
+ isClearable={true}
+ loadOptions={loadServiceNames}
+ defaultOptions
+ menuPlacement="auto"
+ placeholder="Select Service Name"
+ tabSelectsValue={false}
+ isDisabled={!values.serviceType}
+ onChange={(value) => handleServiceNameChange(input, value)}
+ styles={getSelectBoxErrorStyles(meta)}
+ />
+ {meta.touched && meta.error && (
+ <span className="text-danger">{meta.error}</span>
+ )}
+ </>
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* Show Zone Name and Policy Type only if Service Name is selected */}
+ {values.serviceName && !isKeyAdminOrKMSAuditor && (
+ <>
+ {/* Zone Name */}
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label column className="fnt-14 column-1-fixed text-end">
+ Zone Name
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="zoneName">
+ {({ input }) => (
+ <AsyncSelect
+ {...input}
+ key={values?.serviceName?.value}
+ isClearable={true}
+ P
+ loadOptions={loadZoneNames}
+ defaultOptions
+ menuPlacement="auto"
+ placeholder="Select Security Zone"
+ tabSelectsValue={false}
+ onChange={(value) => handleZoneNameChange(input, value)}
+ />
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+
+ {/* Policy Type */}
+ {selectedServiceComponentDef &&
+ (isRenderMasking(selectedServiceComponentDef.dataMaskDef) ||
+ isRenderRowFilter(
+ selectedServiceComponentDef.rowFilterDef
+ )) && (
+ <FormB.Group as={Row} className="mb-4">
+ <FormB.Label column className="column-1-fixed text-end">
+ Policy Type
+ </FormB.Label>
+ <Col className="mw-50">
+ <Field name="policyType">
+ {({ input }) => (
+ <div className="d-flex gap-3">
+ {/* Access Policy - Value: 0 */}
+ <div
+ className="card p-3 w-33"
+ style={{
+ cursor: "pointer",
+ border:
+ input.value === 0 || input.value === undefined
+ ? "2px solid #0b7fad"
+ : "1px solid #dee2e6"
+ }}
+ onClick={() => handlePolicyTypeChange(input, 0)}
+ >
+ <div className="form-check">
+ <input
+ className="form-check-input"
+ type="radio"
+ name="policyType"
+ id="access"
+ value={0}
+ checked={
+ input.value === 0 || input.value === undefined
+ }
+ onChange={() =>
+ handlePolicyTypeChange(input, 0)
+ }
+ />
+ <label
+ className="form-check-label"
+ htmlFor="access"
+ >
+ <strong>Access</strong>
+ </label>
+ </div>
+ <small className="text-muted mt-2">
+ Controls who can access the resource.
+ </small>
+ </div>
+
+ {/* Masking Policy - Value: 1 */}
+ {isRenderMasking(
+ selectedServiceComponentDef.dataMaskDef
+ ) && (
+ <div
+ className="card p-3 w-33"
+ style={{
+ cursor: "pointer",
+ border:
+ input.value === 1
+ ? "2px solid #0b7fad"
+ : "1px solid #dee2e6"
+ }}
+ onClick={() => handlePolicyTypeChange(input, 1)}
+ >
+ <div className="form-check">
+ <input
+ className="form-check-input"
+ type="radio"
+ name="policyType"
+ id="masking"
+ value={1}
+ checked={input.value === 1}
+ onChange={() =>
+ handlePolicyTypeChange(input, 1)
+ }
+ />
+ <label
+ className="form-check-label"
+ htmlFor="masking"
+ >
+ <strong>Masking</strong>
+ </label>
+ </div>
+ <small className="text-muted mt-2">
+ Masks sensitive data fields
+ </small>
+ </div>
+ )}
+
+ {/* Row Filtering Policy - Value: 2 */}
+ {isRenderRowFilter(
+ selectedServiceComponentDef.rowFilterDef
+ ) && (
+ <div
+ className="card p-3 w-33"
+ style={{
+ cursor: "pointer",
+ border:
+ input.value === 2
+ ? "2px solid #0b7fad"
+ : "1px solid #dee2e6"
+ }}
+ onClick={() => handlePolicyTypeChange(input, 2)}
+ >
+ <div className="form-check">
+ <input
+ className="form-check-input"
+ type="radio"
+ name="policyType"
+ id="rowFiltering"
+ value={2}
+ checked={input.value === 2}
+ onChange={() =>
+ handlePolicyTypeChange(input, 2)
+ }
+ />
+ <label
+ className="form-check-label"
+ htmlFor="rowFiltering"
+ >
+ <strong>Row Filtering</strong>
+ </label>
+ </div>
+ <small className="text-muted mt-2">
+ Shows only allowed rows
+ </small>
+ </div>
+ )}
+ </div>
+ )}
+ </Field>
+ </Col>
+ </FormB.Group>
+ )}
+ </>
+ )}
+
+ <Modal show={showResetModal} onHide={handleCancelReset} centered>
+ <Modal.Header closeButton>
+ <Modal.Title>Reset policy form?</Modal.Title>
+ </Modal.Header>
+ <Modal.Body>
+ <p className="mt-2 mb-0 text-muted">
+ All policy form fields will be cleared. Are you sure you want to
+ reset and start over ?
+ </p>
+ </Modal.Body>
+ <Modal.Footer>
+ <Button variant="secondary" size="sm" onClick={handleCancelReset}>
+ Cancel
+ </Button>
+ <Button variant="danger" size="sm" onClick={handleConfirmReset}>
+ Reset form
+ </Button>
+ </Modal.Footer>
+ </Modal>
+ </Col>
+ </Row>
+ );
+};
+
+export default ServiceStep;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/UsersGroupsAndRolesSelectionComponent.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/UsersGroupsAndRolesSelectionComponent.jsx
new file mode 100644
index 000000000..dc0b33649
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/PolicyCreateStepperStepComp/UsersGroupsAndRolesSelectionComponent.jsx
@@ -0,0 +1,495 @@
+/*
+ * 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 React, { useState, useMemo, useCallback } from "react";
+import {
+ Modal,
+ Button,
+ Form,
+ Row,
+ Col,
+ Tab,
+ Tabs,
+ Table
+} from "react-bootstrap";
+import AsyncSelect from "react-select/async";
+import { debounce, isEmpty } from "lodash";
+import { fetchApi } from "Utils/fetchAPI";
+import userGreyIcon from "Images/user-grey.svg";
+import groupGreyIcon from "Images/group-grey.svg";
+import roleGreyIcon from "Images/role-grey.svg";
+import userColourIcon from "Images/user-colour.svg";
+import groupColourIcon from "Images/group-colour.svg";
+import roleColourIcon from "Images/role-colour.svg";
+
+// Normalise any principal into { value: "USER:admin", name: "admin", type: "USER" }
+const normalisePrincipal = (obj) => ({
+ value: obj.value || `${obj.type}:${obj.name}`,
+ name: obj.name || obj.value,
+ type: obj.type
+});
+
+const UsersGroupsAndRolesSelectionComponent = ({
+ value = { users: [], groups: [], roles: [] },
+ onChange,
+ name,
+ placeholder = "Select users, groups, roles...",
+ showModal = true
+}) => {
+ const [modalShow, setModalShow] = useState(false);
+ const [draftSelectedItems, setDraftSelectedItems] = useState({
+ users: [],
+ groups: [],
+ roles: []
+ });
+ const [activeTab, setActiveTab] = useState("all");
+ const [searchInput, setSearchInput] = useState("");
+ const [checkedValues, setCheckedValues] = useState(new Set());
+
+ // Saved (committed) value from form state
+ const savedSelectedItems = {
+ users: Array.isArray(value?.users) ? value.users : [],
+ groups: Array.isArray(value?.groups) ? value.groups : [],
+ roles: Array.isArray(value?.roles) ? value.roles : []
+ };
+
+ // Flat list for AsyncSelect - use userList if available (preserves selection order),
+ // otherwise fall back to users + groups + roles concatenated
+ const flatSavedItems = useMemo(() => {
+ if (Array.isArray(value?.userList) && value.userList.length > 0) {
+ return value.userList;
+ }
+ return [
+ ...savedSelectedItems.users,
+ ...savedSelectedItems.groups,
+ ...savedSelectedItems.roles
+ ];
+ }, [value]);
+
+ const flatDraftItems = useMemo(() => {
+ return [
+ ...draftSelectedItems.users,
+ ...draftSelectedItems.groups,
+ ...draftSelectedItems.roles
+ ];
+ }, [draftSelectedItems]);
+
+ const getIcon = useCallback((type, colour = false) => {
+ if (type === "USER") return colour ? userColourIcon : userGreyIcon;
+ if (type === "GROUP") return colour ? groupColourIcon : groupGreyIcon;
+ if (type === "ROLE") return colour ? roleColourIcon : roleGreyIcon;
+ return userGreyIcon;
+ }, []);
+
+ // AsyncSelect option label (rendered at display time – no JSX stored in form state)
+ const renderOptionLabel = useCallback(
+ (option) => (
+ <div className="d-flex align-items-center">
+ <img
+ src={getIcon(option.type)}
+ height="20px"
+ width="20px"
+ alt={option.type}
+ />
+ <span className="ms-2">{option.name}</span>
+ </div>
+ ),
+ [getIcon]
+ );
+
+ // API fetch for AsyncSelect
+ const fetchPrincipals = async (inputValue) => {
+ if (!inputValue || inputValue.length < 1) return [];
+ try {
+ const resp = await fetchApi({
+ url: "xusers/lookup/principals",
+ params: { name: inputValue }
+ });
+ return (resp.data || []).map((obj) =>
+ normalisePrincipal({
+ value: `${obj.type}:${obj.name}`,
+ name: obj.name,
+ type: obj.type
+ })
+ );
+ } catch {
+ return [];
+ }
+ };
+
+ const debouncedFetch = useMemo(
+ () =>
+ debounce((inputValue, callback) => {
+ fetchPrincipals(inputValue).then(callback);
+ }, 300),
+ []
+ );
+
+ const loadOptions = (inputValue, callback) => {
+ if (isEmpty(inputValue)) {
+ callback([]);
+ return;
+ }
+ debouncedFetch(inputValue, callback);
+ };
+
+ // AsyncSelect change – store flat ordered list + split by type
+ const handleChange = (selected) => {
+ const items = (selected || []).map(normalisePrincipal);
+
+ if (onChange) {
+ onChange({
+ userList: items, // flat ordered list (preserves selection order)
+ users: items.filter((i) => i.type === "USER"),
+ groups: items.filter((i) => i.type === "GROUP"),
+ roles: items.filter((i) => i.type === "ROLE")
+ });
+ }
+ };
+
+ // Open modal – copy current saved selections into draft
+ const handleViewManage = () => {
+ setDraftSelectedItems({
+ users: [...savedSelectedItems.users],
+ groups: [...savedSelectedItems.groups],
+ roles: [...savedSelectedItems.roles]
+ });
+ setCheckedValues(new Set());
+ setSearchInput("");
+ setActiveTab("all");
+ setModalShow(true);
+ };
+
+ const handleSaveModal = () => {
+ if (onChange) onChange(draftSelectedItems);
+ setModalShow(false);
+ };
+
+ const handleCancelModal = () => {
+ setDraftSelectedItems({ users: [], groups: [], roles: [] });
+ setModalShow(false);
+ };
+
+ // Remove a single item – track order removal
+ const handleRemoveItem = (item) => {
+ const key =
+ item.type === "USER"
+ ? "users"
+ : item.type === "GROUP"
+ ? "groups"
+ : "roles";
+ setDraftSelectedItems((prev) => ({
+ ...prev,
+ [key]: prev[key].filter((i) => i.value !== item.value)
+ }));
+
+ // Remove from order tracking
+ setCheckedValues((prev) => {
+ const s = new Set(prev);
+ s.delete(item.value);
+ return s;
+ });
+ };
+
+ // Items visible in the modal – ordered by selection
+ const getFilteredItems = () => {
+ const typeMap = { users: "USER", groups: "GROUP", roles: "ROLE" };
+ let items =
+ activeTab === "all"
+ ? flatDraftItems
+ : flatDraftItems.filter((i) => i.type === typeMap[activeTab]);
+
+ if (searchInput.trim()) {
+ const q = searchInput.toLowerCase();
+ items = items.filter((i) => i.name.toLowerCase().includes(q));
+ }
+ return items;
+ };
+
+ // Toggle a row checkbox
+ const handleToggleCheck = (itemValue) => {
+ setCheckedValues((prev) => {
+ const s = new Set(prev);
+ if (s.has(itemValue)) s.delete(itemValue);
+ else s.add(itemValue);
+ return s;
+ });
+ };
+
+ // Select-all / deselect-all for visible rows
+ const handleSelectAll = (checked) => {
+ if (checked) {
+ setCheckedValues(new Set(filteredItems.map((i) => i.value)));
+ } else {
+ setCheckedValues(new Set());
+ }
+ };
+
+ // Delete all currently checked rows
+ const handleDeleteChecked = () => {
+ setDraftSelectedItems((prev) => ({
+ users: prev.users.filter((i) => !checkedValues.has(i.value)),
+ groups: prev.groups.filter((i) => !checkedValues.has(i.value)),
+ roles: prev.roles.filter((i) => !checkedValues.has(i.value))
+ }));
+ setCheckedValues(new Set());
+ };
+
+ const counts = {
+ all: flatDraftItems.length,
+ users: draftSelectedItems.users.length,
+ groups: draftSelectedItems.groups.length,
+ roles: draftSelectedItems.roles.length
+ };
+
+ const filteredItems = getFilteredItems();
+ const allChecked =
+ filteredItems.length > 0 &&
+ filteredItems.every((i) => checkedValues.has(i.value));
+ const someChecked = filteredItems.some((i) => checkedValues.has(i.value));
+ const checkedCount = filteredItems.filter((i) =>
+ checkedValues.has(i.value)
+ ).length;
+
+ const serviceSelectTheme = (theme) => ({
+ ...theme,
+ colors: { ...theme.colors, primary: "#0081ab" }
+ });
+
+ return (
+ <>
+ <Row>
+ <Col>
+ <AsyncSelect
+ name={name}
+ value={flatSavedItems}
+ onChange={handleChange}
+ loadOptions={loadOptions}
+ isMulti
+ placeholder={placeholder}
+ noOptionsMessage={({ inputValue }) =>
+ !inputValue
+ ? "Type to search users, groups, or roles..."
+ : "No results found"
+ }
+ cacheOptions
+ theme={serviceSelectTheme}
+ formatOptionLabel={renderOptionLabel}
+ getOptionValue={(option) => option.value}
+ loadingMessage={() => "Loading..."}
+ isClearable={false}
+ />
+ </Col>
+ <Col className="column-3-fixed">
+ {showModal && (
+ <Button
+ variant="link"
+ onClick={handleViewManage}
+ className="text-primary"
+ style={{ whiteSpace: "nowrap" }}
+ >
+ View & Manage All
+ </Button>
+ )}
+ </Col>
+ </Row>
+
+ <Modal
+ show={modalShow}
+ onHide={handleCancelModal}
+ size="lg"
+ backdrop="static"
+ >
+ <Modal.Header closeButton>
+ <Modal.Title>Manage Users, Groups & Roles</Modal.Title>
+ </Modal.Header>
+
+ <Modal.Body>
+ {/* Search */}
+ <Form.Group className="mb-3">
+ <Form.Control
+ type="text"
+ placeholder="Search by name..."
+ value={searchInput}
+ onChange={(e) => setSearchInput(e.target.value)}
+ />
+ </Form.Group>
+
+ {/* Tabs */}
+ <Tabs
+ activeKey={activeTab}
+ onSelect={(k) => setActiveTab(k)}
+ className="mb-3"
+ >
+ <Tab
+ eventKey="all"
+ title={`All${counts.all > 0 ? ` (${counts.all})` : ""}`}
+ />
+ <Tab
+ eventKey="users"
+ title={
+ <span className="d-flex align-items-center gap-1">
+ <img
+ src={userColourIcon}
+ height="16px"
+ width="16px"
+ alt="Users"
+ />
+ {`Users${counts.users > 0 ? ` (${counts.users})` : ""}`}
+ </span>
+ }
+ />
+ <Tab
+ eventKey="groups"
+ title={
+ <span className="d-flex align-items-center gap-1">
+ <img
+ src={groupColourIcon}
+ height="16px"
+ width="16px"
+ alt="Groups"
+ />
+ {`Groups${counts.groups > 0 ? ` (${counts.groups})` : ""}`}
+ </span>
+ }
+ />
+ <Tab
+ eventKey="roles"
+ title={
+ <span className="d-flex align-items-center gap-1">
+ <img
+ src={roleColourIcon}
+ height="16px"
+ width="16px"
+ alt="Roles"
+ />
+ {`Roles${counts.roles > 0 ? ` (${counts.roles})` : ""}`}
+ </span>
+ }
+ />
+ </Tabs>
+
+ {/* Empty state */}
+ {filteredItems.length === 0 && (
+ <div className="text-center text-muted py-4">
+ {searchInput.trim()
+ ? `No results for "${searchInput}"`
+ : `No ${activeTab === "all" ? "users, groups, or roles" : activeTab} selected yet. Use the search box on the form to add.`}
+ </div>
+ )}
+
+ {/* Table – only selected items; removing a row makes it disappear */}
+ {filteredItems.length > 0 && (
+ <>
+ {/* Bulk-action toolbar – visible only when rows are checked */}
+ {someChecked && (
+ <div className="d-flex align-items-center gap-3 mb-2 px-1">
+ <span className="text-muted small">
+ {checkedCount} item{checkedCount !== 1 ? "s" : ""} selected
+ </span>
+ <Button
+ variant="danger"
+ size="sm"
+ onClick={handleDeleteChecked}
+ >
+ <i className="fa fa-trash me-1" />
+ Delete Selected
+ </Button>
+ </div>
+ )}
+
+ <div style={{ maxHeight: "350px", overflowY: "auto" }}>
+ <Table bordered hover size="sm" className="mb-0">
+ <thead className="table-light sticky-top">
+ <tr>
+ <th style={{ width: "40px" }} className="text-center">
+ <Form.Check
+ type="checkbox"
+ checked={allChecked}
+ onChange={(e) => handleSelectAll(e.target.checked)}
+ title="Select / deselect all"
+ />
+ </th>
+ <th>Name</th>
+ <th style={{ width: "60px" }} className="text-center">
+ Remove
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {filteredItems.map((item) => {
+ const checked = checkedValues.has(item.value);
+ return (
+ <tr
+ key={item.value}
+ className={checked ? "table-primary" : ""}
+ >
+ <td className="text-center align-middle">
+ <Form.Check
+ type="checkbox"
+ checked={checked}
+ onChange={() => handleToggleCheck(item.value)}
+ />
+ </td>
+ <td className="align-middle">
+ <span className="d-flex align-items-center gap-2">
+ <img
+ src={getIcon(item.type, true)}
+ height="18px"
+ width="18px"
+ alt={item.type}
+ />
+ <span className="fw-medium">{item.name}</span>
+ </span>
+ </td>
+ <td className="text-center align-middle">
+ <Button
+ variant="link"
+ size="sm"
+ className="text-danger p-0"
+ onClick={() => handleRemoveItem(item)}
+ title="Remove"
+ >
+ <i className="fa fa-trash" />
+ </Button>
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </Table>
+ </div>
+ </>
+ )}
+ </Modal.Body>
+
+ <Modal.Footer>
+ <Button variant="secondary" onClick={handleCancelModal}>
+ Cancel
+ </Button>
+ <Button variant="primary" onClick={handleSaveModal}>
+ Save
+ </Button>
+ </Modal.Footer>
+ </Modal>
+ </>
+ );
+};
+
+export default UsersGroupsAndRolesSelectionComponent;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/policyFormValidation.js b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/policyFormValidation.js
new file mode 100644
index 000000000..91bfa331b
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/NewPolicyForm/policyFormValidation.js
@@ -0,0 +1,263 @@
+/*
+ * 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 { isEmpty, isArray } from "lodash";
+
+export const validatePolicyName = (policyName) => {
+ if (!policyName || policyName.trim() === "") {
+ return "Policy Name is required";
+ }
+ return undefined;
+};
+
+const hasPrincipals = (item) => {
+ const usersObj = item.users || {};
+ return (
+ (usersObj.users || []).length > 0 ||
+ (usersObj.groups || []).length > 0 ||
+ (usersObj.roles || []).length > 0
+ );
+};
+
+const hasAccessesInItem = (item) => {
+ if (item.accesses?.tableList) {
+ return item.accesses.tableList.length > 0;
+ } else if (isArray(item.accesses)) {
+ return item.accesses.length > 0;
+ }
+ return false;
+};
+
+const hasDataMaskInItem = (item) => {
+ return !!(item.dataMaskInfo && item.dataMaskInfo.value);
+};
+
+const hasRowFilterInItem = (item) => {
+ return !!(item.rowFilterInfo && item.rowFilterInfo.toString().trim() !== "");
+};
+
+const hasConditionsInItem = (item) => {
+ return !isEmpty(item.conditions);
+};
+
+const validateAccessPolicyItem = (item) => {
+ const ruleErrors = {};
+ const principals = hasPrincipals(item);
+ const accesses = hasAccessesInItem(item);
+ const delegateAdmin = item.delegateAdmin;
+ const conditions = hasConditionsInItem(item);
+
+ if (principals && !accesses && !delegateAdmin) {
+ ruleErrors.accesses = "Please select permission for this policy";
+ }
+ if (accesses && !principals && !delegateAdmin) {
+ ruleErrors.users = "Please select users/groups/roles for this policy";
+ }
+ if (delegateAdmin && !principals) {
+ ruleErrors.users = "Please select user/group/role for this policy";
+ }
+ if (conditions && !principals) {
+ ruleErrors.users = "Please select user/group/role for this policy";
+ }
+
+ return ruleErrors;
+};
+
+const validateDataMaskPolicyItem = (item) => {
+ const ruleErrors = {};
+ const principals = hasPrincipals(item);
+ const accesses = hasAccessesInItem(item);
+ const dataMask = hasDataMaskInItem(item);
+
+ if (principals && !accesses) {
+ ruleErrors.accesses = "Please select permission for this policy";
+ }
+ if (principals && !dataMask) {
+ ruleErrors.dataMaskInfo = "Please select a masking option for this policy";
+ }
+ if ((accesses || dataMask) && !principals) {
+ ruleErrors.users = "Please select users/groups/roles for this policy";
+ }
+
+ return ruleErrors;
+};
+
+const validateRowFilterPolicyItem = (item) => {
+ const ruleErrors = {};
+ const principals = hasPrincipals(item);
+ const accesses = hasAccessesInItem(item);
+ const rowFilter = hasRowFilterInItem(item);
+
+ if (principals && !accesses) {
+ ruleErrors.accesses = "Please select permission for this policy";
+ }
+ if (principals && !rowFilter) {
+ ruleErrors.rowFilterInfo = "Please enter a row level filter expression";
+ }
+ if ((accesses || rowFilter) && !principals) {
+ ruleErrors.users = "Please select users/groups/roles for this policy";
+ }
+
+ return ruleErrors;
+};
+
+export const validateSinglePolicyItem = (item, policyType) => {
+ if (!item || isEmpty(item)) {
+ return {};
+ }
+
+ switch (policyType) {
+ case 1:
+ return validateDataMaskPolicyItem(item);
+ case 2:
+ return validateRowFilterPolicyItem(item);
+ case 0:
+ default:
+ return validateAccessPolicyItem(item);
+ }
+};
+
+const getArraysToValidate = (policyType) => {
+ if (policyType == 1) {
+ return ["dataMaskPolicyItems"];
+ } else if (policyType == 2) {
+ return ["rowFilterPolicyItems"];
+ }
+ return [
+ "policyItems",
+ "allowExceptions",
+ "denyPolicyItems",
+ "denyExceptions"
+ ];
+};
+
+export const validatePolicyItemsArray = (values, policyType) => {
+ const errors = {};
+ const arraysToValidate = getArraysToValidate(policyType);
+
+ arraysToValidate.forEach((key) => {
+ (values[key] || []).forEach((item, i) => {
+ const ruleErrors = validateSinglePolicyItem(item, policyType);
+
+ if (!isEmpty(ruleErrors)) {
+ if (!errors[key]) errors[key] = [];
+ errors[key][i] = ruleErrors;
+ }
+ });
+
+ // Clean up arrays that are empty or all-undefined
+ if (errors[key] && errors[key].every((e) => e === undefined)) {
+ delete errors[key];
+ }
+ });
+
+ return errors;
+};
+
+export const validatePolicyDetails = (values) => {
+ const errors = {};
+ const policyNameError = validatePolicyName(values.policyName);
+ if (policyNameError) {
+ errors.policyName = policyNameError;
+ }
+ return errors;
+};
+
+export const validatePolicyItems = (values) => {
+ const policyType = values.policyType ?? 0;
+ return validatePolicyItemsArray(values, policyType);
+};
+
+/**
+ * True when a rule has principals but no permissions selected, with delegate admin off
+ * (e.g. after resources changed and available permissions were cleared). Use on final
+ * submit to block with a user-facing message.
+ */
+export const hasMissingAccessPermissionOnPolicyItems = (values) => {
+ const errors = validatePolicyItems(values);
+ if (isEmpty(errors)) {
+ return false;
+ }
+ for (const key of Object.keys(errors)) {
+ const arr = errors[key];
+ if (!isArray(arr)) {
+ continue;
+ }
+ for (let i = 0; i < arr.length; i++) {
+ const itemError = arr[i];
+ if (itemError && itemError.accesses) {
+ return true;
+ }
+ }
+ }
+ return false;
+};
+
+export const validatePolicyForm = (values) => ({
+ ...validatePolicyDetails(values),
+ ...validatePolicyItems(values)
+});
+
+export const validateServiceStep = (values) => {
+ const errors = {};
+ if (!values.service || values.service.trim() === "") {
+ errors.service = "Service is required";
+ }
+ return errors;
+};
+
+export const validateResourceStep = (values) => {
+ const errors = {};
+ // Validate that resources are selected based on policy type
+ const policyType = values.policyType ?? 0;
+
+ if (policyType == 1) {
+ // Data Masking policy
+ if (!values.resources || values.resources.length === 0) {
+ errors.resources = "At least one resource is required";
+ }
+ } else if (policyType == 2) {
+ // Row Filter policy
+ if (!values.resources || values.resources.length === 0) {
+ errors.resources = "At least one resource is required";
+ }
+ } else {
+ // Access policy
+ if (!values.resources || values.resources.length === 0) {
+ errors.resources = "At least one resource is required";
+ }
+ }
+
+ return errors;
+};
+
+export const validateAccessRulesStep = (values) => {
+ const policyType = values.policyType ?? 0;
+ return validatePolicyItemsArray(values, policyType);
+};
+
+export const validatePolicyDetailsStep = (values) => {
+ const errors = {};
+ const policyNameError = validatePolicyName(values.policyName);
+ if (policyNameError) {
+ errors.policyName = policyNameError;
+ }
+ // Add other policy metadata validations here if needed
+ return errors;
+};
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/PolicyFormContext.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/PolicyFormContext.jsx
new file mode 100644
index 000000000..c983682cf
--- /dev/null
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/PolicyFormContext.jsx
@@ -0,0 +1,280 @@
+/*
+ * 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 React, { useEffect, useState } from "react";
+import { Outlet, useParams, useNavigate, useLocation } from "react-router-dom";
+import { cloneDeep, pick } from "lodash";
+import { Loader } from "Components/CommonComponents";
+import { fetchApi } from "Utils/fetchAPI";
+import { getServiceDef } from "Utils/appState";
+import { commonBreadcrumb } from "Utils/XAUtils";
+
+const PolicyFormContext = () => {
+ const { serviceId, policyType, policyId } = useParams();
+ const navigate = useNavigate();
+ const location = useLocation();
+ const serviceDefs = cloneDeep(getServiceDef());
+
+ const [loading, setLoading] = useState(true);
+ const [serviceDetails, setServiceDetails] = useState(null);
+ const [serviceCompDetails, setServiceCompDetails] = useState(null);
+ const [policyData, setPolicyData] = useState(null);
+ const isNewForm = location.pathname.endsWith("new-policy-form-edit");
+
+ useEffect(() => {
+ fetchInitialData();
+ }, [serviceId, policyType, policyId]);
+
+ const fetchServiceDetails = async () => {
+ let data = null;
+ try {
+ const resp = await fetchApi({
+ url: `plugins/services/${serviceId}`
+ });
+ data = resp.data || null;
+ } catch (error) {
+ console.error(`Error occurred while fetching policy details ! ${error}`);
+ }
+ return data;
+ };
+
+ const fetchPolicyData = async () => {
+ let data = null;
+ try {
+ const resp = await fetchApi({
+ url: `plugins/policies/${policyId}`
+ });
+ data = resp.data || null;
+ } catch (error) {
+ console.error(`Error occurred while fetching service details ! ${error}`);
+ }
+ return data;
+ };
+
+ const fetchInitialData = async () => {
+ setLoading(true);
+ let serviceData = await fetchServiceDetails();
+
+ let serviceCompData = serviceDefs?.allServiceDefs?.find((serviceDef) => {
+ return serviceDef.name == serviceData.type;
+ });
+ if (serviceCompData) {
+ let serviceDefPolicyType = 0;
+ if (
+ serviceCompData?.dataMaskDef &&
+ Object.keys(serviceCompData.dataMaskDef).length != 0
+ )
+ serviceDefPolicyType++;
+ if (
+ serviceCompData?.rowFilterDef &&
+ Object.keys(serviceCompData.rowFilterDef).length != 0
+ )
+ serviceDefPolicyType++;
+ if (+policyType > serviceDefPolicyType) navigate("/pageNotFound");
+ }
+ let fetchedPolicyData = null;
+ if (policyId) {
+ fetchedPolicyData = await fetchPolicyData();
+ }
+
+ setServiceDetails(serviceData);
+ setServiceCompDetails(serviceCompData);
+ setPolicyData(fetchedPolicyData);
+ setLoading(false);
+ };
+
+ const policyBreadcrumb = () => {
+ if (!serviceDetails || !serviceCompDetails) return null;
+
+ let policyDetails = {};
+ policyDetails["serviceId"] = serviceId;
+ policyDetails["policyType"] = policyId
+ ? policyData?.policyType
+ : policyType;
+ policyDetails["serviceName"] = serviceDetails?.displayName;
+ policyDetails["selectedZone"] = JSON.parse(
+ localStorage.getItem("zoneDetails")
+ );
+
+ if (serviceCompDetails?.name === "tag") {
+ if (policyDetails?.selectedZone) {
+ return commonBreadcrumb(
+ [
+ "TagBasedServiceManager",
+ "ManagePolicies",
+ policyId ? "PolicyEdit" : "PolicyCreate"
+ ],
+ policyDetails
+ );
+ } else {
+ return commonBreadcrumb(
+ [
+ "TagBasedServiceManager",
+ "ManagePolicies",
+ policyId ? "PolicyEdit" : "PolicyCreate"
+ ],
+ pick(policyDetails, ["serviceId", "policyType", "serviceName"])
+ );
+ }
+ } else {
+ if (policyDetails?.selectedZone) {
+ return commonBreadcrumb(
+ [
+ "ServiceManager",
+ "ManagePolicies",
+ policyId ? "PolicyEdit" : "PolicyCreate"
+ ],
+ policyDetails
+ );
+ } else {
+ return commonBreadcrumb(
+ [
+ "ServiceManager",
+ "ManagePolicies",
+ policyId ? "PolicyEdit" : "PolicyCreate"
+ ],
+ pick(policyDetails, ["serviceId", "policyType", "serviceName"])
+ );
+ }
+ }
+ };
+
+ const handleToggleForm = () => {
+ navigate(
+ isNewForm
+ ? `/service/${serviceId}/policies/${policyId}/edit`
+ : `/service/${serviceId}/policies/${policyId}/new-policy-form-edit`
+ );
+ };
+
+ if (loading) {
+ return <Loader />;
+ }
+
+ return (
+ <div>
+ {/* Shared Header */}
+ <div className="header-wraper">
+ <h3 className="wrap-header bold">{`${
+ policyId ? "Edit" : "Create"
+ } Policy`}</h3>
+
+ {/* Switch toggle (only show during edit) */}
+ {policyId && (
+ <div className="ms-2 me-2 d-inline-flex align-items-center policy-form-toggle-switch">
+ <div
+ className="custom-rectangle-switch"
+ onClick={handleToggleForm}
+ style={{
+ width: "216px",
+ height: "31px",
+ borderRadius: "4px",
+ border: `1px solid ${isNewForm ? "#0d6efd" : "#dee2e6"}`,
+ backgroundColor: "#fff",
+ position: "relative",
+ cursor: "pointer",
+ transition: "all 0.2s ease",
+ display: "flex",
+ alignItems: "center",
+ overflow: "hidden",
+ userSelect: "none"
+ }}
+ >
+ {/* Active side background */}
+ <div
+ style={{
+ position: "absolute",
+ top: "0",
+ left: isNewForm ? "50%" : "0",
+ width: "50%",
+ height: "100%",
+ backgroundColor: isNewForm ? "#0d6efd" : "#0d6efd",
+ transition: "left 0.3s ease",
+ zIndex: 1,
+ padding: "4px 10px"
+ }}
+ />
+
+ {/* Left side - Old Form */}
+ <div
+ style={{
+ width: "50%",
+ height: "100%",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ position: "relative",
+ zIndex: 2
+ }}
+ >
+ <span
+ style={{
+ fontSize: "14px",
+ color: !isNewForm ? "#fff" : "#6c757d",
+ transition: "color 0.3s ease"
+ }}
+ >
+ Old Form
+ </span>
+ </div>
+
+ {/* Right side - New Form */}
+ <div
+ style={{
+ width: "50%",
+ height: "100%",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ position: "relative",
+ zIndex: 2
+ }}
+ >
+ <span
+ style={{
+ fontSize: "14px",
+ fontWeight: "500",
+ color: isNewForm ? "#fff" : "#6c757d",
+ transition: "color 0.3s ease"
+ }}
+ >
+ New Form
+ </span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {policyBreadcrumb()}
+ </div>
+
+ {/* Child form content */}
+ <Outlet
+ context={{
+ serviceDetails,
+ serviceCompDetails,
+ policyData: policyData ? cloneDeep(policyData) : null,
+ serviceDefs
+ }}
+ />
+ </div>
+ );
+};
+
+export default PolicyFormContext;
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/PolicyListing.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/PolicyListing.jsx
index 63cc3a03d..8cd7c52bc 100644
--- a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/PolicyListing.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/PolicyListing.jsx
@@ -814,7 +814,7 @@ function PolicyListing(props) {
policySearchInfoMsg = union(ServerAttrName, serverRsrcAttrName);
return (
- <div className="policy-search-info">
+ <div className="font-13">
<p className="m-0">
Wildcard searches ( for example using * or ? ) are not currently
supported.
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/TagBasePermissionItem.jsx b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/TagBasePermissionItem.jsx
index 80fa4a8ae..b1bc6eaef 100644
--- a/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/TagBasePermissionItem.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/views/PolicyListing/TagBasePermissionItem.jsx
@@ -17,7 +17,7 @@
* under the License.
*/
-import React, { useState } from "react";
+import React, { useState, useEffect } from "react";
import { Form as FormB, Modal, Button, Table, Badge } from "react-bootstrap";
import { Form, Field } from "react-final-form";
import Select from "react-select";
@@ -40,17 +40,22 @@ import { RangerPolicyType } from "Utils/XAEnums";
import { getServiceDef } from "Utils/appState";
import { selectInputCustomStyles } from "Components/CommonComponents";
-export default function TagBasePermissionItem(props) {
+export default function TagBasePermissionItem({
+ options,
+ inputVal,
+ formValues,
+ dataMaskIndex,
+ serviceCompDetails,
+ attrName,
+ showModal,
+ handleCloseModal
+}) {
const serviceDefs = cloneDeep(getServiceDef());
- const {
- options,
- inputVal,
- formValues,
- serviceCompDetails,
- dataMaskIndex,
- attrName
- } = props;
- const [showTagPermissionItem, tagPermissionItem] = useState(false);
+ const [localShowModal, setLocalShowModal] = useState(showModal);
+
+ useEffect(() => {
+ setLocalShowModal(showModal);
+ }, [showModal]);
const msgStyles = {
background: "white",
@@ -112,7 +117,10 @@ export default function TagBasePermissionItem(props) {
};
const handleClose = () => {
- tagPermissionItem(false);
+ setLocalShowModal(false);
+ if (handleCloseModal) {
+ handleCloseModal();
+ }
};
const serviceOnChange = (e, input, values, push, remove) => {
@@ -281,56 +289,61 @@ export default function TagBasePermissionItem(props) {
return (
<>
- <div
- className="editable"
- onClick={() => {
- tagPermissionItem(true);
- }}
- >
- {inputVal?.value?.tableList?.length > 0 ? (
- <div className="text-center">
- <div className="editable-edit-text">
- {tagAccessTypeDisplayVal(inputVal?.value?.tableList)}
- </div>
+ {/* Only show editable div if not opening modal directly */}
+ {!showModal && (
+ <div
+ className="editable"
+ onClick={() => {
+ setLocalShowModal(true);
+ }}
+ >
+ {inputVal?.value?.tableList?.length > 0 ? (
+ <div className="text-center">
+ <div className="editable-edit-text">
+ {tagAccessTypeDisplayVal(inputVal?.value?.tableList)}
+ </div>
- <Button
- className="mg-10 mx-auto d-block btn-mini"
- size="sm"
- variant="outline-dark"
- onClick={(e) => {
- e.stopPropagation();
- tagPermissionItem(true);
- }}
- >
- <i className="fa-fw fa fa-pencil"></i>
- </Button>
- </div>
- ) : (
- <div className="text-center">
- <span className="editable-add-text">Add Permissions</span>
- <div>
<Button
- size="sm"
className="mg-10 mx-auto d-block btn-mini"
+ size="sm"
variant="outline-dark"
onClick={(e) => {
e.stopPropagation();
- tagPermissionItem(true);
+ setLocalShowModal(true);
}}
>
- <i className="fa-fw fa fa-plus"></i>
+ <i className="fa-fw fa fa-pencil"></i>
</Button>
</div>
- </div>
- )}
- </div>
+ ) : (
+ <div className="text-center">
+ <span className="editable-add-text">Add Permissions</span>
+ <div>
+ <Button
+ size="sm"
+ className="mg-10 mx-auto d-block btn-mini"
+ variant="outline-dark"
+ onClick={(e) => {
+ e.stopPropagation();
+ setLocalShowModal(true);
+ }}
+ >
+ <i className="fa-fw fa fa-plus"></i>
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
<Modal
- show={showTagPermissionItem}
+ show={localShowModal}
onHide={handleClose}
size="lg"
aria-labelledby="contained-modal-title-vcenter"
centered
+ backdrop="static"
+ keyboard={false}
>
<Form
onSubmit={handleSubmit}
@@ -416,29 +429,27 @@ export default function TagBasePermissionItem(props) {
fields.map((name, index) => (
<tr className="bg-white" key={index}>
<td className="align-middle td-padding-modal">
- <h6>
- <FormB.Group className="d-inline">
- <FormB.Check
- inline
- key={fields.value[
- index
- ].serviceName.toUpperCase()}
- checked={isAllChecked(
- fields.value[index],
- tagServicePerms[
- fields.value[index].serviceName
- ]
- )}
- type="checkbox"
- label={fields.value[
- index
- ].serviceName.toUpperCase()}
- onChange={(e) =>
- handleSelectAllChange(e, index, fields)
- }
- />
- </FormB.Group>
- </h6>
+ <FormB.Group className="d-inline">
+ <FormB.Check
+ inline
+ key={fields.value[
+ index
+ ].serviceName.toUpperCase()}
+ checked={isAllChecked(
+ fields.value[index],
+ tagServicePerms[
+ fields.value[index].serviceName
+ ]
+ )}
+ type="checkbox"
+ label={fields.value[
+ index
+ ].serviceName.toUpperCase()}
+ onChange={(e) =>
+ handleSelectAllChange(e, index, fields)
+ }
+ />
+ </FormB.Group>
</td>
<td className="align-middle">
<Field
@@ -449,7 +460,10 @@ export default function TagBasePermissionItem(props) {
{tagServicePerms[
fields.value[index].serviceName
].map((obj) => (
- <h6 className="d-inline" key={obj.value}>
+ <span
+ className="d-inline"
+ key={obj.value}
+ >
<FormB.Group
className="d-inline"
controlId={obj.value}
@@ -467,7 +481,7 @@ export default function TagBasePermissionItem(props) {
}
/>
</FormB.Group>
- </h6>
+ </span>
))}
</div>
)}
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceComp.jsx b/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceComp.jsx
index 5d3006780..ae1cee2a5 100644
--- a/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceComp.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceComp.jsx
@@ -85,8 +85,10 @@ export default function ResourceComp(props) {
const RenderValidateField = ({ name }) =>
(formValues && formValues[name]?.mandatory && (
- <span className={!isGds ? "" : "top-0"}>*</span>
- )) || <span> </span>;
+ <span className={!isGds ? "required-mark" : "top-0 required-mark"}>
+ *
+ </span>
+ )) || <span className="required-mark"></span>;
const renderResourceSelect = (levelKey, index) => {
let renderLabel = false;
@@ -175,11 +177,11 @@ export default function ResourceComp(props) {
return (
<FormB.Group
as={Row}
- className="mb-3"
+ className="mb-4 align-items-start"
controlId={`Resource-${levelKey}`}
key={`Resource-${levelKey}`}
>
- <Col sm={3}>
+ <Col className="column-1-fixed">
<Field
defaultValue={!policyId && getResourceLabelOp(levelKey, index)[0]}
name={
@@ -191,14 +193,14 @@ export default function ResourceComp(props) {
formValues[resourceKey] ? (
renderResourceSelect(levelKey, index) ? (
<span className="float-end fnt-14">
- <FormB.Label className="position-relative pe-2">
+ <FormB.Label className="position-relative">
{getResourceLabelOp(levelKey, index)[0]["label"]}
<RenderValidateField name={`resourceName-${levelKey}`} />
</FormB.Label>
</span>
) : (
<div className="resource-drop-down">
- <span className="w-75">
+ <span className="w-100">
<Select
{...input}
options={getResourceLabelOp(levelKey, index)}
@@ -222,7 +224,7 @@ export default function ResourceComp(props) {
{formValues[`resourceName-${levelKey}`] && (
<>
- <Col sm={!isGds ? 5 : 9}>
+ <Col className="mw-50">
<ResourceSelectComp
levelKey={levelKey}
formValues={formValues}
@@ -236,10 +238,10 @@ export default function ResourceComp(props) {
)}
{formValues[`resourceName-${levelKey}`] && !isGds && (
- <Col sm={4}>
+ <Col className="column-3-fixed">
<Row>
{formValues[`resourceName-${levelKey}`]["excludesSupported"] && (
- <Col sm={5}>
+ <Col className="resource-toggle-switch">
<Field
className="form-control"
name={
@@ -255,7 +257,7 @@ export default function ResourceComp(props) {
onstyle="primary"
offlabel="Exclude"
offstyle="outline-secondary"
- style="w-100"
+ width={100}
size="xs"
key={`isExcludesSupport-${levelKey}`}
/>
@@ -264,9 +266,9 @@ export default function ResourceComp(props) {
</Col>
)}
{formValues[`resourceName-${levelKey}`]["recursiveSupported"] && (
- <Col sm={5} className="toggle-switch">
+ <Col className="resource-toggle-switch">
<Field
- className="form-control"
+ className="form-control resource-toggle-switch"
name={
isMultiResources
? `${name}.isRecursiveSupport-${levelKey}`
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceSelectComp.jsx b/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceSelectComp.jsx
index 52d2c919a..76e00c1c2 100644
--- a/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceSelectComp.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/views/Resources/ResourceSelectComp.jsx
@@ -222,8 +222,12 @@ export default function ResourceSelectComp(props) {
if (trimmedValue) {
const newOption = { label: trimmedValue, value: trimmedValue };
const currentValue = input.value || [];
- const newValue = isArray(currentValue)
- ? [...currentValue, newOption]
+ const newValue = supportMultipleVal(
+ formValues[`resourceName-${levelKey}`]
+ )
+ ? isArray(currentValue)
+ ? [...currentValue, newOption]
+ : [newOption]
: [newOption];
input.onChange(newValue);
}
diff --git a/security-admin/src/main/webapp/react-webapp/src/views/SideBar/SideBar.jsx b/security-admin/src/main/webapp/react-webapp/src/views/SideBar/SideBar.jsx
index 4006f4e04..20c1f4afd 100644
--- a/security-admin/src/main/webapp/react-webapp/src/views/SideBar/SideBar.jsx
+++ b/security-admin/src/main/webapp/react-webapp/src/views/SideBar/SideBar.jsx
@@ -29,6 +29,7 @@ import zoneIcon from "Images/sidebar/zone.svg";
import settingsIcon from "Images/sidebar/settings.svg";
import accountIcon from "Images/sidebar/account.svg";
import gdsIcon from "Images/sidebar/governed-data.svg";
+import plus from "Images/sidebar/plus.svg";
import { fetchApi } from "Utils/fetchAPI";
import { getServiceDef, getUserProfile } from "Utils/appState";
import {
@@ -37,7 +38,8 @@ import {
isKeyAdmin,
isSystemAdmin,
isKMSAuditor,
- getLandingPageURl
+ getLandingPageURl,
+ isUser
} from "Utils/XAUtils";
import { cloneDeep, filter, sortBy } from "lodash";
import { PathAssociateWithModule } from "Utils/XAEnums";
@@ -234,6 +236,24 @@ export const SideBar = () => {
</div>
<ul className="list-unstyled components">
+ {(hasAccessToTab("Resource Based Policies") ||
+ hasAccessToTab("Tag Based Policies")) &&
+ (isUser() || isKeyAdmin() || isSystemAdmin()) && (
+ <li>
+ <NavLink
+ to="/policymanager/create-policy"
+ className={activeClass("CreateNewPolicyForm")}
+ onClick={() => {
+ setActive(null);
+ setDrawer(false);
+ setAccountDrawer(false);
+ }}
+ >
+ <img src={plus} />
+ <span>Create New Policy</span>
+ </NavLink>
+ </li>
+ )}
{hasAccessToTab("Resource Based Policies") && (
<li
className={