Browse Source

Merge pull request #16456 from smatvienko-tb/fix/api-key-cache-eviction-lts-4.3

Evict stale API key cache entry when the key value changes
pull/16097/merge
Viacheslav Klimov 3 weeks ago
committed by GitHub
parent
commit
30ce08ad4e
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 21
      dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java
  2. 123
      dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java
  3. 53
      dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java

21
dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java

@ -27,6 +27,7 @@ import org.thingsboard.server.dao.eventsourcing.SaveEntityEvent;
import org.thingsboard.server.dao.service.validator.ApiKeyDataValidator; import org.thingsboard.server.dao.service.validator.ApiKeyDataValidator;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@ -82,8 +83,13 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService<ApiKeyCacheKe
} }
var savedApiKey = apiKeyDao.save(tenantId, apiKey); var savedApiKey = apiKeyDao.save(tenantId, apiKey);
eventPublisher.publishEvent(SaveEntityEvent.builder().tenantId(tenantId).entityId(savedApiKey.getId()).entity(savedApiKey).created(apiKey.getId() == null).build()); eventPublisher.publishEvent(SaveEntityEvent.builder().tenantId(tenantId).entityId(savedApiKey.getId()).entity(savedApiKey).created(apiKey.getId() == null).build());
if (old != null && old.isEnabled() != apiKey.isEnabled()) { if (isPublishEvictRequired(old, apiKey)) {
publishEvictEvent(new ApiKeyEvictEvent(apiKey.getValue())); // the cache is keyed by value, so the entry to evict is the one the old value still resolves to
publishEvictEvent(new ApiKeyEvictEvent(old.getValue()));
}
if (value != null && (old == null || !value.equals(old.getValue()))) {
// a failed authentication attempt may have cached a miss for the explicitly provided value (edge sync)
publishEvictEvent(new ApiKeyEvictEvent(value));
} }
return savedApiKey; return savedApiKey;
} catch (Exception e) { } catch (Exception e) {
@ -180,6 +186,17 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService<ApiKeyCacheKe
return prefix + StringUtils.generateSafeToken(Math.min(valueBytesSize, MAX_API_KEY_VALUE_LENGTH)); return prefix + StringUtils.generateSafeToken(Math.min(valueBytesSize, MAX_API_KEY_VALUE_LENGTH));
} }
/**
* Authentication resolves keys by value straight from the cache, so a changed enabled flag or value requires
* evicting the entry under the old value. Null old means create: there is no previous value to evict; a cached
* miss for an explicitly provided value is evicted separately in saveApiKey.
*/
private static boolean isPublishEvictRequired(ApiKey old, ApiKey apiKey) {
return old != null
&& (old.isEnabled() != apiKey.isEnabled()
|| !Objects.equals(old.getValue(), apiKey.getValue()));
}
@Override @Override
public EntityType getEntityType() { public EntityType getEntityType() {
return EntityType.API_KEY; return EntityType.API_KEY;

123
dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java

@ -0,0 +1,123 @@
// SPDX-FileCopyrightText: Copyright The Thingsboard Authors
// SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.dao.pat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import com.datastax.oss.driver.api.core.uuid.Uuids;
import org.thingsboard.server.cache.TbTransactionalCache;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.id.ApiKeyId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.pat.ApiKey;
import org.thingsboard.server.common.data.pat.ApiKeyInfo;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.service.AbstractServiceTest;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.user.UserService;
/**
* Verifies the exact cache interactions of {@link ApiKeyService} saves: which {@link ApiKeyCacheKey}s are evicted
* and how many times. Lives in this package because {@link ApiKeyCacheKey} is package-private.
*/
@DaoSqlTest
public class ApiKeyCacheEvictionTest extends AbstractServiceTest {
@Autowired
ApiKeyService apiKeyService;
@Autowired
UserService userService;
@MockitoSpyBean
TbTransactionalCache<ApiKeyCacheKey, ApiKey> apiKeyCache;
private UserId userId;
@Before
public void before() {
User tenantAdmin = new User();
tenantAdmin.setAuthority(Authority.TENANT_ADMIN);
tenantAdmin.setTenantId(tenantId);
tenantAdmin.setEmail("tenant-api-key-cache@thingsboard.org");
User user = userService.saveUser(TenantId.SYS_TENANT_ID, tenantAdmin);
userId = user.getId();
}
@After
public void after() {
apiKeyService.deleteByTenantId(tenantId);
User user = userService.findUserById(tenantId, userId);
userService.deleteUser(tenantId, user);
}
@Test
public void testSaveApiKeyWithNewValue_evictsOldAndNewValueExactlyOnce() {
ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, createApiKeyInfo());
String originalValue = savedApiKey.getValue();
String newValue = "new-api-key-value-" + StringUtils.randomAlphanumeric(32);
Mockito.clearInvocations(apiKeyCache);
apiKeyService.saveApiKey(tenantId, savedApiKey, newValue, false);
Mockito.verify(apiKeyCache).evict(ApiKeyCacheKey.of(originalValue));
Mockito.verify(apiKeyCache).evict(ApiKeyCacheKey.of(newValue));
Mockito.verify(apiKeyCache, Mockito.times(2)).evict(Mockito.any(ApiKeyCacheKey.class));
}
@Test
public void testCreateApiKeyWithExplicitValue_evictsValueExactlyOnce() {
// the edge uplink creates the key on the cloud with a preset id and the value generated on the edge
ApiKeyInfo apiKeyInfo = createApiKeyInfo();
ApiKeyId apiKeyId = new ApiKeyId(Uuids.timeBased());
apiKeyInfo.setId(apiKeyId);
apiKeyInfo.setCreatedTime(Uuids.unixTimestamp(apiKeyId.getId()));
String value = "edge-api-key-value-" + StringUtils.randomAlphanumeric(32);
Mockito.clearInvocations(apiKeyCache);
apiKeyService.saveApiKey(tenantId, apiKeyInfo, value, false);
Mockito.verify(apiKeyCache).evict(ApiKeyCacheKey.of(value));
Mockito.verify(apiKeyCache, Mockito.times(1)).evict(Mockito.any(ApiKeyCacheKey.class));
}
@Test
public void testDisableApiKey_evictsValueExactlyOnce() {
ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, createApiKeyInfo());
String value = savedApiKey.getValue();
savedApiKey.setEnabled(false);
Mockito.clearInvocations(apiKeyCache);
apiKeyService.saveApiKey(tenantId, savedApiKey);
Mockito.verify(apiKeyCache).evict(ApiKeyCacheKey.of(value));
Mockito.verify(apiKeyCache, Mockito.times(1)).evict(Mockito.any(ApiKeyCacheKey.class));
}
@Test
public void testUpdateApiKeyDescription_noEviction() {
ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, createApiKeyInfo());
savedApiKey.setDescription("Updated description, cached state unchanged");
Mockito.clearInvocations(apiKeyCache);
apiKeyService.saveApiKey(tenantId, savedApiKey);
Mockito.verify(apiKeyCache, Mockito.never()).evict(Mockito.any(ApiKeyCacheKey.class));
}
private ApiKeyInfo createApiKeyInfo() {
ApiKeyInfo apiKeyInfo = new ApiKeyInfo();
apiKeyInfo.setTenantId(tenantId);
apiKeyInfo.setUserId(userId);
apiKeyInfo.setDescription("API key cache eviction test");
apiKeyInfo.setEnabled(true);
return apiKeyInfo;
}
}

53
dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.dao.service; package org.thingsboard.server.dao.service;
import com.datastax.oss.driver.api.core.uuid.Uuids;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -9,6 +10,7 @@ import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.server.common.data.StringUtils; import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.id.ApiKeyId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
@ -130,6 +132,57 @@ public class ApiKeyServiceTest extends AbstractServiceTest {
Assert.assertEquals(savedApiKey.getValue(), foundApiKey.getValue()); Assert.assertEquals(savedApiKey.getValue(), foundApiKey.getValue());
} }
@Test
public void testSaveApiKeyWithNewValue_oldValueEvictedFromCache() {
ApiKeyInfo apiKeyInfo = createApiKeyInfo(TEST_API_KEY_DESCRIPTION);
ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, apiKeyInfo);
String originalValue = savedApiKey.getValue();
// authentication resolves the key by value and caches the lookup
Assert.assertNotNull(apiKeyService.findApiKeyByValue(originalValue));
String newValue = "new-api-key-value-" + StringUtils.randomAlphanumeric(32);
apiKeyService.saveApiKey(tenantId, savedApiKey, newValue, false);
Assert.assertNull("Old API key value must not resolve after the value changed", apiKeyService.findApiKeyByValue(originalValue));
ApiKey foundByNewValue = apiKeyService.findApiKeyByValue(newValue);
Assert.assertNotNull(foundByNewValue);
Assert.assertEquals(savedApiKey.getId(), foundByNewValue.getId());
}
@Test
public void testSaveApiKeyWithNewValue_cachedMissForNewValueEvicted() {
ApiKeyInfo apiKeyInfo = createApiKeyInfo(TEST_API_KEY_DESCRIPTION);
ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, apiKeyInfo);
String newValue = "new-api-key-value-" + StringUtils.randomAlphanumeric(32);
// a failed authentication attempt caches the miss for the not-yet-saved value
Assert.assertNull(apiKeyService.findApiKeyByValue(newValue));
apiKeyService.saveApiKey(tenantId, savedApiKey, newValue, false);
ApiKey foundByNewValue = apiKeyService.findApiKeyByValue(newValue);
Assert.assertNotNull("New API key value must resolve after it is saved", foundByNewValue);
Assert.assertEquals(savedApiKey.getId(), foundByNewValue.getId());
}
@Test
public void testCreateApiKeyWithExplicitValue_cachedMissForValueEvicted() {
String value = "edge-api-key-value-" + StringUtils.randomAlphanumeric(32);
// a failed authentication attempt caches the miss before the edge uplink delivers the key
Assert.assertNull(apiKeyService.findApiKeyByValue(value));
// the edge uplink creates the key on the cloud with a preset id and the value generated on the edge
ApiKeyInfo apiKeyInfo = createApiKeyInfo(TEST_API_KEY_DESCRIPTION);
ApiKeyId apiKeyId = new ApiKeyId(Uuids.timeBased());
apiKeyInfo.setId(apiKeyId);
apiKeyInfo.setCreatedTime(Uuids.unixTimestamp(apiKeyId.getId()));
ApiKey savedApiKey = apiKeyService.saveApiKey(tenantId, apiKeyInfo, value, false);
ApiKey foundByValue = apiKeyService.findApiKeyByValue(value);
Assert.assertNotNull("API key value must resolve after the key is created with it", foundByValue);
Assert.assertEquals(savedApiKey.getId(), foundByValue.getId());
}
@Test @Test
public void testFindApiKeysByUserId() { public void testFindApiKeysByUserId() {
int size = 3; int size = 3;

Loading…
Cancel
Save