8000 Remove creation of default policy, resource and permission upon enabl… by vramik · Pull Request #43969 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
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 @@ -114,6 +114,10 @@ This adds new indexes on `OFFLINE_CLIENT_SESSION` table to improve performance w
If those tables contain more than 300000 entries, {project_name} will skip the index creation by default during the automatic schema migration and instead log the SQL statement on the console during migration to be applied manually after {project_name}'s startup.
See the link:{upgradingguide_link}[{upgradingguide_name}] for details on how to configure a different limit.

=== Default authorization policies and resources are no longer auto-created

When enabling authorization on a new client (creating a Resource Server), Keycloak no longer automatically creates a "Default Resource", a "Default Policy," and a "Default Permission."

// ------------------------ Deprecated features ------------------------ //
== Deprecated features

Expand Down
17 changes: 10 additions & 7 deletions js/apps/admin-ui/test/clients/authorization.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
} from "../utils/table.ts";
import {
assertClipboardHasText,
assertDefaultResource,
assertDownload,
clickAuthenticationSaveButton,
clickCopyButton,
Expand Down Expand Up @@ -69,9 +68,8 @@ test.describe.serial("Client authentication subtab", () => {

test("Should create a resource", async ({ page }) => {
await goToResourcesSubTab(page);
await assertDefaultResource(page);
await createResource(page, {
name: "Resource",
name: "Test Resource",
displayName: "The display name",
type: "type",
uris: ["one", "two"],
Expand All @@ -83,7 +81,7 @@ test.describe.serial("Client authentication subtab", () => {

test("Edit a resource", async ({ page }) => {
await goToResourcesSubTab(page);
await clickTableRowItem(page, "Default Resource");
await clickTableRowItem(page, "Test Resource");

await fillForm(page, { displayName: "updated" });
await clickSaveButton(page);
Expand Down Expand Up @@ -115,7 +113,7 @@ test.describe.serial("Client authentication subtab", () => {
name: "Permission name",
description: "Something describing this permission",
});
await selectResource(page, "Default Resource");
await selectResource(page, "Test Resource");

await clickSaveButton(page);
await assertNotificationMessage(
Expand All @@ -139,7 +137,7 @@ test.describe.serial("Client authentication subtab", () => {

test("Should delete a policy", async ({ page }) => {
await goToPoliciesSubTab(page);
await deletePolicy(page, "Default Policy");
await deletePolicy(page, "Regex Policy");

await assertNotificationMessage(page, "The Policy successfully deleted");
});
Expand Down Expand Up @@ -175,6 +173,7 @@ test.describe.serial("Client authentication subtab", () => {
test.describe
.serial("Client authorization tab access for view-realm-authorization", () => {
const clientId = `realm-view-authz-client-${crypto.randomUUID()}`;
const resourceName = `test-resource-${crypto.randomUUID()}`;

test.beforeAll(async () => {
await adminClient.createRealm("realm-view-authz");
Expand All @@ -197,6 +196,10 @@ test.describe
serviceAccountsEnabled: true,
standardFlowEnabled: true,
});
await adminClient.createResource(clientId, {
realm: "realm-view-authz",
name: resourceName,
});
});

test.afterAll(async () => {
Expand All @@ -219,7 +222,7 @@ test.describe
await goToAuthorizationTab(page);

await goToResourcesSubTab(page);
await clickTableRowItem(page, "Default Resource");
await clickTableRowItem(page, resourceName);
await page.goBack();

await goToScopesSubTab(page);
Expand Down
26 changes: 17 additions & 9 deletions js/apps/admin-ui/test/clients/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,6 @@ export async function clickAuthenticationSaveButton(page: Page) {
await page.getByTestId("authenticationSettings-save").click();
}

export async function assertDefaultResource(page: Page) {
await expect(page.getByTestId("name-column-Default Resource")).toHaveText(
"Default Resource",
);
}

export async function assertResource(page: Page, name: string) {
await expect(getRowByCellText(page, name)).toBeVisible();
}
Expand All @@ -35,7 +29,11 @@ export async function createResource(
page: Page,
resource: ResourceRepresentation,
) {
await page.getByTestId("createResource").click();
await page
.locator(
'[data-testid="createResource"], [data-testid="no-resources-empty-action"]',
)
.click();
await fillForm(page, resource);
}

Expand Down Expand Up @@ -81,7 +79,11 @@ export async function createPolicy(
type: string,
policy: { [key: string]: string },
) {
await page.getByTestId("createPolicy").click();
await page
.locator(
'[data-testid="createPolicy"], [data-testid="no-policies-empty-action"]',
)
.click();
await page.getByRole("gridcell", { name: type, exact: true }).click();
await fillForm(page, policy);
}
Expand All @@ -106,7 +108,13 @@ export async function createPermission(
type: string,
permission: PolicyRepresentation,
) {
await page.getByTestId("permissionCreateDropdown").click();
const dropdown = page.getByTestId("permissionCreateDropdown");
const hasDropdown = (await dropdown.count()) > 0;

if (hasDropdown) {
await dropdown.click();
}

await page.getByTestId(`create-${type}`).click();
await fillForm(page, permission);
}
Expand Down
20 changes: 20 additions & 0 deletions js/apps/admin-ui/test/utils/AdminClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type ClientScopeRepresentation from "@keycloak/keycloak-admin-client/lib/
import type ComponentRepresentation from "@keycloak/keycloak-admin-client/lib/defs/componentRepresentation.js";
import type OrganizationRepresentation from "@keycloak/keycloak-admin-client/lib/defs/organizationRepresentation.js";
import type PolicyRepresentation from "@keycloak/keycloak-admin-client/lib/defs/policyRepresentation.js";
import type ResourceRepresentation from "@keycloak/keycloak-admin-client/lib/defs/resourceRepresentation.js";
import type RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmRepresentation.js";
import type RoleRepresentation from "@keycloak/keycloak-admin-client/lib/defs/roleRepresentation.js";
import type { RoleMappingPayload } from "@keycloak/keycloak-admin-client/lib/defs/roleRepresentation.js";
Expand Down Expand Up @@ -495,6 +496,25 @@ class AdminClient {
);
}

async createResource(
clientId: string,
resource: ResourceRepresentation & { realm?: string },
) {
await this.#login();
const { realm = this.#client.realmName, ...payload } = resource;

const client = (await this.#client.clients.find({ clientId, realm }))[0];

if (!client?.id) {
throw new Error(`Client ${clientId} not found in realm ${realm}`);
}

return await this.#client.clients.createResource(
{ id: client.id, realm },
payload,
);
}

async findUserByUsername(
realm: string,
username: string,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,21 @@ public void delete(ClientModel client) {
String id = client.getId();
ResourceServerEntity entity = entityManager.find(ResourceServerEntity.class, id);
if (entity == null) return;

// reordering deletions to avoid FK issues, but it is not a fix, but only a workaround
// proper fix would be to refactor the whole mess with bidirectional relationships with proper cascade-on-delete behavior.
// this method would become just a one-liner entityManager.remove(entity);
{
TypedQuery<String> query = entityManager.createNamedQuery("findPermissionTicketIdByServerId", String.class);

query.setParameter("serverId", id);

List<String> result = query.getResultList();
for (String permissionId : result) {
entityManager.remove(entityManager.getReference(PermissionTicketEntity.class, permissionId));
}
}

//This didn't work, had to loop through and remove each policy individually
//entityManager.createNamedQuery("deletePolicyByResourceServer")
// .setParameter("serverId", id).executeUpdate();
Expand All @@ -80,17 +95,6 @@ public void delete(ClientModel client) {
}
}

{
TypedQuery<String> query = entityManager.createNamedQuery("findPermissionTicketIdByServerId", String.class);

query.setParameter("serverId", id);

List<String> result = query.getResultList();
for (String permissionId : result) {
entityManager.remove(entityManager.getReference(PermissionTicketEntity.class, permissionId));
}
}

//entityManager.createNamedQuery("deleteResourceByResourceServer")
// .setParameter("serverId", id).executeUpdate();
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@

import static org.keycloak.models.utils.ModelToRepresentation.toRepresentation;

import java.util.Collections;
import java.util.HashMap;

import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.GET;
Expand All @@ -44,11 +42,6 @@
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.models.utils.Representati 10BC8 onToModel;
import org.keycloak.representations.idm.authorization.DecisionStrategy;
import org.keycloak.representations.idm.authorization.Logic;
import org.keycloak.representations.idm.authorization.PolicyRepresentation;
import org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation;
import org.keycloak.representations.idm.authorization.ResourceRepresentation;
import org.keycloak.representations.idm.authorization.ResourceServerRepresentation;
import org.keycloak.services.resources.KeycloakOpenAPI;
import org.keycloak.services.resources.admin.AdminEventBuilder;
Expand Down Expand Up @@ -89,7 +82,6 @@ public ResourceServer create(boolean newClient) {

if (this.resourceServer == null) {
this.resourceServer = RepresentationToModel.createResourceServer(client, session, true);
createDefaultPermission(createDefaultResource(), createDefaultPolicy());
audit(ModelToRepresentation.toRepresentation(resourceServer, client), OperationType.CREATE, session.getContext().getUri(), newClient);
}

Expand Down Expand Up @@ -175,53 +167,6 @@ public PermissionService getPermissionTypeResource() {
return new PermissionService(this.resourceServer, this.authorization, this.auth, adminEvent);
}

private void createDefaultPermission(ResourceRepresentation resource, PolicyRepresentation policy) {
ResourcePermissionRepresentation defaultPermission = new ResourcePermissionRepresentation();

defaultPermission.setName("Default Permission");
defaultPermission.setDescription("A permission that applies to the default resource type");
defaultPermission.setDecisionStrategy(DecisionStrategy.UNANIMOUS);
defaultPermission.setLogic(Logic.POSITIVE);

defaultPermission.setResourceType(resource.getType());
defaultPermission.addPolicy(policy.getName());

getPolicyResource().create(defaultPermission);
}

private PolicyRepresentation createDefaultPolicy() {
PolicyRepresentation defaultPolicy = new PolicyRepresentation();

defaultPolicy.setName("Default Policy");
defaultPolicy.setDescription("A policy that grants access only for users within this realm");
defaultPolicy.setType("js");
defaultPolicy.setDecisionStrategy(DecisionStrategy.AFFIRMATIVE);
defaultPolicy.setLogic(Logic.POSITIVE);

HashMap<String, String> defaultPolicyConfig = new HashMap<>();

defaultPolicyConfig.put("code", "// by default, grants any permission associated with this policy\n$evaluation.grant();\n");

defaultPolicy.setConfig(defaultPolicyConfig);

session.setAttribute("ALLOW_CREATE_POLICY", true);

getPolicyResource().create(defaultPolicy);

return defaultPolicy;
}

private ResourceRepresentation createDefaultResource() {
ResourceRepresentation defaultResource = new ResourceRepresentation();

defaultResource.setName("Default Resource");
defaultResource.setUris(Collections.singleton("/*"));
defaultResource.setType("urn:" + this.client.getClientId() + ":resources:default");

getResourceSetResource().create(defaultResource);
return defaultResource;
}

private void audit(ResourceServerRepresentation rep, OperationType operation, UriInfo uriInfo, boolean newClient) {
if (newClient) {
adminEvent.resource(ResourceType.AUTHORIZATION_RESOURCE_SERVER).operation(operation).resourcePath(uriInfo, client.getId())
Expand Down
Loading
0