Search in sources :

Example 11 with ApiKey

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

the class ApiKeyServiceImpl method renew.

@Override
public ApiKeyEntity renew(String subscription) {
    try {
        LOGGER.debug("Renew API Key for subscription {}", subscription);
        ApiKey newApiKey = generateForSubscription(subscription);
        newApiKey = apiKeyRepository.create(newApiKey);
        Instant expirationInst = newApiKey.getCreatedAt().toInstant().plus(Duration.ofHours(2));
        Date expirationDate = Date.from(expirationInst);
        // Previously generated keys should be set as revoked
        // Get previously generated keys to set their expiration date
        Set<ApiKey> oldKeys = apiKeyRepository.findBySubscription(subscription);
        for (ApiKey oldKey : oldKeys) {
            if (!oldKey.equals(newApiKey)) {
                setExpiration(expirationDate, oldKey);
            }
        }
        // TODO: Send a notification to the application owner
        // Audit
        final PlanEntity plan = planService.findById(newApiKey.getPlan());
        auditService.createApiAuditLog(plan.getApis().iterator().next(), Collections.singletonMap(API_KEY, newApiKey.getKey()), APIKEY_RENEWED, newApiKey.getCreatedAt(), null, newApiKey);
        return convert(newApiKey);
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while trying to renew an API Key for {}", subscription, ex);
        throw new TechnicalManagementException(String.format("An error occurs while trying to renew an API Key for %s", subscription), ex);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Instant(java.time.Instant) TechnicalManagementException(io.gravitee.management.service.exceptions.TechnicalManagementException)

Example 12 with ApiKey

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

the class ApiKeyServiceImpl method setExpiration.

private void setExpiration(Date expirationDate, ApiKey key) throws TechnicalException {
    ApiKey oldkey = new ApiKey(key);
    if (!key.isRevoked() && key.getExpireAt() == null) {
        key.setUpdatedAt(new Date());
        key.setExpireAt(expirationDate);
        apiKeyRepository.update(key);
        // notify
        final ApplicationEntity application = applicationService.findById(key.getApplication());
        final PlanEntity plan = planService.findById(key.getPlan());
        final ApiModelEntity api = apiService.findByIdForTemplates(plan.getApis().iterator().next());
        final PrimaryOwnerEntity owner = application.getPrimaryOwner();
        NotificationParamsBuilder paramsBuilder = new NotificationParamsBuilder();
        paramsBuilder.api(api).application(application).apikey(key).plan(plan).owner(owner);
        if (key.getExpireAt() != null && new Date().before(key.getExpireAt())) {
            paramsBuilder.expirationDate(key.getExpireAt());
        }
        final Map<String, Object> params = paramsBuilder.build();
        notifierService.trigger(ApiHook.APIKEY_EXPIRED, api.getId(), params);
        // Audit
        auditService.createApiAuditLog(plan.getApis().iterator().next(), Collections.singletonMap(API_KEY, key.getKey()), APIKEY_EXPIRED, key.getUpdatedAt(), oldkey, key);
    }
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) NotificationParamsBuilder(io.gravitee.management.service.notification.NotificationParamsBuilder)

Example 13 with ApiKey

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

the class ApiKeyServiceTest method shouldRevoke.

@Test
public void shouldRevoke() throws Exception {
    apiKey = new ApiKey();
    apiKey.setKey("123-456-789");
    apiKey.setSubscription(SUBSCRIPTION_ID);
    apiKey.setCreatedAt(new Date());
    apiKey.setPlan(PLAN_ID);
    apiKey.setApplication(APPLICATION_ID);
    final ApiModelEntity api = mock(ApiModelEntity.class);
    when(api.getId()).thenReturn("123");
    // Prepare data
    when(subscription.getApplication()).thenReturn(APPLICATION_ID);
    when(subscription.getPlan()).thenReturn(PLAN_ID);
    when(plan.getApis()).thenReturn(Collections.singleton(API_ID));
    // Stub
    when(apiKeyRepository.findById(API_KEY)).thenReturn(Optional.of(apiKey));
    when(subscriptionService.findById(subscription.getId())).thenReturn(subscription);
    when(applicationService.findById(subscription.getApplication())).thenReturn(application);
    when(planService.findById(subscription.getPlan())).thenReturn(plan);
    when(apiService.findByIdForTemplates(any())).thenReturn(api);
    // Run
    apiKeyService.revoke(API_KEY, true);
    // Verify
    verify(apiKeyRepository, times(1)).update(any());
}
Also used : ApiKey(io.gravitee.repository.management.model.ApiKey) Date(java.util.Date) Test(org.junit.Test)

Example 14 with ApiKey

use of io.gravitee.repository.management.model.ApiKey in project gravitee-gateway by gravitee-io.

the class ApiKeyRepositoryRefresherTest method shouldRefreshWithRevokedApiKeyAndRemoveFromCache.

@Test
public void shouldRefreshWithRevokedApiKeyAndRemoveFromCache() throws TechnicalException {
    String apiKey = "1234-4567-7890";
    Mockito.when(plan.getSecurity()).thenReturn(io.gravitee.repository.management.model.Plan.PlanSecurityType.API_KEY.name());
    List<Plan> plans = Collections.singletonList(plan);
    Mockito.when(api.getPlans()).thenReturn(plans);
    ApiKey apiKey1 = Mockito.mock(ApiKey.class);
    Mockito.when(apiKey1.getKey()).thenReturn(apiKey);
    Mockito.when(apiKey1.isRevoked()).thenReturn(false);
    ApiKey apiKey2 = Mockito.mock(ApiKey.class);
    Mockito.when(apiKey2.getKey()).thenReturn(apiKey);
    Mockito.when(apiKey2.isRevoked()).thenReturn(true);
    Mockito.when(apiKeyRepository.findByCriteria(Mockito.any(ApiKeyCriteria.class))).thenReturn(Collections.singletonList(apiKey1)).thenReturn(Collections.singletonList(apiKey2));
    refresher.initialize();
    refresher.run();
    refresher.run();
    InOrder inOrder = Mockito.inOrder(apiKeyRepository, apiKeyRepository);
    inOrder.verify(apiKeyRepository).findByCriteria(Matchers.argThat(new ArgumentMatcher<ApiKeyCriteria>() {

        @Override
        public boolean matches(Object arg) {
            ApiKeyCriteria criteria = (ApiKeyCriteria) arg;
            return !criteria.isIncludeRevoked() && criteria.getFrom() == 0 && criteria.getTo() == 0 && criteria.getPlans().size() == 1;
        }
    }));
    inOrder.verify(apiKeyRepository).findByCriteria(Matchers.argThat(new ArgumentMatcher<ApiKeyCriteria>() {

        @Override
        public boolean matches(Object arg) {
            ApiKeyCriteria criteria = (ApiKeyCriteria) arg;
            return criteria.isIncludeRevoked() && criteria.getFrom() != 0 && criteria.getTo() != 0 && criteria.getPlans().size() == 1;
        }
    }));
    InOrder inOrderCache = Mockito.inOrder(cache, cache);
    inOrderCache.verify(cache).put(Matchers.any(Element.class));
    inOrderCache.verify(cache).remove(apiKey);
}
Also used : ApiKeyCriteria(io.gravitee.repository.management.api.search.ApiKeyCriteria) ApiKey(io.gravitee.repository.management.model.ApiKey) Element(net.sf.ehcache.Element) Plan(io.gravitee.gateway.handlers.api.definition.Plan) Test(org.junit.Test)

Aggregations

ApiKey (io.gravitee.repository.management.model.ApiKey)14 TechnicalManagementException (io.gravitee.management.service.exceptions.TechnicalManagementException)6 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)6 Test (org.junit.Test)6 ApiKeyNotFoundException (io.gravitee.management.service.exceptions.ApiKeyNotFoundException)3 ApiKeyCriteria (io.gravitee.repository.management.api.search.ApiKeyCriteria)3 Element (net.sf.ehcache.Element)3 Plan (io.gravitee.gateway.handlers.api.definition.Plan)2 NotificationParamsBuilder (io.gravitee.management.service.notification.NotificationParamsBuilder)2 Date (java.util.Date)2 SubscriptionClosedException (io.gravitee.management.service.exceptions.SubscriptionClosedException)1 Instant (java.time.Instant)1