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

View File

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