Search in sources :

Example 56 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project carbon-apimgt by wso2.

the class DefaultIdentityProviderImplTestCase method testGetRoleNamesOfUser.

@Test
public void testGetRoleNamesOfUser() throws Exception {
    SCIMServiceStub scimServiceStub = Mockito.mock(SCIMServiceStub.class);
    UserNameMapper userNameMapper = Mockito.mock(UserNameMapperImpl.class);
    DefaultIdentityProviderImpl idpImpl = new DefaultIdentityProviderImpl(scimServiceStub, userNameMapper);
    String validUserId = "a42b4760-120d-432e-8042-4a7f12e3346c";
    String roleName1 = "subscriber";
    String roleId1 = "fb5aaf9c-1fdf-4b2d-86bc-6e3203b99618";
    String roleName2 = "manager";
    String roleId2 = "097435bc-c460-402b-9137-8ab65fd28c3e";
    String roleName3 = "engineer";
    String roleId3 = "ac093278-9343-466c-8a71-af47921a575b";
    List<String> roleNames = new ArrayList<>();
    roleNames.add(roleName1);
    roleNames.add(roleName2);
    roleNames.add(roleName3);
    String successResponseBody = "{\"emails\":[{\"type\":\"home\",\"value\":\"john_home.com\"},{\"type\":\"work\"" + ",\"value\":\"john_work.com\"}],\"meta\":{\"created\":\"2017-06-02T10:12:26\",\"location\":" + "\"https://localhost:9443/wso2/scim/Users/" + validUserId + "\",\"lastModified\":" + "\"2017-06-02T10:12:26\"},\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"name\":{\"familyName\":" + "\"Smith\",\"givenName\":\"John\"},\"groups\":[{\"display\":\"" + roleName1 + "\",\"value\":\"" + roleId1 + "\"},{\"display\":\"" + roleName2 + "\",\"value\":\"" + roleId2 + "\"},{\"display\":\"" + roleName3 + "\",\"value\":\"" + roleId3 + "\"}],\"id\":\"" + validUserId + "\",\"userName\":" + "\"John\"}";
    Response successfulResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body(successResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(validUserId)).thenReturn(successfulResponse);
    List<String> roles = idpImpl.getRoleNamesOfUser(validUserId);
    Assert.assertEquals(roleNames.size(), roles.size());
    roles.forEach(roleName -> Assert.assertTrue(roleNames.contains(roleName)));
    // Error case - When response is null
    String invalidUserIdResponseNull = "invalidUserId_Response_Null";
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseNull)).thenReturn(null);
    try {
        idpImpl.getRoleNamesOfUser(invalidUserIdResponseNull);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with Id " + invalidUserIdResponseNull + ". Error : Response is null.");
    }
    // Error case - When the request did not return a 200 OK response
    String invalidUserIdNot200OK = "invalidUserId_Not_200_OK";
    String errorResponseBody = "{\"Errors\":[{\"code\":\"404\",\"description\":\"User not found in the user " + "store.\"}]}";
    Response errorResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_404_NOT_FOUND).headers(new HashMap<>()).body(errorResponseBody.getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdNot200OK)).thenReturn(errorResponse);
    try {
        idpImpl.getRoleNamesOfUser(invalidUserIdNot200OK);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving role names of user with Id " + invalidUserIdNot200OK + ". Error : User not found in the user store.");
    }
    // Error case - When response body is empty
    String invalidUserIdResponseEmpty = "invalidUserId_Response_Empty";
    Response emptyResponse = Response.builder().status(APIMgtConstants.HTTPStatusCodes.SC_200_OK).headers(new HashMap<>()).body("".getBytes()).build();
    Mockito.when(scimServiceStub.getUser(invalidUserIdResponseEmpty)).thenReturn(emptyResponse);
    try {
        idpImpl.getRoleNamesOfUser(invalidUserIdResponseEmpty);
    } catch (IdentityProviderException ex) {
        Assert.assertEquals(ex.getMessage(), "Error occurred while retrieving user with user Id " + invalidUserIdResponseEmpty + " from SCIM endpoint. Response body is null or empty.");
    }
}
Also used : Response(feign.Response) UserNameMapper(org.wso2.carbon.apimgt.core.api.UserNameMapper) ArrayList(java.util.ArrayList) SCIMServiceStub(org.wso2.carbon.apimgt.core.auth.SCIMServiceStub) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) Test(org.testng.annotations.Test)

Example 57 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project carbon-apimgt by wso2.

the class RESTAPISecurityInterceptor method preCall.

/**
 * preCall is run before a handler method call is made. If any of the preCalls throw exception or return false then
 * no other subsequent preCalls will be called and the request processing will be terminated,
 * also no postCall interceptors will be called.
 *
 * @param request           HttpRequest being processed.
 * @param response          HttpResponder to send response.
 * @param serviceMethodInfo Info on handler method that will be called.
 * @return true if the request processing can continue, otherwise the hook should send response and return false to
 * stop further processing.
 * @throws APIMgtSecurityException if error occurs while executing the preCall
 */
@Override
public boolean preCall(Request request, Response response, ServiceMethodInfo serviceMethodInfo) throws APIMgtSecurityException {
    ErrorHandler errorHandler = null;
    boolean isAuthenticated = false;
    // CORS for Environments - Add allowed Origin when User-Agent sent 'Origin' header.
    String origin = request.getHeader(RestApiConstants.ORIGIN_HEADER);
    String allowedOrigin = EnvironmentUtils.getAllowedOrigin(origin);
    if (allowedOrigin != null) {
        response.setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, allowedOrigin).setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER, "true");
    }
    // CORS for Environments - Add allowed Methods and Headers when 'OPTIONS' method is called.
    if (request.getHttpMethod().equalsIgnoreCase(APIConstants.HTTP_OPTIONS)) {
        try {
            String definedHttpMethods = RestApiUtil.getDefinedMethodHeadersInSwaggerContent(request, serviceMethodInfo);
            if (definedHttpMethods != null) {
                response.setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_METHODS_HEADER, definedHttpMethods).setHeader(RestApiConstants.ACCESS_CONTROL_ALLOW_HEADERS_HEADER, RestApiConstants.ACCESS_CONTROL_ALLOW_HEADERS_LIST).setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).send();
                return false;
            }
        } catch (APIManagementException e) {
            String msg = "Couldn't find declared HTTP methods in swagger.yaml";
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
            log.error(msg, e);
            response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            return false;
        }
    }
    /* TODO: Following string contains check is done to avoid checking security headers in non API requests.
         * Consider this as a temporary fix until MSF4J support context based interceptor registration */
    String requestURI = request.getUri().toLowerCase(Locale.ENGLISH);
    if (!requestURI.contains("/api/am/")) {
        return true;
    }
    if (requestURI.contains("/login/token")) {
        return true;
    }
    String yamlContent = null;
    String protocol = (String) request.getProperty(PROTOCOL);
    Swagger swagger = null;
    if (requestURI.contains("/api/am/publisher")) {
        if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getPublisherRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for publisher";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    } else if (requestURI.contains("/api/am/store")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getStoreRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.STORE));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.json for store";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        } else if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getStoreRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for store";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    } else if (requestURI.contains("/api/am/analytics")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getAnalyticsRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ANALYTICS));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
            } catch (APIManagementException e) {
                log.error("Couldn't find swagger.json for analytics", e);
            }
            response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            return false;
        }
    } else if (requestURI.contains("/editor") || requestURI.contains("keyserver") || requestURI.contains("core") || requestURI.contains("/api/am/config")) {
        return true;
    } else if (requestURI.contains("/api/am/admin")) {
        if (requestURI.contains("swagger.json")) {
            try {
                yamlContent = RestApiUtil.getAdminRestAPIResource();
                swagger = new SwaggerParser().parse(yamlContent);
                swagger.setBasePath(RestApiUtil.getContext(RestApiConstants.APPType.ADMIN));
                swagger.setHost(RestApiUtil.getHost(protocol.toLowerCase(Locale.ENGLISH)));
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(Json.pretty(swagger)).setMediaType(MediaType.APPLICATION_JSON).send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for admin";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        } else if (requestURI.contains("swagger.yaml")) {
            try {
                yamlContent = RestApiUtil.getAdminRestAPIResource();
                response.setStatus(javax.ws.rs.core.Response.Status.OK.getStatusCode()).setEntity(yamlContent).setMediaType("text/x-yaml").send();
            } catch (APIManagementException e) {
                String msg = "Couldn't find swagger.yaml for admin";
                ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler());
                log.error(msg, e);
                response.setStatus(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).setEntity(errorDTO).send();
            }
            return false;
        }
    }
    try {
        if (authenticatorImplClass == null) {
            Class<?> implClass = null;
            try {
                implClass = Class.forName(authenticatorName);
            } catch (ClassNotFoundException e) {
                throw new APIMgtSecurityException("Error while loading class " + authenticatorName, e);
            }
            authenticatorImplClass = (RESTAPIAuthenticator) implClass.newInstance();
        }
        isAuthenticated = authenticatorImplClass.authenticate(request, response, serviceMethodInfo);
    } catch (APIMgtSecurityException e) {
        errorHandler = e.getErrorHandler();
        log.error(e.getMessage() + " Requested Path: " + request.getUri());
    } catch (InstantiationException e) {
        log.error(e.getMessage() + " Error while instantiating authenticator: " + authenticatorName);
        isAuthenticated = false;
        errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
    } catch (IllegalAccessException e) {
        log.error(e.getMessage() + " Error while accessing resource : " + authenticatorName);
        isAuthenticated = false;
        errorHandler = ExceptionCodes.AUTH_GENERAL_ERROR;
    }
    if (!isAuthenticated) {
        handleSecurityError(errorHandler, response);
    }
    return isAuthenticated;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIMgtSecurityException(org.wso2.carbon.apimgt.rest.api.common.exception.APIMgtSecurityException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) Swagger(io.swagger.models.Swagger)

Example 58 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project carbon-apimgt by wso2.

the class RestApiUtil method getDefinedMethodHeadersInSwaggerContent.

/**
 * Get defined HTTP methods in the swagger definition as a comma separated string
 *
 * @param request           Request
 * @param serviceMethodInfo Method information for the request
 * @return Http Methods as a comma separated string
 * @throws APIManagementException if failed to get defined http methods
 */
public static String getDefinedMethodHeadersInSwaggerContent(Request request, ServiceMethodInfo serviceMethodInfo) throws APIManagementException {
    String requestURI = request.getUri().toLowerCase(Locale.ENGLISH);
    Swagger swagger = null;
    Method resourceMethod;
    if (requestURI.contains("/api/am/publisher")) {
        swagger = swaggerRestAPIDefinitions.get(RestApiConstants.APPType.PUBLISHER);
    } else if (requestURI.contains("/api/am/store")) {
        swagger = swaggerRestAPIDefinitions.get(RestApiConstants.APPType.STORE);
    } else if (requestURI.contains("/api/am/analytics")) {
        swagger = swaggerRestAPIDefinitions.get(RestApiConstants.APPType.ANALYTICS);
    } else if (requestURI.contains("/api/am/admin")) {
        swagger = swaggerRestAPIDefinitions.get(RestApiConstants.APPType.ADMIN);
    } else {
        return null;
    }
    if (swagger == null) {
        throw new APIManagementException("Error while parsing the swagger definition", ExceptionCodes.SWAGGER_URL_MALFORMED);
    }
    resourceMethod = serviceMethodInfo.getMethod();
    if (resourceMethod == null) {
        throw new APIManagementException("Could not read required properties from HTTP Request.", ExceptionCodes.SWAGGER_URL_MALFORMED);
    }
    String apiPath = resourceMethod.getDeclaringClass().getAnnotation(javax.ws.rs.ApplicationPath.class).value();
    javax.ws.rs.Path apiPathAnnotation = resourceMethod.getAnnotation(javax.ws.rs.Path.class);
    if (apiPathAnnotation != null) {
        apiPath += apiPathAnnotation.value();
    }
    Path swaggerAPIPath = swagger.getPath(apiPath);
    if (swaggerAPIPath == null) {
        throw new APIManagementException("Could not read API path from the swagger definition", ExceptionCodes.SWAGGER_URL_MALFORMED);
    }
    return swaggerAPIPath.getOperationMap().keySet().stream().map(Enum::toString).collect(Collectors.joining(", "));
}
Also used : Path(io.swagger.models.Path) Collectors(java.util.stream.Collectors) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Swagger(io.swagger.models.Swagger) Method(java.lang.reflect.Method)

Example 59 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project carbon-apimgt by wso2.

the class RestApiUtilTestCase method testGetContext.

@Test(description = "Test get Context")
public void testGetContext() throws Exception {
    APIMConfigurations apimConfigurations = new APIMConfigurations();
    String actualPubContext = RestApiUtil.getContext("publisher");
    String expectedPubContext = apimConfigurations.getPublisherContext();
    Assert.assertEquals(actualPubContext, expectedPubContext);
    String actualStoreContext = RestApiUtil.getContext("store");
    String expectedStoreStoreContext = apimConfigurations.getStoreContext();
    Assert.assertEquals(actualStoreContext, expectedStoreStoreContext);
    String actualAdminContext = RestApiUtil.getContext("admin");
    String expectedAdminContext = apimConfigurations.getAdminContext();
    Assert.assertEquals(actualAdminContext, expectedAdminContext);
    String actualContext = RestApiUtil.getContext("test");
    Assert.assertEquals(actualContext, null);
}
Also used : APIMConfigurations(org.wso2.carbon.apimgt.core.configuration.models.APIMConfigurations) Test(org.testng.annotations.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 60 with Store

use of org.wso2.siddhi.query.api.execution.query.input.store.Store in project carbon-apimgt by wso2.

the class H2SQLStatements method prepareAttributeSearchStatementForStore.

/**
 * @see ApiDAOVendorSpecificStatements#prepareAttributeSearchStatementForStore(Connection connection, List, List,
 * Map, int, int)
 */
@Override
@SuppressFBWarnings({ "SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING", "OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE" })
public PreparedStatement prepareAttributeSearchStatementForStore(Connection connection, List<String> roles, List<String> labels, Map<String, String> attributeMap, int offset, int limit) throws APIMgtDAOException {
    StringBuilder roleListBuilder = new StringBuilder();
    roleListBuilder.append("?");
    for (int i = 0; i < roles.size() - 1; i++) {
        roleListBuilder.append(",?");
    }
    StringBuilder searchQuery = new StringBuilder();
    Iterator<Map.Entry<String, String>> entries = attributeMap.entrySet().iterator();
    while (entries.hasNext()) {
        Map.Entry<String, String> entry = entries.next();
        searchQuery.append("LOWER(");
        if (APIMgtConstants.TAG_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.TAG_NAME_COLUMN);
        } else if (APIMgtConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
            searchQuery.append(APIMgtConstants.URL_PATTERN_COLUMN);
        } else {
            searchQuery.append(entry.getKey());
        }
        searchQuery.append(") LIKE ?");
        if (entries.hasNext()) {
            searchQuery.append(" AND ");
        }
    }
    // retrieve the attribute applicable for the search
    String searchAttribute = attributeMap.entrySet().iterator().next().getKey();
    // get the corresponding implementation based on the attribute to be searched
    String query = searchMap.get(searchAttribute).getStoreAttributeSearchQuery(roleListBuilder, searchQuery, offset, limit);
    query = "Select * from ( " + query + " ) " + getStoreAPIsByLabelJoinQuery(labels);
    try {
        int queryIndex = 1;
        PreparedStatement statement = connection.prepareStatement(query);
        // include the attribute in the query (for APIs with public visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        // include user roles in the query
        for (String role : roles) {
            statement.setString(queryIndex, role);
            queryIndex++;
        }
        // include the attribute in the query (for APIs with restricted visibility)
        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {
            statement.setString(queryIndex, '%' + entry.getValue().toLowerCase(Locale.ENGLISH) + '%');
            queryIndex++;
        }
        for (String label : labels) {
            statement.setString(queryIndex, label);
            queryIndex++;
        }
        // setting 0 as the default offset based on store-api.yaml and H2 specifications
        statement.setInt(queryIndex, (offset < 0) ? 0 : offset);
        statement.setInt(++queryIndex, limit);
        return statement;
    } catch (SQLException e) {
        String errorMsg = "Error occurred while searching APIs for attributes in the database.";
        log.error(errorMsg, e);
        throw new APIMgtDAOException(errorMsg, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) HashMap(java.util.HashMap) Map(java.util.Map) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

HashMap (java.util.HashMap)25 Test (org.testng.annotations.Test)21 ArrayList (java.util.ArrayList)18 CharonException (org.wso2.charon3.core.exceptions.CharonException)18 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)18 UserManager (org.wso2.charon3.core.extensions.UserManager)15 Produces (javax.ws.rs.Produces)14 ApiOperation (io.swagger.annotations.ApiOperation)12 ApiResponses (io.swagger.annotations.ApiResponses)12 Path (javax.ws.rs.Path)10 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)10 Map (java.util.Map)9 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)8 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)8 UserStoreException (org.wso2.carbon.user.api.UserStoreException)8 Consumes (javax.ws.rs.Consumes)7 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)7 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)7 Response (feign.Response)6 IOException (java.io.IOException)6