8000 fix: using resourceVersion instead of data for secret hashing by shawkins · Pull Request #55795 · 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.
8000
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/guides/operator/advanced-configuration.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,10 @@ Similarly ConfigMap References are used by options such as the `configMapFile`.

When specifying a Secret or ConfigMap Reference, make sure that a Secret or ConfigMap containing the referenced keys is present in the same namespace as the CR referencing it.

The operator will poll approximately every minute for changes to referenced Secrets or ConfigMaps. When a meaningful change is detected, the Operator performs a rolling restart of the {project_name} Deployment to pick up the changes.
The operator will poll approximately every minute for changes to referenced Secrets or ConfigMaps.
When a change is detected, the Operator performs a rolling restart of the {project_name} Deployment to pick up the changes.
For a ConfigMap, a change to its data is a meaningful change.
For a Secret, any update to the Secret is a meaningful change, including updates that only modify its metadata such as labels or annotations, as the Operator tracks the Secret by its resource version.

=== Unsupported features

Expand Down
5 changes: 4 additions & 1 deletion operator/src/main/java/org/keycloak/operator/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,10 @@ private static MessageDigest getMessageDigest() {

private static Object getData(Object object) {
if (object instanceof Secret) {
return ((Secret) object).getData();
// never derive anything from the secret data, the digest is published in resources
// that may be readable without access to the secret - the resourceVersion changes with the data
var metadata = ((Secret) object).getMetadata();
return metadata.getName() + "/" + metadata.getResourceVersion();
Comment thread
shawkins marked this conversation as resolved.
Resolved
}
if (object instanceof ConfigMap) {
return ((ConfigMap) object).getData();
Expand Down
8000
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,15 @@ public abstract class KeycloakClientBaseController<R extends CustomResource<? ex
public static final String CLIENT_ADMIN_API_V2 = "client-admin-api:v2";
private static final String HTTPS = "https";

/**
* @param poll if the resource should be polled for changes
* @param hash the hash of the client, or null to use the hash of the target representation. It is published
* in the status, so it must not be derived from any secret data that was inlined in the representation.
* Use for example the secret resourceVersion instead.
*/
record PreparedClient(boolean poll, String hash) {
}

static class KeycloakClientStatusAggregator {
Long generation;
KeycloakClientStatus existingStatus;
Expand Down Expand Up @@ -175,11 +184,11 @@ public UpdateControl<R> reconcile(R resource, Context<R> context) throws Excepti
var map = context.getClient().getKubernetesSerialization().convertValue(client, Map.class);
map.put(BaseClientRepresentation.DISCRIMINATOR_FIELD, client.getProtocol());
T rep = context.getClient().getKubernetesSerialization().convertValue(map, getTargetRepresentation());
// then let the controller subclass apply specific handling
boolean poll = prepareRepresentation(client, rep, context);
rep.setClientId(resource.getMetadata().getName());

String hash = Utils.hash(List.of(rep));
// then let the controller subclass apply specific handling
PreparedClient prepared = prepareRepresentation(client, rep, context);
boolean poll = prepared.poll();
String hash = prepared.hash() != null ? prepared.hash() : Utils.hash(List.of(rep));

if (!hash.equals(statusAggregator.getExistingStatus().getHash())) {
var response = invoke(resource, context, keycloak, clientApi -> {
Expand Down Expand Up @@ -234,7 +243,7 @@ protected static boolean hasFeatureEnabled(Keycloak keycloak) {
.filter(ef -> ef.contains(CLIENT_ADMIN_API_V2) || (ef.size() == 1 && ef.contains("preview"))).isPresent();
}

abstract boolean prepareRepresentation(S crRepresentation, T targetRepresentation, Context<?> context);
abstract PreparedClient prepareRepresentation(S crRepresentation, T targetRepresentation, Context<?> context);

abstract Class<T> getTargetRepresentation();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

import org.keycloak.operator.Constants;
import org.keycloak.operator.Utils;
import org.keycloak.operator.crds.v2alpha1.client.KeycloakOIDCClient;
import org.keycloak.operator.crds.v2alpha1.client.KeycloakOIDCClientRepresentation;
import org.keycloak.representations.admin.v2.OIDCClientRepresentation;
Expand All @@ -41,10 +43,12 @@ Class<OIDCClientRepresentation> getTargetRepresentation() {
}

@Override
boolean prepareRepresentation(
PreparedClient prepareRepresentation(
KeycloakOIDCClientRepresentation crRepresentation, OIDCClientRepresentation targetRepresentation,
Context<?> context) {
boolean poll = false;
String secretIdentity = null;
String secretValue = null;
// create the payload via inlining of the secret
Auth auth = crRepresentation.getAuth();
if (auth != null) {
Expand All @@ -66,19 +70,27 @@ boolean prepareRepresentation(
throw new ResourceNotFoundException(String.format("Secret %s/%s not found with %s=%s label", namespace, secretSelector.getName(), Constants.KEYCLOAK_KIND_ANNOTATION, kind));
}
} else {
// changes to the data change the resourceVersion, which is safe to publish unlike a digest of the data
secretIdentity = secret.getMetadata().getName() + "/" + secretSelector.getKey() + "/" + secret.getMetadata().getResourceVersion();
String value = secret.getData().get(secretSelector.getKey());

if (value == null) {
if (!optional) {
throw new ResourceNotFoundException(String.format("Secret key %s in %s/%s not found", secretSelector.getKey(), namespace, secretSelector.getName()));
}
} else {
targetRepresentation.getAuth().setSecret(new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8));
secretValue = new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8);
}
}
}
}
return poll;
// the hash is published in the status, so it is computed before the secret value is inlined
// and uses the identity of the secret (name and resourceVersion) instead
String hash = Utils.hash(secretIdentity == null ? List.of(targetRepresentation) : List.of(targetRepresentation, secretIdentity));
Comment thread
shawkins marked this conversation as resolved.
Resolved
if (secretValue != null) {
targetRepresentation.getAuth().setSecret(secretValue);
}
return new PreparedClient(poll, hash);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ Class<SAMLClientRepresentation> getTargetRepresentation() {
}

@Override
boolean prepareRepresentation(KeycloakSAMLClientRepresentation crRepresentation,
PreparedClient prepareRepresentation(KeycloakSAMLClientRepresentation crRepresentation,
SAMLClientRepresentation targetRepresentation, Context<?> context) {
// Nothing to do, and no polling
return false;
return new PreparedClient(false, null);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* 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.operator.controllers;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

import org.keycloak.operator.Constants;
import org.keycloak.operator.controllers.KeycloakClientBaseController.PreparedClient;
import org.keycloak.operator.crds.v2alpha1.client.KeycloakOIDCClient;
import org.keycloak.operator.crds.v2alpha1.client.KeycloakOIDCClientBuilder;
import org.keycloak.operator.crds.v2alpha1.client.KeycloakOIDCClientRepresentation;
import org.keycloak.representations.admin.v2.OIDCClientRepresentation;

import io.fabric8.kubernetes.api.model.HasMetadata;
import io.fabric8.kubernetes.api.model.KubernetesResourceList;
import io.fabric8.kubernetes.api.model.Secret;
import io.fabric8.kubernetes.api.model.SecretBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.NonNamespaceOperation;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.fabric8.kubernetes.client.utils.KubernetesSerialization;
import io.javaoperatorsdk.operator.api.reconciler.Context;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;

public class KeycloakOIDCClientControllerTest {

private static final String NAMESPACE = "ns";
private static final String SECRET_NAME = "client-secret";
private static final String SECRET_KEY = "secret";

private final KeycloakOIDCClientController controller = new KeycloakOIDCClientController();

@Test
public void testHashIsNotDerivedFromSecretData() {
PreparedClient first = prepare(newSecret("1", "first-secret-value"), new OIDCClientRepresentation());
PreparedClient second = prepare(newSecret("1", "other-secret-value"), new OIDCClientRepresentation());

// the hash is published in the status, so it must be the same for different data at the same resourceVersion
assertEquals(first.hash(), second.hash());
}

@Test
public void testHashChangesWithResourceVersion() {
PreparedClient first = prepare(newSecret("1", "secret-value"), new OIDCClientRepresentation());
PreparedClient second = prepare(newSecret("2", "secret-value"), new OIDCClientRepresentation());

assertNotEquals(first.hash(), second.hash());
}

@Test
public void testDecodedSecretIsInlinedAndPolled() {
OIDCClientRepresentation target = new OIDCClientRepresentation();
PreparedClient prepared = prepare(newSecret("1", "decoded-secret-value"), target);

assertEquals("decoded-secret-value", target.getAuth().getSecret());
assertEquals(true, prepared.poll());
assertNull(target.getAuth().getAdditionalFields().get("secretRef"));
}

@SuppressWarnings("unchecked")
private PreparedClient prepare(Secret secret, OIDCClientRepresentation target) {
var auth = new OIDCClientRepresentation.Auth();
auth.setMethod("client-secret");
auth.setAdditionalField("secretRef", Map.of("name", SECRET_NAME, "key", SECRET_KEY));

var cr = new KeycloakOIDCClientRepresentation();
cr.setAuth(auth);

var targetAuth = new OIDCClientRepresentation.Auth();
targetAuth.setMethod("client-secret");
targetAuth.setAdditionalField("secretRef", Map.of("name", SECRET_NAME, "key", SECRET_KEY));
target.setAuth(targetAuth);

KubernetesClient client = Mockito.mock(KubernetesClient.class);
Mockito.when(client.getKubernetesSerialization()).thenReturn(new KubernetesSerialization());
MixedOperation<Secret, KubernetesResourceList<Secret>, Resource<Secret>> secrets = Mockito.mock(MixedOperation.class);
NonNamespaceOperation<Secret, KubernetesResourceList<Secret>, Resource<Secret>> namespaced = Mockito.mock(NonNamespaceOperation.class);
Resource<Secret> secretResource = Mockito.mock(Resource.class);
Mockito.when(client.resources(Secret.class)).thenReturn(secrets);
Mockito.when(secrets.inNamespace(NAMESPACE)).thenReturn(namespaced);
Mockito.when(namespaced.withName(SECRET_NAME)).thenReturn(secretResource);
Mockito.when(secretResource.get()).thenReturn(secret);

Context<KeycloakOIDCClient> context = Mockito.mock(Context.class);
Mockito.when(context.getClient()).thenReturn(client);
Mockito.when(context.getPrimaryResource()).thenReturn(
new KeycloakOIDCClientBuilder().withNewMetadata().withNamespace(NAMESPACE).withName("client").endMetadata().build());

return controller.prepareRepresentation(cr, target, context);
}

private Secret newSecret(String resourceVersion, String value) {
return new SecretBuilder().withNewMetadata().withNamespace(NAMESPACE).withName(SECRET_NAME)
.withResourceVersion(resourceVersion)
.addToLabels(Constants.KEYCLOAK_KIND_ANNOTATION, HasMetadata.getKind(KeycloakOIDCClient.class))
.endMetadata()
.addToData(SECRET_KEY, Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8)))
.build();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ public void testSecretsAreWatched() {
k8sclient.resource(tlsSecret).update();
});

Log.info("Updating DB Secret metadata, NOT expecting restart");
testDeploymentRestarted(Set.of(), Set.of(kc), () -> {
Log.info("Updating DB Secret metadata, expecting restart as the resourceVersion changes");
testDeploymentRestarted(Set.of(kc), Set.of(), () -> {
dbSecret.getMetadata().getLabels().put(UUID.randomUUID().toString(), "YmxhaGJsYWg");
k8sclient.resource(dbSecret).update();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;

@QuarkusTest
public class WatchedResourcesTest {
Expand All @@ -49,17 +50,30 @@ public class WatchedResourcesTest {
@Test
public void testHashing() {
assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Utils.hash(List.of()));
assertEquals("b5655bfe4d4e130f5023a76a5de0906cf84eb5895bda5d44642673f9eb4024bf", Utils.hash(List.of(newSecret(Map.of("a", "b")), newSecret(Map.of("c", "d")))));
assertEquals("d526224334e65c71095be909b2d14c52f1589abb84a3c76fbe79dd75d7132fbb",
Utils.hash(List.of(new ConfigMapBuilder().withNewMetadata().withName("x")
.withAnnotations(Map.of(UUID.randomUUID().toString(), UUID.randomUUID().toString()))
.endMetadata().withData(Map.of("a", "b")).build())));
}

private Secret newSecret(Map<String, String> data) {
return new SecretBuilder().withNewMetadata().withName(UUID.randomUUID().toString())
.withLabels(Map.of(UUID.randomUUID().toString(), UUID.randomUUID().toString())).endMetadata()
.withData(data).build();
@Test
public void testSecretHashIsNotDerivedFromData() {
// the digest is published in resources that may be readable without access to the secret,
// so it must be the same for different data and only depend on the identity and resourceVersion
assertEquals(Utils.hash(List.of(newSecret("s", "1", Map.of("a", "b")))),
Utils.hash(List.of(newSecret("s", "1", Map.of("a", "c")))));
}

@Test
public void testSecretHashChangesWithResourceVersion() {
Secret secret = newSecret("s", "1", Map.of("a", "b"));
assertNotEquals(Utils.hash(List.of(secret)), Utils.hash(List.of(newSecret("s", "2", Map.of("a", "b")))));
assertNotEquals(Utils.hash(List.of(secret)), Utils.hash(List.of(newSecret("t", "1", Map.of("a", "b")))));
}

private Secret newSecret(String name, String resourceVersion, Map<String, String> data) {
return new SecretBuilder().withNewMetadata().withName(name).withResourceVersion(resourceVersion)
.endMetadata().withData(data).build();
}

}
Loading
0