8000 Remove java.util.Date from VerifiableCredential by Captain-P-Goldfish · Pull Request #30920 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
Expand Down
2 changes: 2 additions & 0 deletions core/src/main/java/org/keycloak/util/JsonSerialization.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.io.InputStream;
Expand All @@ -43,6 +44,7 @@ public class JsonSerialization {

static {
mapper.registerModule(new Jdk8Module());
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
prettyMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ private VerifiableCredential getVCToSign(List<OID4VCMapper> protocolMappers, Str
// set the required claims
VerifiableCredential vc = new VerifiableCredential()
.setIssuer(URI.create(issuerDid))
.setIssuanceDate(Date.from(Instant.ofEpochMilli(timeProvider.currentTimeMillis())))
.setIssuanceDate(Instant.ofEpochMilli(timeProvider.currentTimeMillis()))
.setType(List.of(vcType));

Map<String, Object> subjectClaims = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.keycloak.representations.JsonWebToken;

import java.net.URI;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;

Expand Down Expand Up @@ -74,7 +75,7 @@ public String signCredential(VerifiableCredential verifiableCredential) {
// Get the issuance date from the credential. Since nbf is mandatory, we set it to the current time if not
// provided
long iat = Optional.ofNullable(verifiableCredential.getIssuanceDate())
.map(issuanceDate -> issuanceDate.toInstant().getEpochSecond())
.map(Instant::getEpochSecond)
.orElse((long) timeProvider.currentTimeSeconds());

// set mandatory fields
Expand All @@ -86,7 +87,7 @@ public String signCredential(VerifiableCredential verifiableCredential) {

// expiry is optional
Optional.ofNullable(verifiableCredential.getExpirationDate())
.ifPresent(d -> jsonWebToken.exp(d.toInstant().getEpochSecond()));
.ifPresent(d -> jsonWebToken.exp(d.getEpochSecond()));

// subject id should only be set if the credential subject has an id.
Optional.ofNullable(
Expand All @@ -110,4 +111,4 @@ static String createCredentialId(VerifiableCredential verifiableCredential) {
.orElse(URI.create(String.format(ID_TEMPLATE, UUID.randomUUID())))
.toString();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
package org.keycloak.protocol.oid4vc.issuance.signing;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.keycloak.common.util.Base64;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.crypto.SignatureProvider;
Expand Down Expand Up @@ -48,7 +47,7 @@ public class LDSigningService extends SigningService<VerifiableCredential> {
private final TimeProvider timeProvider;
private final String keyId;

public LDSigningService(KeycloakSession keycloakSession, String keyId, String algorithmType, String ldpType, ObjectMapper objectMapper, TimeProvider timeProvider, Optional<String> kid) {
public LDSigningService(KeycloakSession keycloakSession, String keyId, String algorithmType, String ldpType, TimeProvider timeProvider, Optional<String> kid) {
super(keycloakSession, keyId, algorithmType);
this.timeProvider = timeProvider;
this.keyId = kid.orElse(keyId);
Expand All @@ -66,7 +65,7 @@ public LDSigningService(KeycloakSession keycloakSession, String keyId, String al

linkedDataCryptographicSuite = switch (ldpType) {
case Ed255192018Suite.PROOF_TYPE ->
new Ed255192018Suite(objectMapper, signatureProvider.signer(signingKey));
new Ed255192018Suite(signatureProvider.signer(signingKey));
default -> throw new SigningServiceException(String.format("Proof Type %s is not supported.", ldpType));
};
}
Expand Down Expand Up @@ -96,4 +95,4 @@ private VerifiableCredential addProof(VerifiableCredential verifiableCredential)
throw new SigningServiceException("Was not able to encode the signature.", e);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

package org.keycloak.protocol.oid4vc.issuance.signing;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.keycloak.component.ComponentModel;
import org.keycloak.component.ComponentValidationException;
import org.keycloak.models.KeycloakSession;
Expand All @@ -39,15 +38,13 @@ public class LDSigningServiceProviderFactory implements VCSigningServiceProvider
public static final String SUPPORTED_FORMAT = Format.LDP_VC;
private static final String HELP_TEXT = "Issues Verifiable Credentials in the W3C Data Model, using Linked-Data Proofs. See https://www.w3.org/TR/vc-data-model/";

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

@Override
< 10000 span class='blob-code-inner blob-code-marker ' data-code-marker=" "> public VerifiableCredentialsSigningService create(KeycloakSession session, ComponentModel model) {
String keyId = model.get(SigningProperties.KEY_ID.getKey());
String proofType = model.get(SigningProperties.PROOF_TYPE.getKey());
String algorithmType = model.get(SigningProperties.ALGORITHM_TYPE.getKey());
Optional<String> kid = Optional.ofNullable(model.get(SigningProperties.KID_HEADER.getKey()));
return new LDSigningService(session, keyId, algorithmType, proofType, OBJECT_MAPPER, new OffsetTimeProvider(), kid);
return new LDSigningService(session, keyId, algorithmType, proofType, new OffsetTimeProvider(), kid);
}

@Override
Expand All @@ -58,10 +55,10 @@ public String getHelpText() {
@Override
public List<ProviderConfigProperty> getConfigProperties() {
return VCSigningServiceProviderFactory.configurationBuilder()
.property(SigningProperties.ALGORITHM_TYPE.asConfigProperty())
.property(SigningProperties.PROOF_TYPE.asConfigProperty())
.property(SigningProperties.KID_HEADER.asConfigProperty())
.build();
.property(SigningProperties.ALGORITHM_TYPE.asConfigProperty())
.property(SigningProperties.PROOF_TYPE.asConfigProperty())
.property(SigningProperties.KID_HEADER.asConfigProperty())
.build();
}

@Override
Expand All @@ -72,8 +69,8 @@ public String getId() {
@Override
public void validateSpecificConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException {
ConfigurationValidationHelper.check(model)
.checkRequired(SigningProperties.ALGORITHM_TYPE.asConfigProperty())
.checkRequired(SigningProperties.PROOF_TYPE.asConfigProperty());
.checkRequired(SigningProperties.ALGORITHM_TYPE.asConfigProperty())
.checkRequired(SigningProperties.PROOF_TYPE.asConfigProperty());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.keycloak.sdjwt.SdJwt;
import org.keycloak.sdjwt.SdJwtUtils;

import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
Expand Down Expand Up @@ -121,7 +122,7 @@ public String signCredential(VerifiableCredential verifiableCredential) {
// Get the issuance date from the credential. Since nbf is mandatory, we set it to the current time if not
// provided
long iat = Optional.ofNullable(verifiableCredential.getIssuanceDate())
.map(issuanceDate -> issuanceDate.toInstant().getEpochSecond())
.map(Instant::getEpochSecond)
.orElse((long) timeProvider.currentTimeSeconds());
rootNode.put(NOT_BEFORE_CLAIM, iat);
if (verifiableCredential.getType() == null || verifiableCredential.getType().size() != 1) {
Expand All @@ -141,4 +142,4 @@ public String signCredential(VerifiableCredential verifiableCredential) {
return sdJwt.toSdJwtString();
}

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@
import com.apicatalog.rdf.io.error.RdfWriterException;
import com.apicatalog.rdf.io.error.UnsupportedContentException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.setl.rdf.normalization.RdfNormalize;
import jakarta.json.JsonObject;
import jakarta.json.JsonValue;
import org.keycloak.crypto.SignatureSignerContext;
import org.keycloak.protocol.oid4vc.issuance.signing.SigningServiceException;
import org.keycloak.protocol.oid4vc.model.VerifiableCredential;
import org.keycloak.util.JsonSerialization;

import java.io.IOException;
import java.io.StringReader;
Expand All @@ -59,13 +59,11 @@
*/
public class Ed255192018Suite implements LinkedDataCryptographicSuite {

private final ObjectMapper objectMapper;
private final SignatureSignerContext signerContext;

public static final String PROOF_TYPE = "Ed25519Signature2018";

public Ed255192018Suite(ObjectMapper objectMapper, SignatureSignerContext signerContext) {
this.objectMapper = objectMapper;
public Ed255192018Suite(SignatureSignerContext signerContext) {
this.signerContext = signerContext;
}

Expand All @@ -79,7 +77,7 @@ public byte[] getSignature(VerifiableCredential verifiableCredential) {
private byte[] transform(VerifiableCredential verifiableCredential) {

try {
String credentialString = objectMapper.writeValueAsString(verifiableCredential);
String credentialString = JsonSerialization.mapper.writeValueAsString(verifiableCredential);

var credentialDocument = JsonDocument.of(new StringReader(credentialString));

Expand Down Expand Up @@ -134,4 +132,4 @@ private byte[] sign(byte[] hashData) {
public String getProofType() {
return PROOF_TYPE;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;

import java.net.URI;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
Expand All @@ -50,9 +51,9 @@ public class VerifiableCredential {
private List<String> context = new ArrayList<>(List.of(VC_CONTEXT_V1));
private List<String> type = new ArrayList<>();
private URI issuer;
private Date issuanceDate;
private Instant issuanceDate;
private URI id;
private Date expirationDate;
private Instant expirationDate;
private CredentialSubject credentialSubject = new CredentialSubject();
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<>();
Expand Down Expand Up @@ -95,11 +96,11 @@ public VerifiableCredential setIssuer(URI issuer) {
return this;
}

public Date getIssuanceDate() {
public Instant getIssuanceDate() {
return issuanceDate;
}

public VerifiableCredential setIssuanceDate(Date issuanceDate) {
public VerifiableCredential setIssuanceDate(Instant issuanceDate) {
this.issuanceDate = issuanceDate;
return this;
}
Expand All @@ -113,11 +114,11 @@ public VerifiableCredential setId(URI id) {
return this;
}

public Date getExpirationDate() {
public Instant getExpirationDate() {
return expirationDate;
}

public VerifiableCredential setExpirationDate(Date expirationDate) {
public VerifiableCredential setExpirationDate(Instant expirationDate) {
this.expirationDate = expirationDate;
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

package org.keycloak.testsuite.oid4vc.issuance.signing;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.logging.Logger;
import org.junit.Before;
import org.junit.Test;
Expand All @@ -38,10 +37,10 @@
import org.keycloak.representations.JsonWebToken;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.testsuite.runonserver.RunOnServerException;
import org.keycloak.util.JsonSerialization;

import java.security.PublicKey;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -126,7 +125,7 @@ public void testRsaSignedCredentialWithIssuanceDate() {
Map.of("id", String.format("uri:uuid:%s", UUID.randomUUID()),
"test", "test",
"arrayClaim", List.of("a", "b", "c"),
"issuanceDate", Date.from(Instant.ofEpochSecond(10)))));
"issuanceDate", Instant.ofEpochSecond(10))));
}

@Test
Expand Down Expand Up @@ -184,19 +183,19 @@ public static void testSignJwtCredential(KeycloakSession session, String algorit
try {
JsonWebToken theToken = verifier.getToken();

assertEquals("JWT claim in JWT encoded VC or VP MUST be used to set the value of the “expirationDate” of the VC", TEST_EXPIRATION_DATE.toInstant().getEpochSecond(), theToken.getExp().longValue());
assertEquals("JWT claim in JWT encoded VC or VP MUST be used to set the value of the “expirationDate” of the VC", TEST_EXPIRATION_DATE.getEpochSecond(), theToken.getExp().longValue());
if (claims.containsKey("issuanceDate")) {
assertEquals("VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim.", ((Date) claims.get("issuanceDate")).toInstant().getEpochSecond(), theToken.getNbf().longValue());
assertEquals("VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim.", ((Instant) claims.get("issuanceDate")).getEpochSecond(), theToken.getNbf().longValue());
} else {
// if not specific date is set, check against "currentTime"
assertEquals("VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim.", TEST_ISSUANCE_DATE.toInstant().getEpochSecond(), theToken.getNbf().longValue());
assertEquals("VC Data Model v1.1 specifies that “issuanceDate” property MUST be represented as an nbf JWT claim, and not iat JWT claim.", TEST_ISSUANCE_DATE.getEpochSecond(), theToken.getNbf().longValue());
}
assertEquals("The issuer should be set in the token.", TEST_DID.toString(), theToken.getIssuer());
assertEquals("The credential ID should be set as the token ID.", testCredential.getId().toString(), theToken.getId());
Optional.ofNullable(testCredential.getCredentialSubject().getClaims().get("id")).ifPresent(id -> assertEquals("If the credentials subject id is set, it should be set as the token subject.", id.toString(), theToken.getSubject()));

assertNotNull("The credentials should be included at the vc-claim.", theToken.getOtherClaims().get("vc"));
VerifiableCredential credential = new ObjectMapper().convertValue(theToken.getOtherClaims().get("vc"), VerifiableCredential.class);
VerifiableCredential credential = JsonSerialization.mapper.convertValue(theToken.getOtherClaims().get("vc"), VerifiableCredential.class);
assertEquals("The types should be included", TEST_TYPES, credential.getType());
assertEquals("The issuer should be included", TEST_DID, credential.getIssuer());
assertEquals("The expiration date should be included", TEST_EXPIRATION_DATE, credential.getExpirationDate());
Expand All @@ -213,7 +212,7 @@ public static void testSignJwtCredential(KeycloakSession session, String algorit
}
}


@Override
public void configureTestRealm(RealmRepresentation testRealm) {
if (testRealm.getComponents() != null) {
Expand All @@ -223,4 +222,4 @@ public void configureTestRealm(RealmRepresentation testRealm) {
Map.of("org.keycloak.keys.KeyProvider", List.of(getRsaKeyProvider(rsaKey)))));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

package org.keycloak.testsuite.oid4vc.issuance.signing;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.keycloak.common.crypto.CryptoIntegration;
Expand All @@ -33,7 +32,6 @@
import org.keycloak.testsuite.runonserver.RunOnServerException;

import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -61,7 +59,6 @@ public void testUnsupportedLdpType() throws Throwable {
getKeyFromSession(session).getKid(),
"EdDSA",
"UnsupportedSignatureType",
new ObjectMapper(),
new StaticTimeProvider(1000),
Optional.empty()));
} catch (RunOnServerException ros) {
Expand All @@ -81,7 +78,6 @@ public void testFailIfNoKey() throws Throwable {
"no-such-key",
"EdDSA",
"Ed25519Signature2018",
new ObjectMapper(),
new StaticTimeProvider(1000),
Optional.empty()));
} catch (RunOnServerException ros) {
Expand Down Expand Up @@ -113,7 +109,7 @@ public void testLdpSignedCredentialWithIssuanceDate() {
Map.of("id", String.format("uri:uuid:%s", UUID.randomUUID()),
"test", "test",
"arrayClaim", List.of("a", "b", "c"),
"issuanceDate", Date.from(Instant.ofEpochSecond(10))),
"issuanceDate", Instant.ofEpochSecond(10)),
Optional.empty()));
}

Expand All @@ -127,7 +123,7 @@ public void testLdpSignedCredentialWithCustomKid() {
Map.of("id", String.format("uri:uuid:%s", UUID.randomUUID()),
"test", "test",
"arrayClaim", List.of("a", "b", "c"),
"issuanceDate", Date.from(Instant.ofEpochSecond(10))),
"issuanceDate", Instant.ofEpochSecond(10)),
Optional.of("did:web:test.org#the-key-id")));
}

Expand All @@ -150,7 +146,6 @@ public static void testSignLdCredential(KeycloakSession session, Map<String, Obj
keyWrapper.getKid(),
"EdDSA",
"Ed25519Signature2018",
new ObjectMapper(),
new StaticTimeProvider(1000),
kid);

Expand Down
Loading
0