Compare commits

...

3 Commits

Author SHA1 Message Date
Luca Frosini 9181862d3c Fixed code 2024-04-30 11:04:46 +02:00
Luca Frosini 19053a5492 Fixing code 2024-04-30 10:15:27 +02:00
Luca Frosini c4a4381fdd Added provider inspection to get the current context 2024-04-29 17:25:23 +02:00
6 changed files with 165 additions and 52 deletions

View File

@ -2,6 +2,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
# Changelog for Common Utility For Smartgears 3.X.X
## [v1.1.0-SNAPSHOT]
- Added evaluation of SecurityTokenProvider to calculate the context
## [v1.0.1]
- Fixed issue on getCurrentContextFullName

View File

@ -8,7 +8,7 @@
</parent>
<groupId>org.gcube.common</groupId>
<artifactId>common-utility-sg3</artifactId>
<version>1.0.1</version>
<version>1.1.0-SNAPSHOT</version>
<name>Common Utility For Smartgears 3.X.X</name>
<description>
This library provides utility functions for APIs available in Smartgears 3 but broken in Smartgears 4.
@ -58,6 +58,10 @@
<groupId>org.gcube.common</groupId>
<artifactId>gcube-jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.gcube.common</groupId>
<artifactId>keycloak-client</artifactId>
</dependency>
<!-- Test libraries -->
<dependency>

View File

@ -4,12 +4,16 @@ import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.gcube.com.fasterxml.jackson.databind.JsonNode;
import org.gcube.com.fasterxml.jackson.databind.ObjectMapper;
import org.gcube.com.fasterxml.jackson.databind.node.ArrayNode;
import org.gcube.common.authorization.client.Constants;
import org.gcube.common.authorization.library.AuthorizationEntry;
import org.gcube.common.authorization.library.provider.AccessTokenProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.keycloak.model.AccessToken;
import org.gcube.common.scope.api.ScopeProvider;
import org.gcube.common.scope.impl.ScopeBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
@ -17,36 +21,55 @@ import org.gcube.common.scope.impl.ScopeBean;
@SuppressWarnings("deprecation")
public class ContextUtility {
private static final Logger logger = LoggerFactory.getLogger(ContextUtility.class);
public static String getCurrentContextFullName() {
String context = ScopeProvider.instance.get();
if(context==null) {
String token = AccessTokenProvider.instance.get();
String realUmaTokenEncoded = token.split("\\.")[1];
String realUmaToken = new String(Base64.getDecoder().decode(realUmaTokenEncoded.getBytes()));
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode tokenJsonNode = mapper.readTree(realUmaToken);
JsonNode jsonNode = tokenJsonNode.get("aud");
if(jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (JsonNode aud : arrayNode) {
if (aud != null && aud.isTextual() && aud.asText().compareTo("") != 0) {
String audience = aud.asText();
String contextToBeValidated = URLDecoder.decode(audience, StandardCharsets.UTF_8.toString());
ScopeBean scopeBean = new ScopeBean(contextToBeValidated);
context = scopeBean.toString();
return context;
logger.trace("ScopeProvider is null. Going to get context from SecurityTokenProvider.");
String token = SecurityTokenProvider.instance.get();
if(token!=null) {
logger.trace("Found SecurityTokenProvider");
try {
AuthorizationEntry authorizationEntry = Constants.authorizationService().get(token);
return authorizationEntry.getContext();
}catch (Exception e) {
throw new RuntimeException(e);
}
}else {
logger.trace("ScopeProvider AND SecurityTokenProvider are null. Going to get context from AccessTokenProvider.");
token = AccessTokenProvider.instance.get();
if(token!=null) {
logger.trace("Found AccessTokenProvider");
String realUmaTokenEncoded = token.split("\\.")[1];
String realUmaToken = new String(Base64.getDecoder().decode(realUmaTokenEncoded.getBytes()));
ObjectMapper mapper = new ObjectMapper();
try {
AccessToken accessToken = mapper.readValue(realUmaToken, AccessToken.class);
String[] audience = accessToken.getAudience();
for (String aud : audience) {
if (aud != null && aud.compareTo("") != 0) {
try {
String contextToBeValidated = URLDecoder.decode(aud, StandardCharsets.UTF_8.toString());
ScopeBean scopeBean = new ScopeBean(contextToBeValidated);
context = scopeBean.toString();
return context;
} catch (Exception e) {
// logger.trace("Invalid context name for audience {} in access token. Trying next one if any.", aud, e);
}
}
}
throw new Exception("Unable to find valid context in audience: " + audience.toString());
}catch(Exception e){
throw new RuntimeException("Error parsing JWT token.", e);
}
}else {
logger.trace("ScopeProvider, AccessTokenProvider AND SecurityTokenProvider are null. There is no other possibility to get the context.");
throw new RuntimeException("ScopeProvider, AccessTokenProvider AND SecurityTokenProvider are null. There is no other possibility to get the context.");
}
if(jsonNode.isTextual()) {
return jsonNode.asText();
}
throw new Exception("Unable to get Current Context");
}catch (Exception e) {
new RuntimeException(e);
}
}
logger.trace("Found ScopeProvider");
return context;
}

View File

@ -13,8 +13,8 @@ import org.gcube.common.authorization.utils.secret.JWTSecret;
import org.gcube.common.authorization.utils.secret.Secret;
import org.gcube.common.authorization.utils.secret.SecretUtility;
import org.gcube.common.keycloak.KeycloakClientFactory;
import org.gcube.common.keycloak.KeycloakClientHelper;
import org.gcube.common.keycloak.model.TokenResponse;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
@ -23,44 +23,58 @@ import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
@SuppressWarnings("deprecation")
public class ContextTest {
private static final Logger logger = LoggerFactory.getLogger(ContextTest.class);
protected static final String CONFIG_INI_FILENAME = "config.ini";
public static final String ROOT_DEV;
public static final String ROOT_PREPROD;
public static final String ROOT_PROD;
public static final String DEFAULT_TEST_SCOPE;
public static final String GCUBE;
// public static final String DEVNEXT;
// public static final String NEXTNEXT;
// public static final String DEVSEC;
// public static final String DEVVRE;
//
// private static final String ROOT_PROD;
// private static final String ROOT_PRE;
protected static final Properties properties;
protected static final String CLIENT_ID_PROPERTY_KEY = "client_id";
protected static final String CLIENT_SECRET_PROPERTY_KEY = "client_secret";
protected static final String clientID;
protected static final String clientSecret;
public static final String TYPE_PROPERTY_KEY = "type";
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String PASSWORD_PROPERTY_KEY = "password";
public static final String CLIENT_ID_PROPERTY_KEY = "clientId";
static {
GCUBE = "/gcube";
// DEVNEXT = GCUBE + "/devNext";
// NEXTNEXT = DEVNEXT + "/NextNext";
// DEVSEC = GCUBE + "/devsec";
// DEVVRE = DEVSEC + "/devVRE";
//
// ROOT_PROD = "/d4science.research-infrastructures.eu";
// ROOT_PRE = "/pred4s";
DEFAULT_TEST_SCOPE = GCUBE;
properties = new Properties();
InputStream input = ContextTest.class.getClassLoader().getResourceAsStream(CONFIG_INI_FILENAME);
try {
// load the properties file
properties.load(input);
clientID = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
clientSecret = properties.getProperty(CLIENT_SECRET_PROPERTY_KEY);
} catch (IOException e) {
throw new RuntimeException(e);
}
ROOT_DEV = "/gcube";
ROOT_PREPROD = "/pred4s";
ROOT_PROD = "/d4science.research-infrastructures.eu";
}
private enum Type{
USER, CLIENT_ID
};
public static void set(Secret secret) throws Exception {
SecretManagerProvider.instance.reset();
SecretManager secretManager = new SecretManager();
@ -70,15 +84,56 @@ public class ContextTest {
}
public static void setContextByName(String fullContextName) throws Exception {
logger.debug("Going to set credentials for context {}", fullContextName);
Secret secret = getSecretByContextName(fullContextName);
set(secret);
}
private static TokenResponse getJWTAccessToken(String context) throws Exception {
ScopeProvider.instance.set(context);
TokenResponse tr = KeycloakClientFactory.newInstance().queryUMAToken(clientID, clientSecret, context, null);
return tr;
Type type = Type.valueOf(properties.get(TYPE_PROPERTY_KEY).toString());
TokenResponse tr = null;
int index = context.indexOf('/', 1);
String root = context.substring(0, index == -1 ? context.length() : index);
switch (type) {
case CLIENT_ID:
String clientId = properties.getProperty(CLIENT_ID_PROPERTY_KEY);
String clientSecret = properties.getProperty(root);
tr = KeycloakClientFactory.newInstance().queryUMAToken(context, clientId, clientSecret, context, null);
break;
case USER:
default:
String username = properties.getProperty(USERNAME_PROPERTY_KEY);
String password = properties.getProperty(PASSWORD_PROPERTY_KEY);
switch (root) {
case "/gcube":
default:
clientId = "next.d4science.org";
break;
case "/pred4s":
clientId = "pre.d4science.org";
break;
case "/d4science.research-infrastructures.eu":
clientId = "services.d4science.org";
break;
}
clientSecret = null;
tr = KeycloakClientHelper.getTokenForUser(context, username, password);
break;
}
return tr;
}
public static Secret getSecretByContextName(String context) throws Exception {
@ -98,7 +153,7 @@ public class ContextTest {
}
public static String getUser() {
String user = "Unknown";
String user = "UNKNOWN";
try {
user = SecretManagerProvider.instance.get().getUser().getUsername();
} catch(Exception e) {
@ -109,7 +164,7 @@ public class ContextTest {
@BeforeClass
public static void beforeClass() throws Exception {
setContextByName(ROOT_DEV);
setContextByName(DEFAULT_TEST_SCOPE);
}
@AfterClass

View File

@ -2,22 +2,49 @@ package org.gcube.common.context;
import org.gcube.common.ContextTest;
import org.gcube.common.authorization.library.provider.AccessTokenProvider;
import org.gcube.common.authorization.library.provider.SecurityTokenProvider;
import org.gcube.common.authorization.utils.manager.SecretManager;
import org.gcube.common.authorization.utils.manager.SecretManagerProvider;
import org.gcube.common.scope.api.ScopeProvider;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Luca Frosini (ISTI - CNR)
*/
public class ContextUtilityTest extends ContextTest {
private static final Logger logger = LoggerFactory.getLogger(ContextUtilityTest.class);
@Test
public void testGetContext() throws Exception {
SecretManager secretManager = SecretManagerProvider.instance.get();
String token = secretManager.getCurrentSecretHolder().getSecrets().first().getToken();
String context = secretManager.getContext();
String newToken = secretManager.getCurrentSecretHolder().getSecrets().first().getToken();
ContextTest.afterClass();
AccessTokenProvider.instance.set(token);
ContextUtility.getCurrentContextFullName();
ScopeProvider.instance.set(context);
String gotContext = ContextUtility.getCurrentContextFullName();
logger.debug("Expected context is {} - Got Context is {}", context, gotContext);
Assert.assertTrue(context.compareTo(gotContext)==0);
ScopeProvider.instance.reset();
String oldToken = ContextTest.properties.getProperty("old_token_gcube");
SecurityTokenProvider.instance.set(oldToken);
gotContext = ContextUtility.getCurrentContextFullName();
logger.debug("Expected context is {} - Got Context is {}", context, gotContext);
Assert.assertTrue(context.compareTo(gotContext)==0);
SecurityTokenProvider.instance.reset();
AccessTokenProvider.instance.set(newToken);
gotContext = ContextUtility.getCurrentContextFullName();
logger.debug("Expected context is {} - Got Context is {}", context, gotContext);
Assert.assertTrue(context.compareTo(gotContext)==0);
AccessTokenProvider.instance.reset();
}
}

View File

@ -10,7 +10,7 @@
<logger name="org.gcube" level="ERROR" />
<logger name="org.gcube.common" level="TRACE" />
<logger name="org.gcube.common.context" level="TRACE" />
<root level="WARN">
<appender-ref ref="STDOUT" />