From 66fdc61c12219afcea3a14ec1f2d1583e6a3b3af Mon Sep 17 00:00:00 2001 From: Thomas Diesler Date: Thu, 29 Jan 2026 10:28:21 +0100 Subject: [PATCH 1/3] [OID4VCI] Initial public client for credential issuance Signed-off-by: Thomas Diesler --- .../oid4vc/issuance/OID4VCIssuerEndpoint.java | 3 +- .../protocol/oid4vc/model/Proofs.java | 43 ++---- .../tests/oid4vc/OID4VCBasicWallet.java | 23 +++ .../tests/oid4vc/OID4VCIssuerTestBase.java | 39 +++-- .../tests/oid4vc/OID4VCProofTestUtils.java | 9 +- .../tests/oid4vc/OID4VCPublicClientTest.java | 145 ++++++++++++++++++ .../tests/oid4vc/OID4VCTestContext.java | 1 - .../OID4VCPublicClientPreAuthTest.java | 113 ++++++++++++++ .../util/oauth/AbstractOAuthClient.java | 4 + 9 files changed, 335 insertions(+), 45 deletions(-) create mode 100644 tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java create mode 100644 tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java 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 79cbafdb43a..c32ca580e9a 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 @@ -960,8 +960,7 @@ public Response requestCredential(String requestPayload) { String proofType = originalProofs != null ? originalProofs.getProofType() : null; for (String currentProof : allProofs) { - Proofs proofForIteration = new Proofs(); - proofForIteration.setProofByType(proofType, currentProof); + Proofs proofForIteration = Proofs.create(proofType, currentProof); // Creating credential with keybinding to the current proof credentialRequest.setProofs(proofForIteration); Object theCredential = getCredential(authResult, supportedCredential, tokenAuthDetail, credentialRequest, eventBuilder); diff --git a/services/src/main/java/org/keycloak/protocol/oid4vc/model/Proofs.java b/services/src/main/java/org/keycloak/protocol/oid4vc/model/Proofs.java index b145d471309..e57089c6d73 100644 --- a/services/src/main/java/org/keycloak/protocol/oid4vc/model/Proofs.java +++ b/services/src/main/java/org/keycloak/protocol/oid4vc/model/Proofs.java @@ -42,15 +42,6 @@ public class Proofs { @JsonProperty("attestation") private List attestation; - public Proofs() { - } - - public Proofs(List jwt, List diVp, List attestation) { - this.jwt = jwt; - this.diVp = diVp; - this.attestation = attestation; - } - public List getJwt() { return jwt; } @@ -78,6 +69,23 @@ public Proofs setAttestation(List attestation) { return this; } + /** + * Create proofs based on the proof type. + * Sets the appropriate field (JWT or Attestation) depending on the proof type. + * + * @param proofType the proof type (ProofType.JWT or ProofType.ATTESTATION) + * @param proof the proof value to set + */ + public static Proofs create(String proofType, String proof) { + Proofs proofs = new Proofs(); + if (ProofType.JWT.equals(proofType)) { + proofs.setJwt(List.of(proof)); + } else if (ProofType.ATTESTATION.equals(proofType)) { + proofs.setAttestation(List.of(proof)); + } + return proofs; + } + /** * Determines the proof type based on which field is populated. * Checks JWT first, then Attestation. @@ -94,23 +102,6 @@ public String getProofType() { return null; } - /** - * Sets the proof value based on the proof type. - * Sets the appropriate field (JWT or Attestation) depending on the proof type. - * - * @param proofType the proof type (ProofType.JWT or ProofType.ATTESTATION) - * @param proof the proof value to set - * @return this instance for method chaining - */ - public Proofs setProofByType(String proofType, String proof) { - if (ProofType.JWT.equals(proofType)) { - setJwt(List.of(proof)); - } else if (ProofType.ATTESTATION.equals(proofType)) { - setAttestation(List.of(proof)); - } - return this; - } - /** * Returns all proof values as a list. * Checks JWT proofs first, then Attestation proofs. 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 index 7fabb5cace3..dc635b3cdd5 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java @@ -12,6 +12,7 @@ import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.admin.client.resource.UserResource; +import org.keycloak.crypto.KeyWrapper; import org.keycloak.jose.jws.JWSHeader; import org.keycloak.jose.jws.JWSInput; import org.keycloak.jose.jws.JWSInputException; @@ -22,6 +23,8 @@ 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.protocol.oid4vc.model.ProofType; +import org.keycloak.protocol.oid4vc.model.Proofs; import org.keycloak.representations.JsonWebToken; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testframework.oauth.OAuthClient; @@ -44,7 +47,9 @@ import static org.keycloak.constants.OID4VCIConstants.CREDENTIAL_OFFER_CREATE; import static org.keycloak.tests.oid4vc.OID4VCIssuerTestBase.TEST_PASSWORD; import static org.keycloak.tests.oid4vc.OID4VCIssuerTestBase.VCTestRealmConfig.TEST_REALM_NAME; +import static org.keycloak.tests.oid4vc.OID4VCProofTestUtils.createEcKeyPair; import static org.keycloak.tests.oid4vc.OID4VCTestContext.ACCESS_TOKEN_RESPONSE_ATTACHMENT_KEY; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.AttachmentKey; 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; @@ -188,6 +193,24 @@ public AuthorizationEndpointResponse send(String username, String password) { return request; } + public Proofs generateJwtProof(OID4VCTestContext ctx, String user) { + String aud = getIssuerMetadata(ctx).getCredentialIssuer(); + String nonce = oauth.oid4vc().nonceRequest().send().getNonce(); + KeyWrapper kw = getECKeyPair(ctx, user, null); + return Proofs.create(ProofType.JWT, OID4VCProofTestUtils.generateJwtProof(aud, kw, nonce)); + } + + public KeyWrapper getECKeyPair(OID4VCTestContext ctx, String user, String keyId) { + String cacheKey = user + (keyId != null ? "_" + keyId : ""); + AttachmentKey attachmentKey = new AttachmentKey<>(cacheKey, KeyWrapper.class); + KeyWrapper kw = ctx.getAttachment(attachmentKey); + if (kw == null) { + kw = createEcKeyPair(); + ctx.putAttachment(attachmentKey, kw); + } + return kw; + } + public AccessTokenRequest accessTokenRequest(OID4VCTestContext ctx, String authCode) { AccessTokenRequest request = new AccessTokenRequest(oauth, authCode) { public AccessTokenResponse send() { diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java index 7e76fa644e5..7da42728cd8 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java @@ -24,8 +24,6 @@ import org.keycloak.VCFormat; import org.keycloak.admin.client.Keycloak; import org.keycloak.admin.client.resource.ClientResource; -import org.keycloak.admin.client.resource.ClientScopeResource; -import org.keycloak.admin.client.resource.ClientScopesResource; import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.common.Profile; import org.keycloak.common.crypto.CryptoIntegration; @@ -105,7 +103,8 @@ public abstract class OID4VCIssuerTestBase { protected final Logger log = Logger.getLogger(getClass()); - public static final String OID4VCI_CLIENT_ID = "oid4vci-client"; + public static final String OID4VCI_CLIENT_ID = "oid4vci-test"; + public static final String OID4VCI_PUBLIC_CLIENT_ID = "oid4vci-test-pub"; public static final URI ISSUER_DID = URI.create("did:web:test.org"); public static final String TEST_CREDENTIAL_MAPPERS_FILE = "/oid4vc/test-credential-mappers.json"; public static final String TEST_USER = "john"; @@ -123,9 +122,12 @@ public abstract class OID4VCIssuerTestBase { @InjectRealm(config = VCTestRealmConfig.class) protected ManagedRealm testRealm; - @InjectClient(ref = "oid4vci-client", config = OID4VCIClient.class) + @InjectClient(ref = "oid4vci-client", config = ConfidentialOID4VCIClient.class) protected ManagedClient managedClient; + @InjectClient(ref = OID4VCI_PUBLIC_CLIENT_ID, config = PublicOID4VCIClient.class) + ManagedClient managedPublicClient; + @InjectOAuthClient protected OAuthClient oauth; @@ -150,6 +152,7 @@ public abstract class OID4VCIssuerTestBase { protected String clientId = "test-app"; protected ClientRepresentation client; + protected ClientRepresentation pubClient; @TestSetup public void configureTestRealm() { @@ -164,6 +167,7 @@ public void configureTestRealm() { @BeforeEach void beforeEachInternal() { client = managedClient.admin().toRepresentation(); + pubClient = managedPublicClient.admin().toRepresentation(); jwtTypeCredentialScope = requireExistingCredentialScope(jwtTypeCredentialScopeName); minimalJwtTypeCredentialScope = requireExistingCredentialScope(minimalJwtTypeCredentialScopeName); @@ -323,12 +327,6 @@ protected CredentialScopeRepresentation requireExistingCredentialScope(String sc .orElseThrow(() -> new IllegalStateException("No such credential scope: " + scopeName)); } - protected void updateCredentialScope(CredentialScopeRepresentation clientScope) { - ClientScopesResource clientScopesResource = testRealm.admin().clientScopes(); - ClientScopeResource clientScopeResource = clientScopesResource.get(clientScope.getId()); - clientScopeResource.update(clientScope); - } - // Private --------------------------------------------------------------------------------------------------------- private ComponentRepresentation createRsaKeyProviderComponent(KeyWrapper keyWrapper, String name, int priority) { @@ -394,7 +392,8 @@ public RealmConfigBuilder configure(RealmConfigBuilder realm) { realm.verifiableCredentialsEnabled(true); realm.addRole(CREDENTIAL_OFFER_CREATE); - realm.attribute(CREATE_DEFAULT_CLIENT_SCOPES, String.valueOf(true)); + // Allow the default client scopes to be added as well + realm.attribute(CREATE_DEFAULT_CLIENT_SCOPES, "true"); // Explicitly enable cryptographic binding + proof types for test credential configurations. // The issuer metadata only advertises binding/proofs when it is explicitly configured as required. @@ -544,19 +543,33 @@ private List resolveProtocolMappers(String protoco } } - public static class OID4VCIClient implements ClientConfig { + public static class ConfidentialOID4VCIClient implements ClientConfig { @Override public ClientConfigBuilder configure(ClientConfigBuilder client) { client.clientId(OID4VCI_CLIENT_ID) .serviceAccountsEnabled(true) .directAccessGrantsEnabled(true) - .attribute(OID4VCI_ENABLED_ATTRIBUTE_KEY, "true") .defaultClientScopes("basic", "profile", "roles") .optionalClientScopes(jwtTypeCredentialScopeName, minimalJwtTypeCredentialScopeName, sdJwtTypeCredentialScopeName, "email") + .attribute(OID4VCI_ENABLED_ATTRIBUTE_KEY, "true") .redirectUris("*") .secret("test-secret"); + return client; + } + } + + public static class PublicOID4VCIClient implements ClientConfig { + @Override + public ClientConfigBuilder configure(ClientConfigBuilder client) { + client.clientId(OID4VCI_PUBLIC_CLIENT_ID) + .publicClient(true) + .defaultClientScopes("basic", "profile", "roles") + .optionalClientScopes(jwtTypeCredentialScopeName, minimalJwtTypeCredentialScopeName, sdJwtTypeCredentialScopeName, "email") + .redirectUris("http://127.0.0.1:8500/callback/oauth") + .attribute(OID4VCI_ENABLED_ATTRIBUTE_KEY, "true") + .attribute("pkce.code.challenge.method", "S256"); // require PKCE return client; } } diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java index 841b562296d..d68f59fa9ae 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java @@ -30,7 +30,10 @@ public static Proofs jwtProofs(String audience, String nonce) { } public static String generateJwtProof(String audience, String nonce) { - KeyWrapper keyWrapper = getEcKey(); + return generateJwtProof(audience, createEcKeyPair(), nonce); + } + + public static String generateJwtProof(String audience, KeyWrapper keyWrapper, String nonce) { keyWrapper.setKid(null); JWK jwk = JWKBuilder.create().ec(keyWrapper.getPublicKey()); @@ -85,14 +88,14 @@ public static String generateAttestationProof( } public static KeyWrapper newEcSigningKey(String keyId) { - KeyWrapper kw = getEcKey(); + KeyWrapper kw = createEcKeyPair(); if (keyId != null && !keyId.isBlank()) { kw.setKid(keyId); } return kw; } - private static KeyWrapper getEcKey() { + public static KeyWrapper createEcKeyPair() { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", BouncyIntegration.PROVIDER); kpg.initialize(256); diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java new file mode 100644 index 00000000000..bb8734a2873 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java @@ -0,0 +1,145 @@ +/* + * 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.tests.oid4vc; + +import java.net.URI; +import java.util.List; + +import org.keycloak.TokenVerifier; +import org.keycloak.protocol.oid4vc.model.CredentialIssuer; +import org.keycloak.protocol.oid4vc.model.CredentialResponse; +import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; +import org.keycloak.protocol.oid4vc.model.VerifiableCredential; +import org.keycloak.representations.JsonWebToken; +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.testsuite.util.oauth.PkceGenerator; +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.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + + +/** + * An external wallet would generally not be trusted to keep the client_secret + * oid4vci clients should be configured as public with pkce enabled + */ +@KeycloakIntegrationTest(config = VCTestServerConfig.class) +public class OID4VCPublicClientTest extends OID4VCIssuerTestBase { + + OID4VCBasicWallet wallet; + + @BeforeEach + void beforeEach() { + wallet = new OID4VCBasicWallet(keycloak, oauth); + + // Reconfigure OAuthClient + oauth.client(pubClient.getClientId(), null); + } + + @AfterEach + void afterEach() { + wallet.logout(); + } + + @Test + public void testCredentialFromPublicClient() throws Exception { + + var ctx = new OID4VCTestContext(pubClient, jwtTypeCredentialScope); + + PkceGenerator pkce = PkceGenerator.s256(); + + CredentialIssuer issuerMetadata = wallet.getIssuerMetadata(ctx); + + OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); + authDetail.setType(OPENID_CREDENTIAL); + authDetail.setCredentialConfigurationId(ctx.getCredConfigId()); + authDetail.setLocations(List.of(issuerMetadata.getCredentialIssuer())); + + // Send AuthorizationRequest + // + AuthorizationEndpointResponse authResponse = wallet + .authorizationRequest() + .scope(ctx.getCredScopeName()) + .authorizationDetails(authDetail) + .codeChallenge(pkce) + .send(ctx.getHolder(), "password"); + String authCode = authResponse.getCode(); + + // Build and send AccessTokenRequest + // + AccessTokenResponse tokenResponse = wallet.accessTokenRequest(ctx, authCode) + .codeVerifier(pkce) + .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) + .proofs(wallet.generateJwtProof(ctx, ctx.getHolder())) + .send().getCredentialResponse(); + + verifyCredentialResponse(ctx, ctx.getHolder(), credResponse); + } + + @Test + public void testAuthorizationRequestNoPkce() throws Exception { + + var ctx = new OID4VCTestContext(pubClient, jwtTypeCredentialScope); + + // Send AuthorizationRequest + // + AuthorizationEndpointResponse authResponse = wallet + .authorizationRequest() + .scope(ctx.getCredScopeName()) + .send(ctx.getHolder(), "password"); + + assertEquals("invalid_request", authResponse.getError()); + assertEquals("Missing parameter: code_challenge_method", authResponse.getErrorDescription()); + } + + // Private --------------------------------------------------------------------------------------------------------- + + private void verifyCredentialResponse(OID4VCTestContext ctx, String expUser, CredentialResponse credResponse) throws Exception { + + String scope = ctx.getCredScopeName(); + 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 index 1e49f3d6c5b..66a0337eb38 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java @@ -46,7 +46,6 @@ public class OID4VCTestContext { public OID4VCTestContext(ClientRepresentation client, CredentialScopeRepresentation credentialScope) { this.client = client; - this.clientId = client.getClientId(); this.issuer = "john"; this.holder = "alice"; this.credentialScope = credentialScope; diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java new file mode 100644 index 00000000000..7017a396fb7 --- /dev/null +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java @@ -0,0 +1,113 @@ +/* + * 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.tests.oid4vc.preauth; + +import java.net.URI; +import java.util.List; + +import org.keycloak.TokenVerifier; +import org.keycloak.protocol.oid4vc.model.CredentialResponse; +import org.keycloak.protocol.oid4vc.model.CredentialsOffer; +import org.keycloak.protocol.oid4vc.model.VerifiableCredential; +import org.keycloak.representations.JsonWebToken; +import org.keycloak.testframework.annotations.KeycloakIntegrationTest; +import org.keycloak.tests.oid4vc.OID4VCBasicWallet; +import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase; +import org.keycloak.tests.oid4vc.OID4VCTestContext; +import org.keycloak.testsuite.util.oauth.AccessTokenResponse; +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.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + + +/** + * An external wallet would generally not be trusted to keep the client_secret + * oid4vci clients should be configured as public with pkce enabled + */ +@KeycloakIntegrationTest(config = OID4VCIssuerTestBase.VCTestServerWithPreAuthCodeEnabled.class) +public class OID4VCPublicClientPreAuthTest extends OID4VCIssuerTestBase { + + OID4VCBasicWallet wallet; + + @BeforeEach + void beforeEach() { + wallet = new OID4VCBasicWallet(keycloak, oauth); + + // Reconfigure OAuthClient + oauth.client(pubClient.getClientId(), null); + } + + @AfterEach + void afterEach() { + wallet.logout(); + } + + @Test + public void testCredentialFromPreAuthCode() throws Exception { + + var ctx = new OID4VCTestContext(pubClient, jwtTypeCredentialScope); + + // Create Pre-Authorized CredentialOffer + // + CredentialsOffer credOffer = wallet.createPreAuthCredentialOffer(ctx, ctx.getHolder()); + String preAuthCode = credOffer.getPreAuthorizedCode(); + + // Redeem Pre-Authorized Code for AccessToken + // + AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode).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) + .proofs(wallet.generateJwtProof(ctx, ctx.getHolder())) + .send().getCredentialResponse(); + + verifyCredentialResponse(ctx, ctx.getHolder(), credResponse); + } + + // Private --------------------------------------------------------------------------------------------------------- + + private void verifyCredentialResponse(OID4VCTestContext ctx, String expUser, CredentialResponse credResponse) throws Exception { + + String scope = ctx.getCredScopeName(); + 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/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AbstractOAuthClient.java b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AbstractOAuthClient.java index 7442a71ec2f..fff0ac51698 100644 --- a/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AbstractOAuthClient.java +++ b/tests/utils-shared/src/main/java/org/keycloak/testsuite/util/oauth/AbstractOAuthClient.java @@ -306,6 +306,10 @@ public T driver(WebDriver webDriver) { return client(); } + public WebDriver getDriver() { + return driver; + } + public HttpClientManager httpClient() { return httpClientManager; } From 5bd4356b7fb4cd2fafcde33ee2ead207b30374a4 Mon Sep 17 00:00:00 2001 From: Thomas Diesler Date: Fri, 27 Mar 2026 19:25:27 +0100 Subject: [PATCH 2/3] -- revisit OID4VCTestContext convenience methods Signed-off-by: Thomas Diesler --- .../tests/oid4vc/OID4VCActionTest.java | 4 +- .../tests/oid4vc/OID4VCBasicWallet.java | 155 +++++++++++------- .../tests/oid4vc/OID4VCIssuerTestBase.java | 13 +- .../tests/oid4vc/OID4VCPublicClientTest.java | 36 ++-- .../tests/oid4vc/OID4VCTestContext.java | 41 ++--- .../OID4VCredentialOfferAuthCodeTest.java | 40 ++--- .../OID4VCAuthorizationCodeFlowTestBase.java | 23 ++- ...ID4VCAuthorizationDetailsFlowTestBase.java | 3 +- .../preauth/JwtPreAuthCodeHandlerTest.java | 19 +-- .../preauth/OID4VCActionPreAuthTest.java | 5 +- .../OID4VCPublicClientPreAuthTest.java | 17 +- .../OID4VCredentialOfferPreAuthTest.java | 20 +-- 12 files changed, 180 insertions(+), 196 deletions(-) diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCActionTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCActionTest.java index c1722fc4f30..670a40bd7e6 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCActionTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCActionTest.java @@ -53,11 +53,9 @@ public class OID4VCActionTest extends OID4VCIssuerTestBase { ManagedUser user; OID4VCTestContext ctx; - OID4VCBasicWallet wallet; @BeforeEach void beforeEach() { - wallet = new OID4VCBasicWallet(keycloak, oauth); ctx = new OID4VCTestContext(client, minimalJwtTypeCredentialScope); user.admin().logout(); } @@ -134,7 +132,7 @@ public void testCredentialOfferAIASuccess_authorizationCodeFlow() throws Excepti // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .issuerState(issuerState) .send(user.getUsername(), "password"); String authCode = authResponse.getCode(); 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 index dc635b3cdd5..5672f0ca47f 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCBasicWallet.java @@ -25,10 +25,10 @@ import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; import org.keycloak.protocol.oid4vc.model.ProofType; import org.keycloak.protocol.oid4vc.model.Proofs; +import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation; 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; @@ -49,9 +49,10 @@ import static org.keycloak.tests.oid4vc.OID4VCIssuerTestBase.VCTestRealmConfig.TEST_REALM_NAME; import static org.keycloak.tests.oid4vc.OID4VCProofTestUtils.createEcKeyPair; import static org.keycloak.tests.oid4vc.OID4VCTestContext.ACCESS_TOKEN_RESPONSE_ATTACHMENT_KEY; +import static org.keycloak.tests.oid4vc.OID4VCTestContext.AUTHORIZATION_SERVER_METADATA_ATTACHMENT_KEY; import static org.keycloak.tests.oid4vc.OID4VCTestContext.AttachmentKey; 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.CREDENTIALS_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; @@ -74,8 +75,8 @@ */ public class OID4VCBasicWallet { - final Keycloak keycloak; - final OAuthClient oauth; + private final Keycloak keycloak; + private final OAuthClient oauth; final Set loginUsers = new HashSet<>(); @@ -84,25 +85,26 @@ public OID4VCBasicWallet(Keycloak keycloak, OAuthClient oauth) { this.oauth = oauth; } - // Composite Actions ----------------------------------------------------------------------------------------------- - - public CredentialsOffer createAuthCodeCredentialOffer(OID4VCTestContext ctx, String targetUser) { + /** + * A composite action to create a credential offer with 'authorization_code' grant + */ + public CredentialsOffer createCredentialOfferAuthCode(OID4VCTestContext ctx, String targetUser) { // Get Issuer AccessToken // - AccessTokenResponse issTokenResponse = getIssuerAccessToken(ctx.getIssuer()); + AccessTokenResponse issTokenResponse = getAccessToken(ctx.getIssuer()); // Exclude scope: // Require role: credential-offer-create String issToken = validateIssuerAccessToken(issTokenResponse, - List.of(), List.of(ctx.getCredScopeName()), + List.of(), List.of(ctx.getScope()), List.of(CREDENTIAL_OFFER_CREATE.getName()), List.of()); // Create Authorized Code CredentialOffer // CredentialOfferURI credOfferUri; try { - credOfferUri = createCredentialOffer(ctx, ctx.getCredConfigId()) + credOfferUri = createCredentialOffer(ctx, ctx.getCredentialConfigurationId()) .preAuthorized(false) .targetUser(targetUser) .bearerToken(issToken) @@ -113,7 +115,7 @@ public CredentialsOffer createAuthCodeCredentialOffer(OID4VCTestContext ctx, Str // Fetch the CredentialsOffer // - CredentialsOffer credOffer = getCredentialOffer(ctx, credOfferUri) + CredentialsOffer credOffer = credentialsOfferRequest(ctx, credOfferUri) .send().getCredentialsOffer(); String issuerState = credOffer.getIssuerState(); @@ -122,24 +124,27 @@ public CredentialsOffer createAuthCodeCredentialOffer(OID4VCTestContext ctx, Str return credOffer; } - public CredentialsOffer createPreAuthCredentialOffer(OID4VCTestContext ctx, String targetUser) { + /** + * A composite actions to create a credential offer with 'pre-authorized_code' grant + */ + public CredentialsOffer createCredentialOfferPreAuth(OID4VCTestContext ctx, String targetUser) { // Get Issuer AccessToken // - AccessTokenResponse issTokenResponse = getIssuerAccessToken(ctx.getIssuer()); + AccessTokenResponse issTokenResponse = getAccessToken(ctx.getIssuer()); assertNotNull(issTokenResponse.getAccessToken(), "No accessToken"); // Exclude scope: // Require role: credential-offer-create String issToken = validateIssuerAccessToken(issTokenResponse, - List.of(), List.of(ctx.getCredScopeName()), + List.of(), List.of(ctx.getScope()), List.of(CREDENTIAL_OFFER_CREATE.getName()), List.of()); // Create Pre-Authorized CredentialOffer // CredentialOfferURI credOfferUri; try { - credOfferUri = createCredentialOffer(ctx, ctx.getCredConfigId()) + credOfferUri = createCredentialOffer(ctx, ctx.getCredentialConfigurationId()) .preAuthorized(true) .targetUser(targetUser) .bearerToken(issToken) @@ -150,7 +155,7 @@ public CredentialsOffer createPreAuthCredentialOffer(OID4VCTestContext ctx, Stri // Fetch the CredentialsOffer // - CredentialsOffer credOffer = getCredentialOffer(ctx, credOfferUri) + CredentialsOffer credOffer = credentialsOfferRequest(ctx, credOfferUri) .send().getCredentialsOffer(); String preAuthCode = credOffer.getPreAuthorizedCode(); @@ -159,32 +164,48 @@ public CredentialsOffer createPreAuthCredentialOffer(OID4VCTestContext ctx, Stri 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()); + ctx.putAttachment(CREDENTIALS_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 AccessTokenResponse getAccessToken(String username, String... scope) { + PkceGenerator pkce = PkceGenerator.s256(); + AuthorizationEndpointResponse authResponse = authorizationRequest() + .scope(scope) + .codeChallenge(pkce) + .send(username, TEST_PASSWORD); + String authCode = authResponse.getCode(); + assertNotNull(authCode, "No auth code"); + AccessTokenResponse tokenResponse = oauth.accessTokenRequest(authCode) + .codeVerifier(pkce) + .send(); + assertNotNull(tokenResponse.getAccessToken(), "No AccessToken"); + return tokenResponse; + } + + public CredentialIssuer getIssuerMetadata(OID4VCTestContext ctx) { + var issuerMetadata = Optional.ofNullable(ctx.getAttachment(ISSUER_METADATA_ATTACHMENT_KEY)) + .orElse(oauth.oid4vc().doIssuerMetadataRequest().getMetadata()); + ctx.putAttachment(ISSUER_METADATA_ATTACHMENT_KEY, issuerMetadata); + return issuerMetadata; + } + + public OIDCConfigurationRepresentation getAuthorizationServerMetadata(OID4VCTestContext ctx) { + var authServerMetadata = Optional.ofNullable(ctx.getAttachment(AUTHORIZATION_SERVER_METADATA_ATTACHMENT_KEY)) + .orElse(oauth.doWellKnownRequest()); + ctx.putAttachment(AUTHORIZATION_SERVER_METADATA_ATTACHMENT_KEY, authServerMetadata); + return authServerMetadata; } public AuthorizationEndpointRequest authorizationRequest() { - AuthorizationEndpointRequest request = new AuthorizationEndpointRequest(oauth) { + AuthorizationEndpointRequest request = new AuthorizationEndpointRequest() { public AuthorizationEndpointResponse send(String username, String password) { loginUsers.add(username); return super.send(username, password); @@ -222,7 +243,7 @@ public AccessTokenResponse send() { return request; } - public PreAuthorizedCodeGrantRequest preAuthAccessTokenRequest(OID4VCTestContext ctx, String preAuthCode) { + public PreAuthorizedCodeGrantRequest accessTokenRequestPreAuth(OID4VCTestContext ctx, String preAuthCode) { PreAuthorizedCodeGrantRequest request = new PreAuthorizedCodeGrantRequest(oauth, preAuthCode) { public AccessTokenResponse send() { AccessTokenResponse response = super.send(); @@ -233,6 +254,17 @@ public AccessTokenResponse send() { return request; } + public CredentialOfferRequest credentialsOfferRequest(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 Oid4vcCredentialRequest credentialRequest(OID4VCTestContext ctx, String accessToken) { Oid4vcCredentialRequest request = new Oid4vcCredentialRequest(oauth, new CredentialRequest()) { public Oid4vcCredentialResponse send() { @@ -246,28 +278,6 @@ public Oid4vcCredentialResponse send() { return request; } - public AccessTokenResponse getIssuerAccessToken(String username) { - PkceGenerator pkce = PkceGenerator.s256(); - AuthorizationEndpointResponse authResponse = authorizationRequest() - .codeChallenge(pkce) - .send(username, TEST_PASSWORD); - - String authCode = authResponse.getCode(); - assertNotNull(authCode, "Authorization code (issuer) should not be null"); - AccessTokenResponse tokenResponse = oauth.accessTokenRequest(authCode) - .codeVerifier(pkce) - .send(); - assertNotNull(tokenResponse.getAccessToken(), "Issuer AccessToken should not be null"); - 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; - } - /** * Terminates all active user sessions tracked by this wallet instance. * Recommended to be called in {@code @AfterEach} methods. @@ -387,20 +397,39 @@ public String validateHolderAccessToken(OID4VCTestContext ctx, AccessTokenRespon assertEquals(1, jwtAuthDetails.size(), "Expected one authorization_details entry"); var jwtAuthDetail = jwtAuthDetails.get(0); - assertEquals(ctx.getCredConfigId(), tokenAuthDetail.getCredentialConfigurationId()); + assertEquals(ctx.getCredentialConfigurationId(), tokenAuthDetail.getCredentialConfigurationId()); assertEquals(tokenAuthDetail, jwtAuthDetail); return accessToken; } - public static class AuthorizationEndpointRequest { + /** + * The Authorization request/response follows the known pattern that we have for other message exchanges on + * 'OID4VCClient'. The response does not only capture a successful authorization, but (like the other APIs) + * also error cases, like ... + * + * - login page does not get displayed, because of an invalid request + * - invalid credentials on login page (i.e. redirect url without code) + * + * In all three cases (i.e. success + 2x error cases), we like to return a response as soon as we have it, + * instead of waiting for a timeout like we currently have with authorization through the 'OAuthClient'. + * + * This API also abstracts to the low level details of web driver and login forms that are specific for the interactive + * Authorization Code Flow. In future, we can use the same API for non-interactive flows (e.g. as required by EBSI) + * + * Historically, this Authorization request abstractions was with the 'OID4VCClient', rather than with the 'OAuthClient' + * because we did not want to expose all Keycloak tests to go through this still experimental code. It never got + * approved there and is now only available through the Wallet. We can assume that code similar to this would be found + * in a real OID4VCI Wallet. + * + * 'OID4VCPublicClientTest' covers authorization success and the error cases. + */ + public class AuthorizationEndpointRequest { - protected final AbstractOAuthClient client; protected final LoginUrlBuilder loginForm; - public AuthorizationEndpointRequest(AbstractOAuthClient client) { - this.client = client; - this.loginForm = client.loginForm(); + public AuthorizationEndpointRequest() { + this.loginForm = oauth.loginForm(); } public AuthorizationEndpointRequest authorizationDetails(OID4VCAuthorizationDetail authDetail) { @@ -424,7 +453,9 @@ public AuthorizationEndpointRequest request(String request) { } public AuthorizationEndpointRequest scope(String... scopes) { - loginForm.scope(scopes); + if (scopes != null && scopes.length > 0) { + loginForm.scope(scopes); + } return this; } @@ -433,9 +464,11 @@ public void openLoginForm() { } public AuthorizationEndpointResponse send(String username, String password) { + // [TODO #47649] OAuthClient cannot handle invalid authorization requests + // https://github.com/keycloak/keycloak/issues/47649 openLoginForm(); - client.fillLoginForm(username, password); - return client.parseLoginResponse(); + oauth.fillLoginForm(username, password); + return oauth.parseLoginResponse(); } } } diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java index 7da42728cd8..919ffd3357f 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerTestBase.java @@ -85,6 +85,7 @@ import org.keycloak.util.JsonSerialization; import org.jboss.logging.Logger; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import static org.keycloak.OID4VCConstants.CLAIM_NAME_SUBJECT_ID; @@ -153,6 +154,7 @@ public abstract class OID4VCIssuerTestBase { protected String clientId = "test-app"; protected ClientRepresentation client; protected ClientRepresentation pubClient; + protected OID4VCBasicWallet wallet; @TestSetup public void configureTestRealm() { @@ -165,7 +167,7 @@ public void configureTestRealm() { } @BeforeEach - void beforeEachInternal() { + void beforeEachBase() { client = managedClient.admin().toRepresentation(); pubClient = managedPublicClient.admin().toRepresentation(); @@ -175,6 +177,15 @@ void beforeEachInternal() { oauth.client(client.getClientId(), client.getSecret()); enableVerifiableCredentialEvents(testRealm); + + wallet = new OID4VCBasicWallet(keycloak, oauth); + } + + @AfterEach + void afterEachBase() { + wallet.logout(); + driver.cookies().deleteAll(); + driver.open("about:blank"); } protected CredentialScopeRepresentation getExistingCredentialScope(String scopeName) { diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java index bb8734a2873..aa22ccb6aeb 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java @@ -33,7 +33,6 @@ import org.keycloak.testsuite.util.oauth.PkceGenerator; import org.keycloak.util.JsonSerialization; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -41,6 +40,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** @@ -50,21 +50,12 @@ @KeycloakIntegrationTest(config = VCTestServerConfig.class) public class OID4VCPublicClientTest extends OID4VCIssuerTestBase { - OID4VCBasicWallet wallet; - @BeforeEach void beforeEach() { - wallet = new OID4VCBasicWallet(keycloak, oauth); - // Reconfigure OAuthClient oauth.client(pubClient.getClientId(), null); } - @AfterEach - void afterEach() { - wallet.logout(); - } - @Test public void testCredentialFromPublicClient() throws Exception { @@ -76,14 +67,14 @@ public void testCredentialFromPublicClient() throws Exception { OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); authDetail.setType(OPENID_CREDENTIAL); - authDetail.setCredentialConfigurationId(ctx.getCredConfigId()); + authDetail.setCredentialConfigurationId(ctx.getCredentialConfigurationId()); authDetail.setLocations(List.of(issuerMetadata.getCredentialIssuer())); // Send AuthorizationRequest // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .authorizationDetails(authDetail) .codeChallenge(pkce) .send(ctx.getHolder(), "password"); @@ -110,6 +101,23 @@ public void testCredentialFromPublicClient() throws Exception { verifyCredentialResponse(ctx, ctx.getHolder(), credResponse); } + @Test + public void testAuthorizationRequestSuccess() throws Exception { + + var ctx = new OID4VCTestContext(pubClient, jwtTypeCredentialScope); + + // Send AuthorizationRequest with PKCE + // + AuthorizationEndpointResponse authResponse = wallet + .authorizationRequest() + .scope(ctx.getScope()) + .codeChallenge(PkceGenerator.s256()) + .send(ctx.getHolder(), "password"); + + assertNull(authResponse.getError(), "No error"); + assertNotNull(authResponse.getCode(), "Has auth code"); + } + @Test public void testAuthorizationRequestNoPkce() throws Exception { @@ -119,7 +127,7 @@ public void testAuthorizationRequestNoPkce() throws Exception { // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .send(ctx.getHolder(), "password"); assertEquals("invalid_request", authResponse.getError()); @@ -130,7 +138,7 @@ public void testAuthorizationRequestNoPkce() throws Exception { private void verifyCredentialResponse(OID4VCTestContext ctx, String expUser, CredentialResponse credResponse) throws Exception { - String scope = ctx.getCredScopeName(); + String scope = ctx.getScope(); CredentialResponse.Credential credentialObj = credResponse.getCredentials().get(0); assertNotNull(credentialObj, "The first credential in the array should not be null"); 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 index 66a0337eb38..7854604feff 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCTestContext.java @@ -13,6 +13,7 @@ import org.keycloak.protocol.oid4vc.model.CredentialScopeRepresentation; import org.keycloak.protocol.oid4vc.model.CredentialsOffer; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; +import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; @@ -27,17 +28,15 @@ */ public class OID4VCTestContext { + static final AttachmentKey AUTHORIZATION_SERVER_METADATA_ATTACHMENT_KEY = new AttachmentKey<>(OIDCConfigurationRepresentation.class); 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_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); - private String clientId; private String issuer; // Issuing username (i.e. agent who creates credential offers) private String holder; // Holder who requests the credential - private String credConfigId; - private String credScopeName; private ClientRepresentation client; private CredentialScopeRepresentation credentialScope; @@ -49,8 +48,6 @@ public OID4VCTestContext(ClientRepresentation client, CredentialScopeRepresentat this.issuer = "john"; this.holder = "alice"; this.credentialScope = credentialScope; - this.credScopeName = credentialScope.getName(); - this.credConfigId = credentialScope.getCredentialConfigurationId(); } public List getAuthorizedCredentialIdentifiers() { @@ -92,14 +89,6 @@ public void setClient(ClientRepresentation client) { this.client = client; } - public String getClientId() { - return clientId; - } - - public void setClientId(String clientId) { - this.clientId = clientId; - } - public String getIssuer() { return issuer; } @@ -116,28 +105,24 @@ public void setHolder(String holder) { this.holder = holder; } - public String getCredConfigId() { - return credConfigId; - } - - public void setCredConfigId(String credConfigId) { - this.credConfigId = credConfigId; + public CredentialScopeRepresentation getCredentialScope() { + return credentialScope; } - public String getCredScopeName() { - return credScopeName; + public void setCredentialScope(CredentialScopeRepresentation credentialScope) { + this.credentialScope = credentialScope; } - public void setCredScopeName(String credScopeName) { - this.credScopeName = credScopeName; + public String getCredentialConfigurationId() { + return credentialScope.getCredentialConfigurationId(); } - public CredentialScopeRepresentation getCredentialScope() { - return credentialScope; + public String getCredentialIdentifier() { + return credentialScope.getCredentialIdentifier(); } - public void setCredentialScope(CredentialScopeRepresentation credentialScope) { - this.credentialScope = credentialScope; + public String getScope() { + return credentialScope.getName(); } // Attachment Support ---------------------------------------------------------------------------------------------- diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCredentialOfferAuthCodeTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCredentialOfferAuthCodeTest.java index 4798eeeb40c..73895f11740 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCredentialOfferAuthCodeTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCredentialOfferAuthCodeTest.java @@ -19,8 +19,6 @@ 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.CLAIM_NAME_VCT; @@ -51,18 +49,6 @@ @KeycloakIntegrationTest(config = VCTestServerConfig.class) public class OID4VCredentialOfferAuthCodeTest extends OID4VCIssuerTestBase { - OID4VCBasicWallet wallet; - - @BeforeEach - void beforeEach() { - wallet = new OID4VCBasicWallet(keycloak, oauth); - } - - @AfterEach - void afterEach() { - wallet.logout(); - } - @Test public void testNoOffer_Scope() throws Exception { @@ -72,7 +58,7 @@ public void testNoOffer_Scope() throws Exception { // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .send(ctx.getHolder(), "password"); String authCode = authResponse.getCode(); assertNotNull(authCode, "No authCode"); @@ -105,14 +91,14 @@ public void testNoOffer_Scope_AuthDetails() throws Exception { OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); authDetail.setType(OPENID_CREDENTIAL); - authDetail.setCredentialConfigurationId(ctx.getCredConfigId()); + authDetail.setCredentialConfigurationId(ctx.getCredentialConfigurationId()); authDetail.setLocations(List.of(issuerMetadata.getCredentialIssuer())); // Send AuthorizationRequest // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .authorizationDetails(authDetail) .send(ctx.getHolder(), "password"); String authCode = authResponse.getCode(); @@ -144,7 +130,7 @@ public void testAuthCodeOffer_Anonymous() throws Exception { // Create Authorization Code CredentialOffer // - CredentialsOffer credOffer = wallet.createAuthCodeCredentialOffer(ctx, null); + CredentialsOffer credOffer = wallet.createCredentialOfferAuthCode(ctx, null); String issuerState = credOffer.getIssuerState(); assertNotNull(issuerState, "No IssuerState"); @@ -152,7 +138,7 @@ public void testAuthCodeOffer_Anonymous() throws Exception { // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .issuerState(issuerState) .send(ctx.getHolder(), "password"); String authCode = authResponse.getCode(); @@ -184,7 +170,7 @@ public void testAuthCodeOffer_Anonymous_multipleOffers() throws Exception { // Create Authorization Code CredentialOffer // - CredentialsOffer credOffer = wallet.createAuthCodeCredentialOffer(ctx1, null); + CredentialsOffer credOffer = wallet.createCredentialOfferAuthCode(ctx1, null); String issuerState = credOffer.getIssuerState(); assertNotNull(issuerState, "No IssuerState"); @@ -192,7 +178,7 @@ public void testAuthCodeOffer_Anonymous_multipleOffers() throws Exception { // AuthorizationEndpointResponse authResponse1 = wallet .authorizationRequest() - .scope(ctx1.getCredScopeName()) + .scope(ctx1.getScope()) .issuerState(issuerState) .send(ctx1.getHolder(), "password"); String authCode = authResponse1.getCode(); @@ -216,7 +202,7 @@ public void testAuthCodeOffer_Anonymous_multipleOffers() throws Exception { // Create Authorization Code CredentialOffer and obtain 2nd access-token for different VC // - CredentialsOffer credOffer2 = wallet.createAuthCodeCredentialOffer(ctx2, null); + CredentialsOffer credOffer2 = wallet.createCredentialOfferAuthCode(ctx2, null); issuerState = credOffer2.getIssuerState(); assertNotNull(issuerState, "No IssuerState"); @@ -224,7 +210,7 @@ public void testAuthCodeOffer_Anonymous_multipleOffers() throws Exception { // AuthorizationEndpointResponse authResponse2 = wallet .authorizationRequest() - .scope(ctx2.getCredScopeName()) + .scope(ctx2.getScope()) .issuerState(issuerState) .send(ctx2.getHolder(), "password"); authCode = authResponse2.getCode(); @@ -269,7 +255,7 @@ public void testAuthCodeOffer_Anonymous_expiredOffer() throws Exception { // Create Authorization Code CredentialOffer // - CredentialsOffer credOffer = wallet.createAuthCodeCredentialOffer(ctx, null); + CredentialsOffer credOffer = wallet.createCredentialOfferAuthCode(ctx, null); String issuerState = credOffer.getIssuerState(); assertNotNull(issuerState, "No IssuerState"); @@ -277,7 +263,7 @@ public void testAuthCodeOffer_Anonymous_expiredOffer() throws Exception { // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .issuerState(issuerState) .send(ctx.getHolder(), "password"); String authCode = authResponse.getCode(); @@ -312,7 +298,7 @@ public void testAuthCodeOffer_Targeted() throws Exception { // Create Authorization Code CredentialOffer // - CredentialsOffer credOffer = wallet.createAuthCodeCredentialOffer(ctx, ctx.getHolder()); + CredentialsOffer credOffer = wallet.createCredentialOfferAuthCode(ctx, ctx.getHolder()); String issuerState = credOffer.getIssuerState(); assertNotNull(issuerState, "No IssuerState"); @@ -320,7 +306,7 @@ public void testAuthCodeOffer_Targeted() throws Exception { // AuthorizationEndpointResponse authResponse = wallet .authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .issuerState(issuerState) .send(ctx.getHolder(), "password"); String authCode = authResponse.getCode(); diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/OID4VCAuthorizationCodeFlowTestBase.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/OID4VCAuthorizationCodeFlowTestBase.java index de57e81ba3e..f1eda879f13 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/OID4VCAuthorizationCodeFlowTestBase.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/OID4VCAuthorizationCodeFlowTestBase.java @@ -25,7 +25,6 @@ import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testframework.events.EventAssertion; -import org.keycloak.tests.oid4vc.OID4VCBasicWallet; import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase; import org.keycloak.tests.oid4vc.OID4VCProofTestUtils; import org.keycloak.tests.oid4vc.OID4VCTestContext; @@ -62,7 +61,6 @@ public abstract class OID4VCAuthorizationCodeFlowTestBase extends OID4VCIssuerTe private static final Logger logger = Logger.getLogger(OID4VCAuthorizationCodeFlowTestBase.class); - protected OID4VCBasicWallet wallet; protected OID4VCTestContext ctx; /** Returns the credential format supported by this test (e.g. {@code "jwt_vc"} or {@code "sd_jwt_vc"}). */ @@ -82,7 +80,6 @@ public abstract class OID4VCAuthorizationCodeFlowTestBase extends OID4VCIssuerTe @BeforeEach void setUp() { - wallet = new OID4VCBasicWallet(keycloak, oauth); ctx = new OID4VCTestContext(client, getCredentialScope()); // Clean up before starting cleanupState(); @@ -224,7 +221,7 @@ public void testCompleteFlowWithClaimsValidationAuthorizationCode_credentialRequ AccessTokenResponse tokenResponse = authzCodeFlow(issuer); CredentialRequest credentialRequest = new CredentialRequest(); - credentialRequest.setCredentialConfigurationId(ctx.getCredConfigId()); + credentialRequest.setCredentialConfigurationId(ctx.getCredentialConfigurationId()); credentialRequest.setProofs(newJwtProofs()); Oid4vcCredentialResponse credentialResponse = oauth.oid4vc() @@ -350,13 +347,13 @@ public void testCorrectAccessTokenUsed() throws Exception { // We USE SSO here instead of wallet.logout() because logout would invalidate tokenWithoutMandatory's session. OID4VCAuthorizationDetail authDetailWithMandatory = new OID4VCAuthorizationDetail(); authDetailWithMandatory.setType(OPENID_CREDENTIAL); - authDetailWithMandatory.setCredentialConfigurationId(ctx.getCredConfigId()); + authDetailWithMandatory.setCredentialConfigurationId(ctx.getCredentialConfigurationId()); authDetailWithMandatory.setClaims(mandatoryLastNameClaims()); authDetailWithMandatory.setLocations(Collections.singletonList(issuer.getCredentialIssuer())); // Manually navigate to the authorization URL (exploiting SSO session from Flow 1) wallet.authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .authorizationDetails(authDetailWithMandatory) .openLoginForm(); @@ -537,7 +534,7 @@ public void testTokenExchangeWithoutAuthorizationDetails() throws Exception { // Login with scope only, no explicit authorization_details AuthorizationEndpointResponse authResponse = wallet.authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .send(TEST_USER, TEST_PASSWORD); String code = authResponse.getCode(); assertNotNull(code, "Authorization code should not be null"); @@ -551,7 +548,7 @@ public void testTokenExchangeWithoutAuthorizationDetails() throws Exception { List authDetails = tokenResponse.getOID4VCAuthorizationDetails(); assertNotNull(authDetails, "authorization_details should be derived from requested OID4VC scope"); assertFalse(authDetails.isEmpty(), "authorization_details should not be empty"); - assertEquals(ctx.getCredConfigId(), + assertEquals(ctx.getCredentialConfigurationId(), authDetails.get(0).getCredentialConfigurationId(), "credential_configuration_id should match requested scope"); assertNotNull(authDetails.get(0).getCredentialIdentifiers(), "credential_identifiers should be present"); @@ -701,7 +698,7 @@ public void testTokenExchangeWithMalformedAuthorizationDetails() throws Exceptio // Use loginForm directly to inject the malformed JSON as a raw parameter AuthorizationEndpointResponse authResponse = oauth.loginForm() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .param(OAuth2Constants.AUTHORIZATION_DETAILS, "invalid-json") .doLogin(TEST_USER, TEST_PASSWORD); String code = authResponse.getCode(); @@ -851,12 +848,12 @@ protected AccessTokenResponse authzCodeFlow(CredentialIssuer issuer, OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); authDetail.setType(OPENID_CREDENTIAL); - authDetail.setCredentialConfigurationId(ctx.getCredConfigId()); + authDetail.setCredentialConfigurationId(ctx.getCredentialConfigurationId()); authDetail.setClaims(claimsForAuthorizationDetailsParameter); authDetail.setLocations(Collections.singletonList(issuer.getCredentialIssuer())); AuthorizationEndpointResponse authResponse = wallet.authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .authorizationDetails(authDetail) .send(TEST_USER, TEST_PASSWORD); String code = authResponse.getCode(); @@ -951,7 +948,7 @@ protected OID4VCAuthorizationDetail createAuthorizationDetail(CredentialIssuer i authDetail.setType(OPENID_CREDENTIAL); authDetail.setCredentialConfigurationId(credentialConfigurationId != null ? credentialConfigurationId - : ctx.getCredConfigId()); + : ctx.getCredentialConfigurationId()); authDetail.setLocations(Collections.singletonList(issuer.getCredentialIssuer())); return authDetail; } @@ -959,7 +956,7 @@ protected OID4VCAuthorizationDetail createAuthorizationDetail(CredentialIssuer i /** Performs an authorization code login with the given authorization detail. */ protected String performAuthorizationCodeLoginWithAuthorizationDetails(OID4VCAuthorizationDetail authDetail) { AuthorizationEndpointResponse authResponse = wallet.authorizationRequest() - .scope(ctx.getCredScopeName()) + .scope(ctx.getScope()) .authorizationDetails(authDetail) .send(TEST_USER, TEST_PASSWORD); String code = authResponse.getCode(); diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java index a487157cb42..621d0d01d2f 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/issuance/signing/OID4VCAuthorizationDetailsFlowTestBase.java @@ -9,7 +9,6 @@ import org.keycloak.protocol.oid4vc.model.CredentialResponse; import org.keycloak.protocol.oid4vc.model.OID4VCAuthorizationDetail; import org.keycloak.representations.idm.ClientScopeRepresentation; -import org.keycloak.tests.oid4vc.OID4VCBasicWallet; import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase; import org.keycloak.tests.oid4vc.OID4VCProofTestUtils; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; @@ -42,7 +41,7 @@ private static final class Oid4vcTestContext { private void clearLoginState() { try { - new OID4VCBasicWallet(keycloak, oauth).logout("john"); + wallet.logout("john"); } catch (Exception e) { log.warn("Failed to logout test user before authorization-details flow", e); } diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/JwtPreAuthCodeHandlerTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/JwtPreAuthCodeHandlerTest.java index 6acfb64d7c4..50cdce97afc 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/JwtPreAuthCodeHandlerTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/JwtPreAuthCodeHandlerTest.java @@ -21,13 +21,11 @@ import org.keycloak.testframework.annotations.KeycloakIntegrationTest; import org.keycloak.testframework.remote.runonserver.InjectRunOnServer; import org.keycloak.testframework.remote.runonserver.RunOnServerClient; -import org.keycloak.tests.oid4vc.OID4VCBasicWallet; import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase; import org.keycloak.tests.oid4vc.OID4VCTestContext; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.apache.http.HttpStatus; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -43,7 +41,6 @@ @KeycloakIntegrationTest(config = VCTestServerWithPreAuthCodeEnabled.class) public class JwtPreAuthCodeHandlerTest extends OID4VCIssuerTestBase { - OID4VCBasicWallet wallet; OID4VCTestContext testCtx; @InjectRunOnServer @@ -51,15 +48,9 @@ public class JwtPreAuthCodeHandlerTest extends OID4VCIssuerTestBase { @BeforeEach void beforeEach() { - wallet = new OID4VCBasicWallet(keycloak, oauth); testCtx = new OID4VCTestContext(client, jwtTypeCredentialScope); } - @AfterEach - void afterEach() { - wallet.logout(); - } - @Test public void shouldGenerateValidJwtPreAuthCodes() { // Request a pre-auth code. This will create an offer state in the server @@ -81,7 +72,7 @@ public void shouldGenerateValidJwtPreAuthCodes() { assertPreAuthCodeCtx(preAuthCodeCtx); // Ensure that the pre-auth code can be exchanged for an access token - AccessTokenResponse resp = wallet.preAuthAccessTokenRequest(testCtx, preAuthCode).send(); + AccessTokenResponse resp = wallet.accessTokenRequestPreAuth(testCtx, preAuthCode).send(); assertEquals(HttpStatus.SC_OK, resp.getStatusCode()); assertNotNull(resp.getAccessToken(), "Access token must not be null"); } @@ -115,7 +106,7 @@ public void mustRejectNonPreAuthCodeJwts() { }); // Ensure that it cannot be exchanged for an access token - AccessTokenResponse resp = wallet.preAuthAccessTokenRequest(testCtx, imposterPreAuthCode).send(); + AccessTokenResponse resp = wallet.accessTokenRequestPreAuth(testCtx, imposterPreAuthCode).send(); assertEquals(HttpStatus.SC_BAD_REQUEST, resp.getStatusCode()); assertEquals("Pre-authorized code failed handler verification (invalid_code)", resp.getErrorDescription()); @@ -165,11 +156,11 @@ public void mustRejectReplayedPreAuthCodeJwts() { assertValidPreAuthCodeJwt(preAuthCode); // First use: the pre-auth code can be exchanged for an access token - AccessTokenResponse resp = wallet.preAuthAccessTokenRequest(testCtx, preAuthCode).send(); + AccessTokenResponse resp = wallet.accessTokenRequestPreAuth(testCtx, preAuthCode).send(); assertEquals(HttpStatus.SC_OK, resp.getStatusCode()); // Second use: the same pre-auth code must be rejected as replayed - AccessTokenResponse replayResp = wallet.preAuthAccessTokenRequest(testCtx, preAuthCode).send(); + AccessTokenResponse replayResp = wallet.accessTokenRequestPreAuth(testCtx, preAuthCode).send(); assertEquals(HttpStatus.SC_BAD_REQUEST, replayResp.getStatusCode()); assertEquals("Pre-authorized code has already been used", replayResp.getErrorDescription()); } @@ -182,7 +173,7 @@ private String createPreAuthOffer() { }); try { - CredentialsOffer offer = wallet.createPreAuthCredentialOffer(testCtx, testCtx.getHolder()); + CredentialsOffer offer = wallet.createCredentialOfferPreAuth(testCtx, testCtx.getHolder()); return offer.getPreAuthorizedCode(); } catch (Exception e) { throw new AssertionError("Should not fail to create pre-auth code", e); diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCActionPreAuthTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCActionPreAuthTest.java index d418307ece2..f27b67762f9 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCActionPreAuthTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCActionPreAuthTest.java @@ -12,7 +12,6 @@ import org.keycloak.testframework.ui.annotations.InjectPage; import org.keycloak.testframework.ui.page.OID4VCCredentialOfferPage; import org.keycloak.tests.common.TestRealmUserConfig; -import org.keycloak.tests.oid4vc.OID4VCBasicWallet; import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase; import org.keycloak.tests.oid4vc.OID4VCTestContext; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; @@ -44,11 +43,9 @@ public class OID4VCActionPreAuthTest extends OID4VCIssuerTestBase { ManagedUser user; OID4VCTestContext ctx; - OID4VCBasicWallet wallet; @BeforeEach void beforeEach() { - wallet = new OID4VCBasicWallet(keycloak, oauth); ctx = new OID4VCTestContext(client, minimalJwtTypeCredentialScope); user.admin().logout(); } @@ -104,7 +101,7 @@ public void testCredentialOfferAIASuccess_preAuthorizedCode() throws Exception { // Redeem Pre-Authorized Code for AccessToken // - AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode).send(); + AccessTokenResponse tokenResponse = wallet.accessTokenRequestPreAuth(ctx, preAuthCode).send(); assertTrue(tokenResponse.isSuccess(), tokenResponse.getErrorDescription()); String accessToken = wallet.validateHolderAccessToken(ctx, tokenResponse); diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java index 7017a396fb7..4eaefee9eda 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCPublicClientPreAuthTest.java @@ -26,13 +26,11 @@ import org.keycloak.protocol.oid4vc.model.VerifiableCredential; import org.keycloak.representations.JsonWebToken; import org.keycloak.testframework.annotations.KeycloakIntegrationTest; -import org.keycloak.tests.oid4vc.OID4VCBasicWallet; import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase; import org.keycloak.tests.oid4vc.OID4VCTestContext; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.util.JsonSerialization; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -48,21 +46,12 @@ @KeycloakIntegrationTest(config = OID4VCIssuerTestBase.VCTestServerWithPreAuthCodeEnabled.class) public class OID4VCPublicClientPreAuthTest extends OID4VCIssuerTestBase { - OID4VCBasicWallet wallet; - @BeforeEach void beforeEach() { - wallet = new OID4VCBasicWallet(keycloak, oauth); - // Reconfigure OAuthClient oauth.client(pubClient.getClientId(), null); } - @AfterEach - void afterEach() { - wallet.logout(); - } - @Test public void testCredentialFromPreAuthCode() throws Exception { @@ -70,12 +59,12 @@ public void testCredentialFromPreAuthCode() throws Exception { // Create Pre-Authorized CredentialOffer // - CredentialsOffer credOffer = wallet.createPreAuthCredentialOffer(ctx, ctx.getHolder()); + CredentialsOffer credOffer = wallet.createCredentialOfferPreAuth(ctx, ctx.getHolder()); String preAuthCode = credOffer.getPreAuthorizedCode(); // Redeem Pre-Authorized Code for AccessToken // - AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode).send(); + AccessTokenResponse tokenResponse = wallet.accessTokenRequestPreAuth(ctx, preAuthCode).send(); assertTrue(tokenResponse.isSuccess(), tokenResponse.getErrorDescription()); String accessToken = wallet.validateHolderAccessToken(ctx, tokenResponse); @@ -98,7 +87,7 @@ public void testCredentialFromPreAuthCode() throws Exception { private void verifyCredentialResponse(OID4VCTestContext ctx, String expUser, CredentialResponse credResponse) throws Exception { - String scope = ctx.getCredScopeName(); + String scope = ctx.getScope(); CredentialResponse.Credential credentialObj = credResponse.getCredentials().get(0); assertNotNull(credentialObj, "The first credential in the array should not be null"); diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCredentialOfferPreAuthTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCredentialOfferPreAuthTest.java index 61ce6c2f588..8e116ae3638 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCredentialOfferPreAuthTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/preauth/OID4VCredentialOfferPreAuthTest.java @@ -13,13 +13,11 @@ import org.keycloak.representations.JsonWebToken; import org.keycloak.representations.idm.UserRepresentation; import org.keycloak.testframework.annotations.KeycloakIntegrationTest; -import org.keycloak.tests.oid4vc.OID4VCBasicWallet; import org.keycloak.tests.oid4vc.OID4VCIssuerTestBase; import org.keycloak.tests.oid4vc.OID4VCTestContext; import org.keycloak.testsuite.util.oauth.AccessTokenResponse; import org.keycloak.util.JsonSerialization; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.keycloak.tests.oid4vc.OID4VCProofTestUtils.jwtProofs; @@ -45,14 +43,6 @@ @KeycloakIntegrationTest(config = OID4VCIssuerTestBase.VCTestServerWithPreAuthCodeEnabled.class) public class OID4VCredentialOfferPreAuthTest extends OID4VCIssuerTestBase { - OID4VCBasicWallet wallet; - - @BeforeEach - void beforeEach() { - wallet = new OID4VCBasicWallet(keycloak, oauth); - wallet.logout(); - } - @Test public void testPreAuthOffer_DisabledUser() { @@ -66,7 +56,7 @@ public void testPreAuthOffer_DisabledUser() { try { IllegalStateException error = assertThrows(IllegalStateException.class, - () -> wallet.createPreAuthCredentialOffer(ctx, ctx.getHolder())); + () -> wallet.createCredentialOfferPreAuth(ctx, ctx.getHolder())); assertTrue(error.getMessage().contains("User 'alice' disabled"), error.getMessage()); } finally { userRep.setEnabled(true); @@ -81,12 +71,12 @@ public void testPreAuthOffer_SelfIssued() throws Exception { // Create Pre-Authorized CredentialOffer // - CredentialsOffer credOffer = wallet.createPreAuthCredentialOffer(ctx, null); + CredentialsOffer credOffer = wallet.createCredentialOfferPreAuth(ctx, null); String preAuthCode = credOffer.getPreAuthorizedCode(); // Redeem Pre-Authorized Code for AccessToken // - AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode).send(); + AccessTokenResponse tokenResponse = wallet.accessTokenRequestPreAuth(ctx, preAuthCode).send(); assertTrue(tokenResponse.isSuccess(), tokenResponse.getErrorDescription()); String accessToken = wallet.validateHolderAccessToken(ctx, tokenResponse); @@ -111,12 +101,12 @@ public void testPreAuthOffer_Targeted() throws Exception { // Create Pre-Authorized CredentialOffer // - CredentialsOffer credOffer = wallet.createPreAuthCredentialOffer(ctx, ctx.getHolder()); + CredentialsOffer credOffer = wallet.createCredentialOfferPreAuth(ctx, ctx.getHolder()); String preAuthCode = credOffer.getPreAuthorizedCode(); // Redeem Pre-Authorized Code for AccessToken // - AccessTokenResponse tokenResponse = wallet.preAuthAccessTokenRequest(ctx, preAuthCode).send(); + AccessTokenResponse tokenResponse = wallet.accessTokenRequestPreAuth(ctx, preAuthCode).send(); assertTrue(tokenResponse.isSuccess(), tokenResponse.getErrorDescription()); String accessToken = wallet.validateHolderAccessToken(ctx, tokenResponse); From fc4b5b9afbc4d55a90b8315d5f0381af01da843a Mon Sep 17 00:00:00 2001 From: Thomas Diesler Date: Tue, 31 Mar 2026 19:21:14 +0200 Subject: [PATCH 3/3] -- deal with timeouts and low-level errors in test code Signed-off-by: Thomas Diesler --- .../tests/oid4vc/OID4VCPublicClientTest.java | 42 ++++++++++++++++--- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java index aa22ccb6aeb..4c4472731bc 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCPublicClientTest.java @@ -35,12 +35,16 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.openqa.selenium.NoSuchElementException; +import org.opentest4j.AssertionFailedError; import static org.keycloak.OID4VCConstants.OPENID_CREDENTIAL; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** @@ -123,15 +127,43 @@ public void testAuthorizationRequestNoPkce() throws Exception { var ctx = new OID4VCTestContext(pubClient, jwtTypeCredentialScope); - // Send AuthorizationRequest + // Send AuthorizationRequest without required PKCE // - AuthorizationEndpointResponse authResponse = wallet + NoSuchElementException ex = assertThrows(NoSuchElementException.class, () -> wallet .authorizationRequest() .scope(ctx.getScope()) - .send(ctx.getHolder(), "password"); + .send(ctx.getHolder(), TEST_PASSWORD)); + + assertNotNull(ex.getMessage(), "No error message"); + assertTrue(ex.getMessage().contains("Unable to locate element with ID: 'username'"), ex.getMessage()); + + // [TODO #47649] OAuthClient cannot handle invalid authorization requests + // https://github.com/keycloak/keycloak/issues/47649 + // assertEquals("invalid_request", authResponse.getError()); + // assertEquals("Missing parameter: code_challenge_method", authResponse.getErrorDescription()); + } + + @Test + public void testAuthorizationRequestWrongPassword() throws Exception { + + var ctx = new OID4VCTestContext(pubClient, jwtTypeCredentialScope); + + // Send AuthorizationRequest with incorrect credentials + // + AssertionFailedError ex = assertThrows(AssertionFailedError.class, () -> wallet + .authorizationRequest() + .scope(ctx.getScope()) + .codeChallenge(PkceGenerator.s256()) + .send(ctx.getHolder(), "wrong_password")); + + assertTrue(ex.getMessage().contains("Expected OAuth callback, but URL was"), ex.getMessage()); + assertTrue(ex.getMessage().contains("after timeout"), ex.getMessage()); + + // [TODO #47649] OAuthClient cannot handle invalid authorization requests + // https://github.com/keycloak/keycloak/issues/47649 + // assertEquals("unauthorized", authResponse.getError()); + // assertNull(authResponse.getErrorDescription(), "Null error description"); - assertEquals("invalid_request", authResponse.getError()); - assertEquals("Missing parameter: code_challenge_method", authResponse.getErrorDescription()); } // Private ---------------------------------------------------------------------------------------------------------