Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[INJICERT-434] add optional expiry time override #132

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
import io.mosip.certify.core.repository.TemplateRepository;
import io.mosip.certify.core.spi.SvgTemplateService;
import io.mosip.certify.services.SVGRenderUtils;
import io.mosip.certify.utils.CredentialUtils;
import jakarta.annotation.PostConstruct;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
Expand All @@ -44,8 +46,8 @@ public class VelocityTemplatingEngineImpl implements VCFormatter {
TemplateRepository templateRepository;
@Autowired
SvgTemplateService svgTemplateService;
@Value("${mosip.certify.vcformat.vc.expiry:true}")
boolean shouldHaveDates;
@Value("${mosip.certify.issuer.default.expiry.duration:2y}")
String defaultExpiryDuration;

@PostConstruct
public void initialize() {
Expand Down Expand Up @@ -116,16 +118,18 @@ public String format(JSONObject templateInput, Map<String, Object> defaultSettin
log.error("SVG Template: " + defaultSettings.get(SVG_TEMPLATE) + " not available in DB", e);
}
}
if (shouldHaveDates && !(templateInput.has(VCDM2Constants.VALID_FROM)
&& templateInput.has(VCDM2Constants.VALID_UNITL))) {

if (!(templateInput.has(VCDM2Constants.VALID_FROM)
&& templateInput.has(VCDM2Constants.VALID_UNITL)) && StringUtils.isNotEmpty(defaultExpiryDuration)) {
String time = ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern(Constants.UTC_DATETIME_PATTERN));
// hardcoded time
String expiryTime = ZonedDateTime.now(ZoneOffset.UTC).plusYears(2).format(DateTimeFormatter.ofPattern(Constants.UTC_DATETIME_PATTERN));
String expiryTime = ZonedDateTime.now(ZoneOffset.UTC)
.plusSeconds(CredentialUtils.toSeconds(defaultExpiryDuration))
.format(DateTimeFormatter.ofPattern(Constants.UTC_DATETIME_PATTERN));
finalTemplate.put(VCDM2Constants.VALID_FROM, time);
finalTemplate.put(VCDM2Constants.VALID_UNITL, expiryTime);
}
VelocityContext context = new VelocityContext(finalTemplate);
engine.evaluate(context, writer, /*logTag */ templateName,t.toString());
engine.evaluate(context, writer, /*logTag */ templateName, t.toString());
return writer.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@

import io.mosip.certify.api.dto.VCRequestDto;

import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CredentialUtils {
public static final long DEFAULT_EXPIRY_DURATION_SECONDS = 2 * ChronoUnit.YEARS.getDuration().getSeconds();
// returns true for VC 2.0 VCI requests
public static boolean isVC2_0Request(VCRequestDto r) {
return r.getContext().get(0).equals("https://www.w3.org/ns/credentials/v2");
Expand All @@ -26,4 +31,28 @@ public static String getTemplateName(VCRequestDto vcRequestDto) {
String typeKey = String.join(",", t);
return String.join(":", typeKey, contextKey);
}

/**
* Converts a String time duration to seconds
* @param duration
* @return
*/
public static long toSeconds(String duration) {
Pattern pattern = Pattern.compile("(?:(\\d+)y)?(?:(\\d+)M)?(?:(\\d+)d)?(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?");
Matcher matcher = pattern.matcher(duration);
long total = 0;
TemporalUnit[] durationArray = {ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS };
if (matcher.matches()) {
for (int i = 1; i <= matcher.groupCount(); i++) {
if (matcher.group(i) != null) {
total += Integer.parseInt(matcher.group(i)) * durationArray[i-1].getDuration().getSeconds();
}
}
if (total == 0) {
return DEFAULT_EXPIRY_DURATION_SECONDS;
}
return total;
}
return DEFAULT_EXPIRY_DURATION_SECONDS;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ mosip.certify.authorization.url=http://localhost:8088
mosip.certify.discovery.issuer-id=${mosip.certify.domain.url}${server.servlet.path}
mosip.certify.issuer.vc-sign-algo=Ed25519Signature2018
mosip.certify.issuer=CertifyIssuer

mosip.certify.issuer.default.expiry.duration=2y
##--------------change this later---------------------------------
mosip.certify.supported.jwt-proof-alg={'RS256','PS256','ES256'}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public void setUp() {
"https://vharsh.github.io/DID/mock-context.json,https://www.w3.org/2018/credentials/v1"
);
when(templateRepository.findAll()).thenReturn(List.of(vc1, vc2, vc3));
ReflectionTestUtils.setField(formatter, "shouldHaveDates", true);
ReflectionTestUtils.setField(formatter, "defaultExpiryDuration", "2y");
formatter.initialize();
// engine = new VelocityEngine();
// engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,44 @@

import io.mosip.certify.api.dto.VCRequestDto;
import junit.framework.TestCase;
import org.apache.commons.validator.Arg;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsSource;
import org.junit.jupiter.params.provider.MethodSource;

import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Stream;

public class CredentialUtilsTest extends TestCase {
public class CredentialUtilsTest {

@Test
public void testGetTemplateName() {
VCRequestDto request = new VCRequestDto();
request.setContext(List.of("https://www.w3.org/ns/credentials/v2", "https://example.org/Person.json"));
request.setType(List.of("VerifiableCredential", "UniversityCredential"));
String expected = "UniversityCredential,VerifiableCredential:https://example.org/Person.json,https://www.w3.org/ns/credentials/v2";
assertEquals(expected, CredentialUtils.getTemplateName(request));
Assert.assertEquals(expected, CredentialUtils.getTemplateName(request));
}

@ParameterizedTest
@MethodSource("provideTimeDuration")
public void testToSeconds(long expectedDuration, String duration) {
Assert.assertEquals(expectedDuration, CredentialUtils.toSeconds(duration));
}

private static Stream<Arguments> provideTimeDuration() {
return Stream.of(
Arguments.of(14519, "4h1m59s"),
Arguments.of(59, "59s"),
Arguments.of(3_15_56_952, "1y"),
Arguments.of(60, "1m"),
Arguments.of(86400, "1d"),
Arguments.of(6_31_13_904, ""),
Arguments.of(6_31_13_904, "0s")
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ mosip.certify.integration.scan-base-package=io.mosip.certify
mosip.certify.integration.audit-plugin=TestAuditPlugin
mosip.certify.integration.vci-plugin=TestVCIPluginImpl
mosip.certify.issuer=PluginIssuer
mosip.certify.issuer.vc-sign-algo=Ed25519Signature2018
mosip.certify.issuer.vc-sign-algo=Ed25519Signature2020
mosip.certify.issuer.default.expiry.duration=2y
# mosip.certify.issuer.vc-sign-algo:Ed25519Signature2018 for CertifyIssuer test

## ------------------------------------------ Discovery openid-configuration -------------------------------------------
Expand Down
Loading