From b88ce7e1b70af63d36eaf4072b82d9ff915f25c7 Mon Sep 17 00:00:00 2001 From: Thomas Diesler Date: Tue, 17 Mar 2026 11:43:20 +0100 Subject: [PATCH] [OID4VCI] Migrate OID4VCJWTIssuerEndpointTest (cleanup) Signed-off-by: Thomas Diesler --- .../oid4vc/OID4VCIssuerEndpointTest.java | 297 +++++----- .../tests/oid4vc/OID4VCIssuerTestBase.java | 514 +++++++++--------- .../oid4vc/OID4VCJWTIssuerEndpointTest.java | 76 ++- 3 files changed, 419 insertions(+), 468 deletions(-) diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerEndpointTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerEndpointTest.java index 052dedb67a0..6bf36af189d 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerEndpointTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCIssuerEndpointTest.java @@ -20,7 +20,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.URI; -import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -65,7 +64,6 @@ import org.keycloak.protocol.oidc.utils.OAuth2Code; import org.keycloak.protocol.oidc.utils.OAuth2CodeParser; import org.keycloak.representations.JsonWebToken; -import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.ClientScopeRepresentation; import org.keycloak.representations.idm.ComponentRepresentation; import org.keycloak.representations.idm.ProtocolMapperRepresentation; @@ -85,17 +83,7 @@ import org.keycloak.validate.validators.PatternValidator; import com.fasterxml.jackson.core.type.TypeReference; -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpHeaders; -import org.apache.http.HttpStatus; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; import org.jboss.logging.Logger; -import org.junit.jupiter.api.BeforeEach; import static org.keycloak.OID4VCConstants.CLAIM_NAME_VC; import static org.keycloak.jose.jwe.JWEConstants.RSA_OAEP_256; @@ -116,22 +104,11 @@ public abstract class OID4VCIssuerEndpointTest extends OID4VCIssuerTestBase { - private static final Logger LOGGER = Logger.getLogger(OID4VCIssuerEndpointTest.class); - - protected static final TimeProvider TIME_PROVIDER = new StaticTimeProvider(1000); - - protected ClientScopeRepresentation sdJwtTypeCredentialClientScope; - protected ClientScopeRepresentation jwtTypeCredentialClientScope; - protected ClientScopeRepresentation minimalJwtTypeCredentialClientScope; - - protected CloseableHttpClient httpClient; - protected ClientRepresentation client; + static final TimeProvider TIME_PROVIDER = new OID4VCIssuerTestBase.StaticTimeProvider(1000); @InjectKeycloakUrls KeycloakUrls keycloakUrls; - record OAuth2CodeEntry(String key, OAuth2Code code) {} - @Override public void configureTestRealm() { super.configureTestRealm(); @@ -139,69 +116,7 @@ public void configureTestRealm() { ComponentsResource components = testRealm.admin().components(); components.add(getRsaKeyProvider(getRsaKey_Default())).close(); components.add(getRsaEncKeyProvider(RSA_OAEP_256, "enc-key-oaep256", 100)).close(); - components.add(getUserProfileProvider()); - } - - @BeforeEach - public void setup() { - httpClient = HttpClientBuilder.create().build(); - client = requireExistingClient(OID4VCI_CLIENT_ID); - sdJwtTypeCredentialClientScope = requireExistingClientScope(sdJwtTypeCredentialScopeName); - jwtTypeCredentialClientScope = requireExistingClientScope(jwtTypeCredentialScopeName); - minimalJwtTypeCredentialClientScope = requireExistingClientScope(minimalJwtTypeCredentialScopeName); - } - - protected static OAuth2CodeEntry prepareSessionCode( - KeycloakSession session, - AppAuthManager.BearerTokenAuthenticator authenticator, - String note) { - - AuthenticationManager.AuthResult authResult = authenticator.authenticate(); - UserSessionModel userSessionModel = authResult.session(); - AuthenticatedClientSessionModel authenticatedClientSessionModel = - userSessionModel.getAuthenticatedClientSessionByClient(authResult.client().getId()); - - OAuth2Code oauth2Code = new OAuth2Code( - SecretGenerator.getInstance().randomString(), - Time.currentTime() + 6000, - SecretGenerator.getInstance().randomString(), - CREDENTIAL_OFFER_URI_CODE_SCOPE, - authenticatedClientSessionModel.getUserSession().getId() - ); - - String nonce = OAuth2CodeParser.persistCode(session, authenticatedClientSessionModel, oauth2Code); - authenticatedClientSessionModel.setNote(nonce, note); - - return new OAuth2CodeEntry(nonce, oauth2Code); - } - - protected static OID4VCIssuerEndpoint prepareIssuerEndpoint( - KeycloakSession session, - AppAuthManager.BearerTokenAuthenticator authenticator) { - - JwtCredentialBuilder jwtCredentialBuilder = new JwtCredentialBuilder(TIME_PROVIDER, session); - SdJwtCredentialBuilder sdJwtCredentialBuilder = new SdJwtCredentialBuilder(); - - Map credentialBuilders = Map.of( - jwtCredentialBuilder.getSupportedFormat(), jwtCredentialBuilder, - sdJwtCredentialBuilder.getSupportedFormat(), sdJwtCredentialBuilder - ); - - return prepareIssuerEndpoint(session, authenticator, credentialBuilders); - } - - protected static OID4VCIssuerEndpoint prepareIssuerEndpoint( - KeycloakSession session, - AppAuthManager.BearerTokenAuthenticator authenticator, - Map credentialBuilders) { - - return new OID4VCIssuerEndpoint( - session, - credentialBuilders, - authenticator, - TIME_PROVIDER, - 30 - ); + components.add(getUserProfileProvider()).close(); } protected ClientScopeRepresentation createOptionalClientScope( @@ -261,16 +176,61 @@ protected ClientScopeRepresentation createOptionalClientScope( List protocolMappers; if (protocolMapperReferenceFile == null) { - protocolMappers = getProtocolMappers(scopeName); + protocolMappers = ProtocolMapperUtils.getProtocolMappers(scopeName); } else { protocolMappers = resolveProtocolMappers(protocolMapperReferenceFile); - protocolMappers.add(getStaticClaimMapper(scopeName)); + protocolMappers.add(ProtocolMapperUtils.getStaticClaimMapper(scopeName)); } clientScope.setProtocolMappers(protocolMappers); return clientScope; } + protected String getBasePath(String realm) { + return getRealmPath(realm) + "/protocol/oid4vc/"; + } + + protected String getRealmPath(String realm) { + return keycloakUrls.getBaseUrl() + "/realms/" + realm; + } + + protected String getRealmMetadataPath(String realm) { + return keycloakUrls.getBaseUrl() + "/.well-known/openid-credential-issuer/realms/" + realm; + } + + protected CredentialIssuer getCredentialIssuerMetadata() { + CredentialIssuerMetadataResponse metadataResponse = oauth.oid4vc().doIssuerMetadataRequest(); + return metadataResponse.getMetadata(); + } + + protected ComponentRepresentation getUserProfileProvider() { + // Add the User DID attribute, with the same logic as in DeclarativeUserProfileProviderFactory + UPConfig profileConfig = UPConfigUtils.parseSystemDefaultConfig(); + + if (profileConfig.getAttribute(UserModel.DID) == null) { + UPAttribute attr = new UPAttribute(UserModel.DID); + attr.setDisplayName("${did}"); + attr.setPermissions(new UPAttributePermissions(Set.of(ROLE_ADMIN, ROLE_USER), Set.of(ROLE_ADMIN, ROLE_USER))); + attr.setValidations(Map.of( + PatternValidator.ID, Map.of( + "pattern", "^did:.+:.+$", + "error-message", "Value must start with 'did:scheme:'" + ) + )); + profileConfig.addOrReplaceAttribute(attr); + } + + ComponentRepresentation componentRepresentation = new ComponentRepresentation(); + componentRepresentation.setId(UUID.randomUUID().toString()); + componentRepresentation.setProviderId("declarative-user-profile"); + componentRepresentation.setProviderType(UserProfileProvider.class.getName()); + componentRepresentation.setConfig(new MultivaluedHashMap<>( + Map.of(UP_COMPONENT_CONFIG_KEY, List.of(JsonSerialization.valueAsString(profileConfig))) + )); + + return componentRepresentation; + } + protected ClientScopeRepresentation registerOptionalClientScope(ClientScopeRepresentation clientScope) { // Automatically removed when a test method is finished. try (Response res = testRealm.admin().clientScopes().create(clientScope)) { @@ -281,21 +241,24 @@ protected ClientScopeRepresentation registerOptionalClientScope(ClientScopeRepre return clientScope; } - protected ClientRepresentation requireExistingClient(String clientId) { - return testRealm.admin().clients().findByClientId(clientId).stream() - .findFirst() - .orElseThrow(() -> new AssertionError("No such client: " + clientId)); - } + protected void requestCredentialWithIdentifier( + String token, + String credentialIdentifier, + CredentialResponseHandler responseHandler, + ClientScopeRepresentation expectedClientScope) throws IOException, VerificationException { + + CredentialResponse credentialResponse = oauth.oid4vc() + .credentialRequest() + .credentialIdentifier(credentialIdentifier) + .bearerToken(token) + .send() + .getCredentialResponse(); - protected ClientScopeRepresentation requireExistingClientScope(String scopeName) { - // Check if the client scope already exists - return testRealm.admin().clientScopes().findAll().stream() - .filter(scope -> scope.getName().equals(scopeName)) - .findFirst() - .orElseThrow(() -> new AssertionError("No such client scope: " + scopeName)); + // Use response handler to customize checks based on formats. + responseHandler.handleCredentialResponse(credentialResponse, expectedClientScope); } - public static List resolveProtocolMappers(String protocolMapperReferenceFile) { + protected List resolveProtocolMappers(String protocolMapperReferenceFile) { if (protocolMapperReferenceFile == null) { return null; } @@ -414,78 +377,6 @@ protected void testCredentialIssuanceWithAuthZCodeFlow( } } - protected String getBasePath(String realm) { - return getRealmPath(realm) + "/protocol/oid4vc/"; - } - - protected String getRealmPath(String realm) { - return keycloakUrls.getBaseUrl() + "/realms/" + realm; - } - - protected String getRealmMetadataPath(String realm) { - return keycloakUrls.getBaseUrl() + "/.well-known/openid-credential-issuer/realms/" + realm; - } - - protected void requestCredentialWithIdentifier( - String token, - String credentialEndpoint, - String credentialIdentifier, - CredentialResponseHandler responseHandler, - ClientScopeRepresentation expectedClientScope) throws IOException, VerificationException { - - CredentialRequest request = new CredentialRequest(); - request.setCredentialIdentifier(credentialIdentifier); - - StringEntity stringEntity = new StringEntity(JsonSerialization.writeValueAsString(request), ContentType.APPLICATION_JSON); - - HttpPost postCredential = new HttpPost(credentialEndpoint); - postCredential.addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + token); - postCredential.setEntity(stringEntity); - - CredentialResponse credentialResponse; - try (CloseableHttpResponse credentialRequestResponse = httpClient.execute(postCredential)) { - assertEquals(HttpStatus.SC_OK, credentialRequestResponse.getStatusLine().getStatusCode()); - String s = IOUtils.toString(credentialRequestResponse.getEntity().getContent(), StandardCharsets.UTF_8); - credentialResponse = JsonSerialization.readValue(s, CredentialResponse.class); - } - - // Use response handler to customize checks based on formats. - responseHandler.handleCredentialResponse(credentialResponse, expectedClientScope); - } - - public CredentialIssuer getCredentialIssuerMetadata() { - CredentialIssuerMetadataResponse metadataResponse = oauth.oid4vc().doIssuerMetadataRequest(); - return metadataResponse.getMetadata(); - } - - private ComponentRepresentation getUserProfileProvider() { - // Add the User DID attribute, with the same logic as in DeclarativeUserProfileProviderFactory - UPConfig profileConfig = UPConfigUtils.parseSystemDefaultConfig(); - - if (profileConfig.getAttribute(UserModel.DID) == null) { - UPAttribute attr = new UPAttribute(UserModel.DID); - attr.setDisplayName("${did}"); - attr.setPermissions(new UPAttributePermissions(Set.of(ROLE_ADMIN, ROLE_USER), Set.of(ROLE_ADMIN, ROLE_USER))); - attr.setValidations(Map.of( - PatternValidator.ID, Map.of( - "pattern", "^did:.+:.+$", - "error-message", "Value must start with 'did:scheme:'" - ) - )); - profileConfig.addOrReplaceAttribute(attr); - } - - ComponentRepresentation componentRepresentation = new ComponentRepresentation(); - componentRepresentation.setId(UUID.randomUUID().toString()); - componentRepresentation.setProviderId("declarative-user-profile"); - componentRepresentation.setProviderType(UserProfileProvider.class.getName()); - componentRepresentation.setConfig(new MultivaluedHashMap<>( - Map.of(UP_COMPONENT_CONFIG_KEY, List.of(JsonSerialization.valueAsString(profileConfig))) - )); - - return componentRepresentation; - } - protected void withCausePropagation(Runnable r) throws Throwable { try { r.run(); @@ -497,7 +388,7 @@ protected void withCausePropagation(Runnable r) throws Throwable { } } - protected static class CredentialResponseHandler { + protected class CredentialResponseHandler { final Logger log = Logger.getLogger(OID4VCIssuerEndpointTest.class); protected void handleCredentialResponse(CredentialResponse credentialResponse, ClientScopeRepresentation clientScope) throws VerificationException { @@ -553,4 +444,62 @@ protected void handleCredentialResponse(CredentialResponse credentialResponse, C assertFalse(subClaims.containsKey("AnotherCredentialType"), "Unexpected other claim"); } } + + // Static RunOnServer Utils + + record OAuth2CodeEntry(String key, OAuth2Code code) {} + + + static OID4VCIssuerEndpoint prepareIssuerEndpoint( + KeycloakSession session, + AppAuthManager.BearerTokenAuthenticator authenticator) { + + JwtCredentialBuilder jwtCredentialBuilder = new JwtCredentialBuilder(TIME_PROVIDER, session); + SdJwtCredentialBuilder sdJwtCredentialBuilder = new SdJwtCredentialBuilder(); + + Map credentialBuilders = Map.of( + jwtCredentialBuilder.getSupportedFormat(), jwtCredentialBuilder, + sdJwtCredentialBuilder.getSupportedFormat(), sdJwtCredentialBuilder + ); + + return prepareIssuerEndpoint(session, authenticator, credentialBuilders); + } + + static OID4VCIssuerEndpoint prepareIssuerEndpoint( + KeycloakSession session, + AppAuthManager.BearerTokenAuthenticator authenticator, + Map credentialBuilders) { + + return new OID4VCIssuerEndpoint( + session, + credentialBuilders, + authenticator, + TIME_PROVIDER, + 30 + ); + } + + static OAuth2CodeEntry prepareSessionCode( + KeycloakSession session, + AppAuthManager.BearerTokenAuthenticator authenticator, + String note) { + + AuthenticationManager.AuthResult authResult = authenticator.authenticate(); + UserSessionModel userSessionModel = authResult.session(); + AuthenticatedClientSessionModel authenticatedClientSessionModel = + userSessionModel.getAuthenticatedClientSessionByClient(authResult.client().getId()); + + OAuth2Code oauth2Code = new OAuth2Code( + SecretGenerator.getInstance().randomString(), + Time.currentTime() + 6000, + SecretGenerator.getInstance().randomString(), + CREDENTIAL_OFFER_URI_CODE_SCOPE, + authenticatedClientSessionModel.getUserSession().getId() + ); + + String nonce = OAuth2CodeParser.persistCode(session, authenticatedClientSessionModel, oauth2Code); + authenticatedClientSessionModel.setNote(nonce, note); + + return new OID4VCIssuerEndpointTest.OAuth2CodeEntry(nonce, oauth2Code); + } } 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 87b992983e9..a6e0d049d72 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 @@ -92,7 +92,6 @@ /** * Abstract base class for OID4VCI Testing *

- * [TODO] Can the server runtime mode be configured by the testcase? * Server-side debugging: KC_TEST_SERVER=embedded */ public abstract class OID4VCIssuerTestBase { @@ -100,21 +99,17 @@ public abstract class OID4VCIssuerTestBase { protected final Logger log = Logger.getLogger(getClass()); public static final String OID4VCI_CLIENT_ID = "oid4vci-client"; - static final URI ISSUER_DID = URI.create("did:web:test.org"); - static final String TEST_CREDENTIAL_MAPPERS_FILE = "/oid4vc/test-credential-mappers.json"; + 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"; - protected static final String sdJwtCredentialVct = "https://credentials.example.com/SD-JWT-Credential"; - protected static final String sdJwtTypeCredentialScopeName = "sd-jwt-credential"; - protected static final String sdJwtTypeCredentialConfigurationIdName = "sd-jwt-credential-config-id"; + public static final String sdJwtTypeCredentialScopeName = "sd-jwt-credential"; + public static final String sdJwtTypeCredentialConfigurationIdName = "sd-jwt-credential-config-id"; + public static final String sdJwtTypeCredentialVct = "https://credentials.example.com/SD-JWT-Credential"; - static final String jwtTypeCredentialScopeName = "jwt-credential"; - static final String jwtTypeCredentialConfigurationIdName = "jwt-credential-config-id"; - static final String minimalJwtTypeCredentialScopeName = "vc-with-minimal-config"; - static final String minimalJwtTypeCredentialConfigurationIdName = "vc-with-minimal-config-id"; - - CredentialScopeRepresentation minimalJwtTypeCredentialScope; - CredentialScopeRepresentation jwtTypeCredentialScope; - CredentialScopeRepresentation sdJwtTypeCredentialScope; + public static final String jwtTypeCredentialScopeName = "jwt-credential"; + public static final String jwtTypeCredentialConfigurationIdName = "jwt-credential-config-id"; + public static final String minimalJwtTypeCredentialScopeName = "vc-with-minimal-config"; + public static final String minimalJwtTypeCredentialConfigurationIdName = "vc-with-minimal-config-id"; @InjectRealm(config = VCTestRealmConfig.class) ManagedRealm testRealm; @@ -134,11 +129,15 @@ public abstract class OID4VCIssuerTestBase { @InjectWebDriver ManagedWebDriver driver; - ClientRepresentation client; - @InjectAdminClient Keycloak keycloak; + protected CredentialScopeRepresentation minimalJwtTypeCredentialScope; + protected CredentialScopeRepresentation jwtTypeCredentialScope; + protected CredentialScopeRepresentation sdJwtTypeCredentialScope; + + protected ClientRepresentation client; + @TestSetup public void configureTestRealm() { RealmResource realmResource = testRealm.admin(); @@ -168,50 +167,17 @@ public static void enableVerifiableCredentialEvents(ManagedRealm realm) { } } - public static CredentialScopeRepresentation createCredentialScope( - String scopeName, - String issuerDid, - String credentialConfigurationId, - String credentialIdentifier, - String vct, - String format, - String protocolMapperReferenceFile, - List acceptedKeyAttestationValues) { - - CredentialScopeRepresentation cs = new CredentialScopeRepresentation(scopeName) - .setIncludeInTokenScope(true) - .setExpiryInSeconds(15) - .setIssuerDid(issuerDid) - .setCredentialConfigurationId(credentialConfigurationId) - .setCredentialIdentifier(credentialIdentifier) - .setFormat(format) - .setVct(Optional.ofNullable(vct).orElse(credentialIdentifier)); - - if (credentialConfigurationId != null) { - List displayObjects = List.of( - new DisplayObject().setName(credentialConfigurationId).setLocale("en-EN"), - new DisplayObject().setName(credentialConfigurationId).setLocale("de-DE") - ); - cs.setDisplay(JsonSerialization.valueAsString(displayObjects)); - } - - if (acceptedKeyAttestationValues != null) { - cs.setKeyAttestationRequired(true); - if (!acceptedKeyAttestationValues.isEmpty()) { - cs.setRequiredKeyAttestationKeyStorage(acceptedKeyAttestationValues); - cs.setRequiredKeyAttestationUserAuthentication(acceptedKeyAttestationValues); - } - } + boolean shouldEnableOid4vci(RealmRepresentation realm) { + return true; + } - if (protocolMapperReferenceFile == null) { - cs.setProtocolMappers(getProtocolMappers(scopeName)); - } else { - List protocolMappers = new ArrayList<>(resolveProtocolMappers(protocolMapperReferenceFile)); - protocolMappers.add(getStaticClaimMapper(scopeName)); - cs.setProtocolMappers(protocolMappers); - } + boolean shouldEnableOid4vci(ClientRepresentation client) { + return true; + } - return cs; + boolean isOid4vciEnabled(ClientRepresentation client) { + Map attributes = Optional.ofNullable(client.getAttributes()).orElse(new HashMap<>()); + return Boolean.parseBoolean(attributes.get(OID4VCI_ENABLED_ATTRIBUTE_KEY)); } CredentialScopeRepresentation getExistingCredentialScope(String scopeName) { @@ -222,158 +188,7 @@ CredentialScopeRepresentation getExistingCredentialScope(String scopeName) { .orElse(null); } - CredentialScopeRepresentation requireExistingCredentialScope(String scopeName) { - return Optional.ofNullable(getExistingCredentialScope(scopeName)) - .orElseThrow(() -> new IllegalStateException("No such credential scope: " + scopeName)); - } - - public static ProtocolMapperRepresentation getIssuedAtTimeMapper(String subjectProperty, String truncateToTimeUnit, String valueSource) { - ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); - protocolMapperRepresentation.setName(subjectProperty + "-oid4vc-issued-at-time-claim-mapper"); - protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); - protocolMapperRepresentation.setId(UUID.randomUUID().toString()); - protocolMapperRepresentation.setProtocolMapper("oid4vc-issued-at-time-claim-mapper"); - - Map configMap = new HashMap<>(); - Optional.ofNullable(subjectProperty) - .ifPresent(value -> configMap.put(OID4VCIssuedAtTimeClaimMapper.CLAIM_NAME, value)); - Optional.ofNullable(truncateToTimeUnit) - .ifPresent(value -> configMap.put(OID4VCIssuedAtTimeClaimMapper.TRUNCATE_TO_TIME_UNIT_KEY, value)); - Optional.ofNullable(valueSource) - .ifPresent(value -> configMap.put(OID4VCIssuedAtTimeClaimMapper.VALUE_SOURCE, value)); - - protocolMapperRepresentation.setConfig(configMap); - return protocolMapperRepresentation; - } - - public static ProtocolMapperRepresentation getJtiGeneratedIdMapper() { - ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); - protocolMapperRepresentation.setName("generated-id-mapper"); - protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); - protocolMapperRepresentation.setId(UUID.randomUUID().toString()); - protocolMapperRepresentation.setProtocolMapper("oid4vc-generated-id-mapper"); - protocolMapperRepresentation.setConfig(Map.of(OID4VCGeneratedIdMapper.CLAIM_NAME, "jti")); - return protocolMapperRepresentation; - } - - public static List getProtocolMappers(String scopeName) { - return List.of( - getSubjectIdMapper(CLAIM_NAME_SUBJECT_ID, UserModel.DID), - getUserAttributeMapper("email", "email"), - getUserAttributeMapper("firstName", "firstName"), - getUserAttributeMapper("lastName", "lastName"), - getUserAttributeMapper("address.street_address", "address_street_address"), - getUserAttributeMapper("address.locality", "address_locality"), - getJtiGeneratedIdMapper(), - getStaticClaimMapper(scopeName), - getIssuedAtTimeMapper("iat", ChronoUnit.HOURS.name(), "COMPUTE"), - getIssuedAtTimeMapper("nbf", null, "COMPUTE")); - } - - public static ProtocolMapperRepresentation getSubjectIdMapper(String subjectProperty, String attributeName) { - ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); - protocolMapperRepresentation.setName(attributeName + "-mapper"); - protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); - protocolMapperRepresentation.setId(UUID.randomUUID().toString()); - protocolMapperRepresentation.setProtocolMapper("oid4vc-subject-id-mapper"); - protocolMapperRepresentation.setConfig(Map.of( - "claim.name", subjectProperty, - "userAttribute", attributeName)); - return protocolMapperRepresentation; - } - - public static ProtocolMapperRepresentation getStaticClaimMapper(String scopeName) { - ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); - protocolMapperRepresentation.setName(UUID.randomUUID().toString()); - protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); - protocolMapperRepresentation.setId(UUID.randomUUID().toString()); - protocolMapperRepresentation.setProtocolMapper("oid4vc-static-claim-mapper"); - protocolMapperRepresentation.setConfig( - Map.of("claim.name", "scope-name", - "staticValue", scopeName) - ); - return protocolMapperRepresentation; - } - - public static ProtocolMapperRepresentation getUserAttributeMapper(String subjectProperty, String attributeName) { - ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); - protocolMapperRepresentation.setName(attributeName + "-mapper"); - protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); - protocolMapperRepresentation.setId(UUID.randomUUID().toString()); - protocolMapperRepresentation.setProtocolMapper("oid4vc-user-attribute-mapper"); - protocolMapperRepresentation.setConfig( - Map.of( - "claim.name", subjectProperty, - "userAttribute", attributeName) - ); - return protocolMapperRepresentation; - } - - public static UserRepresentation getUserRepresentation( - String fullName, - Map attributes, - List realmRoles, - Map> clientRoles) { - - String[] nameToks = fullName.split("\\s"); - String firstName = nameToks[0]; - String lastName = nameToks.length > 1 ? nameToks[1] : ""; - String username = firstName.toLowerCase(); - - UserConfigBuilder userBuilder = UserConfigBuilder.create() - .id(KeycloakModelUtils.generateId()) - .username(username) - .enabled(true) - .email(username + "@email.cz") - .emailVerified(true) - .firstName(firstName) - .lastName(lastName) - .password("password") - .attribute("address_street_address", "221B Baker Street") - .attribute("address_locality", "London") - .roles("account", "manage-account", "view-profile"); - - attributes.forEach(userBuilder::attribute); - - // When Keycloak issues a token for a user and client: - // 1. It looks up all effective realm roles and all effective client roles assigned to the user. - // 2. The token includes only those roles that the user actually has. - realmRoles.forEach(userBuilder::roles); - clientRoles.forEach((cid, roles) -> roles.forEach(role -> userBuilder.roles(cid, role))); - - return userBuilder.build(); - } - - public static List resolveProtocolMappers(String protocolMapperReferenceFile) { - if (protocolMapperReferenceFile == null) { - return null; - } - try (InputStream inputStream = OID4VCIssuerTestBase.class.getResourceAsStream(protocolMapperReferenceFile)) { - return JsonSerialization.mapper.readValue(inputStream, ClientScopeRepresentation.class).getProtocolMappers(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static class StaticTimeProvider implements TimeProvider { - private final int currentTimeInS; - - public StaticTimeProvider(int currentTimeInS) { - this.currentTimeInS = currentTimeInS; - } - - @Override - public int currentTimeSeconds() { - return currentTimeInS; - } - - @Override - public long currentTimeMillis() { - return currentTimeInS * 1000L; - } - } - - public static KeyWrapper getRsaKey(KeyUse keyUse, String algorithm, String keyName) { + KeyWrapper getRsaKey(KeyUse keyUse, String algorithm, String keyName) { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); @@ -393,43 +208,20 @@ public static KeyWrapper getRsaKey(KeyUse keyUse, String algorithm, String keyNa } } - public static ComponentRepresentation getRsaKeyProvider(KeyWrapper keyWrapper) { + ComponentRepresentation getRsaKeyProvider(KeyWrapper keyWrapper) { return createRsaKeyProviderComponent(keyWrapper, "rsa-key-provider", 0); } - public static ComponentRepresentation getRsaEncKeyProvider(String algorithm, String keyName, int priority) { + ComponentRepresentation getRsaEncKeyProvider(String algorithm, String keyName, int priority) { KeyWrapper keyWrapper = getRsaKey(KeyUse.ENC, algorithm, keyName); return createRsaKeyProviderComponent(keyWrapper, keyName, priority); } - private static ComponentRepresentation createRsaKeyProviderComponent(KeyWrapper keyWrapper, String name, int priority) { - ComponentRepresentation component = new ComponentRepresentation(); - component.setProviderType(KeyProvider.class.getName()); - component.setName(name); - component.setId(UUID.randomUUID().toString()); - component.setProviderId("rsa"); - - Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate( - new KeyPair((PublicKey) keyWrapper.getPublicKey(), (PrivateKey) keyWrapper.getPrivateKey()), "TestKey"); - - component.setConfig(new MultivaluedHashMap<>(Map.of( - "privateKey", List.of(PemUtils.encodeKey(keyWrapper.getPrivateKey())), - "certificate", List.of(PemUtils.encodeCertificate(certificate)), - "active", List.of("true"), - "priority", List.of(String.valueOf(priority)), - "enabled", List.of("true"), - "algorithm", List.of(keyWrapper.getAlgorithm()), - "keyUse", List.of(keyWrapper.getUse().name()) - ))); - - return component; - } - - public static KeyWrapper getRsaKey_Default() { + KeyWrapper getRsaKey_Default() { return getRsaKey(KeyUse.SIG, "RS256", null); } - public static ComponentRepresentation getAesKeyProvider(String algorithm, String keyName, String keyUse, String providerId) { + ComponentRepresentation getAesKeyProvider(String algorithm, String keyName, String keyUse, String providerId) { // Generate a random AES key (default length: 256 bits) byte[] secret = SecretGenerator.getInstance().randomBytes(32); // 32 bytes = 256 bits String secretBase64 = Base64.getEncoder().encodeToString(secret); @@ -452,28 +244,28 @@ public static ComponentRepresentation getAesKeyProvider(String algorithm, String return component; } - protected String getBearerToken(OAuthClient oauthClient) { + String getBearerToken(OAuthClient oauthClient) { return getBearerToken(oauthClient, null); } - protected String getBearerToken(OAuthClient oauthClient, ClientRepresentation client) { + String getBearerToken(OAuthClient oauthClient, ClientRepresentation client) { return getBearerToken(oauthClient, client, null); } - protected String getBearerToken(OAuthClient oauthClient, ClientRepresentation client, String scope) { + String getBearerToken(OAuthClient oauthClient, ClientRepresentation client, String scope) { return getBearerToken(oauthClient, client, "john", scope); } - protected String getBearerToken(OAuthClient oauthClient, ClientRepresentation client, String username, String scope) { + String getBearerToken(OAuthClient oauthClient, ClientRepresentation client, String username, String scope) { return getBearerTokenCodeFlow(oauthClient, client, username, scope).getAccessToken(); } - protected AccessTokenResponse getBearerTokenCodeFlow(OAuthClient oauthClient, ClientRepresentation client, String username, String scope) { + AccessTokenResponse getBearerTokenCodeFlow(OAuthClient oauthClient, ClientRepresentation client, String username, String scope) { var authCode = getAuthorizationCode(oauthClient, client, username, scope); return oauthClient.accessTokenRequest(authCode).send(); } - protected String getAuthorizationCode(OAuthClient oAuthClient, ClientRepresentation client, String username, String scope) { + String getAuthorizationCode(OAuthClient oAuthClient, ClientRepresentation client, String username, String scope) { if (client != null) { if (client.getSecret() != null) { oAuthClient.client(client.getClientId(), client.getSecret()); @@ -489,7 +281,7 @@ protected String getAuthorizationCode(OAuthClient oAuthClient, ClientRepresentat return authorizationEndpointResponse.getCode(); } - protected AccessTokenResponse getBearerToken(OAuthClient oauthClient, String authCode, OID4VCAuthorizationDetail... authDetail) { + AccessTokenResponse getBearerToken(OAuthClient oauthClient, String authCode, OID4VCAuthorizationDetail... authDetail) { AccessTokenRequest accessTokenRequest = oauthClient.accessTokenRequest(authCode); if (authDetail != null && authDetail.length > 0) { accessTokenRequest.authorizationDetails(Arrays.asList(authDetail)); @@ -501,7 +293,37 @@ protected AccessTokenResponse getBearerToken(OAuthClient oauthClient, String aut return tokenResponse; } - // Config ---------------------------------------------------------------------------------------------------------- + CredentialScopeRepresentation requireExistingCredentialScope(String scopeName) { + return Optional.ofNullable(getExistingCredentialScope(scopeName)) + .orElseThrow(() -> new IllegalStateException("No such credential scope: " + scopeName)); + } + + // Private --------------------------------------------------------------------------------------------------------- + + private ComponentRepresentation createRsaKeyProviderComponent(KeyWrapper keyWrapper, String name, int priority) { + ComponentRepresentation component = new ComponentRepresentation(); + component.setProviderType(KeyProvider.class.getName()); + component.setName(name); + component.setId(UUID.randomUUID().toString()); + component.setProviderId("rsa"); + + Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate( + new KeyPair((PublicKey) keyWrapper.getPublicKey(), (PrivateKey) keyWrapper.getPrivateKey()), "TestKey"); + + component.setConfig(new MultivaluedHashMap<>(Map.of( + "privateKey", List.of(PemUtils.encodeKey(keyWrapper.getPrivateKey())), + "certificate", List.of(PemUtils.encodeCertificate(certificate)), + "active", List.of("true"), + "priority", List.of(String.valueOf(priority)), + "enabled", List.of("true"), + "algorithm", List.of(keyWrapper.getAlgorithm()), + "keyUse", List.of(keyWrapper.getUse().name()) + ))); + + return component; + } + + // Static Config and RunOnServer Helpers --------------------------------------------------------------------------- static class VCTestServerConfig implements KeycloakServerConfig { @Override @@ -531,7 +353,7 @@ public RealmConfigBuilder configure(RealmConfigBuilder realm) { null, sdJwtTypeCredentialConfigurationIdName, sdJwtTypeCredentialScopeName, - sdJwtCredentialVct, + sdJwtTypeCredentialVct, VCFormat.SD_JWT_VC, null, List.of(OID4VCConstants.KeyAttestationResistanceLevels.HIGH, OID4VCConstants.KeyAttestationResistanceLevels.MODERATE)) @@ -565,9 +387,101 @@ public RealmConfigBuilder configure(RealmConfigBuilder realm) { return realm; } + + private CredentialScopeRepresentation createCredentialScope( + String scopeName, + String issuerDid, + String credentialConfigurationId, + String credentialIdentifier, + String vct, + String format, + String protocolMapperReferenceFile, + List acceptedKeyAttestationValues) { + + CredentialScopeRepresentation cs = new CredentialScopeRepresentation(scopeName) + .setIncludeInTokenScope(true) + .setExpiryInSeconds(15) + .setIssuerDid(issuerDid) + .setCredentialConfigurationId(credentialConfigurationId) + .setCredentialIdentifier(credentialIdentifier) + .setFormat(format) + .setVct(Optional.ofNullable(vct).orElse(credentialIdentifier)); + + if (credentialConfigurationId != null) { + List displayObjects = List.of( + new DisplayObject().setName(credentialConfigurationId).setLocale("en-EN"), + new DisplayObject().setName(credentialConfigurationId).setLocale("de-DE") + ); + cs.setDisplay(JsonSerialization.valueAsString(displayObjects)); + } + + if (acceptedKeyAttestationValues != null) { + cs.setKeyAttestationRequired(true); + if (!acceptedKeyAttestationValues.isEmpty()) { + cs.setRequiredKeyAttestationKeyStorage(acceptedKeyAttestationValues); + cs.setRequiredKeyAttestationUserAuthentication(acceptedKeyAttestationValues); + } + } + + if (protocolMapperReferenceFile == null) { + cs.setProtocolMappers(ProtocolMapperUtils.getProtocolMappers(scopeName)); + } else { + List protocolMappers = new ArrayList<>(resolveProtocolMappers(protocolMapperReferenceFile)); + protocolMappers.add(ProtocolMapperUtils.getStaticClaimMapper(scopeName)); + cs.setProtocolMappers(protocolMappers); + } + + return cs; + } + + private UserRepresentation getUserRepresentation( + String fullName, + Map attributes, + List realmRoles, + Map> clientRoles) { + + String[] nameToks = fullName.split("\\s"); + String firstName = nameToks[0]; + String lastName = nameToks.length > 1 ? nameToks[1] : ""; + String username = firstName.toLowerCase(); + + UserConfigBuilder userBuilder = UserConfigBuilder.create() + .id(KeycloakModelUtils.generateId()) + .username(username) + .enabled(true) + .email(username + "@email.cz") + .emailVerified(true) + .firstName(firstName) + .lastName(lastName) + .password("password") + .attribute("address_street_address", "221B Baker Street") + .attribute("address_locality", "London") + .roles("account", "manage-account", "view-profile"); + + attributes.forEach(userBuilder::attribute); + + // When Keycloak issues a token for a user and client: + // 1. It looks up all effective realm roles and all effective client roles assigned to the user. + // 2. The token includes only those roles that the user actually has. + realmRoles.forEach(userBuilder::roles); + clientRoles.forEach((cid, roles) -> roles.forEach(role -> userBuilder.roles(cid, role))); + + return userBuilder.build(); + } + + private List resolveProtocolMappers(String protocolMapperReferenceFile) { + if (protocolMapperReferenceFile == null) { + return null; + } + try (InputStream inputStream = OID4VCIssuerTestBase.class.getResourceAsStream(protocolMapperReferenceFile)) { + return JsonSerialization.mapper.readValue(inputStream, ClientScopeRepresentation.class).getProtocolMappers(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } } - public static class OID4VCIClient implements ClientConfig { + static class OID4VCIClient implements ClientConfig { @Override public ClientConfigBuilder configure(ClientConfigBuilder client) { @@ -584,16 +498,106 @@ public ClientConfigBuilder configure(ClientConfigBuilder client) { } } - protected boolean shouldEnableOid4vci(RealmRepresentation realm) { - return true; - } + static class ProtocolMapperUtils { - protected boolean shouldEnableOid4vci(ClientRepresentation client) { - return true; + static ProtocolMapperRepresentation getIssuedAtTimeMapper(String subjectProperty, String truncateToTimeUnit, String valueSource) { + ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); + protocolMapperRepresentation.setName(subjectProperty + "-oid4vc-issued-at-time-claim-mapper"); + protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); + protocolMapperRepresentation.setId(UUID.randomUUID().toString()); + protocolMapperRepresentation.setProtocolMapper("oid4vc-issued-at-time-claim-mapper"); + + Map configMap = new HashMap<>(); + Optional.ofNullable(subjectProperty) + .ifPresent(value -> configMap.put(OID4VCIssuedAtTimeClaimMapper.CLAIM_NAME, value)); + Optional.ofNullable(truncateToTimeUnit) + .ifPresent(value -> configMap.put(OID4VCIssuedAtTimeClaimMapper.TRUNCATE_TO_TIME_UNIT_KEY, value)); + Optional.ofNullable(valueSource) + .ifPresent(value -> configMap.put(OID4VCIssuedAtTimeClaimMapper.VALUE_SOURCE, value)); + + protocolMapperRepresentation.setConfig(configMap); + return protocolMapperRepresentation; + } + + static ProtocolMapperRepresentation getJtiGeneratedIdMapper() { + ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); + protocolMapperRepresentation.setName("generated-id-mapper"); + protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); + protocolMapperRepresentation.setId(UUID.randomUUID().toString()); + protocolMapperRepresentation.setProtocolMapper("oid4vc-generated-id-mapper"); + protocolMapperRepresentation.setConfig(Map.of(OID4VCGeneratedIdMapper.CLAIM_NAME, "jti")); + return protocolMapperRepresentation; + } + + static List getProtocolMappers(String scopeName) { + return List.of( + getSubjectIdMapper(CLAIM_NAME_SUBJECT_ID, UserModel.DID), + getUserAttributeMapper("email", "email"), + getUserAttributeMapper("firstName", "firstName"), + getUserAttributeMapper("lastName", "lastName"), + getUserAttributeMapper("address.street_address", "address_street_address"), + getUserAttributeMapper("address.locality", "address_locality"), + getJtiGeneratedIdMapper(), + getStaticClaimMapper(scopeName), + getIssuedAtTimeMapper("iat", ChronoUnit.HOURS.name(), "COMPUTE"), + getIssuedAtTimeMapper("nbf", null, "COMPUTE")); + } + + static ProtocolMapperRepresentation getStaticClaimMapper(String scopeName) { + ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); + protocolMapperRepresentation.setName(UUID.randomUUID().toString()); + protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); + protocolMapperRepresentation.setId(UUID.randomUUID().toString()); + protocolMapperRepresentation.setProtocolMapper("oid4vc-static-claim-mapper"); + protocolMapperRepresentation.setConfig( + Map.of("claim.name", "scope-name", + "staticValue", scopeName) + ); + return protocolMapperRepresentation; + } + + static ProtocolMapperRepresentation getSubjectIdMapper(String subjectProperty, String attributeName) { + ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); + protocolMapperRepresentation.setName(attributeName + "-mapper"); + protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); + protocolMapperRepresentation.setId(UUID.randomUUID().toString()); + protocolMapperRepresentation.setProtocolMapper("oid4vc-subject-id-mapper"); + protocolMapperRepresentation.setConfig(Map.of( + "claim.name", subjectProperty, + "userAttribute", attributeName)); + return protocolMapperRepresentation; + } + + static ProtocolMapperRepresentation getUserAttributeMapper(String subjectProperty, String attributeName) { + ProtocolMapperRepresentation protocolMapperRepresentation = new ProtocolMapperRepresentation(); + protocolMapperRepresentation.setName(attributeName + "-mapper"); + protocolMapperRepresentation.setProtocol(OID4VCIConstants.OID4VC_PROTOCOL); + protocolMapperRepresentation.setId(UUID.randomUUID().toString()); + protocolMapperRepresentation.setProtocolMapper("oid4vc-user-attribute-mapper"); + protocolMapperRepresentation.setConfig( + Map.of( + "claim.name", subjectProperty, + "userAttribute", attributeName) + ); + return protocolMapperRepresentation; + } } - boolean isOid4vciEnabled(ClientRepresentation client) { - Map attributes = Optional.ofNullable(client.getAttributes()).orElse(new HashMap<>()); - return Boolean.parseBoolean(attributes.get(OID4VCI_ENABLED_ATTRIBUTE_KEY)); + static class StaticTimeProvider implements TimeProvider { + private final int currentTimeInS; + + public StaticTimeProvider(int currentTimeInS) { + this.currentTimeInS = currentTimeInS; + } + + @Override + public int currentTimeSeconds() { + return currentTimeInS; + } + + @Override + public long currentTimeMillis() { + return currentTimeInS * 1000L; + } } } diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java index b1ee877390f..81a1d89b291 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCJWTIssuerEndpointTest.java @@ -171,8 +171,8 @@ void testGetCredentialOfferUriInvalidToken() { @Test public void testGetCredentialOfferURI() { - final String scopeName = jwtTypeCredentialClientScope.getName(); - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + final String scopeName = jwtTypeCredentialScope.getName(); + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); String token = getBearerToken(oauth, client, scopeName); @@ -340,9 +340,9 @@ public void testRequestCredentialInvalidToken() { @Test public void testRequestCredentialNoMatchingCredentialBuilder() throws Throwable { - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); - final String scopeName = jwtTypeCredentialClientScope.getName(); + final String scopeName = jwtTypeCredentialScope.getName(); CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); @@ -407,8 +407,8 @@ public void testRequestCredentialUnsupportedCredential() { @Test public void testRequestCredential() { - String scopeName = jwtTypeCredentialClientScope.getName(); - String credConfigId = jwtTypeCredentialClientScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID); + String scopeName = jwtTypeCredentialScope.getName(); + String credConfigId = jwtTypeCredentialScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID); CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); @@ -473,7 +473,7 @@ public void testRequestCredential() { @Test public void testRequestCredentialWithNeitherIdSet() { - final String scopeName = minimalJwtTypeCredentialClientScope.getName(); + final String scopeName = minimalJwtTypeCredentialScope.getName(); String token = getBearerToken(oauth, client, scopeName); runOnServer.run(session -> { @@ -500,10 +500,10 @@ public void testRequestCredentialWithNeitherIdSet() { @Test public void testCredentialIssuance() { - String token = getBearerToken(oauth, client, jwtTypeCredentialClientScope.getName()); + String token = getBearerToken(oauth, client, jwtTypeCredentialScope.getName()); // 1. Retrieving the credential-offer-uri - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); CredentialOfferURI credOfferUri = oauth.oid4vc() @@ -568,10 +568,9 @@ public void testCredentialIssuance() { try { requestCredentialWithIdentifier( theToken, - credentialIssuer.getCredentialEndpoint(), credentialIdentifier, new CredentialResponseHandler(), - jwtTypeCredentialClientScope + jwtTypeCredentialScope ); } catch (IOException e) { fail("Was not able to get the credential."); @@ -583,8 +582,8 @@ public void testCredentialIssuance() { @Test public void testCredentialIssuanceWithAuthZCodeWithScopeMatched() throws Exception { - String scopeName = jwtTypeCredentialClientScope.getName(); - String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + String scopeName = jwtTypeCredentialScope.getName(); + String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); @@ -607,17 +606,16 @@ public void testCredentialIssuanceWithAuthZCodeWithScopeMatched() throws Excepti requestCredentialWithIdentifier( accessTokenResponse.getAccessToken(), - credentialIssuer.getCredentialEndpoint(), credentialIdentifier, new CredentialResponseHandler(), - jwtTypeCredentialClientScope + jwtTypeCredentialScope ); } @Test public void testCredentialIssuanceWithAuthZCodeWithScopeUnmatched() { testCredentialIssuanceWithAuthZCodeFlow( - sdJwtTypeCredentialClientScope, + sdJwtTypeCredentialScope, (testScope) -> getBearerToken(oauth.openid(false).scope("email")), // set registered different scope m -> { String accessToken = (String) m.get("accessToken"); @@ -636,7 +634,7 @@ public void testCredentialIssuanceWithAuthZCodeWithScopeUnmatched() { @Test public void testCredentialIssuanceWithAuthZCodeSWithoutScope() { testCredentialIssuanceWithAuthZCodeFlow( - sdJwtTypeCredentialClientScope, + sdJwtTypeCredentialScope, (testScope) -> getBearerToken(oauth.openid(false).scope(null)), // no scope m -> { String accessToken = (String) m.get("accessToken"); @@ -659,7 +657,7 @@ public void testCredentialIssuanceWithAuthZCodeSWithoutScope() { @Test public void testCredentialIssuanceWithScopeUnmatched() { Function getAccessToken = (testScope) -> - getBearerToken(oauth, client, jwtTypeCredentialClientScope.getName()); + getBearerToken(oauth, client, jwtTypeCredentialScope.getName()); Consumer> sendCredentialRequest = m -> { String accessToken = (String) m.get("accessToken"); @@ -678,14 +676,14 @@ public void testCredentialIssuanceWithScopeUnmatched() { } }; - testCredentialIssuanceWithAuthZCodeFlow(sdJwtTypeCredentialClientScope, getAccessToken, sendCredentialRequest, + testCredentialIssuanceWithAuthZCodeFlow(sdJwtTypeCredentialScope, getAccessToken, sendCredentialRequest, (cid) -> new CredentialRequest().setCredentialIdentifier("sd-jwt-credential")); } @Test public void testRequestMultipleCredentialsWithProofs() { - final String scopeName = jwtTypeCredentialClientScope.getName(); - String credConfigId = jwtTypeCredentialClientScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID); + final String scopeName = jwtTypeCredentialScope.getName(); + String credConfigId = jwtTypeCredentialScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID); CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); @@ -764,8 +762,8 @@ public void testRequestMultipleCredentialsWithProofs() { @Test public void testGetJwtVcConfigFromMetadata() { - final String scopeName = jwtTypeCredentialClientScope.getName(); - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + final String scopeName = jwtTypeCredentialScope.getName(); + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); String expectedIssuer = keycloakUrls.getBase() + "/realms/" + testRealm.getName(); @@ -897,7 +895,7 @@ public void testGetJwtVcConfigFromMetadata() { @Test public void testRequestCredentialWithUnknownCredentialIdentifier() { - String token = getBearerToken(oauth, client, jwtTypeCredentialClientScope.getName()); + String token = getBearerToken(oauth, client, jwtTypeCredentialScope.getName()); runOnServer.run(session -> { try { @@ -925,7 +923,7 @@ public void testRequestCredentialWithUnknownCredentialIdentifier() { @Test public void testRequestCredentialWithUnknownCredentialConfigurationId() { - String token = getBearerToken(oauth, client, jwtTypeCredentialClientScope.getName()); + String token = getBearerToken(oauth, client, jwtTypeCredentialScope.getName()); runOnServer.run(session -> { try { @@ -953,8 +951,8 @@ public void testRequestCredentialWithUnknownCredentialConfigurationId() { @Test public void testRequestCredentialWhenNoCredentialBuilderForFormat() { - String scopeName = jwtTypeCredentialClientScope.getName(); - String credConfigId = jwtTypeCredentialClientScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID); + String scopeName = jwtTypeCredentialScope.getName(); + String credConfigId = jwtTypeCredentialScope.getAttributes().get(CredentialScopeModel.VC_CONFIGURATION_ID); CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); OID4VCAuthorizationDetail authDetail = new OID4VCAuthorizationDetail(); @@ -1000,8 +998,8 @@ public void testRequestCredentialWhenNoCredentialBuilderForFormat() { @Test public void testProofToProofsConversion() { - final String scopeName = jwtTypeCredentialClientScope.getName(); - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + final String scopeName = jwtTypeCredentialScope.getName(); + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); CredentialIssuer credentialIssuer = getCredentialIssuerMetadata(); @@ -1214,8 +1212,8 @@ public void testCannotAssignOid4vciScopeWhenRealmDisabled() { @Test public void testCredentialOfferReplayProtection() { - String token = getBearerToken(oauth, client, jwtTypeCredentialClientScope.getName()); - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + String token = getBearerToken(oauth, client, jwtTypeCredentialScope.getName()); + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); // 1. Retrieving the create-credential-offer @@ -1257,8 +1255,8 @@ public void testCredentialOfferReplayProtection() { @Test public void testCredentialOfferDifferentNoncesIndependent() { - String token = getBearerToken(oauth, client, jwtTypeCredentialClientScope.getName()); - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + String token = getBearerToken(oauth, client, jwtTypeCredentialScope.getName()); + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); // 1. Create first credential offer @@ -1325,8 +1323,8 @@ public void testCredentialOfferDifferentNoncesIndependent() { @Test public void testPreAuthorizedCodeValidAfterOfferConsumed() { - String token = getBearerToken(oauth, client, jwtTypeCredentialClientScope.getName()); - final String credentialConfigurationId = jwtTypeCredentialClientScope.getAttributes() + String token = getBearerToken(oauth, client, jwtTypeCredentialScope.getName()); + final String credentialConfigurationId = jwtTypeCredentialScope.getAttributes() .get(CredentialScopeModel.VC_CONFIGURATION_ID); // 1. Fetch the Offer URI @@ -1377,7 +1375,7 @@ public void testPreAuthorizedCodeValidAfterOfferConsumed() { assertFalse(accessTokenResponse.getAccessToken().isEmpty(), "Access token should not be empty"); } - public String getCNonce() { + private String getCNonce() { UriBuilder builder = UriBuilder.fromUri(keycloakUrls.getBase()); URI oid4vcUri = RealmsResource.protocolUrl(builder) .build(testRealm.getName(), OID4VCLoginProtocolFactory.PROTOCOL_ID); @@ -1412,7 +1410,7 @@ public String getCNonce() { return nonceResponse.getNonce(); } - public static String parseResponse(Response response) { + private static String parseResponse(Response response) { try { return response.readEntity(String.class); } catch (Exception e) { @@ -1420,7 +1418,7 @@ public static String parseResponse(Response response) { } } - public static String generateJwtProof(String aud, String nonce) { + private static String generateJwtProof(String aud, String nonce) { KeyWrapper keyWrapper = getECKey(null); keyWrapper.setKid(null); // erase the autogenerated one @@ -1431,7 +1429,7 @@ public static String generateJwtProof(String aud, String nonce) { .sign(new ECDSASignatureSignerContext(keyWrapper)); } - public static JWSBuilder.EncodingBuilder generateUnsignedJwtProof(JWK jwk, String aud, String nonce) { + private static JWSBuilder.EncodingBuilder generateUnsignedJwtProof(JWK jwk, String aud, String nonce) { AccessToken token = new AccessToken(); token.addAudience(aud); token.setNonce(nonce);