Skip to content

Commit

Permalink
[SELC-5322] merge back (#466)
Browse files Browse the repository at this point in the history
Co-authored-by: pierpaolo.didato@emeal.nttdata.com <Aiap1955?^@#>
  • Loading branch information
gianmarcoplutino and pierpaolo.didato@emeal.nttdata.com authored Sep 5, 2024
1 parent b3abbfa commit 7af7649
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,27 @@
import org.eclipse.microprofile.rest.client.ext.ClientHeadersFactory;

import java.util.List;
import java.util.Objects;


@ApplicationScoped
public class AuthenticationPropagationHeadersFactory implements ClientHeadersFactory {

private static final String USER_ID_HEADER = "user-uuid";
private static final String JWT_BEARER_TOKEN_ENV = "JWT_BEARER_TOKEN";

@Inject
JwtSessionService tokenService;

@Override
public MultivaluedMap<String, String> update(MultivaluedMap<String, String> incomingHeaders, MultivaluedMap<String, String> clientOutgoingHeaders) {
String bearerToken;
if (!clientOutgoingHeaders.isEmpty() && clientOutgoingHeaders.containsKey("user-uuid")) {
final String uuid = clientOutgoingHeaders.get("user-uuid").get(0);
bearerToken = tokenService.createJwt(uuid);
if (!clientOutgoingHeaders.isEmpty() && clientOutgoingHeaders.containsKey(USER_ID_HEADER)) {
final String uuid = clientOutgoingHeaders.get(USER_ID_HEADER).get(0);
final String jwt = tokenService.createJwt(uuid);
bearerToken = Objects.nonNull(jwt) ? jwt : System.getenv(JWT_BEARER_TOKEN_ENV);
} else {
bearerToken = System.getenv("JWT_BEARER_TOKEN");
bearerToken = System.getenv(JWT_BEARER_TOKEN_ENV);
}
clientOutgoingHeaders.put("Authorization", List.of("Bearer " + bearerToken));
return clientOutgoingHeaders;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,27 +43,26 @@ public class JwtSessionServiceDefault implements JwtSessionService {

@Override
public String createJwt(String userId) {
PrivateKey privateKey;
try {
privateKey = getPrivateKey(tokenConfig.signingKey());
PrivateKey privateKey = getPrivateKey(tokenConfig.signingKey());
UserResource userResource = userRegistryApi.findByIdUsingGET(USERS_FIELD_LIST, userId);
return Jwts.builder()
.setId(UUID.randomUUID().toString())
.setIssuedAt(new Date())
.setIssuer(tokenConfig.issuer())
.setExpiration(Date.from(new Date().toInstant().plus(Duration.parse(tokenConfig.duration()))))
.claim("family_name", userResource.getFamilyName().getValue())
.claim("fiscal_number", userResource.getFiscalCode())
.claim("name", userResource.getName().getValue())
.claim("uid", userId)
.signWith(SignatureAlgorithm.RS256, privateKey)
.setHeaderParam(JwsHeader.KEY_ID, tokenConfig.kid())
.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
.compact();
} catch (Exception e) {
logger.error("Impossible to get private key. Error: {}", e.getMessage(), e);
logger.error("Impossible to create jwt token. Error: {}", e.getMessage(), e);
return null;
}
UserResource userResource = userRegistryApi.findByIdUsingGET(USERS_FIELD_LIST, userId);
return Jwts.builder()
.setId(UUID.randomUUID().toString())
.setIssuedAt(new Date())
.setIssuer(tokenConfig.issuer())
.setExpiration(Date.from(new Date().toInstant().plus(Duration.parse(tokenConfig.duration()))))
.claim("family_name", userResource.getFamilyName().getValue())
.claim("fiscal_number", userResource.getFiscalCode())
.claim("name", userResource.getName().getValue())
.claim("uid", userId)
.signWith(SignatureAlgorithm.RS256, privateKey)
.setHeaderParam(JwsHeader.KEY_ID, tokenConfig.kid())
.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
.compact();
}

private PrivateKey getPrivateKey(String signingKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package it.pagopa.selfcare.onboarding.client.auth;

import io.quarkus.test.InjectMock;
import io.quarkus.test.junit.QuarkusTest;
import it.pagopa.selfcare.onboarding.service.JwtSessionService;
import jakarta.inject.Inject;
import jakarta.ws.rs.core.MultivaluedHashMap;
import org.junit.jupiter.api.Test;
Expand All @@ -9,13 +11,18 @@
import java.util.UUID;

import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

@QuarkusTest
class AuthenticationPropagationHeadersFactoryTest {

@Inject
AuthenticationPropagationHeadersFactory authenticationPropagationHeadersFactory;

@InjectMock
JwtSessionService jwtSessionService;

@Test
void update() {
MultivaluedHashMap<String, String> incomingHeaders = new MultivaluedHashMap<>();
Expand All @@ -24,4 +31,23 @@ void update() {
authenticationPropagationHeadersFactory.update(incomingHeaders, outgoingHeaders);
assertTrue(outgoingHeaders.containsKey("Authorization"));
}

@Test
void updateWithNullJwt() {
MultivaluedHashMap<String, String> incomingHeaders = new MultivaluedHashMap<>();
MultivaluedHashMap<String, String> outgoingHeaders = new MultivaluedHashMap<>();
outgoingHeaders.put("user-uuid", List.of(UUID.randomUUID().toString()));
when(jwtSessionService.createJwt(any())).thenReturn(null);
authenticationPropagationHeadersFactory.update(incomingHeaders, outgoingHeaders);
assertTrue(outgoingHeaders.containsKey("Authorization"));
}

@Test
void emptyHeader() {
MultivaluedHashMap<String, String> incomingHeaders = new MultivaluedHashMap<>();
MultivaluedHashMap<String, String> outgoingHeaders = new MultivaluedHashMap<>();
authenticationPropagationHeadersFactory.update(incomingHeaders, outgoingHeaders);
assertTrue(outgoingHeaders.containsKey("Authorization"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import it.pagopa.selfcare.onboarding.exception.ResourceNotFoundException;
import jakarta.inject.Inject;
import org.eclipse.microprofile.rest.client.inject.RestClient;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -62,4 +63,18 @@ void createJwt() {
assertTrue(Objects.nonNull(jwt));
}

@Test
void createNullJwt() {
final String userId = "userId";
UserResource userResource = new UserResource();
userResource.setFiscalCode("fiscalCode");
CertifiableFieldResourceOfstring certifiedField = new CertifiableFieldResourceOfstring();
certifiedField.setValue("name");
userResource.setName(certifiedField);
userResource.setFamilyName(certifiedField);
when(userRegistryApi.findByIdUsingGET(any(), any())).thenThrow(new ResourceNotFoundException("An error occurred", "Code"));
String jwt = tokenService.createJwt(userId);
assertTrue(Objects.isNull(jwt));
}

}

0 comments on commit 7af7649

Please sign in to comment.