This commit is contained in:
Lucio Lelii 2016-09-30 16:27:04 +00:00
parent e5c5e37594
commit fb3f20124f
3 changed files with 127 additions and 71 deletions

View File

@ -34,7 +34,11 @@ public interface AuthorizationProxy {
throws Exception;
String requestActivation(ContainerInfo container) throws Exception;
String requestActivation(ContainerInfo container, String context) throws Exception;
public Map<String, String> retrieveApiKeys() throws Exception;
Map<String, String> retrieveApiKeys() throws Exception;
//File getSymmKey(String filePath) throws Exception;
}

View File

@ -37,11 +37,11 @@ import org.slf4j.LoggerFactory;
public class DefaultAuthorizationProxy implements AuthorizationProxy {
private static Logger log = LoggerFactory.getLogger(AuthorizationProxy.class);
private static Map<String, AuthorizationEntryCache> cache = Collections.synchronizedMap(new HashMap<String, AuthorizationEntryCache>());
private static EndpointsContainer endpoints;
public DefaultAuthorizationProxy() {
if (endpoints==null)
endpoints = AuthorizationEndpointScanner.endpoints();
@ -53,28 +53,28 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
.append(ae.getPort()).append("/authorization-service/gcube/service");
return endpoint.toString();
}
@Override
public String generateServiceToken(ServiceInfo client) throws Exception {
String methodPath = "/token/service";
int infrastructureHash = Utils.getInfrastructureHashFromToken(SecurityTokenProvider.instance.get(), endpoints.getDefaultInfrastructure());
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(infrastructureHash)).append(methodPath);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "PUT", true);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/xml");
try(OutputStream os = new BufferedOutputStream(connection.getOutputStream())){
Binder.getContext().createMarshaller().marshal(client, os);
}
log.debug("response code for "+callUrl.toString()+" is "+connection.getResponseCode()+" "+connection.getResponseMessage());
if (connection.getResponseCode()!=200) throw new Exception("error contacting authorization service");
String token= "";
try(BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream)connection.getContent()))){
@ -87,29 +87,29 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
return Utils.addInfrastructureHashToToken(token, infrastructureHash);
}
@Override
public String generateUserToken(UserInfo client, String context) throws Exception {
String methodPath = "/token/user";
int infrastructureHash = Utils.getInfrastructureHashfromContext(context);
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(infrastructureHash)).append(methodPath).append("?")
.append(CONTEXT_PARAM).append("=").append(context);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "PUT", false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/xml");
try(OutputStream os = new BufferedOutputStream(connection.getOutputStream())){
Binder.getContext().createMarshaller().marshal(client, os);
}
log.debug("response code for "+callUrl.toString()+" is "+connection.getResponseCode()+" "+connection.getResponseMessage());
if (connection.getResponseCode()!=200) throw new Exception("error contacting authorization service");
String token= "";
try(BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream)connection.getContent()))){
@ -122,28 +122,28 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
return Utils.addInfrastructureHashToToken(token, infrastructureHash);
}
@Override
public String generateApiKey(String apiQualifier) throws Exception {
String methodPath = String.format("/apikey?qualifier=%s",apiQualifier);
int infrastructureHash = Utils.getInfrastructureHashFromToken(SecurityTokenProvider.instance.get(), endpoints.getDefaultInfrastructure());
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(infrastructureHash)).append(methodPath);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "PUT", true);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setFixedLengthStreamingMode(0);
connection.setRequestProperty("Content-type", "application/xml");
log.debug("response code for "+callUrl.toString()+" is "+connection.getResponseCode()+" "+connection.getResponseMessage());
if (connection.getResponseCode()!=200) throw new Exception("error contacting authorization service");
String token= "";
try(BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream)connection.getContent()))){
@ -156,56 +156,58 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
return Utils.addInfrastructureHashToToken(token, infrastructureHash);
}
@Override
/**
* return a map with key qualifier and value token
*/
public Map<String, String> retrieveApiKeys() throws Exception{
String methodPath = "/apikey/";
int infrastructureHash = Utils.getInfrastructureHashFromToken(SecurityTokenProvider.instance.get(), endpoints.getDefaultInfrastructure());
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(infrastructureHash)).append(methodPath);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "GET", true);
connection.setDoInput(true);
connection.setDoOutput(true);
if (connection.getResponseCode()!=200) throw new Exception("error retrieving keys (error code is "+connection.getResponseCode()+")");
if (connection.getContentLengthLong()<=0) return Collections.emptyMap();
try(InputStream stream = (InputStream)connection.getContent();){
QualifiersList entries = (QualifiersList)Binder.getContext().createUnmarshaller().unmarshal(stream);
return entries.getQualifiers();
}
}
@Override
public String requestActivation(ContainerInfo container) throws Exception {
public String requestActivation(ContainerInfo container, String context) throws Exception {
String methodPath = "/token/node";
int infrastructureHash = Utils.getInfrastructureHashFromToken(SecurityTokenProvider.instance.get(), endpoints.getDefaultInfrastructure());
StringBuilder callUrl =
new StringBuilder(getInternalEnpoint(infrastructureHash)).append(methodPath);
StringBuilder callUrl;
callUrl = new StringBuilder(getInternalEnpoint(infrastructureHash)).append(methodPath);
if (context!=null) callUrl.append("?context=").append(context);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "PUT", false);
HttpURLConnection connection = makeRequest(url, "PUT", true);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/xml");
try(OutputStream os = new BufferedOutputStream(connection.getOutputStream())){
Binder.getContext().createMarshaller().marshal(container, os);
}
log.debug("response code is "+connection.getResponseCode());
if (connection.getResponseCode()!=200) throw new Exception("error contacting authorization service");
String token= "";
try(BufferedReader reader = new BufferedReader(new InputStreamReader((InputStream)connection.getContent()))){
@ -218,28 +220,35 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
return Utils.addInfrastructureHashToToken(token, infrastructureHash);
}
@Override
public String requestActivation(ContainerInfo container) throws Exception {
return requestActivation(container, null);
}
@Override
public AuthorizationEntry get(String token) throws ObjectNotFound, Exception{
String realToken = Utils.getRealToken(token);
String maskedToken= String.format("%s********",realToken.substring(0, realToken.length()-8));
int infrastructureHashFromToken = Utils.getInfrastructureHashFromToken(token, endpoints.getDefaultInfrastructure());
AuthorizationEndpoint endpoint = getEndpoint(infrastructureHashFromToken);
if (cache.containsKey(realToken) && cache.get(realToken).isValid(endpoint.getClientCacheValidity())){
log.trace("valid entry found in cache for token {}, returning it",maskedToken);
return cache.get(realToken).getEntry();
} else
log.trace("invalid entry found in cache for token {}, contacting auth service",maskedToken);
final String methodPath = "/token/";
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(infrastructureHashFromToken))
.append(methodPath).append(realToken);
.append(methodPath).append(realToken);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "GET", false);
connection.setDoInput(true);
if (connection.getResponseCode()==404) throw new ObjectNotFound("token "+maskedToken+" not found");
if (connection.getResponseCode()!=200) throw new Exception("error contacting authorization service (error code is "+connection.getResponseCode()+")");
if (connection.getContentLengthLong()<=0) return null;
@ -251,24 +260,24 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
}
}
@Override
public void addPolicies(List<Policy> policies) throws Exception {
final String methodPath = "/policyManager";
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(Utils.getInfrastructureHashFromToken(SecurityTokenProvider.instance.get(), endpoints.getDefaultInfrastructure()))).append(methodPath);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "POST", true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-type", "application/xml");
try(OutputStream os = new BufferedOutputStream(connection.getOutputStream())){
Binder.getContext().createMarshaller().marshal(new Policies(policies), os);
}
if (connection.getResponseCode()!=200) throw new Exception("error adding policies");
}
@Override
@ -288,9 +297,9 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
@Override
public List<Policy> getPolicies(String context) throws Exception{
final String methodPath = "/policyManager/";
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(Utils.getInfrastructureHashfromContext(context))).append(methodPath).append("?").append(CONTEXT_PARAM).append("=").append(context);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "GET", true);
connection.setDoInput(true);
@ -302,13 +311,45 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
return policies.getPolicies();
}
}
/*
@Override
public File getSymmKey(String filePath) throws Exception{
final String methodPath = "/symmKey/";
StringBuilder callUrl = new StringBuilder(getInternalEnpoint(Utils.getInfrastructureHashFromToken(SecurityTokenProvider.instance.get(), endpoints.getDefaultInfrastructure())))
.append(methodPath);
URL url = new URL(callUrl.toString());
HttpURLConnection connection = makeRequest(url, "GET", true);
connection.setDoInput(true);
if (connection.getResponseCode()!=200) throw new Exception("error retrieving policies");
if (connection.getContentLengthLong()<=0) return null;
String resourceName = (String)connection.getHeaderField("resource-name");
File toReturnFile = new File(filePath+"/"+resourceName);
toReturnFile.createNewFile();
try(InputStream stream = (InputStream)connection.getContent();
OutputStream os = new FileOutputStream(filePath)){
int read = 0;
byte[] bytes = new byte[1024];
while ((read = stream.read(bytes)) != -1) {
os.write(bytes, 0, read);
}
}
return toReturnFile;
}*/
private HttpURLConnection makeRequest(URL url, String method, boolean includeTokenInHeader) throws Exception{
HttpURLConnection connection;
if (url.toString().startsWith("https://"))
connection = (HttpsURLConnection)url.openConnection();
connection = (HttpsURLConnection)url.openConnection();
else connection = (HttpURLConnection)url.openConnection();
if (includeTokenInHeader){
if (SecurityTokenProvider.instance.get()==null) throw new RuntimeException("null token passed");
connection.setRequestProperty(Constants.TOKEN_HEADER_ENTRY,Utils.getRealToken(SecurityTokenProvider.instance.get()));
@ -328,6 +369,6 @@ public class DefaultAuthorizationProxy implements AuthorizationProxy {
public void setEndpoint(EndpointsContainer newEndpoints) {
endpoints = newEndpoints;
}
}

View File

@ -25,9 +25,7 @@ public class CallTest {
@Test
public void requestNodeToken() throws Exception {
SecurityTokenProvider.instance.set(requestTestToken("/gcube/devNext/NextNext"));
String token = authorizationService().requestActivation(new ContainerInfo("node11.d.d4science.research-infrastructures.eu",8080));
System.out.println(token);
System.out.println(_requestNodeToken());
}
@Test
@ -55,12 +53,19 @@ public class CallTest {
public void createKeyWithError() throws Exception {
authorizationService().generateApiKey("TEST");
}
/*
@Test
public void getSymmKey() throws Exception{
SecurityTokenProvider.instance.set(_requestNodeToken());
authorizationService().getSymmKey("/tmp");
}*/
@Test
public void createKey() throws Exception {
String token = requestTestToken("/gcube/devNext/NextNext");
String token = requestTestToken("/gcube");
SecurityTokenProvider.instance.set(token);
String key = authorizationService().generateApiKey("TEST");
String key = authorizationService().generateApiKey("PIPPO");
System.out.println("key : "+key);
System.out.println(resolveToken(key));
}
@ -74,6 +79,12 @@ public class CallTest {
}
public String _requestNodeToken() throws Exception {
SecurityTokenProvider.instance.set(requestTestToken("/gcube/devNext/NextNext"));
String token = authorizationService().requestActivation(new ContainerInfo("mynode",8080));
return token;
}
@Test
public void createTestToken() throws Exception {
System.out.println(requestTestToken("/gcube/devNext/NextNext"));