8000 [OID4VCI]: bind all attested keys and read kid as index in JWT proofs by Awambeng · Pull Request #54638 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,12 @@
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import jakarta.ws.rs.BadRequestException;
Expand Down Expand Up @@ -128,6 +130,7 @@
import org.keycloak.services.managers.AppAuthManager;
import org.keycloak.services.managers.AuthenticationManager;
import org.keycloak.services.util.DPoPUtil;
import org.keycloak.util.JWKSUtils;
import org.keycloak.util.JsonSerialization;
import org.keycloak.util.Strings;
import org.keycloak.utils.MediaType;
Expand Down Expand Up @@ -1027,44 +1030,52 @@ public Response requestCredential(String requestPayload) {
throw new BadRequestException(getErrorResponse(ErrorType.INVALID_PROOF, "Proof values must not be null or blank"));
}

int maxBatchSize = Optional.ofNullable(issuerMetadata.getBatchCredentialIssuance())
.map(BatchCredentialIssuance::getBatchSize)
.orElse(BATCH_CREDENTIAL_ISSUANCE_DEFAULT_MAX_BATCH_SIZE);

// Prepare credential bodies and validate key binding proofs before consuming the nonce.
List<VCIssuanceContext> vcIssuanceContexts = new ArrayList<>();
Set<String> boundKeyThumbprints = new HashSet<>();

if (allProofs.isEmpty()) {
// Single issuance without proof
VCIssuanceContext vcIssuanceContext = prepareCredential(authResult, supportedCredential, tokenAuthDetail, credentialRequest, eventBuilder);
vcIssuanceContexts.add(vcIssuanceContext);
verifiedProofCNonces.putAll(vcIssuanceContext.getVerifiedCNonces());
vcIssuanceContexts.addAll(prepareCredentials(authResult, supportedCredential, tokenAuthDetail,
credentialRequest, eventBuilder, boundKeyThumbprints, verifiedProofCNonces));
} else {
// Issue credentials for each proof
Proofs originalProofs = credentialRequest.getProofs();
// Determine the proof type from the original proofs
String proofType = originalProofs.getProofType();

if (allProofs.size() > 1) {
Integer maxBatchSize = Optional.ofNullable(issuerMetadata.getBatchCredentialIssuance())
.map(BatchCredentialIssuance::getBatchSize)
.orElse(BATCH_CREDENTIAL_ISSUANCE_DEFAULT_MAX_BATCH_SIZE);
if (allProofs.size() > maxBatchSize) {
LOGGER.warnf("Reducing credential batch size to: %d", maxBatchSize);
allProofs = allProofs.subList(0, maxBatchSize);
}
if (allProofs.size() > maxBatchSize) {
LOGGER.warnf("Reducing credential batch size to: %d", maxBatchSize);
allProofs = allProofs.subList(0, maxBatchSize);
}

try {
for (String currentProof : allProofs) {
Proofs proofForIteration = Proofs.create(proofType, currentProof);
// Creating credential with keybinding to the current proof
// Creating credentials with keybinding to the current proof
credentialRequest.setProofs(proofForIteration);
VCIssuanceContext vcIssuanceContext = prepareCredential(authResult, supportedCredential, tokenAuthDetail, credentialRequest, eventBuilder);
vcIssuanceContexts.add(vcIssuanceContext);
verifiedProofCNonces.putAll(vcIssuanceContext.getVerifiedCNonces());
vcIssuanceContexts.addAll(prepareCredentials(authResult, supportedCredential, tokenAuthDetail,
credentialRequest, eventBuilder, boundKeyThumbprints, verifiedProofCNonces));
}
} finally {
credentialRequest.setProofs(originalProofs);
}
}

// A proof can bind several attested keys, so the limit applies to credentials, not proofs.
if (vcIssuanceContexts.size() > maxBatchSize) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up · No test covers the new credential cap when attested keys exceed batch_size.

Impact:

A WUA with more keys than the realm batch_size relies on this cap, and a regression would issue more credentials than the operator allowed without any test failing.

testCompleteSdJwtIssuanceWithMultipleAttestedKeys uses two keys with the default limit of 2, and the deduplication test uses a limit of 10, so the truncation at line 1070 and the nonce collection after it never run with a cut.

Suggested fix:

Add an end to end test with three attested keys and batch_size 2 that asserts two credentials bound to attested_keys[0] and attested_keys[1] and that the nonce is consumed.

Awambeng asked the tracker's bot account to post this.

Automatic review by Claude Opus 5.5, checked by Claude Fable 5.2: https://oid4vc-sig.eudi-test.dev/reviews/54638.html#c-5faacb5b810f41fd-0

LOGGER.warnf("Reducing credential batch size to: %d", maxBatchSize);
vcIssuanceContexts = new ArrayList<>(vcIssuanceContexts.subList(0, maxBatchSize));
}

for (VCIssuanceContext vcIssuanceContext : vcIssuanceContexts) {
verifiedProofCNonces.putAll(vcIssuanceContext.getVerifiedCNonces());
}

// Fail-fast if any cnonce already consumed without consuming it
rejectConsumedProofCNonce(verifiedProofCNonces);

Expand Down Expand Up @@ -1709,20 +1720,69 @@ private AuthenticationManager.AuthResult getAuthResult(EventBuilder event) {
}

/**
* Prepare an unsigned credential and validate any key binding proof before signing.
* Prepare one unsigned credential per validated binding key, skipping keys already bound in the request.
*/
private VCIssuanceContext prepareCredential(AuthenticationManager.AuthResult authResult,
SupportedCredentialConfiguration credentialConfig,
OID4VCAuthorizationDetail authDetail,
CredentialRequest credentialRequestVO,
EventBuilder eventBuilder
private List<VCIssuanceContext> prepareCredentials(AuthenticationManager.AuthResult authResult,
SupportedCredentialConfiguration credentialConfig,
OID4VCAuthorizationDetail authDetail,
CredentialRequest credentialRequestVO,
EventBuilder eventBuilder,
Set<String> boundKeyThumbprints,
Map<String, JsonWebToken> verifiedProofCNonces
) {

// Get the client scope model from the credential configuration
CredentialScopeModel credentialScopeModel = getClientScopeModel(credentialConfig);

// Get the protocol mappers from the client scope
List<OID4VCMapper> protocolMappers = credentialScopeModel.getProtocolMappersStream()
VCIssuanceContext firstContext = getVCToSign(getProtocolMappers(credentialScopeModel), credentialConfig,
authResult, authDetail, credentialRequestVO, credentialScopeModel, eventBuilder);

// Enforce key binding prior to signing if necessary
List<JWK> keys = enforceKeyBindingIfProofProvided(firstContext, eventBuilder);
if (keys.isEmpty()) {
return List.of(firstContext);
}

List<JWK> unboundKeys = getUnboundKeys(keys, boundKeyThumbprints);
if (unboundKeys.isEmpty()) {
verifiedProofCNonces.putAll(firstContext.getVerifiedCNonces());
return List.of();
}

List<VCIssuanceContext> contexts = new ArrayList<>(unboundKeys.size());
contexts.add(firstContext);
bindKey(firstContext, unboundKeys.get(0), eventBuilder);
for (int i = 1; i < unboundKeys.size(); i++) {
VCIssuanceContext context = getVCToSign(getProtocolMappers(credentialScopeModel), credentialConfig,
authResult, authDetail, credentialRequestVO, credentialScopeModel, eventBuilder);
bindKey(context, unboundKeys.get(i), eventBuilder);
contexts.add(context);
}
return contexts;
}

private static List<JWK> getUnboundKeys(List<JWK> keys, Set<String> boundKeyThumbprints) {
List<JWK> unboundKeys = new ArrayList<>(keys.size());
for (JWK key : keys) {
String thumbprint = getKeyThumbprint(key);
if (thumbprint == null || boundKeyThumbprints.add(thumbprint)) {
unboundKeys.add(key);
}
}
return unboundKeys;
}

private static String getKeyThumbprint(JWK key) {
try {
return JWKSUtils.computeThumbprint(key);
} catch (RuntimeException e) {
LOGGER.debugf(e, "Could not compute thumbprint for JWK of type %s", key.getKeyType());
return null;
}
}

private List<OID4VCMapper> getProtocolMappers(CredentialScopeModel credentialScopeModel) {
return credentialScopeModel.getProtocolMappersStream()
.map(pm -> {
if (session.getProvider(ProtocolMapper.class, pm.getProtocolMapper()) instanceof OID4VCMapper mapperFactory) {
ProtocolMapper protocolMapper = mapperFactory.create(session);
Expand All @@ -1737,13 +1797,23 @@ private VCIssuanceContext prepareCredential(AuthenticationManager.AuthResult aut
.filter(Objects::nonNull)
.filter(mapper -> mapper.supportsCredentialFormat(credentialScopeModel.getFormat()))
.toList();
}

VCIssuanceContext vcIssuanceContext = getVCToSign(protocolMappers, credentialConfig, authResult, authDetail, credentialRequestVO, credentialScopeModel, eventBuilder);
private void bindKey(VCIssuanceContext vcIssuanceContext, JWK jwk, EventBuilder eventBuilder) {
try {
vcIssuanceContext.getCredentialBody().addKeyBinding(jwk);
} catch (CredentialBuilderException e) {
eventBuilder.detail(Details.REASON, e.getMessage())
.error(INVALID_PROOF.getValue());

// Enforce key binding prior to signing if necessary
enforceKeyBindingIfProofProvided(vcIssuanceContext, eventBuilder);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}

return vcIssuanceContext;
// A proof key that cannot be bound to the credential, such as an mDoc COSE_Key conversion that rejects
// the key curve, is an invalid proof rather than a server error.
throw new ErrorResponseException(INVALID_PROOF.getValue(), e.getMessage(), Response.Status.BAD_REQUEST);
}
}

private Object signCredential(SupportedCredentialConfiguration credentialConfig,
Expand Down Expand Up @@ -1898,34 +1968,33 @@ private VCIssuanceContext getVCToSign(List<OID4VCMapper> protocolMappers, Suppor
}

/**
* Enforce key binding: Validate proof and bind associated key to credential in issuance context.
* Validate the provided proofs and return the keys to bind credentials to.
*/
private void enforceKeyBindingIfProofProvided(VCIssuanceContext vcIssuanceContext, EventBuilder eventBuilder) {
private List<JWK> enforceKeyBindingIfProofProvided(VCIssuanceContext vcIssuanceContext, EventBuilder eventBuilder) {
Proofs proofs = vcIssuanceContext.getCredentialRequest().getProofs();
if (proofs == null) {
LOGGER.debugf("No proofs provided, skipping key binding");
return;
return List.of();
}

// Validate each proof type that is present
List<JWK> keys = new ArrayList<>();
for (String proofType : proofs.getPresentProofTypes()) {
validateProofs(vcIssuanceContext, proofType, eventBuilder);
keys.addAll(validateProofs(vcIssuanceContext, proofType, eventBuilder));
}
return keys;
}

private void validateProofs(VCIssuanceContext vcIssuanceContext, String proofType, EventBuilder eventBuilder) {
private List<JWK> validateProofs(VCIssuanceContext vcIssuanceContext, String proofType, EventBuilder eventBuilder) {
ProofValidator proofValidator = session.getProvider(ProofValidator.class, proofType);
if (proofValidator == null) {
throw new BadRequestException(String.format("Unable to validate proofs of type %s", proofType));
}

// Validate proof and bind public keys to credential
// Validate proof and return the keys to bind
try {
List<JWK> jwks = proofValidator.validateProof(vcIssuanceContext);
if (jwks != null && !jwks.isEmpty()) {
// Bind the first JWK to the credential
vcIssuanceContext.getCredentialBody().addKeyBinding(jwks.get(0));
}
return jwks == null ? List.of() : jwks;
} catch (VCIssuerException e) {
eventBuilder.detail(Details.REASON, e.getMessage())
.error(e.getErrorType().getValue());
Expand All @@ -1942,17 +2011,6 @@ private void validateProofs(VCIssuanceContext vcIssuanceContext, String proofTyp
default:
throw new BadRequestException("Could not validate provided proof", e);
}
} catch (CredentialBuilderException e) {
eventBuilder.detail(Details.REASON, e.getMessage())
.error(INVALID_PROOF.getValue());

if (LOGGER.isTraceEnabled()) {
LOGGER.trace(e.getMessage(), e);
}

// A proof key that cannot be bound to the credential, such as an mDoc COSE_Key conversion that rejects
// the key curve, is an invalid proof rather than a server error.
throw new ErrorResponseException(INVALID_PROOF.getValue(), e.getMessage(), Response.Status.BAD_REQUEST);
}
}

Expand Down
Loading
Loading
0