8000 Fix policy delete dialog to separate removed and surviving dependents by edewit · Pull Request #55810 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2415,7 +2415,8 @@ sync-ldap-groups-to-keycloak=Sync LDAP groups to Keycloak
attestationPreference.indirect=Indirect
frontchannelUrlInvalid=Front-channel logout URL is not a valid URL
noCredentialsText=This user does not have any credentials. You can set password for this user.
deletePolicyWarning=The aggregated polices below will be removed automatically\:
deletePolicyWarning=The permissions and aggregated policies below will be removed because this is their only associated policy\:
deletePolicyAssociationWarning=The permissions and aggregated policies below will keep their other associated policies\:
validatingPublicKey=Validating public key
permissionsListIntro=Edit the permission list by clicking the scope-name. It then redirects to the permission details page of the client named <1>{{realm}}</1>
deleteClientConditionSuccess=Condition deleted successfully.
Expand Down
71 changes: 60 additions & 11 deletions js/apps/admin-ui/src/clients/authorization/Policies.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { toPolicyDetails } from "../routes/PolicyDetails";
import { DetailDescriptionLink } from "./DetailDescription";
import { MoreLabel } from "./MoreLabel";
import { NewPolicyDialog } from "./NewPolicyDialog";
import { partitionDependentPolicies } from "./partitionDependentPolicies";
import { SearchDropdown, SearchForm } from "./SearchDropdown";
import { useIsAdminPermissionsClient } from "../../utils/useIsAdminPermissionsClient";
import { toCreatePermissionPolicy } from "../../permissions-configuration/routes/NewPermissionPolicy";
Expand All @@ -50,6 +51,8 @@ type PoliciesProps = {

type ExpandablePolicyRepresentation = PolicyRepresentation & {
dependentPolicies?: PolicyRepresentation[];
dependentsToDelete?: PolicyRepresentation[];
dependentsToKeep?: PolicyRepresentation[];
isExpanded: boolean;
};

Expand Down Expand Up @@ -128,28 +131,47 @@ export const AuthorizationPolicies = ({
[key, search, first, max],
);

const renderDependentNames = (dependents: PolicyRepresentation[]) => (
<p className="pf-v5-u-pt-xs">
{dependents.map((policy) => (
<strong key={policy.id} className="pf-v5-u-pr-md">
{policy.name}
</strong>
))}
</p>
);

const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: "deletePolicy",
children: (
<>
{t("deletePolicyConfirm")}
{selectedPolicy?.dependentPolicies &&
selectedPolicy.dependentPolicies.length > 0 && (
{selectedPolicy?.dependentsToDelete &&
selectedPolicy.dependentsToDelete.length > 0 && (
<Alert
variant="warning"
isInline
isPlain
component="p"
title={t("deletePolicyWarning")}
className="pf-v5-u-pt-lg"
data-testid="delete-policy-removed-alert"
>
<p className="pf-v5-u-pt-xs">
{selectedPolicy.dependentPolicies.map((policy) => (
<strong key={policy.id} className="pf-v5-u-pr-md">
{policy.name}
</strong>
))}
</p>
{renderDependentNames(selectedPolicy.dependentsToDelete)}
</Alert>
)}
{selectedPolicy?.dependentsToKeep &&
selectedPolicy.dependentsToKeep.length > 0 && (
<Alert
variant="info"
isInline
isPlain
component="p"
title={t("deletePolicyAssociationWarning")}
className="pf-v5-u-pt-lg"
data-testid="delete-policy-kept-alert"
>
{renderDependentNames(selectedPolicy.dependentsToKeep)}
</Alert>
)}
</>
Expand All @@ -169,6 +191,34 @@ export const AuthorizationPolicies = ({
},
});

const openDeleteDialog = async (policy: ExpandablePolicyRepresentation) => {
try {
const dependents = policy.dependentPolicies ?? [];
const enriched = await Promise.all(
dependents.map(async (dependent) => {
const associatedPolicies =
await adminClient.clients.getAssociatedPolicies({
id: clientId,
permissionId: dependent.id!,
});
return { ...dependent, associatedPolicies };
}),
);
const { willBeDeleted, willRemain } = partitionDependentPolicies(
policy.id!,
enriched,
);
setSelectedPolicy({
...policy,
dependentsToDelete: willBeDeleted,
dependentsToKeep: willRemain,
});
toggleDeleteDialog();
} catch (error) {
addError("policyDeletedError", error);
}
};

if (!policies) {
return <KeycloakSpinner />;
}
Expand Down Expand Up @@ -303,8 +353,7 @@ export const AuthorizationPolicies = ({
{
title: t("delete"),
onClick: () => {
setSelectedPolicy(policy);
toggleDeleteDialog();
void openDeleteDialog(policy);
},
},
],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vitest";
import { partitionDependentPolicies } from "./partitionDependentPolicies";

describe("partitionDependentPolicies", () => {
const deletedPolicyId = "policy-a";

it("marks dependents with only the deleted policy as removed", () => {
const { willBeDeleted, willRemain } = partitionDependentPolicies(
deletedPolicyId,
[
{
id: "first",
name: "First",
associatedPolicies: [{ id: deletedPolicyId }],
},
],
);

expect(willBeDeleted.map((p) => p.name)).toEqual(["First"]);
expect(willRemain).toEqual([]);
});

it("marks dependents that keep other policies as remaining", () => {
const { willBeDeleted, willRemain } = partitionDependentPolicies(
deletedPolicyId,
[
{
id: "second",
name: "Second",
associatedPolicies: [{ id: deletedPolicyId }, { id: "policy-b" }],
},
],
);

expect(willBeDeleted).toEqual([]);
expect(willRemain.map((p) => p.name)).toEqual(["Second"]);
});

it("splits mixed dependents like the issue reproducer", () => {
const { willBeDeleted, willRemain } = partitionDependentPolicies(
deletedPolicyId,
[
{
id: "first",
name: "First",
associatedPolicies: [{ id: deletedPolicyId }],
},
{
id: "second",
name: "Second",
associatedPolicies: [{ id: deletedPolicyId }, { id: "policy-b" }],
},
],
);

expect(willBeDeleted.map((p) => p.name)).toEqual(["First"]);
expect(willRemain.map((p) => p.name)).toEqual(["Second"]);
});

it("treats missing associatedPolicies as deleted", () => {
const { willBeDeleted, willRemain } = partitionDependentPolicies(
deletedPolicyId,
[{ id: "orphan", name: "Orphan" }],
);

expect(willBeDeleted.map((p) => p.name)).toEqual(["Orphan"]);
expect(willRemain).toEqual([]);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
type WithAssociatedPolicies<T> = T & {
associatedPolicies?: { id?: string }[];
};

/**
* Mirrors AuthorizationProvider.delete: a dependent is removed only when
* removing the deleted policy leaves it with no associated policies.
*/
export function partitionDependentPolicies<T>(
deletedPolicyId: string,
dependents: WithAssociatedPolicies<T>[],
): { willBeDeleted: T[]; willRemain: T[] } {
const willBeDeleted: T[] = [];
const willRemain: T[] = [];

for (const dependent of dependents) {
const remaining = (dependent.associatedPolicies ?? []).filter(
(policy) => policy.id !== deletedPolicyId,
);
Comment on lines +17 to +19
if (remaining.length === 0) {
willBeDeleted.push(dependent);
} else {
willRemain.push(dependent);
}
}

return { willBeDeleted, willRemain };
}
84 changes: 84 additions & 0 deletions js/apps/admin-ui/test/clients/authorization.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,13 @@ import {
clickNextPage,
createAuthorizationScope,
createPermission,
assertDeletePolicyKeptDependents,
assertDeletePolicyRemovedDependents,
createPolicy,
createResource,
deletePolicy,
expandEvaluateResource,
openDeletePolicyDialog,
fillForm,
getEvaluateResourceKeyInput,
getEvaluateResourceKeyOptions,
Expand Down Expand Up @@ -673,3 +676,84 @@ test.describe.serial("Client authorization evaluate permission scopes", () => {
});
});
});

test.describe.serial("Client authorization policy delete dependents", () => {
const clientId = `client-authz-policy-delete-${crypto.randomUUID()}`;
const username = `policy-delete-user-${crypto.randomUUID()}`;

test.beforeAll(async () => {
await adminClient.createClient({
protocol: "openid-connect",
clientId,
publicClient: false,
authorizationServicesEnabled: true,
serviceAccountsEnabled: true,
standardFlowEnabled: true,
});
const user = await adminClient.createUser({ username, enabled: true });

const policyA = await adminClient.createAuthzPolicy(clientId, {
name: "Policy A",
type: "user",
logic: Logic.POSITIVE,
users: [user.id!],
});
const policyB = await adminClient.createAuthzPolicy(clientId, {
name: "Policy B",
type: "user",
logic: Logic.POSITIVE,
users: [user.id!],
});
await adminClient.createAuthzPolicy(clientId, {
name: "First",
type: "aggregate",
logic: Logic.POSITIVE,
policies: [policyA.id!],
});
await adminClient.createAuthzPolicy(clientId, {
name: "Second",
type: "aggregate",
logic: Logic.POSITIVE,
policies: [policyA.id!, policyB.id!],
});
});

test.afterAll(async () => {
await adminClient.deleteClient(clientId);
await adminClient.deleteUser(username);
});

test.beforeEach(async ({ page }) => {
await login(page);
await goToClients(page);
await searchItem(page, "Search for client", clientId);
await clickTableRowItem(page, clientId);
await goToAuthorizationTab(page);
await goToPoliciesSubTab(page);
});

test("Should distinguish dependents that will be removed from those that remain", async ({
page,
}) => {
await openDeletePolicyDialog(page, "Policy A");

await assertDeletePolicyRemovedDependents(page, ["First"]);
await assertDeletePolicyKeptDependents(page, ["Second"]);
await expect(
page.getByTestId("delete-policy-removed-alert").getByText("Second", {
exact: true,
}),
).toHaveCount(0);
await expect(
page.getByTestId("delete-policy-kept-alert").getByText("First", {
exact: true,
}),
).toHaveCount(0);

await confirmModal(page);
await assertNotificationMessage(page, "The Policy successfully deleted");
await assertRowExists(page, "First", false);
await assertRowExists(page, "Second");
await assertRowExists(page, "Policy B");
});
});
26 changes: 26 additions & 0 deletions js/apps/admin-ui/test/clients/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,32 @@ export async function deletePolicy(page: Page, policyName: string) {
await confirmModal(page);
}

export async function openDeletePolicyDialog(page: Page, policyName: string) {
await clickRowKebabItem(page, policyName, "Delete");
}

export async function assertDeletePolicyRemovedDependents(
page: Page,
names: string[],
) {
const alert = page.getByTestId("delete-policy-removed-alert");
await expect(alert).toBeVisible();
for (const name of names) {
await expect(alert.getByText(name, { exact: true })).toBeVisible();
}
}

export async function assertDeletePolicyKeptDependents(
page: Page,
names: string[],
) {
const alert = page.getByTestId("delete-policy-kept-alert");
await expect(alert).toBeVisible();
for (const name of names) {
await expect(alert.getByText(name, { exact: true })).toBeVisible();
}
}

export async function inputClient(page: Page, clientName: string) {
await selectClient(page, clientName);
}
Expand Down
Loading
0