8000 [OID4VCI] Explicit client association for pre-authorized offers by tdiesler · Pull Request #50897 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Closed
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 @@ -330,7 +330,7 @@ private void checkClientEnabled(EventBuilder eventBuilder) {
}

/**
* the OpenId4VCI nonce-endpoint
* The OID4VCI nonce endpoint
*
* @return a short-lived c_nonce value that must be presented in key-bound proofs at the credential endpoint.
* @see <a href="https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0-16.html#name-nonce-endpoint">Nonce endpoint</a>
Expand Down Expand Up @@ -391,37 +391,42 @@ public Response createCredentialOfferPreflight() {
* Creates an authorization code grant offer that is bound to the calling user.
*/
public Response createCredentialOffer(String credConfigId) {
return createCredentialOffer(credConfigId, false, null);
return createCredentialOffer(credConfigId, false, null, null, null, OfferResponseType.URI, 0, 0);
}

/**
* Creates a Credential Offer that is bound to a specific user.
*/
public Response createCredentialOffer(String credConfigId, boolean preAuthorized, String targetUser) {
return createCredentialOffer(credConfigId, preAuthorized, targetUser, null, OfferResponseType.URI, 0, 0);
return createCredentialOffer(credConfigId, preAuthorized, targetUser, null, null, OfferResponseType.URI, 0, 0);
}

/**
* Creates a Credential Offer that can be pre-authorized and/or bound to a specific target user.
* Creates a Credential Offer that can be pre-authorized and/or bound to a specific target user and client.
* <p>
* Credential Offer Validity Matrix for the supported request parameters "pre_authorized", "targetUser" combinations.
* Credential Offer Validity Matrix for the supported request parameters.
* </p>
* +----------+----------+---------+--------------------------------------------+
* | Pre-Auth | Username | Valid | Notes |
* +----------+----------+---------+--------------------------------------------+
* | no | no | yes | Anonymous offer; works for any login user. |
* | no | yes | yes | Offer restricted to a specific user. |
* +----------+----------+---------+--------------------------------------------+
* | yes | no | yes | Self issued pre-auth offer. |
* | yes | yes | yes | Offer restricted to a specific user. |
* +----------+----------+---------+--------------------------------------------+
* +----------+----------+-----------------+---------+------------------------------------------------------+
* | Pre-Auth | Username | Client | Valid | Notes |
* +----------+----------+-----------------+---------+------------------------------------------------------+
* | no | no | no | yes | Anonymous offer; any logged-in user may redeem. |
* | no | no | explicit | yes | Anonymous offer; bound to a specific client. |
* | no | yes | no | yes | Offer restricted to a specific user. |
* | no | yes | explicit | yes | Offer restricted to a specific user and client. |
* +----------+----------+-----------------+---------+------------------------------------------------------+
* | yes | no | explicit/unique | yes | Defaults to the user from the current login session |
* | yes | yes | explicit | yes | Pre-auth for a specific target user and client. |
* | yes | yes | omitted unique | yes | Discovered from credential_configuration_id. |
* | yes | yes | omitted none | no | Discovery fails: no OID4VCI client has that scope. |
* | yes | yes | omitted multi | no | Discovery fails: multiple clients match. |
* +----------+----------+-----------------+---------+------------------------------------------------------+
* </p>
* <b>Pre-Authorized Code Grant Offer</b>
* <ul>
* <li>A pre-authorized offer is authorized for the clientId from the current login session</li>
* <li>If targetUser is null or empty, it defaults to the user from the current login session</li>
* <li>If targetUser is equal to the current login, the generated offer is "self issued"</li>
* <li>To create an offer for another user, the issuing user must hold the {@code credential_offer_create} role</li>
* <li>A targetClient can explicitly be given or be discovered; it selects the keycloak issuance client</li>
* <li>A pre-authorized offer can optionally have an associated tx_code</li>
* <li>An offer can optionally have a predefined expiry date</li>
* </ul>
Expand All @@ -430,8 +435,8 @@ public Response createCredentialOffer(String credConfigId, boolean preAuthorized
* <ul>
* <li>If targetUser is null or empty, the generated offer is "anonymous"</li>
* <li>If targetUser is equal to the current login, the offer is "self issued"</li>
* <li>If targetUser is none of the above, the offer is "targeted"</li>
* <li>For a targeted offer, the issuing user must hold the {@code credential_offer_create} role</li>
* <li>To create an offer for another user, the issuing user must hold the {@code credential_offer_create} role</li>
* <li>A targetClient may be given; it selects the keycloak issuance client</li>
* <li>An offer can optionally have a predefined expiry date</li>
* </ul>
*
Expand All @@ -455,6 +460,7 @@ public Response createCredentialOffer(String credConfigId, boolean preAuthorized
* @param credentialConfigurationId A valid credential configuration id
* @param preAuthorized A flag whether the offer should be pre-authorized
* @param targetUser The username that the offer is authorized for
* @param targetClient The client_id that selects the keycloak issuance client (optional; discovered if omitted for pre-authorized offers)
* @param expiresAt The date/time when the offer expires (in Unix timestamp seconds)
* @param responseType The response type, which can be 'uri', 'qr' or 'uri+qr'
* @param width The width of the QR code image
Expand All @@ -467,6 +473,7 @@ public Response createCredentialOffer(
@QueryParam("credential_configuration_id") String credentialConfigurationId,
@QueryParam("pre_authorized") @DefaultValue("false") Boolean preAuthorized,
@QueryParam("target_user") String targetUser,
@QueryParam("target_client") String targetClient,
@QueryParam("expire") Long expiresAt,
@QueryParam("type") @DefaultValue("uri") OfferResponseType responseType,
@QueryParam("width") @DefaultValue("200") int width,
Expand Down Expand Up @@ -539,17 +546,13 @@ public Response createCredentialOffer(
String grantType = preAuthorized ? PRE_AUTH_GRANT_TYPE : AUTH_CODE_GRANT_TYPE;
List<String> credentialConfigurationIds = List.of(credentialConfigurationId);

// Bind pre-authorized code offers to the authenticated client to prevent redemption from a different client_id.
// Authorization Code Grant offers are intentionally not bound to a client_id.
// https://github.com/keycloak/keycloak/issues/48188
String targetClientId = preAuthorized ? clientModel.getClientId() : null;

CredentialOfferState offerState;
try {

CredentialOfferProvider offerProvider = session.getProvider(CredentialOfferProvider.class);
offerState = offerProvider.createCredentialOffer(loginUserModel, grantType,
credentialConfigurationIds, targetClientId, targetUser, expiresAt);
credentialConfigurationIds, targetClient, targetUser, expiresAt);

if (preAuthorized) {
offerState.setOriginatingUserId(loginUserModel.getId());
// Bearer authentication reconstructs request-scoped sessions for stateless tokens. Bind the offer to
Expand Down Expand Up @@ -587,8 +590,9 @@ public Response createCredentialOffer(
offerStorage.putOfferState(offerState);

String targetUserId = offerState.getTargetUserId();
String targetClientId = offerState.getTargetClientId();
LOGGER.debugf("Stored credential offer state: [grant=%s, ids=%s, cid=%s, uid=%s, nonce=%s]",
grantType, credentialConfigurationIds, offerState.getTargetClientId(), targetUserId, offerState.getNonce());
grantType, credentialConfigurationIds, targetClientId, targetUserId, offerState.getNonce());

// Add event details
eventBuilder.detail(Details.VERIFIABLE_CREDENTIAL_PRE_AUTHORIZED, String.valueOf(preAuthorized))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ CredentialOfferState createCredentialOffer(
String grantType,
List<String> credentialConfigurationIds,
String targetClientId,
String targetUserId,
String targetUsername,
Integer expireAt
);

Expand All @@ -97,15 +97,15 @@ default CredentialOfferState createCredentialOffer(
String grantType,
List<String> credentialConfigurationIds,
String targetClientId,
String targetUserId,
String targetUsername,
long expireAt
) {
if (expireAt < Integer.MIN_VALUE || expireAt > Integer.MAX_VALUE) {
throw new CredentialOfferException(Errors.INVALID_REQUEST,
"Credential offer expiration is outside the integer range supported by this provider: " + expireAt);
}
return createCredentialOffer(user, grantType, credentialConfigurationIds, targetClientId, ta 8 rgetUser 10BC8 Id,
Integer.valueOf((int) expireAt));
return createCredentialOffer(user, grantType, credentialConfigurationIds,
targetClientId, targetUsername, Integer.valueOf((int) expireAt));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@
package org.keycloak.protocol.oid4vc.issuance.credentialoffer;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import org.keycloak.common.Profile;
import org.keycloak.events.Errors;
Expand Down Expand Up @@ -67,8 +70,8 @@ public CredentialOfferState createCredentialOffer(
String targetClientId,
String targetUsername,
Integer expireAt) {
return createCredentialOffer(user, grantType, credentialConfigurationIds, targetClientId, targetUsername,
expireAt.longValue());
return createCredentialOffer(user, grantType, credentialConfigurationIds,
targetClientId, targetUsername, expireAt.longValue());
}

@Override
Expand Down Expand Up @@ -96,16 +99,30 @@ public CredentialOfferState createCredentialOffer(

RealmModel realmModel = this.session.getContext().getRealm();

Map<String, CredentialScopeModel> credScopeModels = new LinkedHashMap<>();
for (String cid : credentialConfigurationIds) {
CredentialScopeModel credScopeModel = Optional.ofNullable(findCredentialScopeModelByConfigurationId(
realmModel, () -> session.clientScopes().getClientScopesStream(realmModel), cid))
.orElseThrow(() -> new CredentialOfferException(Errors.INVALID_REQUEST, "No credential scope model for: " + cid));
credScopeModels.put(cid, credScopeModel);
}

// Validate the target user
//
UserModel targetUser = Optional.ofNullable(targetUsername)
.map(tu -> validateTargetUser(session, realmModel, user, tu))
.orElse(null);
String targetUserId = targetUser == null ? null : targetUser.getId();
String targetUserId = targetUser != null ? targetUser.getId() : null;

// Discovery: find the unique OID4VCI-enabled client that has this scope assigned
if (preAuthorized && targetClientId == null) {
targetClientId = discoverTargetClient(realmModel, credScopeModels);
}
Comment thread
tdiesler marked this conversation as resolved.
Resolved

// Validate the target client
if (targetClientId != null) {
validateTargetClient(realmModel, targetClientId);
List<String> credScopeNames = credScopeModels.values().stream().map(CredentialScopeModel::getName).toList();
validateTargetClient(realmModel, targetClientId, credScopeNames);
}

// Create the CredentialsOffer
Expand All @@ -118,16 +135,11 @@ public CredentialOfferState createCredentialOffer(
//
CredentialOfferState offerState = new CredentialOfferState(credOffer, targetClientId, targetUserId, expireAt, credOffersId -> {
List<OID4VCAuthorizationDetail> authDetails = new ArrayList<>();
for (String credConfigId : credentialConfigurationIds) {
CredentialScopeModel credScope = findCredentialScopeModelByConfigurationId(
realmModel, () -> session.clientScopes().getClientScopesStream(realmModel), credConfigId);
if (credScope == null) {
throw new CredentialOfferException(Errors.INVALID_REQUEST, "No credential scope model for: " + credConfigId);
}
for (CredentialScopeModel credScope : credScopeModels.values()) {
String credConfigId = credScope.getCredentialConfigurationId();
if (targetUser != null && !OID4VCUtil.hasVerifiableCredential(session, targetUser, credScope)) {
throw new CredentialOfferException(Errors.INVALID_REQUEST, "User '" + targetUser.getUsername() + "' does not have verifiable credential '" + credConfigId + "'.");
}

OID4VCAuthorizationDetailsProcessor authDetailsProcessor = new OID4VCAuthorizationDetailsProcessor(session);
authDetails.add(authDetailsProcessor.generateResponseAuthorizationDetails(credScope, credOffersId));
}
Expand Down Expand Up @@ -175,18 +187,51 @@ private UserModel validateTargetUser(KeycloakSession session, RealmModel realmMo
return targetUserModel;
}

private void validateTargetClient(RealmModel realm, String clientId) {
ClientModel client = session.clients().getClientByClientId(realm, clientId);
if (client == null) {
/**
* Discovers the unique OID4VCI-enabled client that has the given credential scope.
* Fails fast if zero or more than one client match.
*/
private String discoverTargetClient(RealmModel realm, Map<String, CredentialScopeModel> credScopeModels) {

Set<String> credConfigIds = credScopeModels.keySet();
List<String> credScopeNames = credScopeModels.values().stream().map(CredentialScopeModel::getName).toList();

List<ClientModel> matches = session.clients().getClientsStream(realm)
.filter(ClientModel::isEnabled)
.filter(c -> Boolean.parseBoolean(c.getAttribute(OID4VCI_ENABLED_ATTRIBUTE_KEY)))
.filter(c -> c.getClientScopes(false).keySet().containsAll(credScopeNames))
.limit(2)
.toList();

if (matches.isEmpty()) {
throw new CredentialOfferException(Errors.INVALID_REQUEST,
"No OID4VCI client found for credential configuration ids: " + credConfigIds);
}
if (matches.size() > 1) {
throw new CredentialOfferException(Errors.INVALID_REQUEST,
"Multiple OID4VCI clients for credential configuration ids: " + credConfigIds);
}
return matches.get(0).getClientId();
}

private void validateTargetClient(RealmModel realm, String clientId, List<String> credentialScopeNames) {
ClientModel clientModel = session.clients().getClientByClientId(realm, clientId);
if (clientModel == null) {
throw new CredentialOfferException(Errors.CLIENT_NOT_FOUND, "Client '" + clientId + "' not found");
}
if (!client.isEnabled()) {
if (!clientModel.isEnabled()) {
throw new CredentialOfferException(Errors.CLIENT_DISABLED, "Client '" + clientId + "' disabled");
}
boolean oid4vciEnabled = Boolean.parseBoolean(client.getAttributes().get(OID4VCI_ENABLED_ATTRIBUTE_KEY));
boolean oid4vciEnabled = Boolean.parseBoolean(clientModel.getAttribute(OID4VCI_ENABLED_ATTRIBUTE_KEY));
if (!oid4vciEnabled) {
throw new CredentialOfferException(Errors.INVALID_CLIENT, "Client '" + clientId + "' is not enabled for OID4VCI features.");
}
Set<String> optionalScopes = clientModel.getClientScopes(false).keySet();
for (String scope : credentialScopeNames) {
if (!optionalScopes.contains(scope)) {
throw new CredentialOfferException(Errors.INVALID_CLIENT, "Client '" + clientId + "' does not support '" + scope + "'");
}
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,14 +170,14 @@ private CredentialOfferState createCredentialsOffer(KeycloakSession session, Rea
String credentialConfigurationId = actionConfig.getCredentialConfigurationId();
event = event.clone().detail(Details.CREDENTIAL_TYPE, credentialConfigurationId);

String clientId = actionConfig.getClientId();
CredentialOfferProvider offerProvider = session.getProvider(CredentialOfferProvider.class);
CredentialOfferState offerState = offerProvider.createCredentialOffer(user, grantType,
List.of(credentialConfigurationId), clientId, user.getUsername(), expiresAt);
List.of(credentialConfigurationId), actionConfig.getClientId(), user.getUsername(), expiresAt);

CredentialOfferStorage offerStorage = session.getProvider(CredentialOfferStorage.class);
offerStorage.putOfferState(offerState);

String clientId = offerState.getTargetClientId();
logger.debugf("Stored credential offer state: [credentialConfigId=%s, clientId=%s, username=%s, nonce=%s]",
credentialConfigurationId, clientId, user.getUsername(), offerState.getNonce());

Expand Down
Loading
Loading
0