Browse Source

Evict API key cache entry by its old value on rotation

pull/16457/head
Sergey Matvienko 1 month ago
parent
commit
df75ff67e8
  1. 78
      application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
  2. 3
      dao/src/main/java/org/thingsboard/server/dao/pat/ApiKeyServiceImpl.java
  3. 16
      dao/src/test/java/org/thingsboard/server/dao/service/ApiKeyServiceTest.java

78
application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java

@ -7,6 +7,8 @@ import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink; import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.pat.ApiKey; import org.thingsboard.server.common.data.pat.ApiKey;
@ -15,6 +17,7 @@ import org.thingsboard.server.common.data.permission.AuthorityPermissionsInfo;
import org.thingsboard.server.common.data.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource; import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.pat.ApiKeyService;
import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.HashMap; import java.util.HashMap;
@ -27,6 +30,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@DaoSqlTest @DaoSqlTest
public class ApiKeyControllerTest extends AbstractControllerTest { public class ApiKeyControllerTest extends AbstractControllerTest {
@Autowired
private ApiKeyService apiKeyService;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
loginTenantAdmin(); loginTenantAdmin();
@ -152,6 +158,68 @@ public class ApiKeyControllerTest extends AbstractControllerTest {
doDelete("/api/apiKey/" + savedApiKey.getId()).andExpect(status().isOk()); doDelete("/api/apiKey/" + savedApiKey.getId()).andExpect(status().isOk());
} }
@Test
public void testRotateInternalApiKey_oldValueNoLongerAuthenticates() throws Exception {
loginSysAdmin();
ApiKeyInfo apiKeyInfo = constructApiKeyInfo(sysAdminPermissionsInfo());
apiKeyInfo.setTenantId(TenantId.SYS_TENANT_ID);
// internal keys cannot be created via REST, so build it directly through the service
ApiKey internalApiKey = apiKeyService.saveApiKey(TenantId.SYS_TENANT_ID, apiKeyInfo);
String originalValue = internalApiKey.getValue();
try {
// authenticate with the original value to warm up the API key cache
setApiKey(originalValue);
doGetWithApiKey("/api/auth/user").andExpect(status().isOk());
ApiKey rotatedApiKey = doPost("/api/apiKey/" + internalApiKey.getId().getId() + "/rotate", ApiKey.class);
Assert.assertNotNull(rotatedApiKey);
Assert.assertNotNull(rotatedApiKey.getValue());
Assert.assertNotEquals(originalValue, rotatedApiKey.getValue());
doGetWithApiKey("/api/auth/user").andExpect(status().isUnauthorized());
setApiKey(rotatedApiKey.getValue());
doGetWithApiKey("/api/auth/user").andExpect(status().isOk());
} finally {
resetApiKey();
apiKeyService.deleteApiKey(TenantId.SYS_TENANT_ID, apiKeyService.findApiKeyById(TenantId.SYS_TENANT_ID, internalApiKey.getId()), true);
}
}
@Test
public void testRotateApiKeyAsTenantAdmin_shouldBeForbidden() throws Exception {
ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Tenant admin API key", true);
ApiKey apiKey = doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
doPost("/api/apiKey/" + apiKey.getId().getId() + "/rotate").andExpect(status().isForbidden());
doDelete("/api/apiKey/" + apiKey.getId()).andExpect(status().isOk());
}
@Test
public void testRotateApiKeyAsCustomerUser_shouldBeForbidden() throws Exception {
ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Tenant admin API key", true);
ApiKey apiKey = doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
loginCustomerUser();
doPost("/api/apiKey/" + apiKey.getId().getId() + "/rotate").andExpect(status().isForbidden());
loginTenantAdmin();
doDelete("/api/apiKey/" + apiKey.getId()).andExpect(status().isOk());
}
@Test
public void testRotateRegularApiKeyOfAnotherUserAsSysAdmin_shouldBeBadRequest() throws Exception {
ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Tenant admin API key", true);
ApiKey apiKey = doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
loginSysAdmin();
doPost("/api/apiKey/" + apiKey.getId().getId() + "/rotate").andExpect(status().isBadRequest());
loginTenantAdmin();
doDelete("/api/apiKey/" + apiKey.getId()).andExpect(status().isOk());
}
@Test @Test
public void testDeleteApiKey() throws Exception { public void testDeleteApiKey() throws Exception {
doDelete("/api/apiKey/" + UUID.randomUUID()).andExpect(status().isNotFound()); doDelete("/api/apiKey/" + UUID.randomUUID()).andExpect(status().isNotFound());
@ -174,6 +242,16 @@ public class ApiKeyControllerTest extends AbstractControllerTest {
return apiKeyInfo; return apiKeyInfo;
} }
private AuthorityPermissionsInfo sysAdminPermissionsInfo() {
Map<Resource, Set<Operation>> permissions = new HashMap<>();
permissions.put(Resource.DEVICE, Set.of(Operation.READ));
Map<Authority, Map<Resource, Set<Operation>>> operationsByResource = new HashMap<>();
operationsByResource.put(Authority.SYS_ADMIN, permissions);
AuthorityPermissionsInfo authorityPermissionsInfo = new AuthorityPermissionsInfo();
authorityPermissionsInfo.setOperationsByResource(operationsByResource);
return authorityPermissionsInfo;
}
private ApiKeyInfo constructApiKeyInfo(AuthorityPermissionsInfo info) { private ApiKeyInfo constructApiKeyInfo(AuthorityPermissionsInfo info) {
ApiKeyInfo apiKeyInfo = new ApiKeyInfo(); ApiKeyInfo apiKeyInfo = new ApiKeyInfo();
apiKeyInfo.setDescription("API key description for internal API key"); apiKeyInfo.setDescription("API key description for internal API key");

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

@ -112,7 +112,8 @@ public class ApiKeyServiceImpl extends AbstractCachedEntityService<ApiKeyCacheKe
try { try {
var rotatedApiKey = apiKeyDao.save(tenantId, apiKey); var rotatedApiKey = apiKeyDao.save(tenantId, apiKey);
eventPublisher.publishEvent(SaveEntityEvent.builder().tenantId(tenantId).entityId(rotatedApiKey.getId()).entity(rotatedApiKey).oldEntity(old).created(false).build()); eventPublisher.publishEvent(SaveEntityEvent.builder().tenantId(tenantId).entityId(rotatedApiKey.getId()).entity(rotatedApiKey).oldEntity(old).created(false).build());
publishEvictEvent(new ApiKeyEvictEvent(apiKey.getValue())); // the cache is keyed by value, so the entry to evict is the one the rotated-away value still resolves to
publishEvictEvent(new ApiKeyEvictEvent(old.getValue()));
return rotatedApiKey; return rotatedApiKey;
} catch (Exception e) { } catch (Exception e) {
checkConstraintViolation(e, "api_key_value_unq_key", "API Key with such value already exists!"); checkConstraintViolation(e, "api_key_value_unq_key", "API Key with such value already exists!");

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

@ -333,6 +333,22 @@ public class ApiKeyServiceTest extends AbstractServiceTest {
Assert.assertEquals(savedApiKey.getDescription(), rotatedApiKey.getDescription()); Assert.assertEquals(savedApiKey.getDescription(), rotatedApiKey.getDescription());
} }
@Test
public void testRotateInternalApiKey_oldValueEvictedFromCache() {
ApiKeyInfo apiKeyInfo = createInternalApiKeyInfo("Internal key for rotation cache eviction");
ApiKey savedApiKey = apiKeyService.saveApiKey(TenantId.SYS_TENANT_ID, apiKeyInfo);
String originalValue = savedApiKey.getValue();
// authentication resolves the key by value and caches the lookup
Assert.assertNotNull(apiKeyService.findApiKeyByValue(originalValue));
ApiKey rotatedApiKey = apiKeyService.rotateInternalApiKey(TenantId.SYS_TENANT_ID, savedApiKey);
Assert.assertNull("Old API key value must not resolve after rotation", apiKeyService.findApiKeyByValue(originalValue));
ApiKey foundByNewValue = apiKeyService.findApiKeyByValue(rotatedApiKey.getValue());
Assert.assertNotNull(foundByNewValue);
Assert.assertEquals(savedApiKey.getId(), foundByNewValue.getId());
}
@Test @Test
public void testRotateRegularApiKey_shouldFail() { public void testRotateRegularApiKey_shouldFail() {
ApiKeyInfo apiKeyInfo = createApiKeyInfo("Regular API key"); ApiKeyInfo apiKeyInfo = createApiKeyInfo("Regular API key");

Loading…
Cancel
Save