From f2785f3b1065becb5ae11b99f84be0ff2249afe5 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Tue, 27 Oct 2026 19:10:47 +0100 Subject: [PATCH 1/4] Evict stale API key cache entry when the key value changes --- .../server/dao/pat/ApiKeyServiceImpl.java | 24 ++++++++++++-- .../server/dao/service/ApiKeyServiceTest.java | 33 +++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java index 7a2fbda4bf..a1843b72a5 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java +++ b/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 java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -82,8 +83,13 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService + * Authentication resolves a key by value straight from the cache, so both the enabled flag and the value must + * trigger an eviction. A regular update preserves the value, but a save with an explicit value (e.g. an edge + * applying a key rotated on the cloud) replaces it, leaving the old value to authenticate from the cache. + */ + private static boolean isPublishEvictRequired(ApiKey old, ApiKey apiKey) { + return old != null + && (old.isEnabled() != apiKey.isEnabled() + || !Objects.equals(old.getValue(), apiKey.getValue())); + } + @Override public EntityType getEntityType() { return EntityType.API_KEY; diff --git a/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java b/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java index 157012d1c9..4fb8942142 100644 --- a/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java +++ b/dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java @@ -130,6 +130,39 @@ public class ApiKeyServiceTest extends AbstractServiceTest { 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 testFindApiKeysByUserId() { int size = 3; From 192836945ff1ca81a6953da11459002438439ba9 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Tue, 27 Oct 2026 20:00:51 +0100 Subject: [PATCH 2/4] Verify exact API key cache evictions and call counts --- .../dao/pat/ApiKeyCacheEvictionTest.java | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java diff --git a/dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java b/dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java new file mode 100644 index 0000000000..ee6ab565b2 --- /dev/null +++ b/dao/src/test/java/org/thingsboard/server/dao/pat/ApiKeyCacheEvictionTest.java @@ -0,0 +1,105 @@ +// 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 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.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 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 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; + } + +} From 91c1d9a619b8f045704542e02b378d13f131731a Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Tue, 27 Oct 2026 20:00:51 +0100 Subject: [PATCH 3/4] Shorten isPublishEvictRequired javadoc --- .../org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java index a1843b72a5..717466e034 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java @@ -187,12 +187,8 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService - * Authentication resolves a key by value straight from the cache, so both the enabled flag and the value must - * trigger an eviction. A regular update preserves the value, but a save with an explicit value (e.g. an edge - * applying a key rotated on the cloud) replaces it, leaving the old value to authenticate from the cache. + * Authentication resolves keys by value straight from the cache, so a changed enabled flag or value (explicit-value + * save, e.g. edge sync) requires eviction. A newly created key has nothing cached yet, hence the null check. */ private static boolean isPublishEvictRequired(ApiKey old, ApiKey apiKey) { return old != null From 6d31dfd95854fb68a16a694cdebf520ec2eb6431 Mon Sep 17 00:00:00 2001 From: Sergey Matvienko Date: Wed, 28 Oct 2026 16:53:13 +0100 Subject: [PATCH 4/4] Evict cached miss when an API key is created with an explicit value --- .../server/dao/pat/ApiKeyServiceImpl.java | 13 ++++++------ .../dao/pat/ApiKeyCacheEvictionTest.java | 18 +++++++++++++++++ .../server/dao/service/ApiKeyServiceTest.java | 20 +++++++++++++++++++ 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java index 717466e034..418b56c9b2 100644 --- a/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java +++ b/dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java @@ -86,10 +86,10 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService