Search in sources :

Example 1 with Policy

use of io.gravitee.definition.model.Policy in project gravitee-management-rest-api by gravitee-io.

the class ApiService_ExportAsJsonTest method setUp.

@Before
public void setUp() throws TechnicalException {
    PropertyFilter apiMembershipTypeFilter = new ApiPermissionFilter();
    objectMapper.setFilterProvider(new SimpleFilterProvider(Collections.singletonMap("apiMembershipTypeFilter", apiMembershipTypeFilter)));
    Api api = new Api();
    api.setId(API_ID);
    api.setDescription("Gravitee.io");
    when(apiRepository.findById(API_ID)).thenReturn(Optional.of(api));
    PageEntity page = new PageEntity();
    page.setName("My Title");
    page.setOrder(1);
    page.setType(PageType.MARKDOWN.toString());
    page.setContent("Read the doc");
    when(pageService.findApiPagesByApi(API_ID)).thenReturn(Collections.singletonList(new PageListItem()));
    when(pageService.findById(any())).thenReturn(page);
    Membership membership = new Membership();
    membership.setUserId("johndoe");
    membership.setReferenceId(API_ID);
    membership.setReferenceType(MembershipReferenceType.API);
    membership.setRoles(Collections.singletonMap(RoleScope.API.getId(), SystemRole.PRIMARY_OWNER.name()));
    when(membershipRepository.findByReferenceAndRole(eq(MembershipReferenceType.API), eq(API_ID), any(), any())).thenReturn(Collections.singleton(membership));
    MemberEntity memberEntity = new MemberEntity();
    memberEntity.setUsername(membership.getUserId());
    memberEntity.setRole(SystemRole.PRIMARY_OWNER.name());
    when(membershipService.getMembers(eq(MembershipReferenceType.API), eq(API_ID), eq(RoleScope.API))).thenReturn(Collections.singleton(memberEntity));
    UserEntity userEntity = new UserEntity();
    userEntity.setUsername(memberEntity.getId());
    when(userService.findByUsername(memberEntity.getId(), false)).thenReturn(userEntity);
    api.setGroups(Collections.singleton("my-group"));
    GroupEntity groupEntity = new GroupEntity();
    groupEntity.setId("my-group");
    groupEntity.setName("My Group");
    when(groupService.findByIds(api.getGroups())).thenReturn(Collections.singleton(groupEntity));
    PlanEntity publishedPlan = new PlanEntity();
    publishedPlan.setId("plan-id");
    publishedPlan.setApis(Collections.singleton(API_ID));
    publishedPlan.setDescription("free plan");
    publishedPlan.setType(PlanType.API);
    publishedPlan.setSecurity(PlanSecurityType.API_KEY);
    publishedPlan.setValidation(PlanValidationType.AUTO);
    publishedPlan.setStatus(PlanStatus.PUBLISHED);
    Map<String, Path> paths = new HashMap<>();
    Path path = new Path();
    path.setPath("/");
    io.gravitee.definition.model.Rule rule = new io.gravitee.definition.model.Rule();
    rule.setEnabled(true);
    rule.setMethods(Collections.singletonList(HttpMethod.GET));
    Policy policy = new Policy();
    policy.setName("rate-limit");
    String ls = System.lineSeparator();
    policy.setConfiguration("{" + ls + "          \"rate\": {" + ls + "            \"limit\": 1," + ls + "            \"periodTime\": 1," + ls + "            \"periodTimeUnit\": \"SECONDS\"" + ls + "          }" + ls + "        }");
    rule.setPolicy(policy);
    path.setRules(Collections.singletonList(rule));
    paths.put("/", path);
    publishedPlan.setPaths(paths);
    PlanEntity closedPlan = new PlanEntity();
    closedPlan.setId("closedPlan-id");
    closedPlan.setApis(Collections.singleton(API_ID));
    closedPlan.setDescription("free closedPlan");
    closedPlan.setType(PlanType.API);
    closedPlan.setSecurity(PlanSecurityType.API_KEY);
    closedPlan.setValidation(PlanValidationType.AUTO);
    closedPlan.setStatus(PlanStatus.CLOSED);
    closedPlan.setPaths(paths);
    Set<PlanEntity> set = new HashSet<>();
    set.add(publishedPlan);
    set.add(closedPlan);
    when(planService.findByApi(API_ID)).thenReturn(set);
}
Also used : Path(io.gravitee.definition.model.Path) Policy(io.gravitee.definition.model.Policy) SimpleFilterProvider(com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider) Membership(io.gravitee.repository.management.model.Membership) PropertyFilter(com.fasterxml.jackson.databind.ser.PropertyFilter) ApiPermissionFilter(io.gravitee.management.service.jackson.filter.ApiPermissionFilter) io.gravitee.management.model(io.gravitee.management.model) Api(io.gravitee.repository.management.model.Api) Before(org.junit.Before)

Example 2 with Policy

use of io.gravitee.definition.model.Policy in project gravitee-gateway by gravitee-io.

the class Api method policies.

private Set<Policy> policies() {
    if (getPaths() == null)
        return Collections.emptySet();
    Set<io.gravitee.definition.model.Policy> policies = new HashSet<>();
    // Load policies from the API
    getPaths().values().forEach(path -> policies.addAll(path.getRules().stream().map(Rule::getPolicy).distinct().collect(Collectors.toSet())));
    // Load policies from Plans
    getPlans().forEach(plan -> {
        String security = plan.getSecurity();
        Policy secPolicy = new Policy();
        switch(security) {
            case "KEY_LESS":
            case "key_less":
                secPolicy.setName("key-less");
                break;
            case "API_KEY":
            case "api_key":
                secPolicy.setName("api-key");
                break;
            case "OAUTH2":
                secPolicy.setName("oauth2");
                break;
            case "JWT":
                secPolicy.setName("jwt");
                break;
        }
        if (secPolicy.getName() != null) {
            policies.add(secPolicy);
        }
        if (plan.getPaths() != null) {
            plan.getPaths().values().forEach(path -> policies.addAll(path.getRules().stream().map(Rule::getPolicy).distinct().collect(Collectors.toSet())));
        }
    });
    return policies;
}
Also used : Policy(io.gravitee.definition.model.Policy) Rule(io.gravitee.definition.model.Rule)

Example 3 with Policy

use of io.gravitee.definition.model.Policy in project gravitee-gateway by gravitee-io.

the class DefaultPolicyManager method initialize.

private void initialize() {
    PolicyPluginManager ppm = applicationContext.getBean(PolicyPluginManager.class);
    PolicyClassLoaderFactory pclf = applicationContext.getBean(PolicyClassLoaderFactory.class);
    ReactorHandler rh = applicationContext.getBean(ReactorHandler.class);
    ResourceLifecycleManager rm = applicationContext.getBean(ResourceLifecycleManager.class);
    Reactable reactable = rh.reactable();
    Set<Policy> requiredPlugins = reactable.dependencies(Policy.class);
    requiredPlugins.forEach(policy -> {
        final PolicyPlugin policyPlugin = ppm.get(policy.getName());
        if (policyPlugin == null) {
            logger.error("Policy [{}] can not be found in policy registry", policy.getName());
            throw new IllegalStateException("Policy [" + policy.getName() + "] can not be found in policy registry");
        }
        PluginClassLoader policyClassLoader = null;
        // Load dependant resources to enhance policy classloader
        Collection<? extends Resource> resources = rm.getResources();
        if (!resources.isEmpty()) {
            ClassLoader[] resourceClassLoaders = rm.getResources().stream().map(new Function<Resource, ClassLoader>() {

                @Override
                public ClassLoader apply(Resource resource) {
                    return resource.getClass().getClassLoader();
                }
            }).toArray(ClassLoader[]::new);
            DelegatingClassLoader parentClassLoader = new DelegatingClassLoader(rh.classloader(), resourceClassLoaders);
            policyClassLoader = pclf.getOrCreateClassLoader(policyPlugin, parentClassLoader);
        } else {
            policyClassLoader = pclf.getOrCreateClassLoader(policyPlugin, rh.classloader());
        }
        logger.debug("Loading policy {} for {}", policy.getName(), rh);
        PolicyMetadataBuilder builder = new PolicyMetadataBuilder();
        builder.setId(policyPlugin.id());
        try {
            // Prepare metadata
            Class<?> policyClass = ClassUtils.forName(policyPlugin.policy().getName(), policyClassLoader);
            builder.setPolicy(policyClass).setMethods(new PolicyMethodResolver().resolve(policyClass));
            if (policyPlugin.configuration() != null) {
                builder.setConfiguration((Class<? extends PolicyConfiguration>) ClassUtils.forName(policyPlugin.configuration().getName(), policyClassLoader));
            }
            // Prepare context if defined
            if (policyPlugin.context() != null) {
                Class<? extends PolicyContext> policyContextClass = (Class<? extends PolicyContext>) ClassUtils.forName(policyPlugin.context().getName(), policyClassLoader);
                // Create policy context instance and initialize context provider (if used)
                PolicyContext context = new PolicyContextFactory(reactable).create(policyContextClass);
                builder.setContext(context);
            }
            RegisteredPolicy registeredPolicy = new RegisteredPolicy();
            registeredPolicy.classLoader = policyClassLoader;
            registeredPolicy.metadata = builder.build();
            policies.put(policy.getName(), registeredPolicy);
        } catch (Exception ex) {
            logger.error("Unable to load policy metadata", ex);
            if (policyClassLoader != null) {
                try {
                    policyClassLoader.close();
                } catch (IOException ioe) {
                    logger.error("Unable to close classloader for policy", ioe);
                }
            }
        }
    });
}
Also used : Policy(io.gravitee.definition.model.Policy) Reactable(io.gravitee.gateway.reactor.Reactable) PolicyClassLoaderFactory(io.gravitee.plugin.policy.PolicyClassLoaderFactory) Function(java.util.function.Function) ReactorHandler(io.gravitee.gateway.reactor.handler.ReactorHandler) PolicyMethodResolver(io.gravitee.plugin.policy.internal.PolicyMethodResolver) PolicyContext(io.gravitee.policy.api.PolicyContext) PluginClassLoader(io.gravitee.plugin.core.api.PluginClassLoader) PluginClassLoader(io.gravitee.plugin.core.api.PluginClassLoader) PolicyPlugin(io.gravitee.plugin.policy.PolicyPlugin) Resource(io.gravitee.resource.api.Resource) IOException(java.io.IOException) IOException(java.io.IOException) ResourceLifecycleManager(io.gravitee.gateway.resource.ResourceLifecycleManager) PolicyPluginManager(io.gravitee.plugin.policy.PolicyPluginManager)

Example 4 with Policy

use of io.gravitee.definition.model.Policy in project gravitee-gateway by gravitee-io.

the class DefaultPolicyManager method doStop.

@Override
protected void doStop() throws Exception {
    // Deactivate policy context
    policies.values().stream().filter(registeredPolicy -> registeredPolicy.metadata.context() != null).forEach(registeredPolicy -> {
        try {
            logger.info("De-activating context for {} [{}]", registeredPolicy.metadata.id(), registeredPolicy.metadata.context().getClass().getName());
            registeredPolicy.metadata.context().onDeactivation();
        } catch (Exception ex) {
            logger.error("Unable to deactivate policy context", ex);
        }
    });
    // Close policy classloaders
    policies.values().forEach(policy -> {
        ClassLoader policyClassLoader = policy.classLoader;
        if (policyClassLoader instanceof PluginClassLoader) {
            try {
                ((PluginClassLoader) policyClassLoader).close();
            } catch (IOException e) {
                logger.error("Unable to close policy classloader for policy {}", policy.metadata.id());
            }
        }
    });
    // Be sure to remove all references to policies
    policies.clear();
}
Also used : OnRequest(io.gravitee.policy.api.annotations.OnRequest) Resource(io.gravitee.resource.api.Resource) AbstractLifecycleComponent(io.gravitee.common.component.AbstractLifecycleComponent) PolicyClassLoaderFactory(io.gravitee.plugin.policy.PolicyClassLoaderFactory) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) Function(java.util.function.Function) Reactable(io.gravitee.gateway.reactor.Reactable) Map(java.util.Map) OnRequestContent(io.gravitee.policy.api.annotations.OnRequestContent) PluginClassLoader(io.gravitee.plugin.core.api.PluginClassLoader) PolicyPluginManager(io.gravitee.plugin.policy.PolicyPluginManager) OnResponseContent(io.gravitee.policy.api.annotations.OnResponseContent) OnResponse(io.gravitee.policy.api.annotations.OnResponse) Logger(org.slf4j.Logger) ClassUtils(org.springframework.util.ClassUtils) ReactorHandler(io.gravitee.gateway.reactor.handler.ReactorHandler) Collection(java.util.Collection) PolicyConfiguration(io.gravitee.policy.api.PolicyConfiguration) Set(java.util.Set) IOException(java.io.IOException) ApplicationContext(org.springframework.context.ApplicationContext) ResourceLifecycleManager(io.gravitee.gateway.resource.ResourceLifecycleManager) Policy(io.gravitee.definition.model.Policy) PolicyMethodResolver(io.gravitee.plugin.policy.internal.PolicyMethodResolver) PolicyPlugin(io.gravitee.plugin.policy.PolicyPlugin) PolicyContext(io.gravitee.policy.api.PolicyContext) io.gravitee.gateway.policy(io.gravitee.gateway.policy) PluginClassLoader(io.gravitee.plugin.core.api.PluginClassLoader) IOException(java.io.IOException) IOException(java.io.IOException) PluginClassLoader(io.gravitee.plugin.core.api.PluginClassLoader)

Aggregations

Policy (io.gravitee.definition.model.Policy)4 Reactable (io.gravitee.gateway.reactor.Reactable)2 ReactorHandler (io.gravitee.gateway.reactor.handler.ReactorHandler)2 ResourceLifecycleManager (io.gravitee.gateway.resource.ResourceLifecycleManager)2 PluginClassLoader (io.gravitee.plugin.core.api.PluginClassLoader)2 PolicyClassLoaderFactory (io.gravitee.plugin.policy.PolicyClassLoaderFactory)2 PolicyPlugin (io.gravitee.plugin.policy.PolicyPlugin)2 PolicyPluginManager (io.gravitee.plugin.policy.PolicyPluginManager)2 PolicyMethodResolver (io.gravitee.plugin.policy.internal.PolicyMethodResolver)2 PolicyContext (io.gravitee.policy.api.PolicyContext)2 Resource (io.gravitee.resource.api.Resource)2 IOException (java.io.IOException)2 Function (java.util.function.Function)2 PropertyFilter (com.fasterxml.jackson.databind.ser.PropertyFilter)1 SimpleFilterProvider (com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider)1 AbstractLifecycleComponent (io.gravitee.common.component.AbstractLifecycleComponent)1 Path (io.gravitee.definition.model.Path)1 Rule (io.gravitee.definition.model.Rule)1 io.gravitee.gateway.policy (io.gravitee.gateway.policy)1 io.gravitee.management.model (io.gravitee.management.model)1