From da0f5e87528b50ef5dbae2b88c3b3a218c4d63a4 Mon Sep 17 00:00:00 2001 From: Thomas Diesler Date: Mon, 2 Mar 2026 10:16:49 +0100 Subject: [PATCH] [OID4VCI] Migrate OID4VCCredentialOfferMatrixTest Signed-off-by: Thomas Diesler --- .../java/org/keycloak/OAuth2Constants.java | 3 + .../models/oid4vci/CredentialScopeModel.java | 2 +- .../oid4vc/issuance/OID4VCIssuerEndpoint.java | 9 +- .../credentialoffer/CredentialOfferState.java | 11 +- .../DefaultCredentialOfferStorage.java | 11 +- .../oid4vc/model/CredentialOfferGrant.java | 34 ++ .../CredentialOfferGrantsDeserializer.java | 41 ++ .../oid4vc/model/CredentialRequest.java | 22 - .../oid4vc/model/CredentialsOffer.java | 46 +- ...dCode.java => PreAuthorizedCodeGrant.java} | 36 +- .../oid4vc/model/PreAuthorizedGrant.java | 60 --- .../utils/CredentialScopeModelUtils.java | 67 +++ .../utils/OID4VCAuthorizationDetailUtils.java | 31 ++ .../protocol/oid4vc/utils/OID4VCUtil.java | 54 -- .../oidc/endpoints/TokenEndpoint.java | 5 +- .../grants/PreAuthorizedCodeGrantType.java | 22 +- .../PreAuthorizedCodeGrantTypeFactory.java | 7 +- .../realm/RealmConfigBuilder.java | 5 + .../tests/oid4vc/OID4VCBasicWallet.java | 383 ++++++++++++++ .../OID4VCCredentialOfferMatrixTest.java | 230 +++++++++ .../tests/oid4vc/OID4VCTestContext.java | 136 +++++ .../util/oauth/AccessTokenResponse.java | 3 +- .../testsuite/util/oauth/LoginUrlBuilder.java | 58 ++- .../oauth/oid4vc/CredentialOfferRequest.java | 4 +- .../oid4vc/CredentialOfferUriRequest.java | 2 +- .../util/oauth/oid4vc/OID4VCClient.java | 8 +- .../oauth/oid4vc/Oid4vcCredentialRequest.java | 8 +- .../oid4vc/PreAuthorizedCodeGrantRequest.java | 12 +- .../rest/TestingResourceProvider.java | 22 +- .../client/resources/TestingResource.java | 1 + .../OID4VCICredentialOfferMatrixTest.java | 478 ------------------ ...ID4VCAuthorizationDetailsFlowTestBase.java | 46 +- .../OID4VCCredentialOfferCorsTest.java | 5 +- .../signing/OID4VCIssuerEndpointTest.java | 54 +- .../signing/OID4VCJWTIssuerEndpointTest.java | 13 +- .../OID4VCSdJwtIssuingEndpointTest.java | 2 +- 36 files changed, 1179 insertions(+), 752 deletions(-) create mode 100644 services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrant.java create mode 100644 services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrantsDeserializer.java rename services/src/main/java/org/keycloak/protocol/oid4vc/model/{PreAuthorizedCode.java => PreAuthorizedCodeGrant.java} (57%) delete mode 100644 services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedGrant.java create mode 100644 services/src/main/java/org/keycloak/protocol/oid4vc/utils/CredentialScopeModelUtils.java create mode 100644 services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCAuthorizationDetailUtils.java delete mode 100644 services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCUtil.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCCredentialOfferMatrixTest.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java delete mode 100644 testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/OID4VCICredentialOfferMatrixTest.java diff --git a/core/src/main/java/org/keycloak/OAuth2Constants.java b/core/src/main/java/org/keycloak/OAuth2Constants.java index 39872d0ed33..92ddaedf8eb 100755 --- a/core/src/main/java/org/keycloak/OAuth2Constants.java +++ b/core/src/main/java/org/keycloak/OAuth2Constants.java @@ -174,4 +174,7 @@ public interface OAuth2Constants { String DPOP_JWT_HEADER_TYPE = "dpop+jwt"; String ALGS_ATTRIBUTE = "algs"; + // OID4VCI - https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#section-5.1.3 + // Used to pass the issuer_state value back to the Credential Issuer. + String ISSUER_STATE = "issuer_state"; } diff --git a/server-spi-private/src/main/java/org/keycloak/models/oid4vci/CredentialScopeModel.java b/server-spi-private/src/main/java/org/keycloak/models/oid4vci/CredentialScopeModel.java index 4eacc9d9f97..1d88554d092 100644 --- a/server-spi-private/src/main/java/org/keycloak/models/oid4vci/CredentialScopeModel.java +++ b/server-spi-private/src/main/java/org/keycloak/models/oid4vci/CredentialScopeModel.java @@ -172,7 +172,7 @@ public String getScope() { } public String getCredentialConfigurationId() { - return clientScope.getAttribute(VC_CONFIGURATION_ID); + return Optional.ofNullable(clientScope.getAttribute(VC_CONFIGURATION_ID)).orElse(clientScope.getName()); } public void setCredentialConfigurationId(String credentialConfigurationId) { diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/OID4VCIssuerEndpoint.java b/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/OID4VCIssuerEndpoint.java index d75b05cf236..b3c31d40d3b 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/OID4VCIssuerEndpoint.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/OID4VCIssuerEndpoint.java @@ -103,8 +103,7 @@ import org.keycloak.protocol.oid4vc.model.NonceResponse; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; import org.keycloak.protocol.oid4vc.model.OfferResponseType; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedGrant; +import org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant; import org.keycloak.protocol.oid4vc.model.Proofs; import org.keycloak.protocol.oid4vc.model.SupportedCredentialConfiguration; import org.keycloak.protocol.oid4vc.model.VerifiableCredential; @@ -543,8 +542,7 @@ public Response createCredentialOffer( if (preAuthorized) { String code = "urn:oid4vci:code:" + SecretGenerator.getInstance().randomString(64); - credOffer.setGrants(new PreAuthorizedGrant().setPreAuthorizedCode( - new PreAuthorizedCode().setPreAuthorizedCode(code))); + credOffer.addGrant(new PreAuthorizedCodeGrant().setPreAuthorizedCode(code)); } // Create the CredentialOfferState @@ -581,11 +579,10 @@ public Response createCredentialOffer( .detail(Details.VERIFIABLE_CREDENTIAL_TARGET_USER_ID, targetUserId) .success(); - String redactedTxCode = !Strings.isEmpty(offerState.getTxCode()) ? "******" : null; CredentialOfferURI credOfferURI = new CredentialOfferURI() .setIssuer(credOffer.getCredentialIssuer() + "/protocol/" + OID4VC_PROTOCOL + "/" + CREDENTIAL_OFFER_PATH) .setNonce(offerState.getNonce()) - .setTxCode(redactedTxCode); + .setTxCode(offerState.getTxCode()); // Respond with QR-Code as 'image/png' if (responseType == OfferResponseType.QR) { diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/CredentialOfferState.java b/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/CredentialOfferState.java index 919357424de..28f67733a56 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/CredentialOfferState.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/CredentialOfferState.java @@ -24,12 +24,13 @@ import org.keycloak.common.util.Time; import org.keycloak.protocol.oid4vc.model.CredentialsOffer; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedGrant; +import org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant; import org.keycloak.saml.RandomSecret; import com.fasterxml.jackson.annotation.JsonInclude; +import static org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE; + @JsonInclude(JsonInclude.Include.NON_NULL) public class CredentialOfferState { @@ -55,9 +56,9 @@ public CredentialOfferState(CredentialsOffer credOffer, String clientId, String @Transient public Optional getPreAuthorizedCode() { - return Optional.ofNullable(credentialsOffer.getGrants()) - .map(PreAuthorizedGrant::getPreAuthorizedCode) - .map(PreAuthorizedCode::getPreAuthorizedCode); + return Optional.ofNullable(credentialsOffer.getGrant(PRE_AUTH_GRANT_TYPE)) + .map(it -> (PreAuthorizedCodeGrant) it) + .map(PreAuthorizedCodeGrant::getPreAuthorizedCode); } public void generateTxCode() { diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/DefaultCredentialOfferStorage.java b/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/DefaultCredentialOfferStorage.java index 74532c346a6..43cd384ef2c 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/DefaultCredentialOfferStorage.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/issuance/credentialoffer/DefaultCredentialOfferStorage.java @@ -21,6 +21,7 @@ import org.keycloak.common.util.Time; import org.keycloak.models.KeycloakSession; +import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; import org.keycloak.util.JsonSerialization; /** @@ -69,11 +70,11 @@ public void putOfferState(KeycloakSession session, CredentialOfferState entry) { entry.getPreAuthorizedCode().ifPresent(it -> { session.singleUseObjects().put(it, lifespanSeconds, Map.of(ENTRY_KEY, entryJson)); }); - Optional.ofNullable(entry.getAuthorizationDetails()).ifPresent(it -> { - it.getCredentialIdentifiers().forEach( cid -> { - session.singleUseObjects().put(cid, lifespanSeconds, Map.of(ENTRY_KEY, entryJson)); - }); - }); + OID4VCAuthorizationDetail authDetails = entry.getAuthorizationDetails(); + if (authDetails != null && authDetails.getCredentialIdentifiers() != null) { + authDetails.getCredentialIdentifiers().forEach( cid -> + session.singleUseObjects().put(cid, lifespanSeconds, Map.of(ENTRY_KEY, entryJson))); + } } @Override diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrant.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrant.java new file mode 100644 index 00000000000..9441ef2016f --- /dev/null +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrant.java @@ -0,0 +1,34 @@ +/* + * Copyright 2024 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.protocol.oid4vc.model; + + +import com.fasterxml.jackson.annotation.JsonIgnore; + +/** + * Container for the grants to be used in a Credential Offer + *

+ * {@see https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#name-credential-offer} + * + * @author Thomas Diesler + */ +public interface CredentialOfferGrant { + + @JsonIgnore + String getGrantType(); +} diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrantsDeserializer.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrantsDeserializer.java new file mode 100644 index 00000000000..d378a7b7210 --- /dev/null +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialOfferGrantsDeserializer.java @@ -0,0 +1,41 @@ +package org.keycloak.protocol.oid4vc.model; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.exc.InvalidFormatException; + +import static org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE; + +public final class CredentialOfferGrantsDeserializer extends JsonDeserializer> { + + @Override + public Map deserialize(JsonParser p, DeserializationContext ctx) throws IOException { + + Map grants = new LinkedHashMap<>(); + var mapper = (ObjectMapper) p.getCodec(); + var node = mapper.readTree(p); + + var fields = node.fieldNames(); + while (fields.hasNext()) { + var grantType = fields.next(); + var valueNode = node.get(grantType); + + Class target = + switch (grantType) { + case PRE_AUTH_GRANT_TYPE -> PreAuthorizedCodeGrant.class; + default -> throw new InvalidFormatException( + p, "Unknown grant type key: " + grantType, grantType, CredentialOfferGrant.class); + }; + + CredentialOfferGrant grant = mapper.treeToValue(valueNode, target); + grants.put(grantType, grant); + } + return grants; + } +} diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialRequest.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialRequest.java index 9000edd510d..84e8b2dce63 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialRequest.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialRequest.java @@ -17,12 +17,7 @@ package org.keycloak.protocol.oid4vc.model; -import java.util.Map; -import java.util.Optional; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.RealmModel; -import org.keycloak.models.oid4vci.CredentialScopeModel; import org.keycloak.util.JsonSerialization; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -130,23 +125,6 @@ public CredentialRequest setCredentialResponseEncryption(CredentialResponseEncry return this; } - public Optional findCredentialScope(KeycloakSession keycloakSession) { - Map searchAttributeMap = - Optional.ofNullable(credentialConfigurationId) - .map(credentialIdentifier -> { - return Map.of(CredentialScopeModel.VC_CONFIGURATION_ID, credentialConfigurationId); - }).orElseGet(() -> { - return Map.of(CredentialScopeModel.VC_IDENTIFIER, credentialIdentifier); - }); - - RealmModel currentRealm = keycloakSession.getContext().getRealm(); - final boolean useOrExpression = false; - return keycloakSession.clientScopes() - .getClientScopesByAttributes(currentRealm, searchAttributeMap, useOrExpression) - .map(CredentialScopeModel::new) - .findAny(); - } - @Override public String toString() { try { diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialsOffer.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialsOffer.java index 7d785672f79..f50191bd3ba 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialsOffer.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/model/CredentialsOffer.java @@ -17,17 +17,23 @@ package org.keycloak.protocol.oid4vc.model; -import java.beans.Transient; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.Optional; import org.keycloak.common.util.KeycloakUriBuilder; +import org.keycloak.util.JsonSerialization; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import static org.keycloak.OID4VCConstants.WELL_KNOWN_OPENID_CREDENTIAL_ISSUER; +import static org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE; /** * Represents a CredentialsOffer according to the OID4VCI Spec @@ -45,8 +51,9 @@ public class CredentialsOffer { @JsonProperty("credential_configuration_ids") private List credentialConfigurationIds; - // current implementation only supports pre-authorized codes. - private PreAuthorizedGrant grants; + @JsonProperty("grants") + @JsonDeserialize(using = CredentialOfferGrantsDeserializer.class) + private Map grants = new HashMap<>(); public String getCredentialIssuer() { return credentialIssuer; @@ -57,7 +64,7 @@ public CredentialsOffer setCredentialIssuer(String credentialIssuer) { return this; } - @Transient + @JsonIgnore public String getIssuerMetadataUrl() { var metadataUrl = KeycloakUriBuilder .fromUri(credentialIssuer) @@ -83,24 +90,43 @@ public CredentialsOffer setCredentialConfigurationIds(List credentialCon return this; } - public PreAuthorizedGrant getGrants() { - return grants; + public CredentialOfferGrant getGrant(String grantType) { + return grants.get(grantType); } - public CredentialsOffer setGrants(PreAuthorizedGrant grants) { - this.grants = grants; + public CredentialsOffer addGrant(CredentialOfferGrant grant) { + grants.put(grant.getGrantType(), grant); return this; } + @JsonIgnore + public PreAuthorizedCodeGrant getPreAuthorizedGrant() { + return (PreAuthorizedCodeGrant) grants.get(PRE_AUTH_GRANT_TYPE); + } + + @JsonIgnore + public String getPreAuthorizedCode() { + return Optional.ofNullable(getPreAuthorizedGrant()) + .map(PreAuthorizedCodeGrant::getPreAuthorizedCode) + .orElse(null); + } + @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof CredentialsOffer that)) return false; - return Objects.equals(getCredentialIssuer(), that.getCredentialIssuer()) && Objects.equals(getCredentialConfigurationIds(), that.getCredentialConfigurationIds()) && Objects.equals(getGrants(), that.getGrants()); + boolean match = Objects.equals(credentialIssuer, that.credentialIssuer); + match &= Objects.equals(credentialConfigurationIds, that.credentialConfigurationIds); + match &= Objects.equals(grants, that.grants); + return match; } @Override public int hashCode() { - return Objects.hash(getCredentialIssuer(), getCredentialConfigurationIds(), getGrants()); + return Objects.hash(credentialIssuer, credentialConfigurationIds, grants); + } + + public String toString() { + return JsonSerialization.valueAsString(this); } } diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedCode.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedCodeGrant.java similarity index 57% rename from services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedCode.java rename to services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedCodeGrant.java index 97f38d7fee1..78210a4c45f 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedCode.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedCodeGrant.java @@ -19,32 +19,45 @@ import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** - * Represents a pre-authorized grant, as used by the Credential Offer in OID4VCI + * Container for the pre-authorized code to be used in a Credential Offer + *

* {@see https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#name-credential-offer} * * @author Stefan Wiedemann */ @JsonInclude(JsonInclude.Include.NON_NULL) -public class PreAuthorizedCode { +public class PreAuthorizedCodeGrant implements CredentialOfferGrant { - @JsonProperty("pre-authorized_code") + public static final String PRE_AUTH_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:pre-authorized_code"; + public static final String AUTHORIZATION_SERVER_PARAM = "authorization_server"; + public static final String CODE_REQUEST_PARAM = "pre-authorized_code"; + public static final String TX_CODE_PARAM = "tx_code"; + + @Override + @JsonIgnore + public String getGrantType() { + return PRE_AUTH_GRANT_TYPE; + } + + @JsonProperty(CODE_REQUEST_PARAM) private String preAuthorizedCode; - @JsonProperty("tx_code") + @JsonProperty(TX_CODE_PARAM) private TxCode txCode; - @JsonProperty("authorization_server") + @JsonProperty(AUTHORIZATION_SERVER_PARAM) private String authorizationServer; public String getPreAuthorizedCode() { return preAuthorizedCode; } - public PreAuthorizedCode setPreAuthorizedCode(String preAuthorizedCode) { + public PreAuthorizedCodeGrant setPreAuthorizedCode(String preAuthorizedCode) { this.preAuthorizedCode = preAuthorizedCode; return this; } @@ -53,7 +66,7 @@ public TxCode getTxCode() { return txCode; } - public PreAuthorizedCode setTxCode(TxCode txCode) { + public PreAuthorizedCodeGrant setTxCode(TxCode txCode) { this.txCode = txCode; return this; } @@ -62,7 +75,7 @@ public String getAuthorizationServer() { return authorizationServer; } - public PreAuthorizedCode setAuthorizationServer(String authorizationServer) { + public PreAuthorizedCodeGrant setAuthorizationServer(String authorizationServer) { this.authorizationServer = authorizationServer; return this; } @@ -70,12 +83,13 @@ public PreAuthorizedCode setAuthorizationServer(String authorizationServer) { @Override public boolean equals(Object o) { if (this == o) return true; - if (!(o instanceof PreAuthorizedCode that)) return false; - return Objects.equals(getPreAuthorizedCode(), that.getPreAuthorizedCode()) && Objects.equals(getTxCode(), that.getTxCode()) && Objects.equals(getAuthorizationServer(), that.getAuthorizationServer()); + if (!(o instanceof PreAuthorizedCodeGrant that)) return false; + return Objects.equals(preAuthorizedCode, that.preAuthorizedCode) + && Objects.equals(txCode, that.txCode) && Objects.equals(authorizationServer, that.authorizationServer); } @Override public int hashCode() { - return Objects.hash(getPreAuthorizedCode(), getTxCode(), getAuthorizationServer()); + return Objects.hash(preAuthorizedCode, txCode, authorizationServer); } } diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedGrant.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedGrant.java deleted file mode 100644 index b7c727ec01e..00000000000 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/model/PreAuthorizedGrant.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2024 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.protocol.oid4vc.model; - -import java.util.Objects; - -import org.keycloak.protocol.oidc.grants.PreAuthorizedCodeGrantTypeFactory; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Container for the pre-authorized code to be used in a Credential Offer - *

- * {@see https://openid.net/specs/openid-4-verifiable-credential-issuance-1_0.html#name-credential-offer} - * - * @author Stefan Wiedemann - */ -@JsonInclude(JsonInclude.Include.NON_NULL) -public class PreAuthorizedGrant { - - @JsonProperty(PreAuthorizedCodeGrantTypeFactory.GRANT_TYPE) - private PreAuthorizedCode preAuthorizedCode; - - public PreAuthorizedCode getPreAuthorizedCode() { - return preAuthorizedCode; - } - - public PreAuthorizedGrant setPreAuthorizedCode(PreAuthorizedCode preAuthorizedCode) { - this.preAuthorizedCode = preAuthorizedCode; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PreAuthorizedGrant grant)) return false; - return Objects.equals(getPreAuthorizedCode(), grant.getPreAuthorizedCode()); - } - - @Override - public int hashCode() { - return Objects.hash(getPreAuthorizedCode()); - } -} diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/utils/CredentialScopeModelUtils.java b/services/src/main/java/org/keycloak/protocol/oid4vc/utils/CredentialScopeModelUtils.java new file mode 100644 index 00000000000..25ffa2a4276 --- /dev/null +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/utils/CredentialScopeModelUtils.java @@ -0,0 +1,67 @@ +package org.keycloak.protocol.oid4vc.utils; + +import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Stream; + +import org.keycloak.models.ClientScopeModel; +import org.keycloak.models.RealmModel; +import org.keycloak.models.oid4vci.CredentialScopeModel; +import org.keycloak.util.Strings; + +import org.jboss.logging.Logger; + +import static org.keycloak.constants.OID4VCIConstants.OID4VC_PROTOCOL; + +public class CredentialScopeModelUtils { + + private static final Logger log = Logger.getLogger(CredentialScopeModelUtils.class); + + // Hide ctor + private CredentialScopeModelUtils() {} + + public static CredentialScopeModel findCredentialScopeModelByConfigurationId(RealmModel realmModel, Supplier> supplier, String credConfigId) { + if (Strings.isEmpty(credConfigId)) { + return null; + } + List credScopes = supplier.get() + .filter(it -> it.getProtocol().equals(OID4VC_PROTOCOL)) + .map(CredentialScopeModel::new) + .filter(it -> credConfigId.equals(it.getCredentialConfigurationId())) + .toList(); + if (credScopes.size() > 1) { + List clientScopeNames = credScopes.stream().map(ClientScopeModel::getName).toList(); + log.warnf("Multiple client scopes found with credential config ID '%s' in the realm '%s'. Please make sure that vc.credential_configuration_id is unique across client scopes. Found client scopes: %s", + credConfigId, realmModel.getName(), clientScopeNames); + return null; + } else if (credScopes.isEmpty()) { + log.warnf("No client scopes found with credential config ID '%s' in the realm '%s'", + credConfigId, realmModel.getName()); + return null; + } else { + return credScopes.get(0); + } + } + + public static CredentialScopeModel findCredentialScopeModelByName(RealmModel realmModel, Supplier> supplier, String scope) { + if (Strings.isEmpty(scope)) { + return null; + } + List credScopes = supplier.get() + .filter(it -> it.getProtocol().equals(OID4VC_PROTOCOL)) + .map(CredentialScopeModel::new) + .filter(it -> scope.equals(it.getScope())) + .toList(); + if (credScopes.size() > 1) { + List clientScopeNames = credScopes.stream().map(ClientScopeModel::getName).toList(); + log.warnf("Multiple client scopes found with scope '%s' in the realm '%s'. Please make sure that vc.scope is unique across client scopes. Found client scopes: %s", + scope, realmModel.getName(), clientScopeNames); + return null; + } else if (credScopes.isEmpty()) { + log.warnf("No client scopes found with scope '%s' in the realm '%s'", scope, realmModel.getName()); + return null; + } else { + return credScopes.get(0); + } + } +} diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCAuthorizationDetailUtils.java b/services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCAuthorizationDetailUtils.java new file mode 100644 index 00000000000..d85c953bf8d --- /dev/null +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCAuthorizationDetailUtils.java @@ -0,0 +1,31 @@ +package org.keycloak.protocol.oid4vc.utils; + +import java.util.List; +import java.util.Optional; + +import org.keycloak.models.oid4vci.CredentialScopeModel; +import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; +import org.keycloak.util.Strings; + +import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; +import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_CONFIGURATION_ID; + +public class OID4VCAuthorizationDetailUtils { + + public static OID4VCAuthorizationDetail buildOID4VCAuthorizationDetail(CredentialScopeModel credScopeModel) { + + // Read the credential_identifiers from the client scope configuration + OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); + authDetail.setType(OPENID_CREDENTIAL); + + String credConfigId = Optional.ofNullable(credScopeModel.getCredentialConfigurationId()) + .orElseThrow(() -> new IllegalStateException("No " + VC_CONFIGURATION_ID + " in client scope: " + credScopeModel.getName())); + authDetail.setCredentialConfigurationId(credConfigId); + + String credIdentifier = credScopeModel.getCredentialIdentifier(); + if (!Strings.isEmpty(credIdentifier)) { + authDetail.setCredentialIdentifiers(List.of(credIdentifier)); + } + return authDetail; + } +} diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCUtil.java b/services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCUtil.java deleted file mode 100644 index ae403866d14..00000000000 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/utils/OID4VCUtil.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.keycloak.protocol.oid4vc.utils; - -import java.util.List; - -import org.keycloak.models.ClientScopeModel; -import org.keycloak.models.KeycloakSession; -import org.keycloak.models.RealmModel; -import org.keycloak.utils.StringUtil; - -import org.jboss.logging.Logger; - -import static org.keycloak.constants.OID4VCIConstants.OID4VC_PROTOCOL; -import static org.keycloak.models.oid4vci.CredentialScopeModel.VC_CONFIGURATION_ID; - -public class OID4VCUtil { - - private static final Logger logger = Logger.getLogger(OID4VCUtil.class); - - private OID4VCUtil() { - } - - /** - * Find OID4VCI client scope by credential config ID - * - * @param session Keycloak session - * @param realmModel realm - * @param credentialConfigId credential configuration ID - * @return Found OID4VCI client scope - */ - public static ClientScopeModel getClientScopeByCredentialConfigId(KeycloakSession session, RealmModel realmModel, String credentialConfigId) { - if (StringUtil.isBlank(credentialConfigId)) { - return null; - } - - List clientScopes = session.clientScopes() - .getClientScopesByProtocol(realmModel, OID4VC_PROTOCOL) - .filter(it -> credentialConfigId.equals(it.getAttribute(VC_CONFIGURATION_ID))) - .toList(); - if (clientScopes.size() > 1) { - List clientScopeNames = clientScopes.stream() - .map(ClientScopeModel::getName) - .toList(); - logger.warnf("Multiple client scopes find with credential config ID '%s' in the realm '%s'. Please make sure that credential-config-id is unique across client scopes. Found client scopes: %s", - credentialConfigId, realmModel.getName(), clientScopeNames); - return null; - } else if (clientScopes.isEmpty()) { - logger.warnf("No client scopes find with credential config ID '%s' in the realm '%s'", - credentialConfigId, realmModel.getName()); - return null; - } else { - return clientScopes.get(0); - } - } -} diff --git a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java index ef2cc21baf6..85762105d91 100644 --- a/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java +++ b/services/src/main/java/org/keycloak/protocol/oidc/endpoints/TokenEndpoint.java @@ -47,7 +47,6 @@ import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.TokenManager; import org.keycloak.protocol.oidc.grants.OAuth2GrantType; -import org.keycloak.protocol.oidc.grants.PreAuthorizedCodeGrantTypeFactory; import org.keycloak.protocol.oidc.utils.AuthorizeClientUtil; import org.keycloak.protocol.saml.JaxrsSAML2BindingBuilder; import org.keycloak.protocol.saml.SamlClient; @@ -65,6 +64,8 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; +import static org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE; + /** * @author Stian Thorgersen */ @@ -132,7 +133,7 @@ public Response processGrantRequest() { if (!grantType.equals(OAuth2Constants.UMA_GRANT_TYPE) // pre-authorized grants are not necessarily used by known clients. - && !grantType.equals(PreAuthorizedCodeGrantTypeFactory.GRANT_TYPE)) { + && !grantType.equals(PRE_AUTH_GRANT_TYPE)) { checkClient(); checkParameterDuplicated(); } diff --git a/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantType.java b/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantType.java index 37f89fb4ddb..fed8d26bbf7 100644 --- a/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantType.java +++ b/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantType.java @@ -30,16 +30,16 @@ import org.keycloak.events.EventType; import org.keycloak.models.AuthenticatedClientSessionModel; import org.keycloak.models.ClientModel; -import org.keycloak.models.ClientScopeModel; import org.keycloak.models.ClientSessionContext; import org.keycloak.models.Constants; import org.keycloak.models.KeycloakSession; import org.keycloak.models.UserSessionModel; +import org.keycloak.models.oid4vci.CredentialScopeModel; import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerEndpoint; import org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerWellKnownProvider; import org.keycloak.protocol.oid4vc.issuance.credentialoffer.CredentialOfferStorage; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; -import org.keycloak.protocol.oid4vc.utils.OID4VCUtil; +import org.keycloak.protocol.oid4vc.utils.CredentialScopeModelUtils; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.TokenManager.AccessTokenResponseBuilder; import org.keycloak.representations.AccessToken; @@ -206,17 +206,17 @@ public Response process(Context context) { sessionContext); // Add the scope referenced by the credential from specified credential offer to the token scopes - String credentialConfigId = authDetails.getCredentialConfigurationId(); - ClientScopeModel clientScope = OID4VCUtil.getClientScopeByCredentialConfigId(session, realm, credentialConfigId); - if (clientScope == null) { - String errorMessage = "Client scope was not found for credential configuration ID: " + credentialConfigId; - event.detail(Details.CREDENTIAL_TYPE, credentialConfigId); - event.detail(REASON, errorMessage) - .error(UNKNOWN_CREDENTIAL_CONFIGURATION.getValue()); + String credConfigId = authDetails.getCredentialConfigurationId(); + CredentialScopeModel credScope = CredentialScopeModelUtils.findCredentialScopeModelByConfigurationId(realm, + () -> session.clientScopes().getClientScopesStream(realm), credConfigId); + if (credScope == null) { + String errorMessage = "Credential client scope was not found for credential_configuration_id: " + credConfigId; + event.detail(Details.CREDENTIAL_TYPE, credConfigId); + event.detail(REASON, errorMessage).error(UNKNOWN_CREDENTIAL_CONFIGURATION.getValue()); throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, errorMessage, Response.Status.BAD_REQUEST); } - accessToken.setScope(clientScope.getName()); + accessToken.setScope(credScope.getName()); accessToken.setSessionId(null); accessToken.setAuthorizationDetails(authorizationDetailsResponses); @@ -237,7 +237,7 @@ public Response process(Context context) { try { tokenResponse = responseBuilder.build(); tokenResponse.setAuthorizationDetails(authorizationDetailsResponses); - tokenResponse.setScope(clientScope.getName()); + tokenResponse.setScope(credScope.getName()); } catch (RuntimeException re) { String errorMessage = "Cannot get encryption KEK"; if (errorMessage.equals(re.getMessage())) { diff --git a/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantTypeFactory.java b/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantTypeFactory.java index 398b5ae3476..80cf9b62463 100644 --- a/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantTypeFactory.java +++ b/services/src/main/java/org/keycloak/protocol/oidc/grants/PreAuthorizedCodeGrantTypeFactory.java @@ -23,6 +23,8 @@ import org.keycloak.models.KeycloakSessionFactory; import org.keycloak.provider.EnvironmentDependentProviderFactory; +import static org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE; + /** * Factory for Pre-Authorized Code Grant * @@ -30,7 +32,8 @@ */ public class PreAuthorizedCodeGrantTypeFactory implements OAuth2GrantTypeFactory, EnvironmentDependentProviderFactory { - public static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:pre-authorized_code"; + // [TODO] Remove deprecated constants used in the old testsuite + @Deprecated public static final String GRANT_TYPE = PRE_AUTH_GRANT_TYPE; public static final String CODE_REQUEST_PARAM = "pre-authorized_code"; public static final String TX_CODE_PARAM = "tx_code"; @@ -53,7 +56,7 @@ public void close() { @Override public String getId() { - return GRANT_TYPE; + return PRE_AUTH_GRANT_TYPE; } @Override diff --git a/test-framework/core/src/main/java/org/keycloak/testframework/realm/RealmConfigBuilder.java b/test-framework/core/src/main/java/org/keycloak/testframework/realm/RealmConfigBuilder.java index c2d58a8d245..1ab9993505b 100644 --- a/test-framework/core/src/main/java/org/keycloak/testframework/realm/RealmConfigBuilder.java +++ b/test-framework/core/src/main/java/org/keycloak/testframework/realm/RealmConfigBuilder.java @@ -306,6 +306,11 @@ public RealmConfigBuilder requiredAction(RequiredActionProviderRepresentation re return this; } + public RealmConfigBuilder verifiableCredentialsEnabled(boolean enabled) { + rep.setVerifiableCredentialsEnabled(enabled); + return this; + } + public RealmConfigBuilder webAuthnPolicySignatureAlgorithms(List algorithms) { rep.setWebAuthnPolicySignatureAlgorithms(algorithms); return this; diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java new file mode 100644 index 00000000000..1d4095b6203 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java @@ -0,0 +1,383 @@ +package org.keycloak.tests.oid4vc; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.keycloak.admin.client.Keycloak; +import org.keycloak.admin.client.resource.RealmResource; +import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.jose.jws.JWSHeader; +import org.keycloak.jose.jws.JWSInput; +import org.keycloak.protocol.oid4vc.model.CredentialIssuer; +import org.keycloak.protocol.oid4vc.model.CredentialOfferURI; +import org.keycloak.protocol.oid4vc.model.CredentialRequest; +import org.keycloak.protocol.oid4vc.model.CredentialResponse; +import org.keycloak.protocol.oid4vc.model.CredentialResponse.Credential; +import org.keycloak.protocol.oid4vc.model.CredentialsOffer; +import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; +import org.keycloak.representations.AuthorizationDetailsJSONRepresentation; +import org.keycloak.representations.JsonWebToken; +import org.keycloak.representations.idm.UserRepresentation; +import org.keycloak.testframework.oauth.OAuthClient; +import org.keycloak.testsuite.util.oauth.AbstractOAuthClient; +import org.keycloak.testsuite.util.oauth.AccessTokenRequest; +import org.keycloak.testsuite.util.oauth.AccessTokenResponse; +import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; +import org.keycloak.testsuite.util.oauth.LoginUrlBuilder; +import org.keycloak.testsuite.util.oauth.PkceGenerator; +import org.keycloak.testsuite.util.oauth.oid4vc.CredentialOfferRequest; +import org.keycloak.testsuite.util.oauth.oid4vc.CredentialOfferResponse; +import org.keycloak.testsuite.util.oauth.oid4vc.CredentialOfferUriRequest; +import org.keycloak.testsuite.util.oauth.oid4vc.CredentialOfferUriResponse; +import org.keycloak.testsuite.util.oauth.oid4vc.Oid4vcCredentialRequest; +import org.keycloak.testsuite.util.oauth.oid4vc.Oid4vcCredentialResponse; +import org.keycloak.testsuite.util.oauth.oid4vc.PreAuthorizedCodeGrantRequest; +import org.keycloak.util.JsonSerialization; + +import static org.keycloak.OAuth2Constants.AUTHORIZATION_DETAILS; +import static org.keycloak.constants.OID4VCIConstants.CREDENTIAL_OFFER_CREATE; +import static org.keycloak.tests.oid4vc.OID4VCIssuerTestBase.VCTestRealmConfig.TEST_REALM_NAME; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.ACCESS_TOKEN_RESPONSE_ATTACHMENT_KEY; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.CREDENTIALS_OFFER_ATTACHMENT_KEY; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.CREDENTIAL_OFFER_URI_ATTACHMENT_KEY; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.CREDENTIAL_RESPONSE_ATTACHMENT_KEY; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.ISSUER_METADATA_ATTACHMENT_KEY; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +/** + * A basic Wallet to exercise various OID4VCI message flows. + * + * Wallet state between messages is maintained in {@code OID4VCTestContext}. + * + * @author Thomas Diesler + */ +public class OID4VCBasicWallet { + + final Keycloak keycloak; + final OAuthClient oauth; + + final Set loginUsers = new HashSet<>(); + + public OID4VCBasicWallet(Keycloak keycloak, OAuthClient oauth) { + this.keycloak = keycloak; + this.oauth = oauth; + } + + // Composite Actions ----------------------------------------------------------------------------------------------- + + public CredentialsOffer createPreAuthCredentialOffer(OID4VCTestContext ctx, String targetUser, boolean withTxCode) throws Exception { + + // Get Issuer AccessToken + // + AccessTokenResponse issTokenResponse = getIssuerAccessToken(ctx.clientId, ctx.issuer); + assertNotNull(issTokenResponse.getAccessToken(), "No accessToken"); + + // Exclude scope: + // Require role: credential-offer-create + String issToken = validateIssuerAccessToken(issTokenResponse, + List.of(), List.of(ctx.credScopeName), + List.of(CREDENTIAL_OFFER_CREATE.getName()), List.of()); + + // Create Pre-Authorized CredentialOffer + // + CredentialOfferURI credOfferUri; + try { + credOfferUri = createCredentialOffer(ctx, ctx.credConfigId) + .preAuthorized(true) + .txCode(withTxCode) + .targetUser(targetUser) + .bearerToken(issToken) + .send().getCredentialOfferURI(); + } finally { + logout(ctx.issuer); + } + + if (withTxCode) { + String txCode = credOfferUri.getTxCode(); + assertNotNull(txCode, "No TxCode"); + } + + // Fetch the CredentialsOffer + // + CredentialsOffer credOffer = getCredentialOffer(ctx, credOfferUri) + .send().getCredentialsOffer(); + + String preAuthCode = credOffer.getPreAuthorizedCode(); + assertNotNull(preAuthCode, "No PreAuth Code"); + + return credOffer; + } + + // Low Level Messages ---------------------------------------------------------------------------------------------- + + public CredentialOfferUriRequest createCredentialOffer(OID4VCTestContext ctx, String credConfigId) { + CredentialOfferUriRequest request = new CredentialOfferUriRequest(oauth, credConfigId) { + public CredentialOfferUriResponse send() { + CredentialOfferUriResponse response = super.send(); + ctx.putAttachment(CREDENTIAL_OFFER_URI_ATTACHMENT_KEY, response.getCredentialOfferURI()); + return response; + } + }; + return request; + } + + public CredentialOfferRequest getCredentialOffer(OID4VCTestContext ctx, CredentialOfferURI credOfferUri) { + CredentialOfferRequest request = new CredentialOfferRequest(oauth, credOfferUri) { + public CredentialOfferResponse send() { + CredentialOfferResponse response = super.send(); + ctx.putAttachment(CREDENTIALS_OFFER_ATTACHMENT_KEY, response.getCredentialsOffer()); + return response; + } + }; + return request; + } + + public AuthorizationEndpointRequest authorizationRequest() { + AuthorizationEndpointRequest request = new AuthorizationEndpointRequest(oauth) { + public AuthorizationEndpointResponse send(String username, String password) { + loginUsers.add(username); + return super.send(username, password); + } + }; + return request; + } + + public AccessTokenRequest accessTokenRequest(OID4VCTestContext ctx, String authCode) { + AccessTokenRequest request = new AccessTokenRequest(oauth, authCode) { + public AccessTokenResponse send() { + AccessTokenResponse response = super.send(); + ctx.putAttachment(ACCESS_TOKEN_RESPONSE_ATTACHMENT_KEY, response); + return response; + } + }; + return request; + } + + public PreAuthorizedCodeGrantRequest preAuthAccessTokenRequest(OID4VCTestContext ctx, String preAuthCode, String txCode) { + PreAuthorizedCodeGrantRequest request = new PreAuthorizedCodeGrantRequest(oauth, preAuthCode) { + public AccessTokenResponse send() { + AccessTokenResponse response = super.send(); + ctx.putAttachment(ACCESS_TOKEN_RESPONSE_ATTACHMENT_KEY, response); + return response; + } + }.txCode(txCode); + return request; + } + + public Oid4vcCredentialRequest credentialRequest(OID4VCTestContext ctx, String accessToken) { + Oid4vcCredentialRequest request = new Oid4vcCredentialRequest(oauth, new CredentialRequest()) { + public Oid4vcCredentialResponse send() { + Oid4vcCredentialResponse response = super.send(); + CredentialResponse credentialResponse = response.getCredentialResponse(); + ctx.putAttachment(CREDENTIAL_RESPONSE_ATTACHMENT_KEY, credentialResponse); + return response; + } + }.bearerToken(accessToken); + return request; + } + + public AccessTokenResponse getIssuerAccessToken(String clientId, String username) { + PkceGenerator pkce = PkceGenerator.s256(); + AuthorizationEndpointResponse authResponse = authorizationRequest() + .client(clientId) + .codeChallenge(pkce) + .send(username, "password"); + + String authCode = authResponse.getCode(); + assertNotNull(authCode, "No authCode"); + AccessTokenResponse tokenResponse = oauth.accessTokenRequest(authCode) + .codeVerifier(pkce) + .send(); + assertNotNull(tokenResponse.getAccessToken(), "No AccessToken"); + return tokenResponse; + } + + public CredentialIssuer getIssuerMetadata(OID4VCTestContext ctx) { + CredentialIssuer issuerMetadata = Optional.ofNullable(ctx.getAttachment(ISSUER_METADATA_ATTACHMENT_KEY)) + .orElse(oauth.oid4vc().doIssuerMetadataRequest().getMetadata()); + ctx.putAttachment(ISSUER_METADATA_ATTACHMENT_KEY, issuerMetadata); + return issuerMetadata; + } + + public void logout() { + for (String user : loginUsers) { + logout(user); + } + loginUsers.clear(); + } + + public void logout(String username) { + RealmResource realm = keycloak.realm(TEST_REALM_NAME); + UserRepresentation userRep = realm.users().search(username).get(0); + UserResource userResource = realm.users().get(userRep.getId()); + userResource.logout(); + } + + // State Validation ------------------------------------------------------------------------------------------------ + + public void verifyCredentialsSignature(CredentialResponse credResponse, String algorithm) throws Exception { + for (Credential credEntry : credResponse.getCredentials()) { + + String encodedCredential = credEntry.getCredential().toString(); + JWSInput jwsInput = new JWSInput(encodedCredential); + JWSHeader header = jwsInput.getHeader(); + + assertEquals(algorithm, header.getRawAlgorithm()); + oauth.verifyToken(encodedCredential, JsonWebToken.class); + } + } + + public String validateIssuerAccessToken( + AccessTokenResponse tokenResponse, + List includeScopes, List excludeScopes, + List includeRoles, List excludeRoles + ) throws Exception { + + String accessToken = tokenResponse.getAccessToken(); + JsonWebToken jwt = JsonSerialization.readValue(new JWSInput(accessToken).getContent(), JsonWebToken.class); + List wasScopes = Arrays.stream(((String) jwt.getOtherClaims().get("scope")).split("\\s")).toList(); + includeScopes.forEach(it -> assertTrue(wasScopes.contains(it), "Missing scope: " + it)); + excludeScopes.forEach(it -> assertFalse(wasScopes.contains(it), "Invalid scope: " + it)); + + List allRoles = new ArrayList<>(); + Object realmAccess = jwt.getOtherClaims().get("realm_access"); + if (realmAccess != null) { + @SuppressWarnings("unchecked") + var realmRoles = ((Map>) realmAccess).get("roles"); + allRoles.addAll(realmRoles); + } + Object resourceAccess = jwt.getOtherClaims().get("resource_access"); + if (resourceAccess != null) { + @SuppressWarnings("unchecked") + var resourceAccessMapping = (Map>>) resourceAccess; + resourceAccessMapping.forEach((k, v) -> + allRoles.addAll(v.get("roles"))); + } + includeRoles.forEach(it -> assertTrue(allRoles.contains(it), "Missing role: " + it)); + excludeRoles.forEach(it -> assertFalse(allRoles.contains(it), "Invalid role: " + it)); + + return accessToken; + } + + public String validateHolderAccessToken(OID4VCTestContext ctx, AccessTokenResponse tokenResponse) throws Exception { + + // Check that we can extract the AccessToken + if (!tokenResponse.isSuccess()) { + fail("Error in AccessToken response: " + tokenResponse.getErrorDescription()); + } + + String accessToken = tokenResponse.getAccessToken(); + assertNotNull(accessToken, "No AccessToken"); + + // Extract authorization_details from AccessTokenResponse + // + List tokenAuthDetails = tokenResponse.getOID4VCAuthorizationDetails(); + assertTrue(tokenAuthDetails != null && !tokenAuthDetails.isEmpty(), "No authorization_details in AccessTokenResponse"); + + // Extract authorization_details from AccessToken (JWT) + // + JsonWebToken jwt = new JWSInput(tokenResponse.getAccessToken()).readJsonContent(JsonWebToken.class); + Object authDetailsClaim = jwt.getOtherClaims().get(AUTHORIZATION_DETAILS); + String authDetailsJson = Optional.ofNullable(authDetailsClaim) + .map(JsonSerialization::valueAsString) + .orElse(null); + List jwtAuthDetails = Optional.ofNullable(authDetailsJson) + .map(it -> JsonSerialization.valueFromString(it, OID4VCAuthorizationDetail[].class)) + .map(Arrays::asList) + .orElse(null); + assertTrue(jwtAuthDetails != null && !jwtAuthDetails.isEmpty(), "No authorization_details in AccessTokenJWT"); + + assertEquals(1, tokenAuthDetails.size(), "Expected one authorization_details entry"); + var tokenAuthDetail = tokenAuthDetails.get(0); + + assertEquals(1, jwtAuthDetails.size(), "Expected one authorization_details entry"); + var jwtAuthDetail = jwtAuthDetails.get(0); + + assertEquals(ctx.credConfigId, tokenAuthDetail.getCredentialConfigurationId()); + assertEquals(tokenAuthDetail, jwtAuthDetail); + + return accessToken; + } + + public static class AuthorizationEndpointRequest { + + protected final AbstractOAuthClient client; + protected final LoginUrlBuilder loginForm; + + public AuthorizationEndpointRequest(AbstractOAuthClient client) { + this.client = client; + this.loginForm = client.loginForm(); + } + + public AuthorizationEndpointRequest authorizationDetails(OID4VCAuthorizationDetail authDetail) { + loginForm.authorizationDetails(List.of(authDetail)); + return this; + } + + public AuthorizationEndpointRequest authorizationDetails(List authDetails) { + loginForm.authorizationDetails(authDetails.stream().map(it -> (AuthorizationDetailsJSONRepresentation)it).toList()); + return this; + } + + public AuthorizationEndpointRequest client(String clientId) { + loginForm.clientId(clientId); + return this; + } + + public AuthorizationEndpointRequest clientState(String clientState) { + loginForm.state(clientState); + return this; + } + + public AuthorizationEndpointRequest codeChallenge(PkceGenerator pkce) { + loginForm.codeChallenge(pkce); + return this; + } + + public AuthorizationEndpointRequest redirectUri(String redirectUri) { + loginForm.redirectUri(redirectUri); + return this; + } + + public AuthorizationEndpointRequest responseType(String responseType) { + loginForm.responseType(responseType); + return this; + } + + public AuthorizationEndpointRequest responseMode(String responseMode) { + loginForm.responseMode(responseMode); + return this; + } + + public AuthorizationEndpointRequest request(String request) { + loginForm.request(request); + return this; + } + + public AuthorizationEndpointRequest scope(String... scopes) { + loginForm.scope(scopes); + return this; + } + + public AuthorizationEndpointRequest nonce(String nonce) { + loginForm.nonce(nonce); + return this; + } + + public AuthorizationEndpointResponse send(String username, String password) { + loginForm.open(); + client.fillLoginForm(username, password); + return client.parseLoginResponse(); + } + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCCredentialOfferMatrixTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCCredentialOfferMatrixTest.java new file mode 100644 index 00000000000..b065466b010 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCCredentialOfferMatrixTest.java @@ -0,0 +1,230 @@ +package org.keycloak.tests.oid4vc; + +import java.net.URI; +import java.util.List; + +import org.keycloak.TokenVerifier; +import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.protocol.oid4vc.model.CredentialIssuer; +import org.keycloak.protocol.oid4vc.model.CredentialResponse; +import org.keycloak.protocol.oid4vc.model.CredentialsOffer; +import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; +import org.keycloak.protocol.oid4vc.model.VerifiableCredential; +import org.keycloak.representations.JsonWebToken; +import org.keycloak.representations.idm.RealmRepresentation; +import org.keycloak.representations.idm.UserRepresentation; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase.VCTestServerConfig; +import org.keycloak.testsuite.util.oauth.AccessTokenResponse; +import org.keycloak.testsuite.util.oauth.AuthorizationEndpointResponse; +import org.keycloak.util.JsonSerialization; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.CREDENTIAL_OFFER_URI_ATTACHMENT_KEY; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Credential Offer Validity Matrix + *

+ * +----------+----------+---------+------------------------------------------------------+ + * | Pre-Auth | Username | Valid | Notes | + * +----------+----------+---------+------------------------------------------------------+ + * | no | no | yes | Anonymous offer; any logged-in user may redeem. | + * | no | yes | yes | Offer restricted to a specific user. | + * +----------+----------+---------+------------------------------------------------------+ + * | yes | no | no | Pre-auth requires a target user. | + * | yes | yes | yes | Pre-auth for a specific target user. | + * +----------+----------+---------+------------------------------------------------------+ + */ +@KeycloakIntegrationTest(config = VCTestServerConfig.class) +public class OID4VCCredentialOfferMatrixTest extends OID4VCIssuerTestBase { + + OID4VCBasicWallet wallet; + + @BeforeEach + void beforeEach() { + wallet = new OID4VCBasicWallet(keycloak, oauth); + } + + @AfterEach + void afterEach() { + wallet.logout(); + } + + @Test + public void testRealmSetup() { + RealmRepresentation realmRep = testRealm.admin().toRepresentation(); + assertEquals(shouldEnableOid4vci(realmRep), realmRep.isVerifiableCredentialsEnabled()); + assertEquals(shouldEnableOid4vci(client), isOid4vciEnabled(client)); + } + + @Test + public void testWithoutOffer_Scope_AuthDetails() throws Exception { + + var ctx = new OID4VCTestContext(client, jwtTypeCredentialScope); + + CredentialIssuer issuerMetadata = wallet.getIssuerMetadata(ctx); + + OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); + authDetail.setType(OPENID_CREDENTIAL); + authDetail.setCredentialConfigurationId(ctx.credConfigId); + authDetail.setLocations(List.of(issuerMetadata.getCredentialIssuer())); + + // Send AuthorizationRequest + // + AuthorizationEndpointResponse authResponse = wallet + .authorizationRequest() + .scope(ctx.credScopeName) + .authorizationDetails(authDetail) + .send(ctx.holder, "password"); + String authCode = authResponse.getCode(); + assertNotNull(authCode, "No authCode"); + + // Build and send AccessTokenRequest + // + AccessTokenResponse tokenResponse = wallet.accessTokenRequest(ctx, authCode).send(); + String accessToken = wallet.validateHolderAccessToken(ctx, tokenResponse); + assertNotNull(accessToken, "No accessToken"); + + String authorizedIdentifier = ctx.getAuthorizedCredentialIdentifier(); + assertNotNull(authorizedIdentifier,"No authorized credential identifier"); + + // Send the CredentialRequest + // + CredentialResponse credResponse = wallet.credentialRequest(ctx, accessToken) + .credentialIdentifier(authorizedIdentifier) + .send().getCredentialResponse(); + + verifyCredentialResponse(ctx, ctx.holder, credResponse); + } + + @Test + public void testPreAuthOffer_DisabledUser() { + + var ctx = new OID4VCTestContext(client, jwtTypeCredentialScope); + + // Disable user + UserRepresentation userRep = testRealm.admin().users().search(ctx.holder).get(0); + UserResource userResource = testRealm.admin().users().get(userRep.getId()); + userRep.setEnabled(false); + userResource.update(userRep); + + try { + IllegalStateException error = assertThrows(IllegalStateException.class, + () -> wallet.createPreAuthCredentialOffer(ctx, ctx.holder, false)); + assertTrue(error.getMessage().contains("User 'alice' disabled"), error.getMessage()); + } finally { + userRep.setEnabled(true); + userResource.update(userRep); + } + } + + @Test + public void testPreAuthOffer_SelfIssued() throws Exception { + + var ctx = new OID4VCTestContext(client, jwtTypeCredentialScope); + + // Create Pre-Authorized CredentialOffer + // + CredentialsOffer credOffer = wallet.createPreAuthCredentialOffer(ctx, null, false); + String preAuthCode = credOffer.getPreAuthorizedCode(); + + // Redeem Pre-Authorized Code for AccessToken + // + AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode, null).send(); + assertTrue(tokenResponse.isSuccess(), tokenResponse.getErrorDescription()); + + String accessToken = wallet.validateHolderAccessToken(ctx, tokenResponse); + assertNotNull(accessToken,"No accessToken"); + + String authorizedIdentifier = ctx.getAuthorizedCredentialIdentifier(); + assertNotNull(authorizedIdentifier,"No authorized credential identifier"); + + // Send the CredentialRequest + // + CredentialResponse credResponse = wallet.credentialRequest(ctx, accessToken) + .credentialIdentifier(authorizedIdentifier) + .send().getCredentialResponse(); + + verifyCredentialResponse(ctx, ctx.issuer, credResponse); + } + + @Test + public void testPreAuthOffer_Targeted() throws Exception { + var ctx = new OID4VCTestContext(client, jwtTypeCredentialScope); + + // Create Pre-Authorized CredentialOffer + // + CredentialsOffer credOffer = wallet.createPreAuthCredentialOffer(ctx, ctx.holder, true); + String preAuthCode = credOffer.getPreAuthorizedCode(); + + // Redeem Pre-Authorized Code for AccessToken + // + String txCode = ctx.getAttachment(CREDENTIAL_OFFER_URI_ATTACHMENT_KEY).getTxCode(); + AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode, txCode).send(); + assertTrue(tokenResponse.isSuccess(), tokenResponse.getErrorDescription()); + + String accessToken = wallet.validateHolderAccessToken(ctx, tokenResponse); + assertNotNull(accessToken, "No accessToken"); + + String authorizedIdentifier = ctx.getAuthorizedCredentialIdentifier(); + assertNotNull(authorizedIdentifier, "No authorized credential identifier"); + + // Send the CredentialRequest + // + CredentialResponse credResponse = wallet.credentialRequest(ctx, accessToken) + .credentialIdentifier(authorizedIdentifier) + .send().getCredentialResponse(); + + verifyCredentialResponse(ctx, ctx.holder, credResponse); + } + + @Test + public void testPreAuthOffer_Targeted_Invalid_TxCode() throws Exception { + var ctx = new OID4VCTestContext(client, jwtTypeCredentialScope); + + // Create Pre-Authorized CredentialOffer + // + CredentialsOffer credOffer = wallet.createPreAuthCredentialOffer(ctx, ctx.holder, true); + String preAuthCode = credOffer.getPreAuthorizedCode(); + + // Test missing TxCode + { + AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode, null).send(); + AssertionError error = assertThrows(AssertionError.class, () -> wallet.validateHolderAccessToken(ctx, tokenResponse)); + assertTrue(error.getMessage().contains("Missing TxCode"), error.getMessage()); + } + + // Test wrong TxCode + { + AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode, "wrong-code").send(); + AssertionError error = assertThrows(AssertionError.class, () -> wallet.validateHolderAccessToken(ctx, tokenResponse)); + assertTrue(error.getMessage().contains("Invalid TxCode"), error.getMessage()); + } + } + + // Private --------------------------------------------------------------------------------------------------------- + + private void verifyCredentialResponse(OID4VCTestContext ctx, String expUser, CredentialResponse credResponse) throws Exception { + + String scope = ctx.credentialScope.getName(); + CredentialResponse.Credential credentialObj = credResponse.getCredentials().get(0); + assertNotNull(credentialObj, "The first credential in the array should not be null"); + + JsonWebToken jsonWebToken = TokenVerifier.create((String) credentialObj.getCredential(), JsonWebToken.class).getToken(); + assertEquals("did:web:test.org", jsonWebToken.getIssuer()); + Object vc = jsonWebToken.getOtherClaims().get("vc"); + VerifiableCredential credential = JsonSerialization.mapper.convertValue(vc, VerifiableCredential.class); + assertEquals(List.of(scope), credential.getType()); + assertEquals(URI.create("did:web:test.org"), credential.getIssuer()); + assertEquals(expUser + "@email.cz", credential.getCredentialSubject().getClaims().get("email")); + } +} diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java new file mode 100644 index 00000000000..d74a6cda6da --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java @@ -0,0 +1,136 @@ +package org.keycloak.tests.oid4vc; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +import org.keycloak.protocol.oid4vc.model.CredentialIssuer; +import org.keycloak.protocol.oid4vc.model.CredentialOfferURI; +import org.keycloak.protocol.oid4vc.model.CredentialResponse; +import org.keycloak.protocol.oid4vc.model.CredentialScopeRepresentation; +import org.keycloak.protocol.oid4vc.model.CredentialsOffer; +import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; +import org.keycloak.representations.idm.ClientRepresentation; +import org.keycloak.testsuite.util.oauth.AccessTokenResponse; + + +/** + * A context that can maintain state across OID4VCI message flows. + * + * It uses a typed in-memory value store based on attachment keys. + * Values can be accessed by type and when there are multiple values - by name+type. + * + * @author Thomas Diesler + */ +public class OID4VCTestContext { + + static final AttachmentKey ISSUER_METADATA_ATTACHMENT_KEY = new AttachmentKey<>(CredentialIssuer.class); + static final AttachmentKey CREDENTIAL_OFFER_URI_ATTACHMENT_KEY = new AttachmentKey<>(CredentialOfferURI.class); + static final AttachmentKey CREDENTIALS_OFFER_ATTACHMENT_KEY = new AttachmentKey<>(CredentialsOffer.class); + static final AttachmentKey ACCESS_TOKEN_RESPONSE_ATTACHMENT_KEY = new AttachmentKey<>(AccessTokenResponse.class); + static final AttachmentKey CREDENTIAL_RESPONSE_ATTACHMENT_KEY = new AttachmentKey<>(CredentialResponse.class); + + ClientRepresentation client; + String clientId; + String issuer; // Issuing username (i.e. agent who creates credential offers) + String holder; // Holder who requests the credential + String credConfigId; + String credScopeName; + CredentialScopeRepresentation credentialScope; + + Map, Object> attachments = new HashMap<>(); + + public OID4VCTestContext(ClientRepresentation client, CredentialScopeRepresentation credentialScope) { + this.client = client; + this.clientId = client.getClientId(); + this.issuer = "john"; + this.holder = "alice"; + this.credentialScope = credentialScope; + this.credScopeName = credentialScope.getName(); + this.credConfigId = credentialScope.getCredentialConfigurationId(); + } + + public List getAuthorizedCredentialIdentifiers() { + OID4VCAuthorizationDetail tokenAuthDetails = getOID4VCAuthorizationDetail(); + return Optional.ofNullable(tokenAuthDetails) + .map(OID4VCAuthorizationDetail::getCredentialIdentifiers) + .orElse(Collections.emptyList()); + } + + public String getAuthorizedCredentialIdentifier() { + List authorizedIdentifiers = getAuthorizedCredentialIdentifiers(); + return authorizedIdentifiers.size() == 1 ? authorizedIdentifiers.get(0) : null; + } + + public String getAuthorizedCredentialConfigurationId() { + OID4VCAuthorizationDetail tokenAuthDetails = getOID4VCAuthorizationDetail(); + return Optional.ofNullable(tokenAuthDetails) + .map(OID4VCAuthorizationDetail::getCredentialConfigurationId) + .orElse(null); + } + + public List getOID4VCAuthorizationDetails() { + AccessTokenResponse response = assertAttachment(ACCESS_TOKEN_RESPONSE_ATTACHMENT_KEY); + return Optional.ofNullable(response) + .map(AccessTokenResponse::getOID4VCAuthorizationDetails) + .orElse(Collections.emptyList()); + } + + public OID4VCAuthorizationDetail getOID4VCAuthorizationDetail() { + List tokenAuthDetails = getOID4VCAuthorizationDetails(); + return tokenAuthDetails.size() == 1 ? tokenAuthDetails.get(0) : null; + } + + // Attachment Support ---------------------------------------------------------------------------------------------- + + void putAttachment(AttachmentKey key, T value) { + if (value != null) { + attachments.put(key, value); + } else { + attachments.remove(key, value); + } + } + + T assertAttachment(AttachmentKey key) { + return Optional.of(getAttachment(key)).get(); + } + + @SuppressWarnings("unchecked") + T getAttachment(AttachmentKey key) { + return (T) attachments.get(key); + } + + @SuppressWarnings("unchecked") + T removeAttachment(AttachmentKey key) { + return (T) attachments.remove(key); + } + + static class AttachmentKey { + private final String name; + private final Class type; + + AttachmentKey(Class type) { + this(null, type); + } + + AttachmentKey(String name, Class type) { + this.name = Optional.ofNullable(name).orElse(""); + this.type = Optional.of(type).get(); + } + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) return false; + AttachmentKey that = (AttachmentKey) o; + return Objects.equals(name, that.name) && Objects.equals(type, that.type); + } + + @Override + public int hashCode() { + return Objects.hash(name, type); + } + } +} diff --git a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AccessTokenResponse.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AccessTokenResponse.java index c70b3dce92f..d9ea032cef4 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AccessTokenResponse.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AccessTokenResponse.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -136,7 +137,7 @@ public List getOID4VCAuthorizationDetails() { private List getAuthorizationDetails(Class clazz) { if (authorizationDetails == null) { - return null; + return Collections.emptyList(); } return authorizationDetails.stream() .map(authzResponse -> authzResponse.asSubtype(clazz)) diff --git a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/LoginUrlBuilder.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/LoginUrlBuilder.java index 21c43d55472..e58ba9b858e 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/LoginUrlBuilder.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/LoginUrlBuilder.java @@ -1,10 +1,12 @@ package org.keycloak.testsuite.util.oauth; import java.util.Arrays; +import java.util.List; import org.keycloak.OAuth2Constants; import org.keycloak.models.Constants; import org.keycloak.protocol.oidc.OIDCLoginProtocol; +import org.keycloak.representations.AuthorizationDetailsJSONRepresentation; import org.keycloak.representations.ClaimsRepresentation; public class LoginUrlBuilder extends AbstractUrlBuilder { @@ -23,17 +25,37 @@ public LoginUrlBuilder param(String name, String value) { return this; } + public LoginUrlBuilder clientId(String clientId) { + parameter(OAuth2Constants.CLIENT_ID, clientId); + return this; + } + public LoginUrlBuilder scope(String... scopes) { String joinedScopes = String.join(" ", Arrays.asList(scopes)); parameter(OAuth2Constants.SCOPE, joinedScopes); return this; } + public LoginUrlBuilder authorizationDetails(AuthorizationDetailsJSONRepresentation authDetail) { + parameter(OAuth2Constants.AUTHORIZATION_DETAILS, authDetail != null ? List.of(authDetail) : List.of()); + return this; + } + + public LoginUrlBuilder authorizationDetails(List authDetails) { + parameter(OAuth2Constants.AUTHORIZATION_DETAILS, authDetails); + return this; + } + public LoginUrlBuilder state(String state) { parameter(OIDCLoginProtocol.STATE_PARAM, state); return this; } + public LoginUrlBuilder issuerState(String issuerState) { + parameter(OAuth2Constants.ISSUER_STATE, issuerState); + return this; + } + public LoginUrlBuilder nonce(String nonce) { parameter(OIDCLoginProtocol.NONCE_PARAM, nonce); return this; @@ -87,6 +109,11 @@ public LoginUrlBuilder claims(ClaimsRepresentation claims) { return this; } + public LoginUrlBuilder redirectUri(String redirectUri) { + parameter(OAuth2Constants.REDIRECT_URI, redirectUri); + return this; + } + public LoginUrlBuilder request(String request) { parameter(OIDCLoginProtocol.REQUEST_PARAM, request); return this; @@ -97,14 +124,33 @@ public LoginUrlBuilder requestUri(String requestUri) { return this; } + public LoginUrlBuilder responseType(String responseType) { + parameter(OAuth2Constants.RESPONSE_TYPE, responseType); + return this; + } + + public LoginUrlBuilder responseMode(String responseMode) { + parameter(OIDCLoginProtocol.RESPONSE_MODE_PARAM, responseMode); + return this; + } + @Override protected void initRequest() { - parameter(OAuth2Constants.RESPONSE_TYPE, client.config().getResponseType()); - parameter(OIDCLoginProtocol.RESPONSE_MODE_PARAM, client.config().getResponseMode()); - parameter(OAuth2Constants.CLIENT_ID, client.config().getClientId()); - parameter(OAuth2Constants.REDIRECT_URI, client.config().getRedirectUri()); - - parameter(OAuth2Constants.SCOPE, client.config().getScope()); + if (!params.containsKey(OAuth2Constants.CLIENT_ID)) { + parameter(OAuth2Constants.CLIENT_ID, client.config().getClientId()); + } + if (!params.containsKey(OAuth2Constants.SCOPE)) { + parameter(OAuth2Constants.SCOPE, client.config().getScope()); + } + if (!params.containsKey(OAuth2Constants.REDIRECT_URI)) { + parameter(OAuth2Constants.REDIRECT_URI, client.config().getRedirectUri()); + } + if (!params.containsKey(OAuth2Constants.RESPONSE_TYPE)) { + parameter(OAuth2Constants.RESPONSE_TYPE, client.config().getResponseType()); + } + if (!params.containsKey(OIDCLoginProtocol.RESPONSE_MODE_PARAM)) { + parameter(OIDCLoginProtocol.RESPONSE_MODE_PARAM, client.config().getResponseMode()); + } } public AuthorizationEndpointResponse doLogin(String username, String password) { diff --git a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferRequest.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferRequest.java index b7af1c5acf3..a839c31b2fd 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferRequest.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferRequest.java @@ -13,12 +13,12 @@ public class CredentialOfferRequest extends AbstractHttpGetRequest client, CredentialOfferURI credOfferUri) { + public CredentialOfferRequest(AbstractOAuthClient client, CredentialOfferURI credOfferUri) { super(client); this.credOfferURI = credOfferUri; } - CredentialOfferRequest(AbstractOAuthClient client, String nonce) { + public CredentialOfferRequest(AbstractOAuthClient client, String nonce) { super(client); credOfferURI = new CredentialOfferURI(); credOfferURI.setIssuer(client.getEndpoints().getOid4vcCredentialOffer()); diff --git a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferUriRequest.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferUriRequest.java index 9e98b8c5a05..965c35d7f66 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferUriRequest.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/CredentialOfferUriRequest.java @@ -20,7 +20,7 @@ public class CredentialOfferUriRequest extends AbstractHttpGetRequest client, String credConfigId) { + public CredentialOfferUriRequest(AbstractOAuthClient client, String credConfigId) { super(client); this.credConfigId = credConfigId; } diff --git a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/OID4VCClient.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/OID4VCClient.java index 801961a40ee..6c1902cab7f 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/OID4VCClient.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/OID4VCClient.java @@ -45,12 +45,12 @@ public Oid4vcCredentialRequest credentialRequest(CredentialRequest credRequest) return new Oid4vcCredentialRequest(client, credRequest); } - public PreAuthorizedCodeGrantRequest preAuthorizedCodeGrantRequest(String preAuthorizedCode) { - return new PreAuthorizedCodeGrantRequest(client, preAuthorizedCode); + public PreAuthorizedCodeGrantRequest preAuthorizedCodeGrantRequest(String preAuthCode) { + return new PreAuthorizedCodeGrantRequest(client, preAuthCode); } - public AccessTokenResponse doPreAuthorizedCodeGrantRequest(String preAuthorizedCode) { - return preAuthorizedCodeGrantRequest(preAuthorizedCode).send(); + public AccessTokenResponse doPreAuthorizedCodeGrantRequest(String preAuthCode) { + return preAuthorizedCodeGrantRequest(preAuthCode).send(); } public Oid4vcNonceRequest nonceRequest() { diff --git a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/Oid4vcCredentialRequest.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/Oid4vcCredentialRequest.java index ecba7ba23e4..101819f8331 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/Oid4vcCredentialRequest.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/Oid4vcCredentialRequest.java @@ -14,9 +14,9 @@ public class Oid4vcCredentialRequest extends AbstractHttpPostRequest { - private final CredentialRequest credRequest; + protected final CredentialRequest credRequest; - Oid4vcCredentialRequest(AbstractOAuthClient client, CredentialRequest credRequest) { + public Oid4vcCredentialRequest(AbstractOAuthClient client, CredentialRequest credRequest) { super(client); this.credRequest = credRequest; } @@ -36,6 +36,10 @@ public Oid4vcCredentialRequest proofs(Proofs proofs) { return this; } + public CredentialRequest getCredentialRequest() { + return credRequest; + } + @Override protected String getEndpoint() { return client.getEndpoints().getOid4vcCredential(); diff --git a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/PreAuthorizedCodeGrantRequest.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/PreAuthorizedCodeGrantRequest.java index 6d06a65618a..29f20e944e5 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/PreAuthorizedCodeGrantRequest.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/oid4vc/PreAuthorizedCodeGrantRequest.java @@ -5,7 +5,7 @@ import org.keycloak.OAuth2Constants; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; -import org.keycloak.protocol.oidc.grants.PreAuthorizedCodeGrantTypeFactory; +import org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant; import org.keycloak.testsuite.util.oauth.AbstractHttpPostRequest; import org.keycloak.testsuite.util.oauth.AbstractOAuthClient; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; @@ -13,12 +13,14 @@ import org.apache.http.client.methods.CloseableHttpResponse; +import static org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant.PRE_AUTH_GRANT_TYPE; + public class PreAuthorizedCodeGrantRequest extends AbstractHttpPostRequest { private final String preAuthCode; private String txCode; - PreAuthorizedCodeGrantRequest(AbstractOAuthClient client, String preAuthorizedCode) { + public PreAuthorizedCodeGrantRequest(AbstractOAuthClient client, String preAuthorizedCode) { super(client); this.preAuthCode = preAuthorizedCode; } @@ -40,9 +42,9 @@ protected String getEndpoint() { @Override protected void initRequest() { - parameter(OAuth2Constants.GRANT_TYPE, PreAuthorizedCodeGrantTypeFactory.GRANT_TYPE); - parameter(PreAuthorizedCodeGrantTypeFactory.CODE_REQUEST_PARAM, preAuthCode); - parameter(PreAuthorizedCodeGrantTypeFactory.TX_CODE_PARAM, txCode); + parameter(OAuth2Constants.GRANT_TYPE, PRE_AUTH_GRANT_TYPE); + parameter(PreAuthorizedCodeGrant.CODE_REQUEST_PARAM, preAuthCode); + parameter(PreAuthorizedCodeGrant.TX_CODE_PARAM, txCode); } @Override diff --git a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java index 82b5e1333d1..44edc0b59bc 100644 --- a/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java +++ b/testsuite/integration-arquillian/servers/auth-server/services/testsuite-providers/src/main/java/org/keycloak/testsuite/rest/TestingResourceProvider.java @@ -90,8 +90,8 @@ import org.keycloak.protocol.oid4vc.issuance.credentialoffer.CredentialOfferState; import org.keycloak.protocol.oid4vc.issuance.credentialoffer.CredentialOfferStorage; import org.keycloak.protocol.oid4vc.model.CredentialsOffer; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedGrant; +import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; +import org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant; import org.keycloak.protocol.oidc.encode.AccessTokenContext; import org.keycloak.protocol.oidc.encode.TokenContextEncoderProvider; import org.keycloak.provider.Provider; @@ -134,6 +134,8 @@ import static java.util.Objects.requireNonNull; +import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; + /** * @author Stian Thorgersen */ @@ -1128,16 +1130,24 @@ public String getPreAuthorizedCode(@QueryParam("realm") final String realmName, RealmModel realm = getRealmByName(realmName); UserSessionModel userSession = session.sessions().getUserSession(realm, userSessionId); + String credConfigId = "oid4vc_natural_person_sd"; + String code = "urn:oid4vci:code:" + UUID.randomUUID(); CredentialsOffer credOffer = new CredentialsOffer() .setCredentialIssuer(OID4VCIssuerWellKnownProvider.getIssuer(session.getContext())) - .setCredentialConfigurationIds(List.of("oid4vc_natural_person_sd")) - .setGrants(new PreAuthorizedGrant().setPreAuthorizedCode( - new PreAuthorizedCode().setPreAuthorizedCode(code))); + .setCredentialConfigurationIds(List.of(credConfigId)) + .addGrant(new PreAuthorizedCodeGrant().setPreAuthorizedCode(code)); + + OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); + authDetail.setType(OPENID_CREDENTIAL); + authDetail.setCredentialConfigurationId(credConfigId); String userId = userSession.getUser().getId(); + CredentialOfferState offerState = new CredentialOfferState(credOffer, clientId, userId, expiration); + offerState.setAuthorizationDetails(authDetail); + var offerStorage = session.getProvider(CredentialOfferStorage.class); - offerStorage.putOfferState(session, new CredentialOfferState(credOffer, clientId, userId, expiration)); + offerStorage.putOfferState(session, offerState); return code; } diff --git a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/resources/TestingResource.java b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/resources/TestingResource.java index 26d72c73e93..1839f2e30a2 100644 --- a/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/resources/TestingResource.java +++ b/testsuite/integration-arquillian/tests/base/src/main/java/org/keycloak/testsuite/client/resources/TestingResource.java @@ -46,6 +46,7 @@ import org.jboss.resteasy.reactive.NoCache; /** + * For an implementation see TestingResourceProvider * @author Marko Strukelj */ diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/OID4VCICredentialOfferMatrixTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/OID4VCICredentialOfferMatrixTest.java deleted file mode 100644 index 2d914f04910..00000000000 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/OID4VCICredentialOfferMatrixTest.java +++ /dev/null @@ -1,478 +0,0 @@ -/* - * Copyright 2025 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.testsuite.oid4vc.issuance; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import org.keycloak.OAuth2Constants; -import org.keycloak.TokenVerifier; -import org.keycloak.admin.client.resource.UserResource; -import org.keycloak.jose.jws.JWSInput; -import org.keycloak.protocol.oid4vc.model.CredentialIssuer; -import org.keycloak.protocol.oid4vc.model.CredentialOfferURI; -import org.keycloak.protocol.oid4vc.model.CredentialRequest; -import org.keycloak.protocol.oid4vc.model.CredentialResponse; -import org.keycloak.protocol.oid4vc.model.CredentialsOffer; -import org.keycloak.protocol.oid4vc.model.ErrorType; -import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode; -import org.keycloak.protocol.oid4vc.model.SupportedCredentialConfiguration; -import org.keycloak.protocol.oid4vc.model.VerifiableCredential; -import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation; -import org.keycloak.representations.JsonWebToken; -import org.keycloak.representations.idm.ClientRepresentation; -import org.keycloak.representations.idm.UserRepresentation; -import org.keycloak.testsuite.admin.ApiUtil; -import org.keycloak.testsuite.oid4vc.issuance.signing.OID4VCIssuerEndpointTest; -import org.keycloak.testsuite.util.oauth.AccessTokenResponse; -import org.keycloak.testsuite.util.oauth.oid4vc.CredentialOfferResponse; -import org.keycloak.testsuite.util.oauth.oid4vc.CredentialOfferUriResponse; -import org.keycloak.testsuite.util.oauth.oid4vc.Oid4vcCredentialResponse; -import org.keycloak.util.JsonSerialization; - -import com.fasterxml.jackson.core.type.TypeReference; -import org.apache.directory.api.util.Strings; -import org.junit.Test; - -import static org.keycloak.OAuth2Constants.SCOPE_OPENID; -import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; -import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsernameId; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - - -/** - * Credential Offer Validity Matrix - *

- * +----------+----------+---------+------------------------------------------------------+ - * | Pre-Auth | Username | Valid | Notes | - * +----------+----------+---------+------------------------------------------------------+ - * | no | no | yes | Anonymous offer; any logged-in user may redeem. | - * | no | yes | yes | Offer restricted to a specific user. | - * +----------+----------+---------+------------------------------------------------------+ - * | yes | no | no | Pre-auth requires a target user. | - * | yes | yes | yes | Pre-auth for a specific target user. | - * +----------+----------+---------+------------------------------------------------------+ - */ -public class OID4VCICredentialOfferMatrixTest extends OID4VCIssuerEndpointTest { - - String namedClientId = "named-test-app"; - - String issUsername = "john"; - - String appUsername = "alice"; - - String credScopeName = jwtTypeNaturalPersonScopeName; - String credConfigId = jwtTypeNaturalPersonScopeName; - - class TestContext { - boolean preAuthorized; - String issUser; - String appUser; - CredentialIssuer issuerMetadata; - OIDCConfigurationRepresentation authorizationMetadata; - SupportedCredentialConfiguration credentialConfiguration; - - TestContext(boolean preAuth, String appUser) { - this.preAuthorized = preAuth; - this.issUser = issUsername; - this.appUser = appUser; - this.issuerMetadata = getCredentialIssuerMetadata(); - this.authorizationMetadata = getAuthorizationMetadata(this.issuerMetadata.getAuthorizationServers().get(0)); - this.credentialConfiguration = this.issuerMetadata.getCredentialsSupported().get(credConfigId); - } - } - - @Override - protected void afterAbstractKeycloakTestRealmImport() { - ClientRepresentation namedClient = requireExistingClient(namedClientId); - assignOptionalClientScope(namedClient, credScopeName); - setOid4vciEnabled(namedClient, true); - } - - @Test - public void testCredentialWithoutOffer() throws Exception { - var ctx = new TestContext(false, appUsername); - - OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); - authDetail.setType(OPENID_CREDENTIAL); - authDetail.setCredentialConfigurationId(credConfigId); - authDetail.setLocations(List.of(ctx.issuerMetadata.getCredentialIssuer())); - - // [TODO #44320] Requires Credential scope in AuthorizationRequest although already given in AuthorizationDetails - // https://github.com/keycloak/keycloak/issues/44320 - String accessToken = getBearerToken(clientId, ctx.appUser, credScopeName, authDetail); - - // Extract credential_identifier from the access token's authorization_details - JsonWebToken tokenDecoded = new JWSInput(accessToken).readJsonContent(JsonWebToken.class); - Object tokenAuthDetails = tokenDecoded.getOtherClaims().get(OAuth2Constants.AUTHORIZATION_DETAILS); - assertNotNull("authorization_details not found in access token", tokenAuthDetails); - - // When authorization_details are sent in token request, they are returned in token response with credential_identifiers - // The credential request MUST use credential_identifier (not credential_configuration_id) - List authDetailsResponse = JsonSerialization.readValue( - JsonSerialization.writeValueAsString(tokenAuthDetails), - new TypeReference<>() {} - ); - assertNotNull("authorization_details should be present in the response", authDetailsResponse); - assertFalse("authorization_details should not be empty", authDetailsResponse.isEmpty()); - - OID4VCAuthorizationDetail authDetailResponse = authDetailsResponse.get(0); - List credentialIdentifiers = authDetailResponse.getCredentialIdentifiers(); - assertNotNull("credential_identifiers should be present", credentialIdentifiers); - assertFalse("credential_identifiers should not be empty", credentialIdentifiers.isEmpty()); - - var credRequest = new CredentialRequest() - .setCredentialIdentifier(credentialIdentifiers.get(0)); - - CredentialResponse credResponse = sendCredentialRequest(accessToken, credRequest); - verifyCredentialResponse(ctx, credResponse); - } - - // Pre Authorized -------------------------------------------------------------------------------------------------- - - @Test - public void testCredentialOffer_PreAuth_SelfIssued() throws Exception { - runCredentialOfferTest(new TestContext(true, issUsername)); - } - - @Test - public void testCredentialOffer_PreAuth_Targeted() throws Exception { - runCredentialOfferTest(new TestContext(true, appUsername)); - } - - @Test - public void testCredentialOffer_PreAuth_DisabledUser() throws Exception { - // Disable user - UserResource user = ApiUtil.findUserByUsernameId(testRealm(), appUsername); - UserRepresentation userRep = user.toRepresentation(); - userRep.setEnabled(false); - user.update(userRep); - - try { - runCredentialOfferTest(new TestContext(true, appUsername)); - fail("Expected " + ErrorType.INVALID_CREDENTIAL_OFFER_REQUEST.getValue()); - } catch (RuntimeException ex) { - List.of(ErrorType.INVALID_CREDENTIAL_OFFER_REQUEST.getValue(), "User '" + appUsername + "' disabled") - .forEach(it -> assertTrue(ex.getMessage() + " does not contain " + it, ex.getMessage().contains(it))); - } finally { - // Re-enable user - userRep.setEnabled(true); - user.update(userRep); - } - } - - // Authorization Code ---------------------------------------------------------------------------------------------- - - @Test - public void testCredentialOffer_noPreAuth_Anonymous() throws Exception { - runCredentialOfferTest(new TestContext(false, null)); - } - - @Test - public void testCredentialOffer_noPreAuth_Targeted() throws Exception { - runCredentialOfferTest(new TestContext(false, appUsername)); - } - - void runCredentialOfferTest(TestContext ctx) throws Exception { - - // Issuer login - // - String issToken = getBearerToken(clientId, ctx.issUser, SCOPE_OPENID); - - // Exclude scope: - // Require role: credential-offer-create - // [TODO] Require role: credential-offer-create - verifyTokenJwt(issToken, - List.of(), List.of(ctx.credentialConfiguration.getScope()), - List.of(), List.of()); - - // Retrieving the credential-offer-uri - // - CredentialOfferURI credOfferUri = getCredentialOfferUri(ctx, issToken); - - // Issuer logout in order to remove unwanted session state - // - logout(ctx.issUser); - - try { - - // Using the uri to get the actual credential offer - // - CredentialsOffer credOffer = getCredentialsOffer(ctx, credOfferUri); - - if (credOffer.getCredentialConfigurationIds().size() > 1) - throw new IllegalStateException("Multiple credential configuration ids not supported in: " + JsonSerialization.valueAsString(credOffer)); - - if (ctx.preAuthorized) { - - // Get an access token for the pre-authorized code (PAC) - // - // For a PAC access token, we treat all scopes and all roles as non-meaningful. - // The access token: - // 1. has no authenticated user, and therefore cannot carry any user roles - // 2. does not perform authorization-based scope filtering - // 3. does not derive scopes from the client configuration - // 4. does not reflect anything from the credential offer - // - AccessTokenResponse accessToken = getPreAuthorizedAccessTokenResponse(credOffer); - assertTrue(accessToken.getErrorDescription(), accessToken.isSuccess()); - - List authDetailsResponse = accessToken.getOID4VCAuthorizationDetails(); - if (authDetailsResponse == null || authDetailsResponse.isEmpty()) { - throw new IllegalStateException("No authorization_details in token response"); - } - if (authDetailsResponse.size() > 1) { - throw new IllegalStateException("Multiple authorization_details in token response"); - } - OID4VCAuthorizationDetail authDetailResponse = authDetailsResponse.get(0); - - // Get the credential and verify - // - CredentialResponse credResponse = getCredentialByAuthDetail(accessToken.getAccessToken(), authDetailResponse); - verifyCredentialResponse(ctx, credResponse); - - } else { - - String username = ctx.appUser != null ? ctx.appUser : appUsername; - String credConfigId = credOffer.getCredentialConfigurationIds().get(0); - - SupportedCredentialConfiguration credConfig = ctx.issuerMetadata.getCredentialsSupported().get(credConfigId); - String scope = credConfig.getScope(); - - AccessTokenResponse tokenResponse = getBearerTokenResponse(clientId, username, scope); - String accessToken = tokenResponse.getAccessToken(); - - // Get the credential and verify - // - CredentialResponse credResponse = getCredentialByOffer(accessToken, tokenResponse, credOffer); - verifyCredentialResponse(ctx, credResponse); - } - } finally { - if (ctx.appUser != null) { - logout(ctx.appUser); - } - } - } - - // Private --------------------------------------------------------------------------------------------------------- - - private AccessTokenResponse getBearerTokenResponse(String clientId, String username, String scope) { - ClientRepresentation client = testRealm().clients().findByClientId(clientId).get(0); - - // For credential scopes, we need to request authorization_details to get credential_identifier - if (scope != null && scope.equals(credScopeName)) { - OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); - authDetail.setType(OPENID_CREDENTIAL); - authDetail.setCredentialConfigurationId(credConfigId); - authDetail.setLocations(List.of(getCredentialIssuerMetadata().getCredentialIssuer())); - - // Set the redirect URI from the client's configuration - if (client.getRedirectUris() != null && !client.getRedirectUris().isEmpty()) { - oauth.redirectUri(client.getRedirectUris().get(0)); - } - - String authCode = getAuthorizationCode(oauth, client, username, scope); - return getBearerToken(oauth, authCode, authDetail); - } - - // For non-credential scopes, use the appropriate flow based on client configuration - if (client.isDirectAccessGrantsEnabled()) { - return getBearerTokenDirectAccess(oauth, client, username, scope); - } else { - return getBearerTokenCodeFlow(oauth, client, username, scope); - } - } - - private List extractAuthorizationDetails(AccessTokenResponse tokenResponse) { - // First check if already populated in token response - List authDetailsResponse = tokenResponse.getOID4VCAuthorizationDetails(); - if (authDetailsResponse != null && !authDetailsResponse.isEmpty()) { - return authDetailsResponse; - } - - // Otherwise, extract from JWT access token - try { - JsonWebToken jwt = new JWSInput(tokenResponse.getAccessToken()).readJsonContent(JsonWebToken.class); - Object authDetails = jwt.getOtherClaims().get(OAuth2Constants.AUTHORIZATION_DETAILS); - if (authDetails != null) { - return JsonSerialization.readValue( - JsonSerialization.writeValueAsString(authDetails), - new TypeReference<>() {} - ); - } - } catch (Exception e) { - // Ignore - authorization_details not present or couldn't be parsed - } - return null; - } - - private String getBearerToken(String clientId, String username, String scope) { - return getBearerTokenResponse(clientId, username, scope).getAccessToken(); - } - - private String getBearerToken(String clientId, String username, String scope, OID4VCAuthorizationDetail... authDetail) { - ClientRepresentation client = testRealm().clients().findByClientId(clientId).get(0); - String authCode = getAuthorizationCode(oauth, client, username, scope); - return getBearerToken(oauth, authCode, authDetail).getAccessToken(); - } - - private String getBearerTokenAndLogout(String clientId, String userId, String scope) { - String token = getBearerToken(clientId, userId, scope); - logout(userId); - return token; - } - - private void logout(String userId) { - findUserByUsernameId(testRealm(), userId).logout(); - } - - private CredentialOfferURI getCredentialOfferUri(TestContext ctx, String token) throws Exception { - String credConfigId = ctx.credentialConfiguration.getId(); - CredentialOfferUriResponse credentialOfferURIResponse = oauth.oid4vc() - .credentialOfferUriRequest(credConfigId) - .preAuthorized(ctx.preAuthorized) - .txCode(ctx.preAuthorized) - .targetUser(ctx.appUser) - .bearerToken(token) - .send(); - CredentialOfferURI credentialOfferURI = credentialOfferURIResponse.getCredentialOfferURI(); - assertTrue(credentialOfferURI.getIssuer().startsWith(ctx.issuerMetadata.getCredentialIssuer())); - assertTrue(Strings.isNotEmpty(credentialOfferURI.getNonce())); - return credentialOfferURI; - } - - private CredentialsOffer getCredentialsOffer(TestContext ctx, CredentialOfferURI credOfferUri) throws Exception { - CredentialOfferResponse credentialOfferResponse = oauth.oid4vc().doCredentialOfferRequest(credOfferUri); - CredentialsOffer credOffer = credentialOfferResponse.getCredentialsOffer(); - assertEquals(List.of(ctx.credentialConfiguration.getId()), credOffer.getCredentialConfigurationIds()); - return credOffer; - } - - private AccessTokenResponse getPreAuthorizedAccessTokenResponse(CredentialsOffer credOffer) throws Exception { - PreAuthorizedCode preAuthCodeGrant = credOffer.getGrants().getPreAuthorizedCode(); - String preAuthCode = preAuthCodeGrant.getPreAuthorizedCode(); - String txCode = getTestingClient().testing().getTxCode(preAuthCode); - return oauth.oid4vc().preAuthorizedCodeGrantRequest(preAuthCode) - .txCode(txCode) - .send(); - } - - private CredentialResponse getCredentialByAuthDetail(String accessToken, OID4VCAuthorizationDetail authDetail) throws Exception { - var credentialRequest = new CredentialRequest(); - if (authDetail.getCredentialIdentifiers() != null) { - credentialRequest.setCredentialIdentifier(authDetail.getCredentialIdentifiers().get(0)); - } else if (authDetail.getCredentialConfigurationId() == null) { - credentialRequest.setCredentialConfigurationId(authDetail.getCredentialConfigurationId()); - } - return sendCredentialRequest(accessToken, credentialRequest); - } - - private CredentialResponse getCredentialByOffer(String accessToken, AccessTokenResponse tokenResponse, CredentialsOffer credOffer) throws Exception { - List credConfigIds = credOffer.getCredentialConfigurationIds(); - if (credConfigIds.size() > 1) - throw new IllegalStateException("Multiple credential configuration ids not supported in: " + JsonSerialization.valueAsString(credOffer)); - var credentialRequest = new CredentialRequest(); - - // Extract authorization_details (from token response or JWT) - List authDetailsResponse = extractAuthorizationDetails(tokenResponse); - - if (authDetailsResponse != null && !authDetailsResponse.isEmpty()) { - // If authorization_details are present, credential_identifier is required - if (authDetailsResponse.get(0).getCredentialIdentifiers() != null && - !authDetailsResponse.get(0).getCredentialIdentifiers().isEmpty()) { - String credentialIdentifier = authDetailsResponse.get(0).getCredentialIdentifiers().get(0); - credentialRequest.setCredentialIdentifier(credentialIdentifier); - } else { - throw new IllegalStateException("authorization_details present but no credential_identifier found"); - } - } else { - // No authorization_details, use credential_configuration_id - credentialRequest.setCredentialConfigurationId(credConfigIds.get(0)); - } - - return sendCredentialRequest(accessToken, credentialRequest); - } - - private CredentialResponse sendCredentialRequest(String accessToken, CredentialRequest credRequest) { - - Oid4vcCredentialResponse credRequestResponse = oauth.oid4vc() - .credentialRequest(credRequest) - .bearerToken(accessToken) - .send(); - - CredentialResponse credResponse = credRequestResponse.getCredentialResponse(); - assertNotNull("The credentials array should be present in the response", credResponse.getCredentials()); - assertFalse("The credentials array should not be empty", credResponse.getCredentials().isEmpty()); - return credResponse; - } - - private void verifyCredentialResponse(TestContext ctx, CredentialResponse credResponse) throws Exception { - - String issuer = ctx.issuerMetadata.getCredentialIssuer(); - List expectedTypes = ctx.credentialConfiguration.getCredentialDefinition().getType(); - CredentialResponse.Credential credentialObj = credResponse.getCredentials().get(0); - assertNotNull("The first credential in the array should not be null", credentialObj); - - String expUsername = ctx.appUser != null ? ctx.appUser : appUsername; - - JsonWebToken jsonWebToken = TokenVerifier.create((String) credentialObj.getCredential(), JsonWebToken.class).getToken(); - assertEquals(issuer, jsonWebToken.getIssuer()); - Object vc = jsonWebToken.getOtherClaims().get("vc"); - VerifiableCredential credential = JsonSerialization.mapper.convertValue(vc, VerifiableCredential.class); - assertEquals(expectedTypes, credential.getType()); - assertEquals(URI.create(issuer), credential.getIssuer()); - assertEquals(expUsername + "@email.cz", credential.getCredentialSubject().getClaims().get("email")); - } - - private void verifyTokenJwt( - String token, - List includeScopes, - List excludeScopes, - List includeRoles, - List excludeRoles - ) throws Exception { - JsonWebToken jwt = JsonSerialization.readValue(new JWSInput(token).getContent(), JsonWebToken.class); - List wasScopes = Arrays.stream(((String) jwt.getOtherClaims().get("scope")).split("\\s")).toList(); - includeScopes.forEach(it -> assertTrue("Missing scope: " + it, wasScopes.contains(it))); - excludeScopes.forEach(it -> assertFalse("Invalid scope: " + it, wasScopes.contains(it))); - - List allRoles = new ArrayList<>(); - Object realmAccess = jwt.getOtherClaims().get("realm_access"); - if (realmAccess != null) { - var realmRoles = ((Map>) realmAccess).get("roles"); - allRoles.addAll(realmRoles); - } - Object resourceAccess = jwt.getOtherClaims().get("resource_access"); - if (resourceAccess != null) { - var resourceAccessMapping = (Map>>) resourceAccess; - resourceAccessMapping.forEach((k, v) -> { - allRoles.addAll(v.get("roles")); - }); - } - includeRoles.forEach(it -> assertTrue("Missing role: " + it, allRoles.contains(it))); - excludeRoles.forEach(it -> assertFalse("Invalid role: " + it, allRoles.contains(it))); - } -} diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java index 23ab509a45d..d44488db8ec 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java @@ -23,7 +23,6 @@ import java.util.Collections; import java.util.List; import java.util.Set; -import java.util.UUID; import java.util.stream.Collectors; import org.keycloak.events.Details; @@ -36,7 +35,6 @@ import org.keycloak.protocol.oid4vc.model.CredentialsOffer; import org.keycloak.protocol.oid4vc.model.ErrorType; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode; import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation; import org.keycloak.representations.AccessToken; import org.keycloak.representations.idm.ClientRepresentation; @@ -69,7 +67,6 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * Base class for authorization details flow tests. @@ -304,7 +301,7 @@ public void testPreAuthorizedCodeWithAuthorizationDetailsCredentialConfiguration List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); @@ -329,11 +326,6 @@ public void testPreAuthorizedCodeWithAuthorizationDetailsCredentialConfiguration String firstIdentifier = authDetailResponse.getCredentialIdentifiers().get(0); assertNotNull("Identifier should not be null", firstIdentifier); assertFalse("Identifier should not be empty", firstIdentifier.isEmpty()); - try { - UUID.fromString(firstIdentifier); - } catch (IllegalArgumentException e) { - fail("Identifier should be a valid UUID, but was: " + firstIdentifier); - } } @Test @@ -365,7 +357,7 @@ public void testPreAuthorizedCodeWithAuthorizationDetailsAndClaims() throws Exce List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); @@ -415,7 +407,7 @@ public void testPreAuthorizedCodeWithUnsupportedClaims() throws Exception { List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); @@ -446,7 +438,7 @@ public void testPreAuthorizedCodeWithMandatoryClaimMissing() throws Exception { List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); @@ -477,7 +469,7 @@ public void testPreAuthorizedCodeWithComplexClaimsPath() throws Exception { List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); @@ -510,7 +502,7 @@ public void testPreAuthorizedCodeWithInvalidAuthorizationDetails() throws Except List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); @@ -541,7 +533,7 @@ public void testPreAuthorizedCodeWithInvalidClaims() throws Exception { List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); @@ -560,7 +552,7 @@ public void testPreAuthorizedCodeWithEmptyAuthorizationDetails() throws Exceptio // Send empty authorization_details array - should fail AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(List.of()) .send(); @@ -579,7 +571,7 @@ public void testPreAuthorizedCodeWithCredentialOfferBasedAuthorizationDetails() // The system should generate authorization_details based on credential_configuration_ids from the credential offer AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .send(); @@ -604,11 +596,6 @@ public void testPreAuthorizedCodeWithCredentialOfferBasedAuthorizationDetails() String credentialIdentifier = authDetailResponse.getCredentialIdentifiers().get(0); assertNotNull("Identifier should not be null", credentialIdentifier); assertFalse("Identifier should not be empty", credentialIdentifier.isEmpty()); - try { - UUID.fromString(credentialIdentifier); - } catch (IllegalArgumentException e) { - fail("Identifier should be a valid UUID, but was: " + credentialIdentifier); - } } } @@ -617,11 +604,10 @@ public void testPreAuthorizedFlowWithCredentialOfferBasedAuthorizationDetails() String token = getBearerToken(oauth, client, getCredentialClientScope().getName()); Oid4vcTestContext ctx = prepareOid4vcTestContext(token); - PreAuthorizedCode preAuthorizedCode = ctx.credentialsOffer.getGrants().getPreAuthorizedCode(); // Step 1: Request token without authorization_details parameter (no scope needed) AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(preAuthorizedCode.getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .send(); @@ -700,11 +686,10 @@ public void testPreAuthorizedFlowWithCredentialOfferBasedAuthorizationDetails() public void testPreAuthorizedCodeTokenEndpointRestriction() throws Exception { String token = getBearerToken(oauth, client, getCredentialClientScope().getName()); Oid4vcTestContext ctx = prepareOid4vcTestContext(token); - PreAuthorizedCode preAuthorizedCode = ctx.credentialsOffer.getGrants().getPreAuthorizedCode(); // Step 1: Get pre-authorized code token AccessTokenResponse accessTokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(preAuthorizedCode.getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .send(); @@ -801,7 +786,7 @@ public void testMultipleCredentialConfigurationsFromOffer() throws Exception { // Step 1: Request token without authorization_details parameter AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .send(); @@ -831,11 +816,6 @@ public void testMultipleCredentialConfigurationsFromOffer() throws Exception { String credentialIdentifier = authDetail.getCredentialIdentifiers().get(0); assertNotNull("Credential identifier should not be null", credentialIdentifier); assertFalse("Credential identifier should not be empty", credentialIdentifier.isEmpty()); - try { - UUID.fromString(credentialIdentifier); - } catch (IllegalArgumentException e) { - fail("Credential identifier should be a valid UUID, but was: " + credentialIdentifier); - } } // Verify that all credential identifiers are unique @@ -875,7 +855,7 @@ public void testCompleteFlowWithClaimsValidation() throws Exception { List authDetails = List.of(authDetail); AccessTokenResponse tokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(ctx.credentialsOffer.getPreAuthorizedCode()) .endpoint(ctx.openidConfig.getTokenEndpoint()) .authorizationDetails(authDetails) .send(); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java index bfee5d7939a..2d040e60953 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCCredentialOfferCorsTest.java @@ -35,8 +35,7 @@ import org.keycloak.protocol.oid4vc.model.CredentialOfferURI; import org.keycloak.protocol.oid4vc.model.CredentialsOffer; import org.keycloak.protocol.oid4vc.model.ErrorType; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedGrant; +import org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.services.cors.Cors; import org.keycloak.testsuite.AssertEvents; @@ -327,7 +326,7 @@ public void testCredentialOfferWithExpiredNonce() throws Exception { String nonce = testingClient.server(TEST_REALM_NAME).fetchString(session -> { CredentialsOffer credOffer = new CredentialsOffer() .setCredentialIssuer(issuerPath) - .setGrants(new PreAuthorizedGrant().setPreAuthorizedCode(new PreAuthorizedCode().setPreAuthorizedCode("test-code"))) + .addGrant(new PreAuthorizedCodeGrant().setPreAuthorizedCode("test-code")) .setCredentialConfigurationIds(List.of(jwtTypeCredentialConfigurationIdName)); CredentialOfferStorage offerStorage = session.getProvider(CredentialOfferStorage.class); diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java index 2343e60fad7..4260e8225ad 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCIssuerEndpointTest.java @@ -37,6 +37,7 @@ import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; +import java.util.function.Function; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; @@ -130,6 +131,8 @@ import static org.keycloak.jose.jwe.JWEConstants.RSA_OAEP; import static org.keycloak.jose.jwe.JWEConstants.RSA_OAEP_256; import static org.keycloak.models.Constants.CREATE_DEFAULT_CLIENT_SCOPES; +import static org.keycloak.models.oid4vci.CredentialScopeModel.CONFIGURATION_ID; +import static org.keycloak.models.oid4vci.CredentialScopeModel.FORMAT; import static org.keycloak.protocol.oid4vc.issuance.OID4VCIssuerEndpoint.CREDENTIAL_OFFER_URI_CODE_SCOPE; import static org.keycloak.protocol.oid4vc.model.ProofType.JWT; import static org.keycloak.userprofile.DeclarativeUserProfileProvider.UP_COMPONENT_CONFIG_KEY; @@ -348,9 +351,9 @@ protected ClientScopeRepresentation createOptionalClientScope(String scopeName, } }; addAttribute.accept(CredentialScopeModel.ISSUER_DID, issuerDid); - addAttribute.accept(CredentialScopeModel.CONFIGURATION_ID, credentialConfigurationId); + addAttribute.accept(CONFIGURATION_ID, credentialConfigurationId); addAttribute.accept(CredentialScopeModel.CREDENTIAL_IDENTIFIER, credentialIdentifier); - addAttribute.accept(CredentialScopeModel.FORMAT, format); + addAttribute.accept(FORMAT, format); addAttribute.accept(CredentialScopeModel.VCT, Optional.ofNullable(vct).orElse(credentialIdentifier)); if (credentialConfigurationId != null) { String vcDisplay; @@ -554,12 +557,43 @@ protected void setOid4vciEnabled(ClientRepresentation testClient, boolean enable // 2. Using the code to get access token // 3. Get the credential configuration id from issuer metadata at .wellKnown // 4. With the access token, get the credential - protected void testCredentialIssuanceWithAuthZCodeFlow(ClientScopeRepresentation clientScope, + protected void testCredentialIssuanceWithAuthZCodeFlow(ClientScopeRepresentation credScope, BiFunction f, Consumer> c) { - String testScope = clientScope.getName(); - String testFormat = clientScope.getAttributes().get(CredentialScopeModel.FORMAT); - String testCredentialConfigurationId = clientScope.getAttributes().get(CredentialScopeModel.CONFIGURATION_ID); + + // Use credential_identifier if available, otherwise use configuration_id for error testing + String testCredentialConfigurationId = credScope.getAttributes().get(CONFIGURATION_ID); + testCredentialIssuanceWithAuthZCodeFlow(credScope, f, c, (credentialIdentifier) -> { + CredentialRequest request = new CredentialRequest(); + if (credentialIdentifier != null) { + request.setCredentialIdentifier(credentialIdentifier); + } else { + request.setCredentialConfigurationId(testCredentialConfigurationId); + } + return request; + }); + } + + protected void testCredentialIssuanceWithAuthZCodeFlow(ClientScopeRepresentation credScope, + BiFunction f, + Consumer> c, + Function crf) { + String testScope = credScope.getName(); + String testFormat = credScope.getAttributes().get(FORMAT); + String testCredentialConfigurationId = credScope.getAttributes().get(CONFIGURATION_ID); + + // Use credential_identifier if available, otherwise use configuration_id for error testing + if (crf == null) { + crf = (credentialIdentifier) -> { + CredentialRequest request = new CredentialRequest(); + if (credentialIdentifier != null) { + request.setCredentialIdentifier(credentialIdentifier); + } else { + request.setCredentialConfigurationId(testCredentialConfigurationId); + } + return request; + }; + } try (Client client = AdminClientUtil.createResteasyClient()) { String metadataUrl = getRealmMetadataPath(TEST_REALM_NAME); @@ -604,13 +638,7 @@ protected void testCredentialIssuanceWithAuthZCodeFlow(ClientScopeRepresentation URI credentialUri = credentialUriBuilder.build(); WebTarget credentialTarget = clientForCredentialRequest.target(credentialUri); - CredentialRequest request = new CredentialRequest(); - // Use credential_identifier if available, otherwise use configuration_id for error testing - if (credentialIdentifier != null) { - request.setCredentialIdentifier(credentialIdentifier); - } else { - request.setCredentialConfigurationId(testCredentialConfigurationId); - } + CredentialRequest request = crf.apply(credentialIdentifier); assertEquals(testFormat, oid4vciIssuerConfig.getCredentialsSupported() diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointTest.java index c8deb315635..a11191e2940 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCJWTIssuerEndpointTest.java @@ -53,8 +53,7 @@ import org.keycloak.protocol.oid4vc.model.ErrorType; import org.keycloak.protocol.oid4vc.model.JwtProof; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedCode; -import org.keycloak.protocol.oid4vc.model.PreAuthorizedGrant; +import org.keycloak.protocol.oid4vc.model.PreAuthorizedCodeGrant; import org.keycloak.protocol.oid4vc.model.Proofs; import org.keycloak.protocol.oid4vc.model.SupportedCredentialConfiguration; import org.keycloak.protocol.oid4vc.model.VerifiableCredential; @@ -238,7 +237,7 @@ public void testGetCredentialOffer() { authenticator.setTokenString(token); CredentialsOffer credOffer = new CredentialsOffer() .setCredentialIssuer("the-issuer") - .setGrants(new PreAuthorizedGrant().setPreAuthorizedCode(new PreAuthorizedCode().setPreAuthorizedCode("the-code"))) + .addGrant(new PreAuthorizedCodeGrant().setPreAuthorizedCode("the-code")) .setCredentialConfigurationIds(List.of("credential-configuration-id")); CredentialOfferStorage offerStorage = session.getProvider(CredentialOfferStorage.class); @@ -488,7 +487,7 @@ public void testCredentialIssuance() throws Exception { // 5. Get an access token for the pre-authorized code AccessTokenResponse accessTokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(credentialsOffer.getPreAuthorizedCode()) .endpoint(openidConfig.getTokenEndpoint()) .send(); @@ -1224,8 +1223,7 @@ public void testCredentialOfferReplayProtection() { .send() .getCredentialsOffer(); assertNotNull("Credential offer should not be null", credentialsOffer); - assertNotNull("Pre-authorized grant should be present", credentialsOffer.getGrants()); - String preAuthorizedCode = credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode(); + String preAuthorizedCode = credentialsOffer.getPreAuthorizedCode(); assertNotNull("Pre-authorized code value should not be null", preAuthorizedCode); // 3. Second access to the same credential offer URL - should fail with replay protection error @@ -1349,8 +1347,7 @@ public void testPreAuthorizedCodeValidAfterOfferConsumed() { .send() .getCredentialsOffer(); assertNotNull("Credential offer should not be null", credentialsOffer); - assertNotNull("Pre-authorized grant should be present", credentialsOffer.getGrants()); - String preAuthorizedCode = credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode(); + String preAuthorizedCode = credentialsOffer.getPreAuthorizedCode(); assertNotNull("Pre-authorized code value should not be null", preAuthorizedCode); // 3. Immediately perform the Token Request (Pre-Authorized Code Grant) using the valid code diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java index 6cd992dc321..23d12764269 100644 --- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java +++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/oid4vc/issuance/signing/OID4VCSdJwtIssuingEndpointTest.java @@ -412,7 +412,7 @@ public void testCredentialIssuance() throws Exception { // 5. Get an access token for the pre-authorized code AccessTokenResponse accessTokenResponse = oauth.oid4vc() - .preAuthorizedCodeGrantRequest(credentialsOffer.getGrants().getPreAuthorizedCode().getPreAuthorizedCode()) + .preAuthorizedCodeGrantRequest(credentialsOffer.getPreAuthorizedCode()) .endpoint(openidConfig.getTokenEndpoint()) .send();