8000 Enforce attested_keys[0] for OID4VCI proof validation by Awambeng · Pull Request #53476 · 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.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,14 @@ public class CredentialScopeModel implements ClientScopeModel {
*/
public static final String VC_KEY_ATTESTATION_REQUIRED_USER_AUTH = "vc.key_attestations_required.user_authentication";

/**
* OPTIONAL. Position the proof signing key must occupy in the 'attested_keys' array of the key attestation,
* as required by ETSI TS 119 472-3 and Regulation (EU) 2026/1731. Only '0' is a valid value. If this
* attribute is absent, the proof key only has to be included in 'attested_keys' as required by OpenID4VCI
* Appendix D.
*/
public static final String VC_KEY_ATTESTATION_PROOF_KEY_INDEX = "vc.key_attestation.proof_key_index";

/**
* OPTIONAL. Flag that indicates whether cryptographic holder binding is REQUIRED for this credential configuration.
* If this flag is not set or set to false, the issuer metadata MUST omit the
Expand Down Expand Up @@ -438,6 +446,17 @@ public void setRequiredKeyAttestationUserAuthentication(List<String> userAuthent
.map(list -> String.join(",", list)).orElse(null));
}

public Integer getProofKeyIndex() {
return Optional.ofNullable(clientScope.getAttribute(VC_KEY_ATTESTATION_PROOF_KEY_INDEX))
.map(Integer::parseInt)
.orElse(null);
}

public void setProofKeyIndex(Integer proofKeyIndex) {
clientScope.setAttribute(VC_KEY_ATTESTATION_PROOF_KEY_INDEX, Optional.ofNullable(proofKeyIndex)
.map(String::valueOf).orElse(null));
}

@Override
public String getId() {
return clientScope.getId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ public void validateClientScope(KeycloakSession session, ClientScopeRepresentati
validateOID4VCIRefreshInterval(clientScope);
validateCredentialConfigurationId(session, clientScope);
validateBindingConfiguration(session, clientScope);
validateProofKeyIndex(clientScope);
}

@Override
Expand Down Expand Up @@ -508,6 +509,44 @@ private void validateBindingConfiguration(KeycloakSession session, ClientScopeRe
}
}

/**
* Validates the optional proof key index, which requires the proof signing key to occupy a specific position
* in the 'attested_keys' array of the key attestation. Only '0' is supported, as required by ETSI TS 119 472-3
* and Regulation (EU) 2026/1731. The value must be rejected before it is persisted: an unsupported value would
* otherwise be detected only when the issuer metadata is built, which breaks credential discovery for the
* whole realm.
*
* @param clientScope the client scope representation to validate
* @throws ErrorResponseException if the value is not an integer or not '0'
*/
private void validateProofKeyIndex(ClientScopeRepresentation clientScope) {
if (clientScope.getAttributes() == null) {
return;
}

String proofKeyIndex = clientScope.getAttributes().get(CredentialScopeModel.VC_KEY_ATTESTATION_PROOF_KEY_INDEX);
if (proofKeyIndex == null || proofKeyIndex.trim().isEmpty()) {
// Empty values are removed on persist, so they leave the option unset.
return;
}

final int index;
try {
index = Integer.parseInt(proofKeyIndex);
} catch (NumberFormatException ex) {
throw ErrorResponse.error(String.format(
"%s must be an integer value, but was '%s'",
CredentialScopeModel.VC_KEY_ATTESTATION_PROOF_KEY_INDEX, proofKeyIndex),
Response.Status.BAD_REQUEST);
}
if (index != 0) {
throw ErrorResponse.error(String.format(
"%s must be 0 (the proof key must be attested_keys[0] per ETSI TS 119 472-3), but was %d",
CredentialScopeModel.VC_KEY_ATTESTATION_PROOF_KEY_INDEX, index),
Response.Status.BAD_REQUEST);
}
}

private static List<String> parseCommaSeparated(String value) {
if (StringUtil.isBlank(value)) {
return List.of();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,14 +184,9 @@ private JWK validateSingleJwtProof(VCIssuanceContext vcIssuanceContext, String j
throw new VCIssuerException(ErrorType.INVALID_PROOF, "Missing binding key. JWT must contain either jwk, kid, or x5c in header.");
}

// If a key attestation is present, proof key must be one of attested_keys.
if (attestationInfo.isPresent()) {
boolean attested = attestationInfo.attestedKeys().stream()
.anyMatch(attestedKey -> jwkMaterialEquals(attestedKey, jwk));
if (!attested) {
throw new VCIssuerException(ErrorType.INVALID_PROOF,
"JWT proof key is not included in attested_keys");
}
validateProofKeyAttestation(attestationInfo.attestedKeys(), jwk,
vcIssuanceContext.getCredentialConfig().getRequiredProofKeyIndex());
}

// Rest of the validation
Expand Down Expand Up @@ -367,6 +362,36 @@ boolean isPresent() {
}
}

/**
* The proof key must be included in attested_keys (OpenID4VCI Appendix D). When a required index is
* configured, the key has to occupy exactly that position, as mandated by ETSI TS 119 472-3 and
* Regulation (EU) 2026/1731 (TR_KA-6).
*/
void validateProofKeyAttestation(List<JWK> attestedKeys, JWK proofKey, Integer requiredIndex) {
int foundIndex = indexOfAttestedKey(attestedKeys, proofKey);
if (requiredIndex == null) {
if (foundIndex < 0) {
throw new VCIssuerException(ErrorType.INVALID_PROOF,
"JWT proof key is not included in attested_keys");
}
return;
}
if (foundIndex != requiredIndex) {
throw new VCIssuerException(ErrorType.INVALID_PROOF, foundIndex < 0
? "JWT proof key is not attested_keys[" + requiredIndex + "]"
: "JWT proof key is not attested_keys[" + requiredIndex + "], it is at index " + foundIndex);
}
}

private int indexOfAttestedKey(List<JWK> attestedKeys, JWK proofKey) {
for (int i = 0; i < attestedKeys.size(); i++) {
if (jwkMaterialEquals(attestedKeys.get(i), proofKey)) {
return i;
}
}
return -1;
}

/**
* Compare key material instead of object identity so we can correctly match keys even when kid is absent.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_FORMAT_DEFAULT;
import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_IDENTIFIER;
import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_ISSUER_DID;
import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_KEY_ATTESTATION_PROOF_KEY_INDEX;
import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_KEY_ATTESTATION_REQUIRED;
import static 8BD0 org.keycloak.models.oid4vci.CredentialScopeModel.VC_KEY_ATTESTATION_REQUIRED_KEY_STORAGE;
import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_KEY_ATTESTATION_REQUIRED_USER_AUTH;
Expand Down Expand Up @@ -330,6 +331,17 @@ public CredentialScopeRepresentation setRequiredKeyAttestationUserAuthentication
.map(list -> String.join(",", list)).orElse(null));
}

public Integer getProofKeyIndex() {
return Optional.ofNullable(getAttribute(VC_KEY_ATTESTATION_PROOF_KEY_INDEX))
.map(Integer::parseInt)
.orElse(null);
}

public CredentialScopeRepresentation setProofKeyIndex(Integer proofKeyIndex) {
return setAttribute(VC_KEY_ATTESTATION_PROOF_KEY_INDEX, Optional.ofNullable(proofKeyIndex)
.map(String::valueOf).orElse(null));
}

public <T> T getCredentialPolicyValue(CredentialClientPolicy<T> policy) {
T currentValue = policy.getCurrentValue(this);
return currentValue;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ public class SupportedCredentialConfiguration {
@JsonIgnore
private CredentialBuildConfig credentialBuildConfig;

// This is not a normative field for supported credential metadata,
// but enforces the position the proof signing key must occupy in attested_keys.
@JsonIgnore
private Integer requiredProofKeyIndex;

/**
* @param credentialScope The scope that holds the credentials configuration
* @param globalSupportedSigningAlgorithms added as a parameter to avoid reading the global config from the session
Expand All @@ -123,6 +128,12 @@ public static SupportedCredentialConfiguration parse(KeycloakSession keycloakSes
credentialConfiguration.setFormat(format);

KeyAttestationsRequired keyAttestationsRequired = KeyAttestationsRequired.parse(credentialScope);
Integer proofKeyIndex = credentialScope.getProofKeyIndex();
if (proofKeyIndex != null && proofKeyIndex != 0) {
throw new IllegalStateException(CredentialScopeModel.VC_KEY_ATTESTATION_PROOF_KEY_INDEX
+ " must be 0 but was " + proofKeyIndex + " in client scope: " + credentialScope.getName());
Comment thread
Awambeng marked this conversation as resolved.
Resolved
}
credentialConfiguration.setRequiredProofKeyIndex(proofKeyIndex);
boolean bindingRequired = credentialScope.isBindingRequired();
List<String> requiredProofTypes = credentialScope.getRequiredProofTypes();
List<String> configuredBindingMethods = credentialScope.getCryptographicBindingMethods();
Expand Down Expand Up @@ -352,16 +363,25 @@ public SupportedCredentialConfiguration setCredentialBuildConfig(CredentialBuild
return this;
}

public Integer getRequiredProofKeyIndex() {
return requiredProofKeyIndex;
}

public SupportedCredentialConfiguration setRequiredProofKeyIndex(Integer requiredProofKeyIndex) {
this.requiredProofKeyIndex = requiredProofKeyIndex;
return this;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SupportedCredentialConfiguration that = (SupportedCredentialConfiguration) o;
return Objects.equals(id, that.id) && Objects.equals(format, that.format) && Objects.equals(scope, that.scope) && Objects.equals(cryptographicBindingMethodsSupported, that.cryptographicBindingMethodsSupported) && Objects.equals(credentialSigningAlgValuesSupported, that.credentialSigningAlgValuesSupported) && Objects.equals(vct, that.vct) && Objects.equals(docType, that.docType) && Objects.equals(credentialDefinition, that.credentialDefinition) && Objects.equals(proofTypesSupported, that.proofTypesSupported) && Objects.equals(credentialMetadata, that.credentialMetadata) && Objects.equals(credentialBuildConfig, that.credentialBuildConfig);
return Objects.equals(id, that.id) && Objects.equals(format, that.format) && Objects.equals(scope, that.scope) && Objects.equals(cryptographicBindingMethodsSupported, that.cryptographicBindingMethodsSupported) && Objects.equals(credentialSigningAlgValuesSupported, that.credentialSigningAlgValuesSupported) && Objects.equals(vct, that.vct) && Objects.equals(docType, that.docType) && Objects.equals(credentialDefinition, that.credentialDefinition) && Objects.equals(proofTypesSupported, that.proofTypesSupported) && Objects.equals(credentialMetadata, that.credentialMetadata) && Objects.equals(credentialBuildConfig, that.credentialBuildConfig) && Objects.equals(requiredProofKeyIndex, that.requiredProofKeyIndex);
}

@Override
public int hashCode() {
return Objects.hash(id, format, scope, cryptographicBindingMethodsSupported, credentialSigningAlgValuesSupported, vct, docType, credentialDefinition, proofTypesSupported, credentialMetadata, credentialBuildConfig);
return Objects.hash(id, format, scope, cryptographicBindingMethodsSupported, credentialSigningAlgValuesSupported, vct, docType, credentialDefinition, proofTypesSupported, credentialMetadata, credentialBuildConfig, requiredProofKeyIndex);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
package org.keycloak.protocol.oid4vc.issuance.keybinding;

import java.security.GeneralSecurityException;
import java.security.KeyPairGenerator;
import java.security.spec.ECGenParameterSpec;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.keycloak.jose.jwk.JWK;
import org.keycloak.jose.jwk.JWKBuilder;
import org.keycloak.jose.jwk. 10BC8 JWKParser;
import org.keycloak.protocol.oid4vc.issuance.VCIssuerException;
import org.keycloak.protocol.oid4vc.model.ErrorType;
import org.keycloak.utils.AbstractUtilSessionTest;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class JwtProofValidatorTest extends AbstractUtilSessionTest {
Expand Down Expand Up @@ -81,4 +90,66 @@ private void assertAllowed(String alg, Map<String, Object> jwk) {

assertDoesNotThrow(() -> validator.validateNoPrivateKeyInHeaderClaims(alg, headerClaims));
}

@Test
public void testProofKeyAcceptedAtAnyPositionWhenNoIndexRequired() {
JWK firstKey = newEcJwk();
JWK secondKey = newEcJwk();

assertDoesNotThrow(() -> new JwtProofValidator(session, null)
.validateProofKeyAttestation(List.of(firstKey, secondKey), copyOf(secondKey), null));
}

@Test
public void testProofKeyOutsideAttestationRejectedWhenNoIndexRequired() {
VCIssuerException exception = assertThrows(VCIssuerException.class, () -> new JwtProofValidator(session, null)
.validateProofKeyAttestation(List.of(newEcJwk()), copyOf(newEcJwk()), null));

assertEquals(ErrorType.INVALID_PROOF, exception.getErrorType());
assertEquals("JWT proof key is not included in attested_keys", exception.getMessage());
}

@Test
public void testProofKeyAcceptedAtFirstPositionWhenIndexZeroRequired() {
JWK firstKey = newEcJwk();
JWK secondKey = newEcJwk();

assertDoesNotThrow(() -> new JwtProofValidator(session, null)
.validateProofKeyAttestation(List.of(firstKey, secondKey), copyOf(firstKey), 0));
}

@Test
public void testProofKeyAtLaterPositionRejectedWhenIndexZeroRequired() {
JWK firstKey = newEcJwk();
JWK secondKey = newEcJwk();

VCIssuerException exception = assertThrows(VCIssuerException.class, () -> new JwtProofValidator(session, null)
.validateProofKeyAttestation(List.of(firstKey, secondKey), copyOf(secondKey), 0));

assertEquals(ErrorType.INVALID_PROOF, exception.getErrorType());
assertEquals("JWT proof key is not attested_keys[0], it is at index 1", exception.getMessage());
}

@Test
public void testProofKeyOutsideAttestationRejectedWhenIndexZeroRequired() {
VCIssuerException exception = assertThrows(VCIssuerException.class, () -> new JwtProofValidator(session, null)
.validateProofKeyAttestation(List.of(newEcJwk()), copyOf(newEcJwk()), 0));

assertEquals(ErrorType.INVALID_PROOF, exception.getErrorType());
assertEquals("JWT proof key is not attested_keys[0]", exception.getMessage());
}

private static JWK newEcJwk() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
generator.initialize(new ECGenParameterSpec("secp256r1"));
return JWKBuilder.create().ec(generator.generateKeyPair().getPublic());
} catch (GeneralSecurityException e) {
throw new IllegalStateException(e);
}
}

private static JWK copyOf(JWK jwk) {
return JWKBuilder.create().ec(JWKParser.create(jwk).toPublicKey());
}
}
Loading
Loading
0