Search in sources :

Example 1 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceTest method shouldCreateWithAutomaticSubscription_forApiKey.

@Test
public void shouldCreateWithAutomaticSubscription_forApiKey() throws Exception {
    // Prepare data
    when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
    when(plan.getValidation()).thenReturn(PlanValidationType.AUTO);
    when(plan.getSecurity()).thenReturn(PlanSecurityType.API_KEY);
    // subscription object is not a mock since its state is updated by the call to subscriptionService.create()
    Subscription subscription = new Subscription();
    subscription.setId(SUBSCRIPTION_ID);
    subscription.setApplication(APPLICATION_ID);
    subscription.setPlan(PLAN_ID);
    subscription.setStatus(Subscription.Status.PENDING);
    SecurityContextHolder.setContext(new SecurityContext() {

        @Override
        public Authentication getAuthentication() {
            return new Authentication() {

                @Override
                public Collection<? extends GrantedAuthority> getAuthorities() {
                    return null;
                }

                @Override
                public Object getCredentials() {
                    return null;
                }

                @Override
                public Object getDetails() {
                    return null;
                }

                @Override
                public Object getPrincipal() {
                    return new UserDetails("tester", "password", Collections.emptyList());
                }

                @Override
                public boolean isAuthenticated() {
                    return false;
                }

                @Override
                public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
                }

                @Override
                public String getName() {
                    return null;
                }
            };
        }

        @Override
        public void setAuthentication(Authentication authentication) {
        }
    });
    // Stub
    when(planService.findById(PLAN_ID)).thenReturn(plan);
    when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
    when(apiService.findByIdForTemplates(API_ID)).thenReturn(apiModelEntity);
    when(subscriptionRepository.update(any())).thenAnswer(returnsFirstArg());
    when(subscriptionRepository.create(any())).thenAnswer(new Answer<Subscription>() {

        @Override
        public Subscription answer(InvocationOnMock invocation) throws Throwable {
            Subscription subscription = (Subscription) invocation.getArguments()[0];
            subscription.setId(SUBSCRIPTION_ID);
            return subscription;
        }
    });
    when(subscriptionRepository.findById(SUBSCRIPTION_ID)).thenAnswer(new Answer<Optional<Subscription>>() {

        @Override
        public Optional<Subscription> answer(InvocationOnMock invocation) throws Throwable {
            subscription.setCreatedAt(new Date());
            return Optional.of(subscription);
        }
    });
    // Run
    final SubscriptionEntity subscriptionEntity = subscriptionService.create(new NewSubscriptionEntity(PLAN_ID, APPLICATION_ID));
    // Verify
    verify(subscriptionRepository, times(1)).create(any(Subscription.class));
    verify(subscriptionRepository, times(1)).update(any(Subscription.class));
    verify(apiKeyService, times(1)).generate(any());
    assertNotNull(subscriptionEntity.getId());
    assertNotNull(subscriptionEntity.getApplication());
    assertNotNull(subscriptionEntity.getCreatedAt());
}
Also used : GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) InvocationOnMock(org.mockito.invocation.InvocationOnMock) SecurityContext(org.springframework.security.core.context.SecurityContext) Subscription(io.gravitee.repository.management.model.Subscription) Test(org.junit.Test)

Example 2 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceTest method shouldUpdateSubscriptionWithEndingDateButExpiredApiKey.

@Test
public void shouldUpdateSubscriptionWithEndingDateButExpiredApiKey() throws Exception {
    UpdateSubscriptionEntity updatedSubscription = new UpdateSubscriptionEntity();
    updatedSubscription.setId(SUBSCRIPTION_ID);
    updatedSubscription.setEndingAt(new Date());
    // subscription object is not a mock since its state is updated by the call to subscriptionService.create()
    Subscription subscription = new Subscription();
    subscription.setId(SUBSCRIPTION_ID);
    subscription.setApplication(APPLICATION_ID);
    subscription.setPlan(PLAN_ID);
    subscription.setStatus(Subscription.Status.ACCEPTED);
    subscription.setEndingAt(updatedSubscription.getEndingAt());
    // Stub
    when(subscriptionRepository.findById(SUBSCRIPTION_ID)).thenReturn(Optional.of(subscription));
    when(subscriptionRepository.update(subscription)).thenAnswer(returnsFirstArg());
    when(apiKeyService.findBySubscription(SUBSCRIPTION_ID)).thenReturn(Collections.singleton(apiKeyEntity));
    when(apiKeyEntity.isRevoked()).thenReturn(false);
    when(apiKeyEntity.getExpireAt()).thenReturn(new Date());
    when(planService.findById(PLAN_ID)).thenReturn(plan);
    when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
    when(plan.getSecurity()).thenReturn(PlanSecurityType.API_KEY);
    // Run
    subscriptionService.update(updatedSubscription);
    // Verify
    verify(subscriptionRepository, times(1)).update(subscription);
    verify(apiKeyService, times(1)).findBySubscription(SUBSCRIPTION_ID);
    verify(apiKeyService, times(1)).update(apiKeyEntity);
}
Also used : Subscription(io.gravitee.repository.management.model.Subscription) Test(org.junit.Test)

Example 3 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceTest method shouldCreateWithAutomaticSubscription_notApiKey.

@Test
public void shouldCreateWithAutomaticSubscription_notApiKey() throws Exception {
    // Prepare data
    when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
    when(plan.getValidation()).thenReturn(PlanValidationType.AUTO);
    when(plan.getSecurity()).thenReturn(PlanSecurityType.OAUTH2);
    when(application.getClientId()).thenReturn("my-client-id");
    // subscription object is not a mock since its state is updated by the call to subscriptionService.create()
    Subscription subscription = new Subscription();
    subscription.setId(SUBSCRIPTION_ID);
    subscription.setApplication(APPLICATION_ID);
    subscription.setPlan(PLAN_ID);
    subscription.setStatus(Subscription.Status.PENDING);
    SecurityContextHolder.setContext(new SecurityContext() {

        @Override
        public Authentication getAuthentication() {
            return new Authentication() {

                @Override
                public Collection<? extends GrantedAuthority> getAuthorities() {
                    return null;
                }

                @Override
                public Object getCredentials() {
                    return null;
                }

                @Override
                public Object getDetails() {
                    return null;
                }

                @Override
                public Object getPrincipal() {
                    return new UserDetails("tester", "password", Collections.emptyList());
                }

                @Override
                public boolean isAuthenticated() {
                    return false;
                }

                @Override
                public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
                }

                @Override
                public String getName() {
                    return null;
                }
            };
        }

        @Override
        public void setAuthentication(Authentication authentication) {
        }
    });
    // Stub
    when(planService.findById(PLAN_ID)).thenReturn(plan);
    when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
    when(apiService.findByIdForTemplates(API_ID)).thenReturn(apiModelEntity);
    when(subscriptionRepository.update(any())).thenAnswer(returnsFirstArg());
    when(subscriptionRepository.create(any())).thenAnswer(new Answer<Subscription>() {

        @Override
        public Subscription answer(InvocationOnMock invocation) throws Throwable {
            Subscription subscription = (Subscription) invocation.getArguments()[0];
            subscription.setId(SUBSCRIPTION_ID);
            return subscription;
        }
    });
    when(subscriptionRepository.findById(SUBSCRIPTION_ID)).thenAnswer(new Answer<Optional<Subscription>>() {

        @Override
        public Optional<Subscription> answer(InvocationOnMock invocation) throws Throwable {
            subscription.setCreatedAt(new Date());
            return Optional.of(subscription);
        }
    });
    // Run
    final SubscriptionEntity subscriptionEntity = subscriptionService.create(new NewSubscriptionEntity(PLAN_ID, APPLICATION_ID));
    // Verify
    verify(subscriptionRepository, times(1)).create(any(Subscription.class));
    verify(subscriptionRepository, times(1)).update(any(Subscription.class));
    verify(apiKeyService, never()).generate(any());
    assertNotNull(subscriptionEntity.getId());
    assertNotNull(subscriptionEntity.getApplication());
    assertNotNull(subscriptionEntity.getCreatedAt());
}
Also used : GrantedAuthority(org.springframework.security.core.GrantedAuthority) UserDetails(io.gravitee.management.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) InvocationOnMock(org.mockito.invocation.InvocationOnMock) SecurityContext(org.springframework.security.core.context.SecurityContext) Subscription(io.gravitee.repository.management.model.Subscription) Test(org.junit.Test)

Example 4 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceTest method shouldProcessButReject.

@Test
public void shouldProcessButReject() throws Exception {
    // Prepare data
    ProcessSubscriptionEntity processSubscription = new ProcessSubscriptionEntity();
    processSubscription.setId(SUBSCRIPTION_ID);
    processSubscription.setAccepted(false);
    Subscription subscription = new Subscription();
    subscription.setApplication(APPLICATION_ID);
    subscription.setPlan(PLAN_ID);
    subscription.setStatus(Subscription.Status.PENDING);
    when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
    // Stub
    when(subscriptionRepository.findById(SUBSCRIPTION_ID)).thenReturn(Optional.of(subscription));
    when(planService.findById(PLAN_ID)).thenReturn(plan);
    when(applicationService.findById(APPLICATION_ID)).thenReturn(application);
    when(apiService.findById(API_ID)).thenReturn(apiEntity);
    when(subscriptionRepository.update(any())).thenAnswer(returnsFirstArg());
    // Run
    final SubscriptionEntity subscriptionEntity = subscriptionService.process(processSubscription, SUBSCRIPTION_VALIDATOR);
    // Verify
    verify(apiKeyService, never()).generate(any());
    assertEquals(SubscriptionStatus.REJECTED, subscriptionEntity.getStatus());
    assertEquals(SUBSCRIPTION_VALIDATOR, subscriptionEntity.getProcessedBy());
    assertNotNull(subscriptionEntity.getProcessedAt());
}
Also used : Subscription(io.gravitee.repository.management.model.Subscription) Test(org.junit.Test)

Example 5 with Subscription

use of io.gravitee.repository.management.model.Subscription in project gravitee-management-rest-api by gravitee-io.

the class SubscriptionServiceImpl method create.

@Override
public SubscriptionEntity create(NewSubscriptionEntity newSubscriptionEntity) {
    String plan = newSubscriptionEntity.getPlan();
    String application = newSubscriptionEntity.getApplication();
    try {
        logger.debug("Create a new subscription for plan {} and application {}", plan, application);
        PlanEntity planEntity = planService.findById(plan);
        if (planEntity.getStatus() == PlanStatus.CLOSED) {
            throw new PlanAlreadyClosedException(plan);
        }
        if (planEntity.getStatus() == PlanStatus.STAGING) {
            throw new PlanNotYetPublishedException(plan);
        }
        if (planEntity.getSecurity() == PlanSecurityType.KEY_LESS) {
            throw new PlanNotSubscribableException("A key_less plan is not subscribable !");
        }
        ApplicationEntity applicationEntity = applicationService.findById(application);
        // Check existing subscriptions
        List<Subscription> subscriptions = subscriptionRepository.search(new SubscriptionCriteria.Builder().applications(Collections.singleton(application)).apis(planEntity.getApis()).build());
        if (!subscriptions.isEmpty()) {
            Predicate<Subscription> onlyValidSubs = subscription -> subscription.getStatus() != Subscription.Status.REJECTED && subscription.getStatus() != Subscription.Status.CLOSED;
            // First, check that there is no subscription to the same plan
            long subscriptionCount = subscriptions.stream().filter(onlyValidSubs).filter(subscription -> subscription.getPlan().equals(plan)).count();
            if (subscriptionCount > 0) {
                throw new PlanAlreadySubscribedException(plan);
            }
            // Check that there is no existing subscription based on an OAuth2 or JWT plan
            if (planEntity.getSecurity() == PlanSecurityType.OAUTH2 || planEntity.getSecurity() == PlanSecurityType.JWT) {
                long count = subscriptions.stream().filter(onlyValidSubs).map(Subscription::getPlan).distinct().map(plan1 -> planService.findById(plan1)).filter(subPlan -> subPlan.getSecurity() == PlanSecurityType.OAUTH2 || subPlan.getSecurity() == PlanSecurityType.JWT).count();
                if (count > 0) {
                    throw new PlanNotSubscribableException("An other OAuth2 or JWT plan is already subscribed by the same application.");
                }
            }
        }
        if (planEntity.getSecurity() == PlanSecurityType.OAUTH2 || planEntity.getSecurity() == PlanSecurityType.JWT) {
            // Check that the application contains a client_id
            if (applicationEntity.getClientId() == null || applicationEntity.getClientId().trim().isEmpty()) {
                throw new PlanNotSubscribableException("A client_id is required to subscribe to an OAuth2 or JWT plan.");
            }
        }
        Subscription subscription = new Subscription();
        subscription.setPlan(plan);
        subscription.setId(UUID.toString(UUID.random()));
        subscription.setApplication(application);
        subscription.setCreatedAt(new Date());
        subscription.setUpdatedAt(subscription.getCreatedAt());
        subscription.setStatus(Subscription.Status.PENDING);
        subscription.setRequest(newSubscriptionEntity.getRequest());
        subscription.setSubscribedBy(getAuthenticatedUser().getUsername());
        subscription.setClientId(applicationEntity.getClientId());
        String apiId = planEntity.getApis().iterator().next();
        subscription.setApi(apiId);
        subscription = subscriptionRepository.create(subscription);
        createAudit(apiId, application, SUBSCRIPTION_CREATED, subscription.getCreatedAt(), null, subscription);
        final ApiModelEntity api = apiService.findByIdForTemplates(apiId);
        final PrimaryOwnerEntity apiOwner = api.getPrimaryOwner();
        // final PrimaryOwnerEntity appOwner = applicationEntity.getPrimaryOwner();
        String portalUrl = environment.getProperty("portalURL");
        String subscriptionsUrl = "";
        if (portalUrl != null) {
            if (portalUrl.endsWith("/")) {
                portalUrl = portalUrl.substring(0, portalUrl.length() - 1);
            }
            subscriptionsUrl = portalUrl + "/#!/management/apis/" + api.getId() + "/subscriptions/" + subscription.getId();
        }
        final Map<String, Object> params = new NotificationParamsBuilder().api(api).plan(planEntity).application(applicationEntity).owner(apiOwner).subscription(convert(subscription)).subscriptionsUrl(subscriptionsUrl).build();
        if (PlanValidationType.AUTO == planEntity.getValidation()) {
            ProcessSubscriptionEntity process = new ProcessSubscriptionEntity();
            process.setId(subscription.getId());
            process.setAccepted(true);
            process.setStartingAt(new Date());
            // Do process
            return process(process, SUBSCRIPTION_SYSTEM_VALIDATOR);
        } else {
            notifierService.trigger(ApiHook.SUBSCRIPTION_NEW, apiId, params);
            notifierService.trigger(ApplicationHook.SUBSCRIPTION_NEW, application, params);
            return convert(subscription);
        }
    } catch (TechnicalException ex) {
        logger.error("An error occurs while trying to subscribe to the plan {}", plan, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to subscribe to the plan %s", plan), ex);
    }
}
Also used : SubscriptionQuery(io.gravitee.management.model.subscription.SubscriptionQuery) java.util(java.util) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) SubscriptionCriteria(io.gravitee.repository.management.api.search.SubscriptionCriteria) Autowired(org.springframework.beans.factory.annotation.Autowired) Subscription(io.gravitee.repository.management.model.Subscription) io.gravitee.management.service.exceptions(io.gravitee.management.service.exceptions) UUID(io.gravitee.common.utils.UUID) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) io.gravitee.management.model(io.gravitee.management.model) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) AuditEvent(io.gravitee.repository.management.model.Subscription.AuditEvent) API(io.gravitee.repository.management.model.Audit.AuditProperties.API) APPLICATION(io.gravitee.repository.management.model.Audit.AuditProperties.APPLICATION) Logger(org.slf4j.Logger) Pageable(io.gravitee.management.model.common.Pageable) Metadata(io.gravitee.management.model.pagedresult.Metadata) ApiHook(io.gravitee.management.service.notification.ApiHook) SubscriptionRepository(io.gravitee.repository.management.api.SubscriptionRepository) Predicate(java.util.function.Predicate) Audit(io.gravitee.repository.management.model.Audit) Collectors(java.util.stream.Collectors) Component(org.springframework.stereotype.Component) io.gravitee.management.service(io.gravitee.management.service) ApplicationHook(io.gravitee.management.service.notification.ApplicationHook) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder) Subscription(io.gravitee.repository.management.model.Subscription)

Aggregations

Subscription (io.gravitee.repository.management.model.Subscription)28 Test (org.junit.Test)19 SubscriptionCriteria (io.gravitee.repository.management.api.search.SubscriptionCriteria)10 SubscriptionRepository (io.gravitee.repository.management.api.SubscriptionRepository)8 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)7 ExecutionContext (io.gravitee.gateway.api.ExecutionContext)5 Request (io.gravitee.gateway.api.Request)5 Response (io.gravitee.gateway.api.Response)5 PolicyChain (io.gravitee.policy.api.PolicyChain)5 UserDetails (io.gravitee.management.idp.api.authentication.UserDetails)3 NotificationParamsBuilder (io.gravitee.management.service.notification.NotificationParamsBuilder)3 Authentication (org.springframework.security.core.Authentication)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SecurityContext (org.springframework.security.core.context.SecurityContext)3 Element (net.sf.ehcache.Element)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 Page (io.gravitee.common.data.domain.Page)1 HttpHeaders (io.gravitee.common.http.HttpHeaders)1 UUID (io.gravitee.common.utils.UUID)1 io.gravitee.management.model (io.gravitee.management.model)1