Search in sources :

Example 1 with VerifiableCredential

use of uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential in project di-ipv-cri-uk-passport-back by alphagov.

the class JwtHelperTest method shouldCreateValidSignedJWT.

@Test
void shouldCreateValidSignedJWT() throws JOSEException, ParseException, InvalidKeySpecException, NoSuchAlgorithmException, JsonProcessingException {
    ECDSASigner ecSigner = new ECDSASigner(getPrivateKey());
    VerifiableCredential verifiableCredential = new VerifiableCredential(new CredentialSubject(new Name(List.of(new NameParts(GIVEN_NAME, NamePartType.GIVEN_NAME.getName(), VALID_FROM, VALID_UNTIL))), PASSPORT_NUMBER, new BirthDate(BIRTH_DATE), LocalDate.parse(EXPIRY_DATE).toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString(), new DcsResponse()), Collections.singletonList(new Evidence()));
    JWTClaimsSet testClaimsSet = new JWTClaimsSet.Builder().claim("sub", "test-subject").claim("iss", "test-issuer").claim("nbf", Instant.now().getEpochSecond()).claim("vc", verifiableCredential).claim("exp", Instant.now().plusSeconds(100000).getEpochSecond()).build();
    SignedJWT signedJWT = JwtHelper.createSignedJwtFromClaimSet(testClaimsSet, ecSigner);
    JWTClaimsSet generatedClaims = signedJWT.getJWTClaimsSet();
    assertTrue(signedJWT.verify(new ECDSAVerifier(ECKey.parse(EC_PUBLIC_JWK_1))));
    JsonNode claimsSet = objectMapper.readTree(generatedClaims.toString());
    JsonNode vcNode = claimsSet.get("vc");
    JsonNode credentialSubjectNode = vcNode.get("credentialSubject");
    JsonNode nameNode = credentialSubjectNode.get("name");
    assertEquals(GIVEN_NAME, nameNode.get("nameParts").get(0).get("value").asText());
    assertEquals(NamePartType.GIVEN_NAME.getName(), nameNode.get("nameParts").get(0).get("type").asText());
    assertEquals(VALID_FROM, nameNode.get("nameParts").get(0).get("validFrom").asText());
    assertEquals(VALID_UNTIL, nameNode.get("nameParts").get(0).get("validUntil").asText());
    assertEquals(BIRTH_DATE, credentialSubjectNode.get("birthDate").get("value").asText());
    assertEquals(EXPIRY_DATE, credentialSubjectNode.get("expiryDate").asText());
}
Also used : DcsResponse(uk.gov.di.ipv.cri.passport.library.domain.DcsResponse) CredentialSubject(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.CredentialSubject) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) JsonNode(com.fasterxml.jackson.databind.JsonNode) SignedJWT(com.nimbusds.jwt.SignedJWT) Name(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.Name) VerifiableCredential(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential) ECDSAVerifier(com.nimbusds.jose.crypto.ECDSAVerifier) NameParts(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.NameParts) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) Evidence(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.Evidence) BirthDate(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.BirthDate) Test(org.junit.jupiter.api.Test)

Example 2 with VerifiableCredential

use of uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential in project di-ipv-cri-uk-passport-back by alphagov.

the class IssueCredentialHandlerTest method shouldReturnCredentialsOnSuccessfulDcsCredentialRequest.

@Test
void shouldReturnCredentialsOnSuccessfulDcsCredentialRequest() throws JsonProcessingException, ParseException, JOSEException {
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    AccessToken accessToken = new BearerAccessToken();
    Map<String, String> headers = Collections.singletonMap("Authorization", accessToken.toAuthorizationHeader());
    event.setHeaders(headers);
    when(mockAccessTokenService.getResourceIdByAccessToken(anyString())).thenReturn(TEST_RESOURCE_ID);
    when(mockDcsPassportCheckService.getDcsPassportCheck(anyString())).thenReturn(dcsCredential);
    when(mockConfigurationService.getVerifiableCredentialIssuer()).thenReturn("test-issuer");
    APIGatewayProxyResponseEvent response = issueCredentialHandler.handleRequest(event, mockContext);
    SignedJWT signedJWT = SignedJWT.parse(response.getBody());
    JsonNode claimsSet = objectMapper.readTree(signedJWT.getJWTClaimsSet().toString());
    assertEquals(200, response.getStatusCode());
    assertEquals(7, claimsSet.size());
    JsonNode vcNode = claimsSet.get("vc");
    VerifiableCredential verifiableCredential = objectMapper.convertValue(vcNode, VerifiableCredential.class);
    assertEquals(dcsCredential.getUserId(), claimsSet.get("sub").asText());
    List<NameParts> nameParts = verifiableCredential.getCredentialSubject().getName().getNameParts();
    assertTrue(nameParts.stream().anyMatch(o -> isType(NamePartType.FAMILY_NAME).and(hasValue(dcsCredential.getAttributes().getSurname())).test(o)));
    assertTrue(nameParts.stream().anyMatch(o -> isType(NamePartType.GIVEN_NAME).and(hasValue(dcsCredential.getAttributes().getForenames().get(0))).test(o)));
    assertEquals(dcsCredential.getAttributes().getPassportNumber(), verifiableCredential.getCredentialSubject().getPassportNumber());
    assertEquals(dcsCredential.getAttributes().getDateOfBirth().toString(), verifiableCredential.getCredentialSubject().getBirthDate().getValue());
    assertEquals(dcsCredential.getAttributes().getExpiryDate().toString(), verifiableCredential.getCredentialSubject().getExpiryDate());
    assertEquals(dcsCredential.getAttributes().getRequestId().toString(), verifiableCredential.getCredentialSubject().getRequestId());
    assertEquals(dcsCredential.getAttributes().getCorrelationId().toString(), verifiableCredential.getCredentialSubject().getCorrelationId());
    assertEquals(dcsCredential.getGpg45Score().getStrength(), verifiableCredential.getEvidence().get(0).getStrength());
    assertEquals(dcsCredential.getGpg45Score().getValidity(), verifiableCredential.getEvidence().get(0).getValidity());
    ECDSAVerifier ecVerifier = new ECDSAVerifier(ECKey.parse(EC_PUBLIC_JWK_1));
    assertTrue(signedJWT.verify(ecVerifier));
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) NamePartType(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.NamePartType) ECDSASigner(com.nimbusds.jose.crypto.ECDSASigner) PassportCheckDao(uk.gov.di.ipv.cri.passport.library.persistence.item.PassportCheckDao) VerifiableCredential(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential) JOSEException(com.nimbusds.jose.JOSEException) Context(com.amazonaws.services.lambda.runtime.Context) AuditEventTypes(uk.gov.di.ipv.cri.passport.library.auditing.AuditEventTypes) JWTClaimNames(com.nimbusds.jwt.JWTClaimNames) PlainJWT(com.nimbusds.jwt.PlainJWT) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) EC_PUBLIC_JWK_1(uk.gov.di.ipv.cri.passport.library.helpers.fixtures.TestFixtures.EC_PUBLIC_JWK_1) ECDSAVerifier(com.nimbusds.jose.crypto.ECDSAVerifier) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) TypeReference(com.fasterxml.jackson.core.type.TypeReference) ParseException(java.text.ParseException) EC_PRIVATE_KEY_1(uk.gov.di.ipv.cri.passport.library.helpers.fixtures.TestFixtures.EC_PRIVATE_KEY_1) DcsPassportCheckService(uk.gov.di.ipv.cri.passport.library.service.DcsPassportCheckService) PassportAttributes(uk.gov.di.ipv.cri.passport.library.domain.PassportAttributes) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) Predicate(java.util.function.Predicate) UUID(java.util.UUID) SignedJWT(com.nimbusds.jwt.SignedJWT) NameParts(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.NameParts) KeyFactory(java.security.KeyFactory) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) List(java.util.List) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LocalDate(java.time.LocalDate) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) OAuth2Error(com.nimbusds.oauth2.sdk.OAuth2Error) BearerTokenError(com.nimbusds.oauth2.sdk.token.BearerTokenError) AccessTokenService(uk.gov.di.ipv.cri.passport.library.service.AccessTokenService) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) Mock(org.mockito.Mock) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) HashMap(java.util.HashMap) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) SqsException(uk.gov.di.ipv.cri.passport.library.exceptions.SqsException) ECKey(com.nimbusds.jose.jwk.ECKey) ECPrivateKey(java.security.interfaces.ECPrivateKey) DcsResponse(uk.gov.di.ipv.cri.passport.library.domain.DcsResponse) Evidence(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.Evidence) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) AuditService(uk.gov.di.ipv.cri.passport.library.service.AuditService) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) ConfigurationService(uk.gov.di.ipv.cri.passport.library.service.ConfigurationService) Collections(java.util.Collections) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) SignedJWT(com.nimbusds.jwt.SignedJWT) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) VerifiableCredential(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential) ECDSAVerifier(com.nimbusds.jose.crypto.ECDSAVerifier) NameParts(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.NameParts) AccessToken(com.nimbusds.oauth2.sdk.token.AccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) BearerAccessToken(com.nimbusds.oauth2.sdk.token.BearerAccessToken) Test(org.junit.jupiter.api.Test)

Example 3 with VerifiableCredential

use of uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential in project di-ipv-cri-uk-passport-back by alphagov.

the class VerifiableCredentialTest method shouldConvertPassportCheckDaoToPassportCredentialIssuerResponse.

@Test
void shouldConvertPassportCheckDaoToPassportCredentialIssuerResponse() {
    PassportAttributes attributes = new PassportAttributes(PASSPORT_NUMBER, FAMILY_NAME, GIVEN_NAMES, DATE_OF_BIRTH, EXPIRY_DATE);
    Evidence evidence = new Evidence(4, 4);
    attributes.setDcsResponse(new DcsResponse(UUID.randomUUID().toString(), UUID.randomUUID().toString(), true, false, Collections.emptyList()));
    PassportCheckDao passportCheckDao = new PassportCheckDao(RESOURCE_ID, attributes, evidence, "test-user-id");
    VerifiableCredential verifiableCredential = VerifiableCredential.fromPassportCheckDao(passportCheckDao);
    assertEquals(FAMILY_NAME, verifiableCredential.getCredentialSubject().getName().getNameParts().get(1).getValue());
    assertEquals(GIVEN_NAMES.get(0), verifiableCredential.getCredentialSubject().getName().getNameParts().get(0).getValue());
    assertEquals(PASSPORT_NUMBER, verifiableCredential.getCredentialSubject().getPassportNumber());
    assertEquals(DATE_OF_BIRTH.toString(), verifiableCredential.getCredentialSubject().getBirthDate().getValue());
    assertEquals(EXPIRY_DATE.toString(), verifiableCredential.getCredentialSubject().getExpiryDate());
    assertEquals(passportCheckDao.getAttributes().getRequestId().toString(), verifiableCredential.getCredentialSubject().getRequestId());
    assertEquals(passportCheckDao.getAttributes().getCorrelationId().toString(), verifiableCredential.getCredentialSubject().getCorrelationId());
    assertEquals(passportCheckDao.getAttributes().getDcsResponse(), verifiableCredential.getCredentialSubject().getDcsResponse());
}
Also used : DcsResponse(uk.gov.di.ipv.cri.passport.library.domain.DcsResponse) VerifiableCredential(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential) PassportAttributes(uk.gov.di.ipv.cri.passport.library.domain.PassportAttributes) Evidence(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.Evidence) PassportCheckDao(uk.gov.di.ipv.cri.passport.library.persistence.item.PassportCheckDao) Test(org.junit.jupiter.api.Test)

Example 4 with VerifiableCredential

use of uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential in project di-ipv-cri-uk-passport-back by alphagov.

the class IssueCredentialHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    try {
        String accessTokenString = RequestHelper.getHeaderByKey(input.getHeaders(), AUTHORIZATION_HEADER_KEY);
        // Performs validation on header value and throws a ParseException if invalid
        AccessToken.parse(accessTokenString);
        String resourceId = accessTokenService.getResourceIdByAccessToken(accessTokenString);
        if (StringUtils.isBlank(resourceId)) {
            LOGGER.error("User credential could not be retrieved. The supplied access token was not found in the database.");
            return ApiGatewayResponseGenerator.proxyJsonResponse(OAuth2Error.ACCESS_DENIED.getHTTPStatusCode(), OAuth2Error.ACCESS_DENIED.appendDescription(" - The supplied access token was not found in the database").toJSONObject());
        }
        PassportCheckDao passportCheck = dcsPassportCheckService.getDcsPassportCheck(resourceId);
        VerifiableCredential verifiableCredential = VerifiableCredential.fromPassportCheckDao(passportCheck);
        SignedJWT signedJWT = generateAndSignVerifiableCredentialJwt(verifiableCredential, passportCheck.getUserId());
        auditService.sendAuditEvent(AuditEventTypes.PASSPORT_CREDENTIAL_ISSUED);
        return ApiGatewayResponseGenerator.proxyJwtResponse(HttpStatus.SC_OK, signedJWT.serialize());
    } catch (ParseException e) {
        LOGGER.error("Failed to parse access token");
        return ApiGatewayResponseGenerator.proxyJsonResponse(e.getErrorObject().getHTTPStatusCode(), e.getErrorObject().toJSONObject());
    } catch (JOSEException e) {
        LOGGER.error("Failed to sign verifiable credential: '{}'", e.getMessage());
        return ApiGatewayResponseGenerator.proxyJsonResponse(OAuth2Error.SERVER_ERROR.getHTTPStatusCode(), OAuth2Error.SERVER_ERROR.appendDescription(" " + e.getMessage()).toJSONObject());
    } catch (SqsException e) {
        LOGGER.error("Failed to send audit event to SQS queue because: {}", e.getMessage());
        return ApiGatewayResponseGenerator.proxyJsonResponse(HttpStatus.SC_BAD_REQUEST, ErrorResponse.FAILED_TO_SEND_AUDIT_MESSAGE_TO_SQS_QUEUE);
    }
}
Also used : VerifiableCredential(uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential) SqsException(uk.gov.di.ipv.cri.passport.library.exceptions.SqsException) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(com.nimbusds.oauth2.sdk.ParseException) JOSEException(com.nimbusds.jose.JOSEException) PassportCheckDao(uk.gov.di.ipv.cri.passport.library.persistence.item.PassportCheckDao)

Aggregations

VerifiableCredential (uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.VerifiableCredential)4 SignedJWT (com.nimbusds.jwt.SignedJWT)3 Test (org.junit.jupiter.api.Test)3 DcsResponse (uk.gov.di.ipv.cri.passport.library.domain.DcsResponse)3 Evidence (uk.gov.di.ipv.cri.passport.library.domain.verifiablecredential.Evidence)3 PassportCheckDao (uk.gov.di.ipv.cri.passport.library.persistence.item.PassportCheckDao)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 JOSEException (com.nimbusds.jose.JOSEException)2 ECDSASigner (com.nimbusds.jose.crypto.ECDSASigner)2 ECDSAVerifier (com.nimbusds.jose.crypto.ECDSAVerifier)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 PassportAttributes (uk.gov.di.ipv.cri.passport.library.domain.PassportAttributes)2 SqsException (uk.gov.di.ipv.cri.passport.library.exceptions.SqsException)2 Context (com.amazonaws.services.lambda.runtime.Context)1 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)1 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)1 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 JavaTimeModule (com.fasterxml.jackson.datatype.jsr310.JavaTimeModule)1