Skip to content

Commit

Permalink
P4ADEV-24P4ADEV-248-creation-api-get-token-selfcare tests
Browse files Browse the repository at this point in the history
  • Loading branch information
LarissaASLeite committed May 10, 2024
1 parent 3173ff3 commit bf89164
Show file tree
Hide file tree
Showing 4 changed files with 160 additions and 67 deletions.
5 changes: 4 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,13 @@ test {
jacocoTestReport {
dependsOn test
reports {
xml.required = false
html.enabled = true
xml.enabled = true
csv.enabled = false
}
}


processResources {
expand(project.properties)
exclude 'logback-spring.xml'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,75 +1,48 @@
package it.gov.pagopa.payhub.auth.service;

import com.auth0.jwk.Jwk;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import it.gov.pagopa.payhub.auth.constants.AuthConstants;
import it.gov.pagopa.payhub.auth.exception.InvalidTokenException;
import it.gov.pagopa.payhub.auth.utils.JWTValidator;
import org.json.JSONObject;
import it.gov.pagopa.payhub.auth.utils.JWTValidatorUtils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class AuthServiceTest {

private AuthService authService;
private WireMockServer wireMockServer;
public static final Date EXPIRES_AT = new Date(System.currentTimeMillis() + 3600000);
private static final String AUD = "AUD";
private static final String ISS = "ISS";

private AuthService authService;
private WireMockServer wireMockServer;
private JWTValidatorUtils utils;

@Mock
private JWTValidator jwtValidator;
@Mock
private Jwk jwk;
private String setUp() throws Exception {
KeyPair keyPair = generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
String token = generateToken(keyPair);

@BeforeEach
void setup(){
wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());
wireMockServer.start();

JWK jwk = new RSAKey.Builder(rsaPublicKey)
.keyID("my-key-id")
.build();
JWKSet jwkSet = new JWKSet(jwk);
JSONObject jsonObject = new JSONObject();
jsonObject.put("keys", jwkSet.toJSONObject().get("keys"));

WireMock.configureFor("localhost", wireMockServer.port());
stubFor(get(urlEqualTo("/jwks/.well-known/jwks.json"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody(String.valueOf(jwkSet))));

authService = new AuthServiceImpl(AUD, ISS, getUrlJwkProvider(), jwtValidator);

return token;
utils = new JWTValidatorUtils(wireMockServer);
authService = new AuthServiceImpl(AUD, ISS, utils.getUrlJwkProvider(), jwtValidator);
}

@AfterEach
Expand All @@ -78,10 +51,10 @@ void clean(){
}
@Test
void authToken() throws Exception {
String token = setUp();
String token = utils.generateJWK(EXPIRES_AT);
Map<String, String> claimsMap = createJWKClaims(ISS, AUD);

String wireMockUrl = getUrlJwkProvider();
String wireMockUrl = utils.getUrlJwkProvider();
when(jwtValidator.validate(token, wireMockUrl)).thenReturn(claimsMap);

authService.authToken(token);
Expand All @@ -90,10 +63,10 @@ void authToken() throws Exception {

@Test
void authTokenWrongIss() throws Exception {
String token = setUp();
String token = utils.generateJWK(EXPIRES_AT);
Map<String, String> claimsMap = createJWKClaims("ISS_FAKE", AUD);

String wireMockUrl = getUrlJwkProvider();
String wireMockUrl = utils.getUrlJwkProvider();
when(jwtValidator.validate(token, wireMockUrl)).thenReturn(claimsMap);

InvalidTokenException result =
Expand All @@ -105,10 +78,10 @@ void authTokenWrongIss() throws Exception {

@Test
void authTokenWrongAud() throws Exception {
String token = setUp();
String token = utils.generateJWK(EXPIRES_AT);
Map<String, String> claimsMap = createJWKClaims(ISS, "AUD_FAKE");

String wireMockUrl = getUrlJwkProvider();
String wireMockUrl = utils.getUrlJwkProvider();
when(jwtValidator.validate(token, wireMockUrl)).thenReturn(claimsMap);

InvalidTokenException result =
Expand All @@ -118,26 +91,6 @@ void authTokenWrongAud() throws Exception {
assertEquals(AuthConstants.ExceptionCode.INVALID_TOKEN, result.getCode());
}

public static String generateToken(KeyPair keyPair) {
return JWT.create()
.withIssuer(ISS)
.withAudience(AUD)
.withKeyId("my-key-id")
.withJWTId("my-jwt-id")
.withExpiresAt(new Date(System.currentTimeMillis() + 3600000))
.sign(Algorithm.RSA256((RSAPrivateKey) keyPair.getPrivate()));
}

private String getUrlJwkProvider() {
return "http://localhost:" + wireMockServer.port() + "/jwks";
}

private static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}

private Map<String, String> createJWKClaims (String iss, String aud){
Map<String, String> claims = new HashMap<>();
claims.put("iss", iss);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package it.gov.pagopa.payhub.auth.utils;

import com.github.tomakehurst.wiremock.WireMockServer;
import it.gov.pagopa.payhub.auth.exception.InvalidTokenException;
import it.gov.pagopa.payhub.auth.exception.TokenExpiredException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.Date;
import java.util.Map;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

@ExtendWith(SpringExtension.class)
class JWTValidatorTest {

private JWTValidator jwtValidator;
private WireMockServer wireMockServer;
private JWTValidatorUtils utils;

@BeforeEach
void setup(){
wireMockServer = new WireMockServer(wireMockConfig().dynamicPort());
wireMockServer.start();
utils = new JWTValidatorUtils(wireMockServer);
jwtValidator = new JWTValidator();
}

@AfterEach
void clean(){
wireMockServer.stop();
}

@Test
void validateToken() throws Exception {
String token = utils.generateJWK(new Date(System.currentTimeMillis() + 3600000));

String urlJwkProvider = utils.getUrlJwkProvider();

Map<String, String> claimsMap = jwtValidator.validate(token, urlJwkProvider);

assertNotNull(claimsMap);
}

@Test
void validate_ExpiredToken_ThrowsTokenExpiredException() throws Exception {
String expiredToken = utils.generateJWK(new Date(System.currentTimeMillis() - 3600000));
String urlJwkProvider = utils.getUrlJwkProvider();

assertThrows(TokenExpiredException.class, () -> jwtValidator.validate(expiredToken, urlJwkProvider));
}

@Test
void validate_InvalidToken_ThrowsInvalidTokenException() {
String invalidToken = "your_invalid_token_here";
String urlJwkProvider = "your_jwk_provider_url_here";

assertThrows(InvalidTokenException.class, () -> jwtValidator.validate(invalidToken, urlJwkProvider));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package it.gov.pagopa.payhub.auth.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import org.json.JSONObject;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

import static com.github.tomakehurst.wiremock.client.WireMock.*;

public class JWTValidatorUtils {

private final WireMockServer wireMockServer;

private static final String AUD = "AUD";
private static final String ISS = "ISS";

public JWTValidatorUtils(WireMockServer wireMockServer) {
this.wireMockServer = wireMockServer;
}

public String generateJWK(Date expiresAt) throws Exception {
KeyPair keyPair = generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();

String token = generateToken(keyPair, expiresAt);

JWK jwk = new RSAKey.Builder(rsaPublicKey)
.keyID("my-key-id")
.build();
JWKSet jwkSet = new JWKSet(jwk);
JSONObject jsonObject = new JSONObject();
jsonObject.put("keys", jwkSet.toJSONObject().get("keys"));

WireMock.configureFor("localhost", wireMockServer.port());
stubFor(get(urlEqualTo("/jwks/.well-known/jwks.json"))
.willReturn(aResponse()
.withHeader("Content-Type", "application/json")
.withBody(String.valueOf(jwkSet))));

return token;
}

public static String generateToken(KeyPair keyPair, Date expiresAt) {
return JWT.create()
.withIssuer(ISS)
.withAudience(AUD)
.withKeyId("my-key-id")
.withJWTId("my-jwt-id")
.withExpiresAt(expiresAt)
.sign(Algorithm.RSA256((RSAPrivateKey) keyPair.getPrivate()));
}

public String getUrlJwkProvider() {
return "http://localhost:" + wireMockServer.port() + "/jwks";
}

private static KeyPair generateKeyPair() throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
}
}

0 comments on commit bf89164

Please sign in to comment.