8000 Validate authorization resource URI templates on every import path by sguilhen · Pull Request #55634 · 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 @@ -37,7 +37,9 @@ When the pattern has a path in front of the wildcard, that path must match as we
A pattern is matched in the form it is registered. A pattern that contains only a path, such as `+/*.html+`, matches requested URIs given as paths, such as `+/page.html+`, and does not match a requested URI given in absolute form, such as `+https://myserver/page.html+`. To match absolute URIs, register the resource with an absolute URI, in which case the scheme and authority must match too: `+https://myserver/public/*.json+` does not match `+https://other.example/public/report.json+`.
+
These patterns can be combined, for example `+/api/{id}/files/*+`.
Wildcards (`+*+`) are only supported as a trailing `+/*+` or as a suffix `+/*.ext+`. A wildcard in the middle of a path, such as `+/api/*/info+`, never matches and will be rejected when creating or updating resources.
A `+*+` is recognized as a wildcard only when it is the last character of the pattern, or when it is preceded by `+/+` and followed by `+.+`; everywhere else it is treated as a literal character.
For example, `+/a/*.x/b+` is read as the literal prefix `+/a/+`, a suffix wildcard, and the extension `+.x/b+`, so it matches `+/a/some.x/b+`. `+/api/*/info+`, however, has its `+*+` followed by `+/+`, so it is never recognized as a wildcard and the pattern is instead treated as a literal path that matches only `+/api/*/info+` itself.
A `+*+` used in neither of the recognized forms is rejected when creating or updating resources.
Comment thread
pedroigor marked this conversation as resolved.
Resolved
+
When a requested URI matches more than one pattern, the patterns are compared segment by segment and the one that pins the most down is selected.
Within a segment, a literal name such as `+admin+` is the strongest constraint, a parameter such as `+{id}+` accepts any single segment, and a wildcard accepts everything that is left; the first segment where two patterns differ decides between them.
Expand Down
23 changes: 23 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
8000
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,29 @@ Explicit `false` values for `wantAssertionsSigned` and `validateSignature` remai

Disabling signature validation reduces protection against forged identity-provider responses.

=== Authorization resource URI templates are now validated on every creation and import path
// https://github.com/keycloak/keycloak/issues/55592

{project_name} rejects an Authorization Services resource URI template that uses a `+*+` wildcard outside of the
two supported forms, a trailing `+/*+` or a suffix `+/*.ext+`, with an error such as `+URI [...] is not a valid
template: wildcard '*' is only supported as trailing '/*' or as a suffix pattern '/*.ext'+`. This validation
previously ran only on the resource endpoints, `+POST+`/`+PUT .../authz/resource-server/resource+` and the
Protection API's `+resource_set+` endpoint. Every other path that stores resources skipped it, so a template the
resource endpoints reject could still be imported and would be matched at runtime like any other resource.

The same validation now also runs on:

* `+POST .../authz/resource-server/import+`
* Client create and update with an embedded `+authorizationSettings+`
Comment thread
pedroigor marked this conversation as resolved.
Resolved
* Dynamic client registration update
* Realm import, partial import, and the directory-based import of a realm's authorization settings

A realm export, partial export, or client configuration created on an earlier version can contain a resource URI
that was never a valid template, since nothing enforced the rule where it was stored. Importing it now fails with
the error above instead of silently storing it. Correct the URI before re-importing: a wildcard belongs only at
the end of the pattern or as a file-extension suffix, for example `+/api/*+` or `+/api/*.json+`, never in the
middle of a path such as `+/api/*/info+`.

// ------------------------ Notable changes ------------------------ //
== Notable changes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
import org.keycloak.common.Profile.Feature;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.common.util.ObjectUtil;
import org.keycloak.common.util.PathMatcher;
import org.keycloak.common.util.UriUtils;
import org.keycloak.component.ComponentModel;
import org.keycloak.connections.jpa.support.EntityManagers;
Expand Down Expand Up @@ -1315,6 +1316,8 @@ public static ResourceServer toModel(ResourceServerRepresentation rep, Authoriza
RealmModel realm = authorization.getRealm();

for (ResourceRepresentation resource : rep.getResources()) {
validateUris(resource);

ResourceOwnerRepresentation owner = resource.getOwner();

if (owner == null) {
Expand All @@ -1337,6 +1340,21 @@ public static ResourceServer toModel(ResourceServerRepresentation rep, Authoriza
return resourceServer;
}

private static void validateUris(ResourceRepresentation resource) {
Set<String> uris = resource.getUris();

if (uris == null) {
return;
}

for (String uri : uris) {
String error = PathMatcher.validateTemplate(uri);
if (error != null) {
throw new ModelValidationException("URI [" + uri + "] is not a valid template: " + error);
}
}
}

private static Policy importPolicies(AuthorizationProvider authorization, ResourceServer resourceServer, List<PolicyRepresentation> policiesToImport, String parentPolicyName) {
StoreFactory storeFactory = authorization.getStoreFactory();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import jakarta.ws.rs.core.Response;

Expand All @@ -17,10 +18,12 @@
import org.keycloak.partialimport.ResourceType;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.ErrorRepresentation;
import org.keycloak.representations.idm.OAuth2ErrorRepresentation;
import org.keycloak.representations.idm.PartialImportRepresentation;
import org.keycloak.representations.idm.RoleRepresentation;
import org.keycloak.representations.idm.RolesRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.representations.idm.authorization.ResourceRepresentation;
import org.keycloak.representations.idm.authorization.ResourceServerRepresentation;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.tests.suites.DatabaseTest;
Expand Down Expand Up @@ -210,4 +213,34 @@ public void testIllegalSchemeBaseUrlPartialImport() {

assertTrue(managedRealm.admin().clients().findByClientId("evil-partial-import-test").isEmpty());
}

// https://github.com/keycloak/keycloak/issues/55592
@Test
public void testAddClientsWithInvalidAuthorizationResourceUriFails() {
setFail();

ClientRepresentation client = new ClientRepresentation();
client.setClientId("invalid-uri-partial-import-test");
client.setServiceAccountsEnabled(true);
client.setBearerOnly(false);
client.setPublicClient(false);
client.setAuthorizationServicesEnabled(true);

ResourceServerRepresentation authzSettings = new ResourceServerRepresentation();
ResourceRepresentation resource = new ResourceRepresentation("foo");

resource.setUris(Set.of("/api/*/info"));
authzSettings.setResources(List.of(resource));
client.setAuthorizationSettings(authzSettings);

piRep.setClients(List.of(client));

try (Response response = managedRealm.admin().partialImport(piRep)) {
assertEquals(400, response.getStatus());
OAuth2ErrorRepresentation errorRep = response.readEntity(OAuth2ErrorRepresentation.class);
Assertions.assertTrue(errorRep.getErrorDescription().contains("is not a valid template"));
}

assertTrue(managedRealm.admin().clients().findByClientId("invalid-uri-partial-import-test").isEmpty());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/*
* Copyright 2026 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed 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.
*/
package org.keycloak.tests.authz.admin;

import java.util.List;
import java.util.Set;

import jakarta.ws.rs.BadRequestException;
import jakarta.ws.rs.NotFoundException;
import jakarta.ws.rs.core.Response;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.authorization.ResourceRepresentation;
import org.keycloak.representations.idm.authorization.ResourceServerRepresentation;
import org.keycloak.testframework.annotations.InjectAdminClient;
import org.keycloak.testframework.annotations.InjectClient;
import org.keycloak.testframework.annotations.InjectRealm;
import org.keycloak.testframework.annotations.KeycloakIntegrationTest;
import org.keycloak.testframework.injection.LifeCycle;
import org.keycloak.testframework.realm.ClientBuilder;
import org.keycloak.testframework.realm.ClientConfig;
import org.keycloak.testframework.realm.ManagedClient;
import org.keycloak.testframework.realm.ManagedRealm;

import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Resource URI templates that the resource endpoints reject, such as a wildcard in the middle of a path, must be
* rejected consistently on every path that creates or imports resources.
*
* @see <a href="https://github.com/keycloak/keycloak/issues/55592">#55592</a>
*/
@KeycloakIntegrationTest
public class ResourceServerUriTemplateValidationTest {

private static final String INVALID_URI = "/api/*/info";

@InjectRealm(lifecycle = LifeCycle.METHOD)
ManagedRealm realm;

@InjectClient(config = ResourceServerConfig.class, lifecycle = LifeCycle.METHOD)
ManagedClient resourceServer;

@InjectAdminClient
Keycloak adminClient;

@Test
public void testImportSettingsRejectsInvalidResourceUri() {
ResourceServerRepresentation settings = new ResourceServerRepresentation();
ResourceRepresentation resource = new ResourceRepresentation("invalid-uri-resource");

resource.setUris(Set.of(INVALID_URI));
settings.setResources(List.of(resource));

assertThrows(BadRequestException.class, () -> resourceServer.admin().authorization().importSettings(settings));

assertTrue(resourceServer.admin().authorization().exportSettings().getResources().isEmpty());
}

@Test
public void testClientCreateWithAuthorizationSettingsRejectsInvalidResourceUri() {
ClientRepresentation client = new ClientRepresentation();

client.setClientId("invalid-uri-client-create-test");
client.setServiceAccountsEnabled(true);
client.setAuthorizationServicesEnabled(true);

ResourceServerRepresentation authzSettings = new ResourceServerRepresentation();
ResourceRepresentation resource = new ResourceRepresentation("invalid-uri-resource");

resource.setUris(Set.of(INVALID_URI));
authzSettings.setResources(List.of(resource));
client.setAuthorizationSettings(authzSettings);

try (Response response = realm.admin().clients().create(client)) {
assertEquals(400, response.getStatus());
assertThat(response.readEntity(String.class), containsString("is not a valid template"));
}

assertTrue(realm.admin().clients().findByClientId(client.getClientId()).isEmpty());
}

@Test
public void testRealmImportRejectsInvalidResourceUri() {
String realmName = "invalid-uri-realm-import-test";
RealmRepresentation realmRep = new RealmRepresentation();

realmRep.setRealm(realmName);
realmRep.setEnabled(true);

ClientRepresentation client = new ClientRepresentation();

client.setClientId("invalid-uri-client");
client.setServiceAccountsEnabled(true);
client.setAuthorizationServicesEnabled(true);

ResourceServerRepresentation authzSettings = new ResourceServerRepresentation();
ResourceRepresentation resource = new ResourceRepresentation("invalid-uri-resource");

resource.setUris(Set.of(INVALID_URI));
authzSettings.setResources(List.of(resource));
client.setAuthorizationSettings(authzSettings);

realmRep.setClients(List.of(client));

try {
assertThrows(BadRequestException.class, () -> adminClient.realms().create(realmRep));
assertThrows(NotFoundException.class, () -> adminClient.realm(realmName).toRepresentation());
} finally {
try {
adminClient.realm(realmName).remove();
} catch (NotFoundException ignored) {
}
}
}

public static class ResourceServerConfig implements ClientConfig {

@Override
public ClientBuilder configure(ClientBuilder client) {
return client.clientId("resource-server")
.secret("secret")
.authorizationServicesEnabled(true)
.directAccessGrantsEnabled();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,47 @@ public void testUpdateAuthorizationSettings() throws ClientRegistrationException
assertFalse(authzSettings.getPolicies().isEmpty());
}

// https://github.com/keycloak/keycloak/issues/55592
@Test
@DatabaseTest
public void testUpdateAuthorizationSettingsRejectsInvalidResourceUri() throws ClientRegistrationException {
authManageClients();
ClientRepresentation clientRep = buildClient();
clientRep.setAuthorizationServicesEnabled(true);

ClientRepresentation rep = registerClient(clientRep, true);
rep = managedRealm.admin().clients().get(rep.getId()).toRepresentation();

assertTrue(rep.getAuthorizationServicesEnabled());

ResourceServerRepresentation authzSettings = new ResourceServerRepresentation();
ResourceRepresentation resource = new ResourceRepresentation("foo", "scope-a");

resource.setUris(Set.of("/api/*/info"));
authzSettings.setResources(List.of(resource));

rep.setAuthorizationSettings(authzSettings);

try {
reg.update(rep);
fail("Expected ClientRegistrationException — invalid resource URI template must be rejected");
} catch (ClientRegistrationException e) {
HttpErrorException cause = (HttpErrorException) e.getCause();
assertThat(cause.getStatusLine().getStatusCode(), is(400));

OAuth2ErrorRepresentation errorRep;
try {
errorRep = JsonSerialization.readValue(cause.getErrorResponse(), OAuth2ErrorRepresentation.class);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
assertThat(errorRep.getErrorDescription(), CoreMatchers.containsString("is not a valid template"));
}

authzSettings = managedRealm.admin().clients().get(rep.getId()).authorization().exportSettings();
assertTrue(authzSettings.getResources().isEmpty());
}

//#51340
@Test
public void updateProtocolViaRegistrationTokenShouldBeRejected() throws ClientRegistrationException {
Expand Down
Loading
0