use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20TestCase method testGenerateMergedResourceDefinition.
@Test
public void testGenerateMergedResourceDefinition() throws IOException {
APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithAuthorization.yaml"));
UriTemplate uriTemplate1 = new UriTemplate.UriTemplateBuilder().uriTemplate("/apis").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
UriTemplate uriTemplate2 = new UriTemplate.UriTemplateBuilder().uriTemplate("/endpoints").httpVerb("post").scopes(Arrays.asList("apim:api_create")).build();
Map<String, UriTemplate> hasTemplateMap = new HashMap<>();
hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate1.getUriTemplate(), uriTemplate1.getHttpVerb()), uriTemplate1);
hasTemplateMap.put(APIUtils.generateOperationIdFromPath(uriTemplate2.getUriTemplate(), uriTemplate2.getHttpVerb()), uriTemplate2);
API api = new API.APIBuilder("admin", "admin", "1.0.0").uriTemplates(hasTemplateMap).id(UUID.randomUUID().toString()).build();
apiDefinitionFromSwagger20.generateMergedResourceDefinition(sampleApi, api);
}
use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIDefinitionFromSwagger20TestCase method testAddNewScopeToSecurityDefinitionExistingSwaggerNonExisting.
@Test()
public void testAddNewScopeToSecurityDefinitionExistingSwaggerNonExisting() throws IOException, APIManagementException {
APIDefinitionFromSwagger20 apiDefinitionFromSwagger20 = new APIDefinitionFromSwagger20();
String sampleApi = IOUtils.toString(this.getClass().getResourceAsStream(File.separator + "swagger" + File.separator + "swaggerWithAuthorizationApiKey.yaml"));
Scope scope = new Scope();
scope.setName("apim:api_delete");
scope.setDescription("Delete API");
String scopeAddedSwagger = apiDefinitionFromSwagger20.addScopeToSwaggerDefinition(sampleApi, scope);
Map<String, String> scopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(scopeAddedSwagger);
Assert.assertTrue(scopes.containsKey("apim:api_delete"));
}
use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class OAuth2Authenticator method validateScopes.
/*
* This method validates the given scope against scopes defined in the api resource
* @param Request
* @param ServiceMethodInfo
* @param scopesToValidate scopes extracted from the access token
* @return true if scope validation successful
* */
@SuppressFBWarnings({ "DLS_DEAD_LOCAL_STORE" })
private boolean validateScopes(Request request, ServiceMethodInfo serviceMethodInfo, String scopesToValidate, String restAPIResource) throws APIMgtSecurityException {
final boolean[] authorized = { false };
String path = (String) request.getProperty(APIConstants.REQUEST_URL);
String verb = (String) request.getProperty(APIConstants.HTTP_METHOD);
if (log.isDebugEnabled()) {
log.debug("Invoking rest api resource path " + verb + " " + path + " ");
log.debug("LoggedIn user scopes " + scopesToValidate);
}
String[] scopesArr = new String[0];
if (scopesToValidate != null) {
scopesArr = scopesToValidate.split(" ");
}
if (scopesToValidate != null && scopesArr.length > 0) {
final List<String> scopes = Arrays.asList(scopesArr);
if (restAPIResource != null) {
APIDefinition apiDefinition = new APIDefinitionFromSwagger20();
try {
String apiResourceDefinitionScopes = apiDefinition.getScopeOfResourcePath(restAPIResource, request, serviceMethodInfo);
if (StringUtils.isEmpty(apiResourceDefinitionScopes)) {
if (log.isDebugEnabled()) {
log.debug("Scope not defined in swagger for matching resource " + path + " and verb " + verb + " . Hence consider as anonymous permission and let request to continue.");
}
// scope validation gets through if no scopes found in the api definition
authorized[0] = true;
} else {
Arrays.stream(apiResourceDefinitionScopes.split(" ")).forEach(scopeKey -> {
Optional<String> key = scopes.stream().filter(scp -> {
return scp.equalsIgnoreCase(scopeKey);
}).findAny();
if (key.isPresent()) {
// scope validation success if one of the
authorized[0] = true;
// apiResourceDefinitionScopes found.
}
});
}
} catch (APIManagementException e) {
String message = "Error while validating scopes";
log.error(message, e);
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
} else {
if (log.isDebugEnabled()) {
log.debug("Rest API resource could not be found for request path '" + path + "'");
}
}
} else {
// scope validation gets through if access token does not contain scopes to validate
authorized[0] = true;
}
if (!authorized[0]) {
String message = "Scope validation fails for the scopes " + scopesToValidate;
throw new APIMgtSecurityException(message, ExceptionCodes.INVALID_SCOPE);
}
return authorized[0];
}
use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIPublisherImplTestCase method testGetScopesFromApi.
@Test(description = "Save swagger definition for API")
public void testGetScopesFromApi() throws APIManagementException, IOException {
ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
APIPublisherImpl apiPublisher = getApiPublisherImpl(apiDAO);
String newSwagger = IOUtils.toString(new FileInputStream("src" + File.separator + "test" + File.separator + "resources" + File.separator + "swagger" + File.separator + "swaggerWithAuthorization" + ".yaml"));
Mockito.when(apiDAO.getApiSwaggerDefinition("abcd")).thenReturn(newSwagger);
Map<String, String> scopesSet = apiPublisher.getScopesForApi("abcd");
Map<String, String> scopes = new APIDefinitionFromSwagger20().getScopesFromSecurityDefinition(newSwagger);
scopesSet.keySet().removeAll(scopes.keySet());
Assert.assertTrue(scopesSet.isEmpty());
}
use of org.wso2.carbon.apimgt.core.impl.APIDefinitionFromSwagger20 in project carbon-apimgt by wso2.
the class APIPublisherImpl method saveSwagger20Definition.
/**
* {@inheritDoc}
*/
@Override
public void saveSwagger20Definition(String apiId, String jsonText) throws APIManagementException {
try {
LocalDateTime localDateTime = LocalDateTime.now();
Map<String, String> oldScopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(getApiSwaggerDefinition(apiId));
Map<String, String> newScopes = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(jsonText);
Map<String, String> updatedScopes = new HashMap<>(newScopes);
updatedScopes.keySet().retainAll(oldScopes.keySet());
oldScopes.keySet().removeAll(updatedScopes.keySet());
newScopes.keySet().removeAll(updatedScopes.keySet());
for (Map.Entry<String, String> scopeEntry : newScopes.entrySet()) {
getKeyManager().registerScope(new Scope(scopeEntry.getKey(), scopeEntry.getValue()));
}
for (Map.Entry<String, String> scopeEntry : oldScopes.entrySet()) {
getKeyManager().deleteScope(scopeEntry.getKey());
}
for (Map.Entry<String, String> scopeEntry : updatedScopes.entrySet()) {
Scope scope = getKeyManager().retrieveScope(scopeEntry.getKey());
scope.setDescription(scopeEntry.getValue());
getKeyManager().updateScope(scope);
}
API api = getAPIbyUUID(apiId);
Map<String, UriTemplate> oldUriTemplateMap = api.getUriTemplates();
List<APIResource> apiResourceList = apiDefinitionFromSwagger20.parseSwaggerAPIResources(new StringBuilder(jsonText));
Map<String, UriTemplate> updatedUriTemplateMap = new HashMap<>();
for (APIResource apiResource : apiResourceList) {
updatedUriTemplateMap.put(apiResource.getUriTemplate().getTemplateId(), apiResource.getUriTemplate());
}
Map<String, UriTemplate> uriTemplateMapNeedTobeUpdate = APIUtils.getMergedUriTemplates(oldUriTemplateMap, updatedUriTemplateMap);
API.APIBuilder apiBuilder = new API.APIBuilder(api);
apiBuilder.uriTemplates(uriTemplateMapNeedTobeUpdate);
createUriTemplateList(apiBuilder, true);
apiBuilder.updatedBy(getUsername());
apiBuilder.lastUpdatedTime(localDateTime);
api = apiBuilder.build();
GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
String existingGatewayConfig = getApiGatewayConfig(apiId);
String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(existingGatewayConfig, jsonText);
getApiDAO().updateAPI(apiId, api);
getApiDAO().updateApiDefinition(apiId, jsonText, getUsername());
getApiDAO().updateGatewayConfig(apiId, updatedGatewayConfig, getUsername());
} catch (APIMgtDAOException e) {
String errorMsg = "Couldn't update the Swagger Definition";
log.error(errorMsg, e);
throw new APIManagementException(errorMsg, e, e.getErrorHandler());
}
}
Aggregations