8000 Migrate authz tests to new framework by edewit · Pull Request #51836 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
bd4dbfe
Migrate authz package tests to the new testsuite (part 1)
edewit Aug 19, 2026
61a240b
Migrate authz admin AuthorizationTest to the new testsuite
edewit Aug 19, 2026
4c1e9ef
Migrate authz package tests to the new testsuite (part 2)
edewit Aug 19, 2026
e2b9bcb
fixed tests
edewit Aug 24, 2026
21988ea
pr review comments
edewit Aug 24, 2026
ca1dca9
fix authz migration CI regressions
edewit Aug 25, 2026
3f077f8
test fix
edewit Aug 26, 2026
497c0e4
fix merge error
edewit Aug 27, 2026
7d40312
pr review
edewit Aug 28, 2026
731089a
Restore crypto provider after AuthzClientTest
edewit Sep 16, 2026
a1b7c7f
Wire authz admin tests through AbstractAuthzTest realm import
edewit Sep 16, 2026
3a5102d
Fix ResourceManagementWithAuthzClientTest authz config method clash
edewit Sep 16, 2026
6ba30e5
Fix authz Base2 suite provider and realm setup issues
edewit Sep 16, 2026
dc2a335
Apply spotless formatting to authz test files
edewit Sep 17, 2026
7445f4c
Fix authz Base2 URL rewriting, scripts, and realm setup
edewit Sep 17, 2026
a17709e
Address authz migration review feedback and fix test compilation
edewit Sep 17, 2026
44b3c4a
Apply spotless formatting to authz review fixes
edewit Sep 17, 2026
7236d6b
Fix adminClient field shadowing in AbstractAuthzTest
edewit Sep 17, 2026
461449a
Deploy testsuite providers jar for authz Base2 tests
edewit Sep 17, 2026
c7d8f37
Fix authz test URLs and realm import hooks for Base2 suite
edewit Sep 17, 2026
f3a3b83
Use testing event queue and JUnit Jupiter in authz tests
edewit Sep 17, 2026
6a30f02
Enable test events listener on imported authz realms
edewit Sep 17, 2026
008894c
Deploy authz script policies and fix remaining Base2 failures
edewit Sep 18, 2026
4f4886c
Avoid enabling AUTHORIZATION in Base2 suite config
edewit Sep 18, 2026
ad799d7
Fix authz Base2 CI failures and shared server config
edewit Sep 18, 2026
94e2414
Address review comments for authz test migration
edewit Sep 29, 2026
9745851
moved
edewit Oct 1, 2026
84895d2
Fix authz event polling for non-default event types
edewit Oct 1, 2026
6e52e2e
removed migrated constuctor that's no longer used
edewit Oct 2, 2026
3c74323
added assertion to see if hack still works
edewit Oct 2, 2026
839cdf2
Document why testframework surefire args include --add-opens
edewit Oct 2, 2026
534c9d8
Fix invalid XML comment in pom.xml that broke Maven parsing
edewit Oct 2, 2026
baf845f
Replace leftover Arquillian testingClient calls in authz tests
edewit Dec 2, 2026
4d52269
Drop unused Keycloak IT setup from local authz unit tests
edewit Dec 2, 2026
1ccbbec
Remove unused AdminApiUtil import after rebase onto upstream/main
edewit Dec 4, 2026
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
3 changes: 3 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,10 @@
</surefire.system.args>

<!-- Testframework Settings -->
<!-- Include surefire.system.args (add-opens) so tests can use reflection
into System.getenv()'s internal map (e.g. AuthzClientTest#setEnv). -->
<testframework.surefire.args>
${surefire.system.args}
Comment thread
edewit marked this conversation as resolved.
Resolved
-XX:+ExitOnOutOfMemoryError
-XX:+HeapDumpOnOutOfMemoryError
-Djava.util.logging.manager=org.jboss.logmanager.LogManager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@ public OAuthClient(String baseUrl, CloseableHttpClient httpClient, ManagedWebDri
this(baseUrl, httpClient, managedWebDriver, null);
}

public OAuthClient newConfig() {
return new OAuthClient(baseUrl, httpClient().get(), managedWebDriver, clientResource);
}

@Override
public void fillLoginForm(String username, String password) {
LoginPage loginPage = new LoginPage(managedWebDriver);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,29 +50,7 @@ public void enableForCaches() {
*/
public void set(int offset) throws RuntimeException {
currentOffset = offset;

// set for tests
Time.setOffset(currentOffset);

// set for KC server
var time = Map.of(KEY_OFFSET, currentOffset, CACHES, enableForCaches);
try {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(time);

HttpPut request = new HttpPut(serverUrl + TIME_OFFSET_ENDPOINT);
request.setEntity(new StringEntity(json));
request.setHeader("Content-type", "application/json");

HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != Response.Status.OK.getStatusCode()) {
var statusLine = response.getStatusLine();
throw new WebApplicationException(String.format("Unexpected response status for TimeOffSet: %d %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}

setRemoteOffset(offset);
}

/**
Expand All @@ -97,4 +75,32 @@ public int get() {
public boolean hasChanged() {
return currentOffset != 0;
}

private void setRemoteOffset(int offset) {
if (httpClient == null || serverUrl == null) {
throw new IllegalStateException("Remote time offset is not initialized");
}

// set for tests
Time.setOffset(offset);

// set for KC server
var time = Map.of(KEY_OFFSET, offset, CACHES, enableForCaches);
try {
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(time);

HttpPut request = new HttpPut(serverUrl + TIME_OFFSET_ENDPOINT);
request.setEntity(new StringEntity(json));
request.setHeader("Content-type", "application/json");

HttpResponse response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() != Response.Status.OK.getStatusCode()) {
var statusLine = response.getStatusLine();
throw new WebApplicationException(String.format("Unexpected response status for TimeOffSet: %d %s", statusLine.getStatusCode(), statusLine.getReasonPhrase()));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
5 changes: 5 additions & 0 deletions tests/base/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,11 @@
<artifactId>keycloak-admin-cli</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-authz-client-tests</artifactId>
Comment thread
edewit marked this conversation as resolved.
Resolved
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
package org.keycloak.tests.authz;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.AuthorizationResource;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.JWSInputException;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.AccessToken;
import org.keycloak.representations.idm.ClientRepresentation;
import org.keycloak.representations.idm.EventRepresentation;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.representations.idm.authorization.PolicyRepresentation;
import org.keycloak.testframework.annotations.InjectAdminClient;
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.SectorIdentifierRedirectUrisProvider;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectSectorIdentifierRedirectUrisProvider;
import org.keycloak.testframework.realm.ManagedRealm;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;

/**
* @author mhajas
*/
public abstract class AbstractAuthzTest extends AuthzTestRealmSupport {

private final List<String> importedRealmNames = new ArrayList<>();
private final LinkedList<EventRepresentation> eventQueue = new LinkedList<>();
private final Set<String> processedEventIds = new HashSet<>();

@InjectAdminClient
protected Keycloak injectedAdminClient;

@InjectOAuthClient
protected OAuthClient oauth;
Comment thread
edewit marked this conversation as resolved.
Resolved

@InjectSectorIdentifierRedirectUrisProvider
protected SectorIdentifierRedirectUrisProvider sectorIdentifierRedirectUrisProvider;

@BeforeEach
public void beforeAuthzTest() {
adminClient = injectedAdminClient;
// OAuthClient is CLASS-scoped; clear mutable state left by earlier test methods.
oauth.scope(null);
importedRealmNames.clear();
Comment thread
edewit marked this conversation as resolved.
Resolved
eventQueue.clear();
processedEventIds.clear();
testRealmReps = new ArrayList<>();
addTestRealms(testRealmReps);
ensureInjectedOAuthRedirectUris(testRealmReps);
importTestRealms();
testRealmReps.forEach(r -> importedRealmNames.add(r.getRealm()));
}

@AfterEach
public void afterAuthzTest() {
try {
runManagedCleanupBeforeRealmRemoval();
} finally {
for (String realmName : importedRealmNames) {
removeRealm(realmName);
}
importedRealmNames.clear();
eventQueue.clear();
processedEventIds.clear();
}
Comment thread
edewit marked this conversation as resolved.
Resolved
}

protected void runManagedCleanupBeforeRealmRemoval() {
Set<ManagedRealm> processedManagedRealms = Collections.newSetFromMap(new IdentityHashMap<>());

for (Class<?> type = getClass(); type != null; type = type.getSuperclass()) {
for (Field field : type.getDeclaredFields()) {
if (!ManagedRealm.class.isAssignableFrom(field.getType())) {
continue;
}

field.setAccessible(true);
try {
ManagedRealm managedRealm = (ManagedRealm) field.get(this);
if (managedRealm != null && processedManagedRealms.add(managedRealm)) {
managedRealm.runCleanup();
}
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to run managed realm cleanup", e);
}
}
}
}

protected AccessToken toAccessToken(String rpt) {
AccessToken accessToken;

try {
accessToken = new JWSInput(rpt).readJsonContent(AccessToken.class);
} catch (JWSInputException cause) {
throw new RuntimeException("Failed to deserialize RPT", cause);
}
return accessToken;
}

protected PolicyRepresentation createAlwaysGrantPolicy(AuthorizationResource authorization) {
PolicyRepresentation policy = new PolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId());
policy.setType("always-grant");
authorization.policies().create(policy).close();
return policy;
}

protected PolicyRepresentation createAlwaysDenyPolicy(AuthorizationResource authorization) {
PolicyRepresentation policy = new PolicyRepresentation();
policy.setName(KeycloakModelUtils.generateId());
policy.setType("always-deny");
authorization.policies().create(policy).close();
return policy;
}

protected PolicyRepresentation createOnlyOwnerPolicy(AuthorizationResource authorization) {
PolicyRepresentation PolicyRepresentation();

onlyOwnerPolicy.setName(KeycloakModelUtils.generateId());
onlyOwnerPolicy.setType("allow-resource-owner");

authorization.policies().create(onlyOwnerPolicy).close();

return onlyOwnerPolicy;
}

protected InputStream authzConfigurationStream(InputStream input) {
try {
String authServerRoot = authServerRoot();
String config = new String(input.readAllBytes(), StandardCharsets.UTF_8)
.replace("http://localhost:8180/auth", authServerRoot)
.replace("https://localhost:8543/auth", authServerRoot);
return new ByteArrayInputStream(config.getBytes(StandardCharsets.UTF_8));
Comment on lines +145 to +149
} catch (Exception e) {
throw new RuntimeException("Failed to read authz configuration", e);
}
}

private void ensureInjectedOAuthRedirectUris(List<RealmRepresentation> realms) {
String redirectUri = oauth.getRedirectUri();
if (redirectUri == null || redirectUri.isBlank()) {
return;
}

for (RealmRepresentation realm : realms) {
if (realm.getClients() == null) {
continue;
}

for (ClientRepresentation client : realm.getClients()) {
if (!Boolean.TRUE.equals(client.isPublicClient())) {
continue;
}

if (client.getRedirectUris() == null) {
client.setRedirectUris(new ArrayList<>());
}
if (!client.getRedirectUris().contains(redirectUri)) {
client.getRedirectUris().add(redirectUri);
}
}
}
}

protected String authServerRoot() {
String root = oauth.getBaseUrl();
int realmSegmentIndex = root.indexOf("/realms/");
if (realmSegmentIndex >= 0) {
root = root.substring(0, realmSegmentIndex);
}
return root;
}

protected String pairwiseSectorIdentifierUri() {
return sectorIdentifierRedirectUrisProvider.getUri();
}

protected void configureSectorIdentifierRedirectUris(String... redirectUris) {
sectorIdentifierRedirectUrisProvider.setSectorIdentifierRedirectUris(Arrays.asList(redirectUris));
}

protected EventRepresentation pollTestEvent() {
long deadline = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < deadline) {
fetchEventsIntoQueue();
EventRepresentation event = eventQueue.poll();
if (event != null) {
return event;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
fetchEventsIntoQueue();
return eventQueue.poll();
}

protected void clearTestEvents() {
eventQueue.clear();
processedEventIds.clear();
for (String realmName : importedRealmNames) {
try {
adminClient.realm(realmName).clearEvents();
} catch (Exception ignore) {
}
}
}

private void fetchEventsIntoQueue() {
for (String realmName : importedRealmNames) {
List<EventRepresentation> events = adminClient.realm(realmName)
.getEvents(null, null, null, null, null, null, null, null, "asc");
if (events == null) {
continue;
}
for (EventRepresentation event : events) {
if (event.getId() != null && processedEventIds.add(event.getId())) {
eventQueue.add(event);
}
}
}
}
}
Loading
Loading
0