8000 Resolve Kubernetes IdP issuer from discovery by chance-coleman · Pull Request #50224 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
77a7d9b
feat: resolve Kubernetes IdP issuer from discovery
chance-coleman Jun 22, 2026
194b0f0
Merge branch 'main' into resolve-kubernetes-idp-issuer-discovery
chance-coleman Aug 27, 2026
5fae487
Address review feedback
chance-coleman Aug 27, 2026
153a81f
Address additional review feedback
chance-coleman Aug 27, 2026
0f8d675
Address latest review feedback
chance-coleman Aug 27, 2026
9486b4d
Address latest review feedback
chance-coleman Aug 27, 2026
9fe8eb7
Address latest review feedback
chance-coleman Aug 27, 2026
22ed9d9
Address latest review feedback
chance-coleman Aug 27, 2026
163c833
copilot latest review feedback
chance-coleman Aug 27, 2026
a40697b
copilot latest review feedback
chance-coleman Aug 27, 2026
53f97b2
Merge branch 'main' into resolve-kubernetes-idp-issuer-discovery
chance-coleman Sep 15, 2026
86c6f0f
fix: kubernetes issuer discovery config and ipv6 host matching
chance-coleman Sep 15, 2026
ab16e39
Fix Kubernetes discovery URL mode detection
chance-coleman Sep 15, 2026
9b1df7b
Handle empty automatic issuer discovery value
chance-coleman Sep 15, 2026
c17c87b
Address Copilot review feedback
chance-coleman Sep 15, 2026
b304c6a
ci: rerun operator checks
chance-coleman Sep 16, 2026
f3de517
fix: allow Kubernetes JWKS discovery on port 8443
chance-coleman Sep 16, 2026
0586dc5
fix: make Kubernetes hostname checks case-insensitive
chance-coleman Sep 16, 2026
4c7eefc
fix: harden Kubernetes JWKS endpoint validation
chance-coleman Sep 16, 2026
cfbe8e8
Simplify Kubernetes issuer discovery configuration
chance-coleman Sep 18, 2026
f3ac7b0
fix: harden Kubernetes issuer discovery
chance-coleman Sep 18, 2026
cbc4c96
Merge branch 'main' into resolve-kubernetes-idp-issuer-discovery
chance-coleman Sep 21, 2026
3373b49
Refine Kubernetes issuer discovery handling
chance-coleman Sep 21, 2026
88cb1f2
Preserve SAML authn context values after save
chance-coleman Sep 21, 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
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ This feature can be enabled and disabled with the feature `kubernetes-service-ac

The default issuer URL for a Kubernetes cluster is `\https://kubernetes.default.svc.cluster.local`. You can discover
this value by decoding a service account token to retrieve the value of the `iss` claim.
For managed Kubernetes clusters where service account tokens use an external issuer, leave the issuer URL empty and
provide the Kubernetes API server or another OIDC discovery URL instead. When the identity provider is saved,
{project_name} resolves and persists the issuer URL and JWKS URL from the discovery document. When the provider is
updated with a discovery URL, {project_name} resolves the discovery document again and updates the persisted values.

Keycloak must be able to invoke the endpoint `<ISSUER>/.well-known/openid-configuration` and additionally the
JWKS endpoint returned in the well-known configuration. By default, these endpoints require authentication with a
service account token. {project_name} will automatically use the token from `/var/run/secrets/kubernetes.io/serviceaccount/token`
if available and the token issuer matches the configured issuer.
When an issuer discovery URL is configured, Keycloak invokes its
`<DISCOVERY_URL>/.well-known/openid-configuration` endpoint when the provider is saved or updated and persists the returned JWKS
URL. Otherwise, it discovers keys from `<ISSUER>/.well-known/openid-configuration` when needed. {project_name} uses the token from
`/var/run/secrets/kubernetes.io/serviceaccount/token` to access the in-cluster discovery endpoint. When loading JWKS,
it uses the token when its `iss` claim matches the configured issuer.

Each identity provider must have a unique issuer. Each client must also have a unique subject identifier for each
issuer. As the subject identifier is built from the namespace and service account name, each client must have its own
Expand All @@ -39,7 +44,10 @@ and make sure tokens can not be intercepted in communication between the client
|The alias for the identity provider is used to link a client to the provider

|Kubernetes Issuer URL
|The issuer URL of service account tokens. The URL `<ISSUER>.well-known/openid-configuration` must be available to {project_name})
|Optional issuer URL of service account tokens. If omitted, {project_name} resolves it from the issuer discovery URL when configured; otherwise, it uses the default Kubernetes issuer.

|Issuer discovery URL
|Optional Kubernetes API server or external OIDC discovery base URL. When configured, {project_name} resolves and persists the issuer and JWKS URL when the provider is saved or updated.

|===
+
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -979,8 +979,10 @@ addKubernetesProvider=Add Kubernetes provider
spiffeTrustDomain=SPIFFE Trust Domain
spiffeTrustDomainHelp=Use a URL starting with 'spiffe://' followed by a domain name. For example, 'spiffe://acme.com'.
spiffeBundleEndpoint=SPIFFE Bundle or OIDC JWKs endpoint
kubernetesIssuerUrlHelp=The issuer of the Kubernetes service account tokens
kubernetesIssuerUrlHelp=Optional issuer of the Kubernetes service account tokens. If omitted, Keycloak resolves it from the issuer discovery URL when configured; otherwise, it uses the default Kubernetes issuer.
kubernetesIssuerUrl=Kubernetes Issuer URL
kubernetesIssuerDiscoveryUrl=Issuer discovery URL
kubernetesIssuerDiscoveryUrlHelp=Optional Kubernetes API server or external OIDC discovery base URL. When configured, Keycloak resolves and persists the issuer and JWKS URL when the identity provider is saved or updated.
permission=Permission
saveEventListeners=Save Event Listeners
capabilityConfig=Capability config
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export default function AddKubernetesConnect() {
const id = "kubernetes";

const form = useForm<DiscoveryIdentityProvider>({
defaultValues: { alias: id, config: { allowCreate: "true" } },
defaultValues: {
alias: id,
config: { allowCreate: "true" },
},
mode: "onChange",
});
const { handleSubmit } = form;
Expand Down
25 changes: 24 additions & 1 deletion js/apps/admin-ui/src/identity-providers/add/DetailSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,30 @@ export default function DetailSettings() {
if (origAuthnContextDeclRefs) {
p.config!.authnContextDeclRefs = origAuthnContextDeclRefs;
}
reset(toFormValues(p));
const updatedProvider = await adminClient.identityProviders.findOne({
alias: provider?.alias || alias,
});

if (updatedProvider) {
setProvider(updatedProvider);
reset(toFormValues(updatedProvider));

if (updatedProvider.config?.authnContextClassRefs) {
form.setValue(
"config.authnContextClassRefs",
JSON.parse(updatedProvider.config.authnContextClassRefs),
);
}

if (updatedProvider.config?.authnContextDeclRefs) {
form.setValue(
"config.authnContextDeclRefs",
JSON.parse(updatedProvider.config.authnContextDeclRefs),
);
}
} else {
reset(toFormValues(p));
}
addAlert(t("updateSuccessIdentityProvider"), AlertVariant.success);
} catch (error) {
addError("updateErrorIdentityProvider", error);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import IdentityProviderRepresentation from "libs/keycloak-admin-client/lib/defs/
export const KubernetesSettings = () => {
const { t } = useTranslation();
const { control } = useFormContext<IdentityProviderRepresentation>();

return (
<>
<TextControl
Expand All @@ -18,12 +19,16 @@ export const KubernetesSettings = () => {
required: t("required"),
}}
/>

<TextControl
name="config.issuer"
labelIcon={t("kubernetesIssuerUrlHelp")}
label={t("kubernetesIssuerUrl")}
/>
<TextControl
name="config.issuerDiscoveryUrl"
labelIcon={t("kubernetesIssuerDiscoveryUrlHelp")}
label={t("kubernetesIssuerDiscoveryUrl")}
/>
<FormGroupField label="fedClientAssertionMaxExp">
<Controller
name="config.fedClientAssertionMaxExp"
Expand Down
1 change: 1 addition & 0 deletions js/apps/admin-ui/test/identity-providers/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ export async function createKubernetesProvider(
issuerUrl: string,
) {
await clickProviderCard(page, providerName);
await expect(page.getByTestId("config.issuer")).toBeEnabled();
await page.getByTestId("config.issuer").fill(issuerUrl);
await clickAddButton(page);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
public interface KubernetesConstants {

String DEFAULT_KUBERNETES_ISSUER_URL = "https://kubernetes.default.svc.cluster.local";
String KUBERNETES_SERVICE_HOST_KEY = "KUBERNETES_SERVICE_HOST";
String KUBERNETES_SERVICE_PORT_HTTPS_KEY = "KUBERNETES_SERVICE_PORT_HTTPS";
String DEFAULT_KUBERNETES_API_SERVER_URL = "https://kubernetes.default.svc";
String SERVICE_ACCOUNT_TOKEN_PATH = "/var/run/secrets/kubernetes.io/serviceaccount/token";

}
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ private boolean verifySignature(AbstractJWTClientValidator validator) {

KeyWrapper publicKey;
try {
publicKey = keyStorage.getPublicKey(modelKey, kid, alg, new KubernetesJwksEndpointLoader(session, config.getIssuer()));
publicKey = keyStorage.getPublicKey(modelKey, kid, alg, new KubernetesJwksEndpointLoader(session, config.getIssuer(), config.getJwksUrl()));
} catch (Exception e) {
// Indicative of an infrastructure/configuration and can't be
// triggered by a client - worth WARN visibility.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
package org.keycloak.broker.kubernetes;


import org.keycloak.broker.oidc.IssuerValidation;
import org.keycloak.http.simple.SimpleHttp;
import org.keycloak.http.simple.SimpleHttpRequest;
import org.keycloak.http.simple.SimpleHttpResponse;
import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.IdentityProviderType;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation;
import org.keycloak.util.Strings;
import org.keycloak.utils.KeycloakSessionUtil;

import static org.keycloak.broker.kubernetes.KubernetesConstants.DEFAULT_KUBERNETES_API_SERVER_URL;
import static org.keycloak.broker.kubernetes.KubernetesConstants.DEFAULT_KUBERNETES_ISSUER_URL;
import static org.keycloak.broker.oidc.OIDCIdentityProviderConfig.JWKS_URL;
import static org.keycloak.common.util.UriUtils.checkUrl;


public class KubernetesIdentityProviderConfig extends IdentityProviderModel implements IssuerValidation {

public static final String ISSUER_DISCOVERY_URL = "issuerDiscoveryUrl";
10BC8
public KubernetesIdentityProviderConfig() {
}

Expand All @@ -28,6 +38,14 @@ public String getIssuer() {
return issuer;
}

public String getIssuerDiscoveryUrl() {
return getConfig().get(ISSUER_DISCOVERY_URL);
}

public String getJwksUrl() {
return getConfig().get(JWKS_URL);
}

public int getAllowedClockSkew() {
String allowedClockSkew = getConfig().get(ALLOWED_CLOCK_SKEW);
if (allowedClockSkew == null || allowedClockSkew.isEmpty()) {
Expand All @@ -49,7 +67,58 @@ public Boolean isHideOnLogin() {
@Override
public void validate(RealmModel realm) {
super.validate(realm);
getConfig().put(ISSUER, getIssuer());

String issuerDiscoveryUrl = getIssuerDiscoveryUrl();
if (!Strings.isEmpty(issuerDiscoveryUrl)) {
resolveIssuer(realm, issuerDiscoveryUrl);
Comment thread
chance-coleman marked this conversation as resolved.
Resolved
} else if (Strings.isEmpty(getConfig().get(ISSUER))) {
getConfig().put(ISSUER, getIssuer());
}

if (Strings.isEmpty(issuerDiscoveryUrl)) {
getConfig().remove(JWKS_URL);
}

validateIssuer(realm, IdentityProviderType.CLIENT_ASSERTION);
}

private void resolveIssuer(RealmModel realm, String issuerDiscoveryUrl) {
checkUrl(realm.getSslRequired(), issuerDiscoveryUrl, ISSUER_DISCOVERY_URL);

try {
KeycloakSession session = KeycloakSessionUtil.getKeycloakSession();
Comment thread
chance-coleman marked this conversation as resolved.
Resolved
SimpleHttpRequest request = SimpleHttp.create(session)
.doGet(KubernetesUtils.discoveryUrl(issuerDiscoveryUrl))
.acceptJson();
Comment thread
chance-coleman marked this conversation as resolved.
Resolved
Comment thread
chance-coleman marked this conversation as resolved.
Resolved
Comment thread
chance-coleman marked this conversation as resolved.
Resolved

if (KubernetesUtils.discoveryUrl(DEFAULT_KUBERNETES_API_SERVER_URL)
.equals(KubernetesUtils.discoveryUrl(issuerDiscoveryUrl))) {
String token = KubernetesUtils.getServiceAccountToken();
if (!Strings.isEmpty(token)) {
request.auth(token);
}
}

OIDCConfigurationRepresentation oidcConfig;
try (SimpleHttpResponse response = request.asResponse()) {
int status = response.getStatus();
if (status != 200) {
throw new IllegalArgumentException(String.format("Failed to resolve Kubernetes issuer from '%s': HTTP status %d", issuerDiscoveryUrl, status));
}
Comment thread
chance-coleman marked this conversation as resolved.
Resolved
oidcConfig = response.asJson(OIDCConfigurationRepresentation.class);
}
if (Strings.isEmpty(oidcConfig.getIssuer()) || Strings.isEmpty(oidcConfig.getJwksUri())) {
throw new IllegalArgumentException(String.format("Could not resolve issuer and JWKS URL from '%s'", issuerDiscoveryUrl));
}

checkUrl(realm.getSslRequired(), oidcConfig.getIssuer(), ISSUER);
checkUrl(realm.getSslRequired(), oidcConfig.getJwksUri(), JWKS_URL);
getConfig().put(ISSUER, oidcConfig.getIssuer());
getConfig().put(JWKS_URL, oidcConfig.getJwksUri());
} catch (IllegalArgumentException e) {
throw e;
} catch (Exception e) {
throw new IllegalArgumentException(String.format("Failed to resolve Kubernetes issuer from '%s'", issuerDiscoveryUrl), e);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,54 +1,49 @@
package org.keycloak.broker.kubernetes;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import org.keycloak.crypto.PublicKeysWrapper;
import org.keycloak.http.simple.SimpleHttp;
import org.keycloak.http.simple.SimpleHttpRequest;
import org.keycloak.jose.jwk.JSONWebKeySet;
import org.keycloak.jose.jwk.JWK;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.keys.PublicKeyLoader;
import org.keycloak.models.KeycloakSession;
import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation;
import org.keycloak.representations.JsonWebToken;
import org.keycloak.util.JWKSUtils;
import org.keycloak.util.Strings;

import org.apache.commons.io.FileUtils;
import org.apache.http.HttpHeaders;
import org.jboss.logging.Logger;

import static org.keycloak.broker.kubernetes.KubernetesConstants.SERVICE_ACCOUNT_TOKEN_PATH;

public class KubernetesJwksEndpointLoader implements PublicKeyLoader {

private static final Logger logger = Logger.getLogger(KubernetesJwksEndpointLoader.class);

private final KeycloakSession session;
private final String issuer;
private final String jwksUrl;

public KubernetesJwksEndpointLoader(KeycloakSession session, String issuer) {
public KubernetesJwksEndpointLoader(KeycloakSession session, String issuer, String jwksUrl) {
this.session = session;
this.issuer = issuer;
this.jwksUrl = jwksUrl;
}

@Override
public PublicKeysWrapper loadKeys() throws Exception {
SimpleHttp simpleHttp = SimpleHttp.create(session);

String token = getToken(issuer);

String wellKnownEndpoint = issuer + "/.well-known/openid-configuration";
String token = KubernetesUtils.getServiceAccountToken(issuer);
String jwksUri = jwksUrl;
if (Strings.isEmpty(jwksUri)) {
String wellKnownEndpoint = KubernetesUtils.discoveryUrl(issuer);
SimpleHttpRequest wellKnownRequest = simpleHttp.doGet(wellKnownEndpoint).acceptJson();
if (token != null) {
wellKnownRequest.auth(token);
}

SimpleHttpRequest wellKnownReqest = simpleHttp.doGet(wellKnownEndpoint).acceptJson();
if (token != null) {
wellKnownReqest.auth(token);
}
String jwksUri = wellKnownReqest.asJson(OIDCConfigurationRepresentation.class).getJwksUri();
if (jwksUri == null) {
throw new IOException("OIDC discovery document from " + wellKnownEndpoint + " did not include a jwks_uri");
jwksUri = wellKnownRequest.asJson(OIDCConfigurationRepresentation.class).getJwksUri();
if (jwksUri == null) {
throw new IOException("OIDC discovery document from " + wellKnownEndpoint + " did not include a jwks_uri");
}
}
Comment thread
chance-coleman marked this conversation as resolved.
Resolved

SimpleHttpRequest jwksRequest = simpleHttp.doGet(jwksUri).header(HttpHeaders.ACCEPT, "application/jwk-set+json");
Expand All @@ -6 909B 0,24 +55,4 @@ public PublicKeysWrapper loadKeys() throws Exception {
return JWKSUtils.getKeyWrappersForUse(jwks, JWK.Use.SIG);
}

private String getToken(String issuer) {
try {
File file = new File(SERVICE_ACCOUNT_TOKEN_PATH);
if (!file.exists()) {
return null;
}

String token = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
JsonWebToken jwt = new JWSInput(token).readJsonContent(JsonWebToken.class);
if (jwt.getIssuer().equals(issuer)) {
logger.trace("Including service account token in request");
return token;
} else {
logger.debug("Not including service account token due to issuer mismatch");
}
} catch (Exception e) {
logger.warn("Failed to read service account token file", e);
}
return null;
}
}
Loading
Loading
0