Browse Source

Fix review comments

pull/16379/head
Roman Kostenko 1 month ago
parent
commit
3a1284de00
  1. 5
      application/src/main/java/org/thingsboard/server/controller/AiModelController.java
  2. 12
      application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
  3. 132
      application/src/test/java/org/thingsboard/server/controller/AiModelControllerTest.java
  4. 2
      dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java
  5. 4
      dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java
  6. 4
      dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelInfoEntity.java
  7. 32
      dao/src/main/java/org/thingsboard/server/dao/sql/ai/AiModelRepository.java

5
application/src/main/java/org/thingsboard/server/controller/AiModelController.java

@ -123,8 +123,7 @@ class AiModelController extends BaseController {
@ApiOperation(
value = "Get AI model infos (getAiModelInfos)",
notes = "Returns a page of AI model infos: AI models without the configuration and its provider credentials. " +
"Requires the 'INVOKE' permission for AI models. " +
"Customer users only get the models with customer access enabled, which are the ones they can send chat requests to. " +
"Customer users only get the models with customer access enabled. " +
PAGE_DATA_PARAMETERS + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH
)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@ -144,7 +143,7 @@ class AiModelController extends BaseController {
@RequestParam(required = false) Boolean customerAccessEnabled
) throws ThingsboardException {
var user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI_MODEL, Operation.INVOKE);
accessControlService.checkPermission(user, Resource.AI_MODEL, Operation.READ);
var pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
return aiModelService.findAiModelInfosByTenantId(user.getTenantId(), user.isCustomerUser() ? Boolean.TRUE : customerAccessEnabled, pageLink);
}

12
application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java

@ -489,18 +489,18 @@ public class CustomerUserPermissions extends AbstractPermissions {
}
};
// Only INVOKE is grantable: reading the model would expose the provider credentials stored in its configuration.
// Roles granting ALL include INVOKE, so the model's 'customerAccessEnabled' flag decides which models such users can call.
// READ only reaches the model infos: endpoints returning the configuration with its provider credentials are tenant administrator only.
// Roles granting ALL include INVOKE, so the model's 'customerAccessEnabled' flag decides which models such users can see and call.
private static final PermissionChecker aiModelPermissionChecker = new PermissionChecker() {
@Override
public boolean hasPermission(SecurityUser user, Resource resource, Operation operation) {
return operation == Operation.INVOKE && user.getUserPermissions().hasGenericPermission(resource, operation);
return isAllowed(operation) && user.getUserPermissions().hasGenericPermission(resource, operation);
}
@Override
public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, TenantEntity entity) {
if (operation != Operation.INVOKE) {
if (!isAllowed(operation)) {
return false;
}
if (!user.getTenantId().equals(entity.getTenantId())) {
@ -511,6 +511,10 @@ public class CustomerUserPermissions extends AbstractPermissions {
}
return user.getUserPermissions().hasGenericPermission(Resource.AI_MODEL, operation);
}
private boolean isAllowed(Operation operation) {
return operation == Operation.READ || operation == Operation.INVOKE;
}
};
private static final PermissionChecker apiKeysPermissionChecker = new PermissionChecker() {

132
application/src/test/java/org/thingsboard/server/controller/AiModelControllerTest.java

@ -9,6 +9,7 @@ import org.junit.Test;
import org.springframework.test.web.servlet.ResultActions;
import org.thingsboard.common.util.SsrfProtectionValidator;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.ai.AiModel;
import org.thingsboard.server.common.data.ai.AiModelInfo;
import org.thingsboard.server.common.data.ai.dto.TbChatRequest;
@ -24,13 +25,17 @@ import org.thingsboard.server.common.data.ai.provider.AnthropicProviderConfig;
import org.thingsboard.server.common.data.ai.provider.GoogleAiGeminiProviderConfig;
import org.thingsboard.server.common.data.ai.provider.GoogleVertexAiGeminiProviderConfig;
import org.thingsboard.server.common.data.ai.provider.OpenAiProviderConfig;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
import org.thingsboard.server.common.data.id.AiModelId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.SortOrder;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@ -393,10 +398,25 @@ public class AiModelControllerTest extends AbstractControllerTest {
.andExpect(statusReason(equalTo("You don't have permission to perform 'INVOKE' operation with AI_MODEL 'Test model'!")));
}
@Test
public void sendChatRequestToAiModel_whenReadOnlyCustomerUser_shouldReturnForbidden() throws Exception {
// GIVEN
loginTenantAdmin();
var model = saveModelWithBlockedBaseUrl();
loginReadOnlyCustomerUser();
// WHEN
ResultActions result = doPost("/api/ai/model/" + model.getId() + "/chat", constructChatRequest());
// THEN
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo("You don't have permission to perform 'INVOKE' operation with AI_MODEL 'Test model'!")));
}
/* --- Customer permission tests --- */
@Test
public void aiModelPermission_whenCustomerAdminGrantedAll_shouldAllowInvokeOnly() throws Exception {
public void aiModelPermission_whenCustomerAdminGrantedAll_shouldAllowReadAndInvokeOnly() throws Exception {
// GIVEN
loginTenantAdmin();
var modelConfig = constructValidOpenAiModel("Test model");
@ -406,30 +426,44 @@ public class AiModelControllerTest extends AbstractControllerTest {
// WHEN / THEN
assertThat(hasAiModelPermission(model, "INVOKE")).isTrue();
assertThat(hasAiModelPermission(model, "READ")).isFalse();
assertThat(hasAiModelPermission(model, "READ")).isTrue();
assertThat(hasAiModelPermission(model, "WRITE")).isFalse();
assertThat(hasAiModelPermission(model, "DELETE")).isFalse();
}
@Test
public void aiModelPermission_whenCustomerAccessDisabled_shouldDenyInvokeForCustomerAdminOnly() throws Exception {
public void aiModelPermission_whenCustomerAccessDisabled_shouldDenyReadAndInvokeForCustomerAdminOnly() throws Exception {
// GIVEN
loginTenantAdmin();
var model = doPost("/api/ai/model", constructValidOpenAiModel("Test model"), AiModel.class);
// WHEN / THEN
assertThat(model.isCustomerAccessEnabled()).isFalse();
assertThat(hasAiModelPermission(model, "READ")).isTrue();
assertThat(hasAiModelPermission(model, "INVOKE")).isTrue();
loginCustomerAdminUser();
assertThat(hasAiModelPermission(model, "READ")).isFalse();
assertThat(hasAiModelPermission(model, "INVOKE")).isFalse();
}
@Test
public void aiModelPermission_whenCustomerUserGrantedReadOnAllResources_shouldDenyReadAndInvoke() throws Exception {
public void aiModelPermission_whenReadOnlyCustomerUser_shouldAllowReadOnly() throws Exception {
// GIVEN
loginTenantAdmin();
var model = doPost("/api/ai/model", constructValidOpenAiModel("Test model"), AiModel.class);
var model = saveModelWithBlockedBaseUrl();
loginReadOnlyCustomerUser();
// WHEN / THEN
assertThat(hasAiModelPermission(model, "READ")).isTrue();
assertThat(hasAiModelPermission(model, "INVOKE")).isFalse();
}
@Test
public void aiModelPermission_whenCustomerUserHasNoRole_shouldDenyReadAndInvoke() throws Exception {
// GIVEN
loginTenantAdmin();
var model = saveModelWithBlockedBaseUrl();
loginCustomerUser();
// WHEN / THEN
@ -671,7 +705,7 @@ public class AiModelControllerTest extends AbstractControllerTest {
}
@Test
public void getAiModelInfos_whenCustomerUserWithoutInvokePermission_shouldReturnForbidden() throws Exception {
public void getAiModelInfos_whenCustomerUserHasNoRole_shouldReturnForbidden() throws Exception {
// GIVEN
loginCustomerUser();
@ -682,6 +716,21 @@ public class AiModelControllerTest extends AbstractControllerTest {
result.andExpect(status().isForbidden());
}
@Test
public void getAiModelInfos_whenReadOnlyCustomerUser_shouldReturnCustomerAccessibleInfos() throws Exception {
// GIVEN
loginTenantAdmin();
var accessible = saveModelWithBlockedBaseUrl("Accessible model", true);
saveModelWithBlockedBaseUrl("Not accessible model", false);
loginReadOnlyCustomerUser();
// WHEN
PageData<AiModelInfo> infos = doGetTypedWithPageLink("/api/ai/model/infos?", new TypeReference<>() {}, new PageLink(10));
// THEN
assertThat(infos.getData()).containsExactly(new AiModelInfo(accessible));
}
@Test
public void getAiModelInfos_whenTenantAdmin_shouldReturnInfosFilteredByCustomerAccessEnabled() throws Exception {
// GIVEN
@ -742,6 +791,64 @@ public class AiModelControllerTest extends AbstractControllerTest {
assertThat(searchByModelId.getData()).containsExactly(new AiModelInfo(anthropicModel));
}
/**
* The infos query mirrors the filter, search and sort rules of the full models query in a separate repository,
* so both endpoints must return the same models in the same order for the same parameters.
*/
@Test
public void getAiModelInfos_shouldMatchGetAiModelsForSameFilterSearchAndSort() throws Exception {
// GIVEN
loginTenantAdmin();
doPost("/api/ai/model", AiModel.builder()
.tenantId(tenantId)
.name("Support assistant")
.configuration(AnthropicChatModelConfig.builder()
.providerConfig(new AnthropicProviderConfig("test-api-key"))
.modelId("claude-sonnet-4-0")
.build())
.customerAccessEnabled(true)
.build(), AiModel.class);
doPost("/api/ai/model", AiModel.builder()
.tenantId(tenantId)
.name("Internal analytics")
.configuration(GoogleAiGeminiChatModelConfig.builder()
.providerConfig(new GoogleAiGeminiProviderConfig("test-api-key"))
.modelId("gemini-2.5-pro")
.build())
.build(), AiModel.class);
var openAiModel = constructValidOpenAiModel("Report assistant");
openAiModel.setCustomerAccessEnabled(true);
doPost("/api/ai/model", openAiModel, AiModel.class);
List<String> filters = List.of("", "customerAccessEnabled=true&", "customerAccessEnabled=false&");
List<String> searches = Arrays.asList(null, "assistant", "google ai", "sonnet");
List<SortOrder> sortOrders = Arrays.asList(null,
SortOrder.of("createdTime", SortOrder.Direction.DESC),
SortOrder.of("name", SortOrder.Direction.ASC),
SortOrder.of("provider", SortOrder.Direction.DESC),
SortOrder.of("modelId", SortOrder.Direction.ASC));
for (String filter : filters) {
for (String search : searches) {
for (SortOrder sortOrder : sortOrders) {
var pageLink = new PageLink(10, 0, search, sortOrder);
// WHEN
PageData<AiModel> models = doGetTypedWithPageLink("/api/ai/model?" + filter, new TypeReference<>() {}, pageLink);
PageData<AiModelInfo> infos = doGetTypedWithPageLink("/api/ai/model/infos?" + filter, new TypeReference<>() {}, pageLink);
// THEN
assertThat(infos.getData())
.as("filter '%s', search '%s', sort %s", filter, search, sortOrder)
.extracting(AiModelInfo::getId)
.containsExactlyElementsOf(models.getData().stream().map(AiModel::getId).toList());
assertThat(infos.getTotalElements()).isEqualTo(models.getTotalElements());
}
}
}
}
@Test
public void getAiModelInfos_whenCustomerAdmin_shouldReturnOnlyCustomerAccessibleInfosWithoutConfiguration() throws Exception {
// GIVEN
@ -1052,6 +1159,19 @@ public class AiModelControllerTest extends AbstractControllerTest {
return new TbChatRequest(null, new TbUserMessage(List.of(new TbContent.TbTextContent("hi"))), null);
}
// The default Customer User role, which grants read-only operations on all resources
private void loginReadOnlyCustomerUser() throws Exception {
loginTenantAdmin();
User user = new User();
user.setAuthority(Authority.CUSTOMER_USER);
user.setTenantId(tenantId);
user.setCustomerId(customerId);
user.setEmail("read-only-customer@thingsboard.org");
EntityGroupInfo customerUsers = findGroupByOwnerIdTypeAndName(customerId, EntityType.USER, EntityGroup.GROUP_CUSTOMER_USERS_NAME);
createUser(user, "customer", customerUsers.getId());
login(user.getEmail(), "customer");
}
private boolean hasAiModelPermission(AiModel model, String operation) throws Exception {
return doGet("/api/permission/AI_MODEL/" + model.getId() + "/" + operation, Boolean.class);
}

2
dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java

@ -1086,6 +1086,8 @@ public class ModelConstants {
public static final String AI_MODEL_NAME_COLUMN_NAME = NAME_PROPERTY;
public static final String AI_MODEL_CONFIGURATION_COLUMN_NAME = "configuration";
public static final String AI_MODEL_CUSTOMER_ACCESS_ENABLED_COLUMN_NAME = "customer_access_enabled";
public static final String AI_MODEL_PROVIDER_EXPRESSION = "(" + AI_MODEL_CONFIGURATION_COLUMN_NAME + " ->> 'provider')";
public static final String AI_MODEL_MODEL_ID_EXPRESSION = "(" + AI_MODEL_CONFIGURATION_COLUMN_NAME + " ->> 'modelId')";
/**
* Api Key constants.

4
dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java

@ -36,8 +36,8 @@ public class AiModelEntity extends BaseVersionedEntity<AiModel> {
public static final Map<String, String> COLUMN_MAP = Map.of(
"createdTime", "created_time",
"provider", "(configuration ->> 'provider')",
"modelId", "(configuration ->> 'modelId')"
"provider", ModelConstants.AI_MODEL_PROVIDER_EXPRESSION,
"modelId", ModelConstants.AI_MODEL_MODEL_ID_EXPRESSION
);
public static final Set<String> ALLOWED_SORT_PROPERTIES = Collections.unmodifiableSet(

4
dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelInfoEntity.java

@ -35,10 +35,10 @@ public class AiModelInfoEntity extends BaseVersionedEntity<AiModelInfo> {
@Column(name = ModelConstants.AI_MODEL_CUSTOMER_ACCESS_ENABLED_COLUMN_NAME)
private boolean customerAccessEnabled;
@Formula("configuration ->> 'provider'")
@Formula(ModelConstants.AI_MODEL_PROVIDER_EXPRESSION)
private String provider;
@Formula("configuration ->> 'modelId'")
@Formula(ModelConstants.AI_MODEL_MODEL_ID_EXPRESSION)
private String modelId;
public AiModelInfoEntity() {}

32
dao/src/main/java/org/thingsboard/server/dao/sql/ai/AiModelRepository.java

@ -19,33 +19,25 @@ import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import static org.thingsboard.server.dao.model.ModelConstants.AI_MODEL_MODEL_ID_EXPRESSION;
import static org.thingsboard.server.dao.model.ModelConstants.AI_MODEL_PROVIDER_EXPRESSION;
interface AiModelRepository extends JpaRepository<AiModelEntity, UUID>, ExportableEntityRepository<AiModelEntity> {
String FIND_BY_TENANT_ID_WHERE = " WHERE model.tenant_id = :tenantId" +
" AND (CAST(:customerAccessEnabled AS BOOLEAN) IS NULL OR model.customer_access_enabled = CAST(:customerAccessEnabled AS BOOLEAN))" +
" AND (:textSearch IS NULL" +
" OR model.name ILIKE '%' || :textSearch || '%'" +
" OR REPLACE(" + AI_MODEL_PROVIDER_EXPRESSION + ", '_', ' ') ILIKE '%' || :textSearch || '%'" +
" OR " + AI_MODEL_MODEL_ID_EXPRESSION + " ILIKE '%' || :textSearch || '%')";
Optional<AiModelEntity> findByTenantIdAndId(UUID tenantId, UUID id);
Optional<AiModelEntity> findByTenantIdAndName(UUID tenantId, String name);
@Query(
value = """
SELECT *
FROM ai_model model
WHERE model.tenant_id = :tenantId
AND (CAST(:customerAccessEnabled AS BOOLEAN) IS NULL OR model.customer_access_enabled = CAST(:customerAccessEnabled AS BOOLEAN))
AND (:textSearch IS NULL
OR model.name ILIKE '%' || :textSearch || '%'
OR REPLACE(model.configuration ->> 'provider', '_', ' ') ILIKE '%' || :textSearch || '%'
OR model.configuration ->> 'modelId' ILIKE '%' || :textSearch || '%')
""",
countQuery = """
SELECT COUNT(*)
FROM ai_model model
WHERE model.tenant_id = :tenantId
AND (CAST(:customerAccessEnabled AS BOOLEAN) IS NULL OR model.customer_access_enabled = CAST(:customerAccessEnabled AS BOOLEAN))
AND (:textSearch IS NULL
OR model.name ILIKE '%' || :textSearch || '%'
OR REPLACE(model.configuration ->> 'provider', '_', ' ') ILIKE '%' || :textSearch || '%'
OR (model.configuration ->> 'modelId') ILIKE '%' || :textSearch || '%')
""",
value = "SELECT * FROM ai_model model" + FIND_BY_TENANT_ID_WHERE,
countQuery = "SELECT COUNT(*) FROM ai_model model" + FIND_BY_TENANT_ID_WHERE,
nativeQuery = true
)
Page<AiModelEntity> findByTenantId(@Param("tenantId") UUID tenantId,

Loading…
Cancel
Save