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);
}
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;
}
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);
}
}
}
});
}
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();
}
Aggregations