Browse Source

Merge thingsboard/master into feature/migrator-postgres-ts-kv-export

Resolve CassandraService against the Spring Data Cassandra 5 update
(SimplePreparedStatementCreator) and switch the migrator test
dependencies to the Testcontainers 2 artifacts managed by Spring Boot 4.
pull/16897/head
dealnat 2 hours ago
parent
commit
02ca632482
  1. 2
      .github/ISSUE_TEMPLATE/---bug-report.md
  2. 2
      .github/ISSUE_TEMPLATE/feature_request.md
  3. 2
      .github/ISSUE_TEMPLATE/question.md
  4. 66
      application/pom.xml
  5. 1
      application/src/main/conf/logback.xml
  6. 33
      application/src/main/data/json/demo/dashboards/thermostats.json
  7. 44
      application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json
  8. 2
      application/src/main/data/json/system/widget_types/google_map.json
  9. 2
      application/src/main/data/json/system/widget_types/here_map.json
  10. 2
      application/src/main/data/json/system/widget_types/markers_placement___google_maps.json
  11. 2
      application/src/main/data/json/system/widget_types/route_map.json
  12. 2
      application/src/main/data/json/system/widget_types/route_map___google.json
  13. 2
      application/src/main/data/json/system/widget_types/trip_map.json
  14. 12
      application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java
  15. 9
      application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java
  16. 7
      application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java
  17. 4
      application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
  18. 6
      application/src/main/java/org/thingsboard/server/controller/AdminController.java
  19. 17
      application/src/main/java/org/thingsboard/server/controller/AiChatController.java
  20. 24
      application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java
  21. 4
      application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java
  22. 53
      application/src/main/java/org/thingsboard/server/controller/BaseController.java
  23. 10
      application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java
  24. 80
      application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java
  25. 13
      application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
  26. 43
      application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java
  27. 46
      application/src/main/java/org/thingsboard/server/controller/IotHubController.java
  28. 59
      application/src/main/java/org/thingsboard/server/controller/NotificationController.java
  29. 17
      application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
  30. 1
      application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
  31. 8
      application/src/main/java/org/thingsboard/server/controller/ReportController.java
  32. 3
      application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java
  33. 24
      application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java
  34. 3
      application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java
  35. 41
      application/src/main/java/org/thingsboard/server/controller/SignUpController.java
  36. 3
      application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java
  37. 4
      application/src/main/java/org/thingsboard/server/controller/UserController.java
  38. 20
      application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java
  39. 28
      application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java
  40. 9
      application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java
  41. 2
      application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
  42. 9
      application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java
  43. 4
      application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java
  44. 26
      application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java
  45. 6
      application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java
  46. 27
      application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java
  47. 12
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java
  48. 4
      application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java
  49. 38
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java
  50. 11
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java
  51. 8
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java
  52. 17
      application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java
  53. 6
      application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java
  54. 2
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java
  55. 5
      application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java
  56. 41
      application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java
  57. 2
      application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java
  58. 26
      application/src/main/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationService.java
  59. 417
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java
  60. 223
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  61. 30
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java
  62. 17
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java
  63. 9
      application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java
  64. 8
      application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java
  65. 5
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java
  66. 2
      application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java
  67. 9
      application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java
  68. 2
      application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java
  69. 8
      application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java
  70. 17
      application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java
  71. 2
      application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java
  72. 2
      application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
  73. 8
      application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java
  74. 7
      application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java
  75. 16
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java
  76. 5
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java
  77. 7
      application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java
  78. 4
      application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
  79. 2
      application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
  80. 8
      application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java
  81. 4
      application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java
  82. 45
      application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java
  83. 33
      application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java
  84. 2
      application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java
  85. 20
      application/src/main/java/org/thingsboard/server/utils/MiscUtils.java
  86. 16
      application/src/main/resources/thingsboard.yml
  87. 40
      application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java
  88. 2
      application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java
  89. 2
      application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java
  90. 57
      application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java
  91. 40
      application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java
  92. 117
      application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java
  93. 26
      application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java
  94. 5
      application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
  95. 11
      application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java
  96. 30
      application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java
  97. 26
      application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java
  98. 51
      application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
  99. 30
      application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java
  100. 62
      application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java

2
.github/ISSUE_TEMPLATE/---bug-report.md

@ -3,7 +3,7 @@ name: "\U0001F41E Bug report"
about: Create a report to help us improve about: Create a report to help us improve
title: "Your title here" title: "Your title here"
labels: ['bug', 'unconfirmed'] labels: ['bug', 'unconfirmed']
assignees: Ultrazombie assignees: mykhailokornieiev
--- ---

2
.github/ISSUE_TEMPLATE/feature_request.md

@ -3,7 +3,7 @@ name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
title: "Your title here" title: "Your title here"
labels: ['feature'] labels: ['feature']
assignees: 'Ultrazombie' assignees: 'mykhailokornieiev'
--- ---

2
.github/ISSUE_TEMPLATE/question.md

@ -3,7 +3,7 @@ name: Question
about: Describe your questions in detail about: Describe your questions in detail
title: "Your title here" title: "Your title here"
labels: ['question'] labels: ['question']
assignees: 'Ultrazombie' assignees: 'mykhailokornieiev'
--- ---

66
application/pom.xml

@ -10,7 +10,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>org.thingsboard</groupId> <groupId>org.thingsboard</groupId>
<version>4.4.1-SNAPSHOT</version> <version>4.4.2-SNAPSHOT</version>
<artifactId>thingsboard</artifactId> <artifactId>thingsboard</artifactId>
</parent> </parent>
<artifactId>application</artifactId> <artifactId>application</artifactId>
@ -31,6 +31,7 @@
<pkg.name>thingsboard</pkg.name> <pkg.name>thingsboard</pkg.name>
<pkg.win.dist>${project.build.directory}/windows</pkg.win.dist> <pkg.win.dist>${project.build.directory}/windows</pkg.win.dist>
<pkg.copyInstallScripts>true</pkg.copyInstallScripts> <pkg.copyInstallScripts>true</pkg.copyInstallScripts>
<pkg.requiresFonts>true</pkg.requiresFonts>
<pkg.implementationTitle>ThingsBoard</pkg.implementationTitle> <pkg.implementationTitle>ThingsBoard</pkg.implementationTitle>
<pkg.mainClass>org.thingsboard.server.ThingsboardServerApplication</pkg.mainClass> <pkg.mainClass>org.thingsboard.server.ThingsboardServerApplication</pkg.mainClass>
</properties> </properties>
@ -221,12 +222,28 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-webmvc</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId> <artifactId>spring-boot-starter-websocket</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-jackson2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-restclient</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-security-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-validation</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.security</groupId> <groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId> <artifactId>spring-security-oauth2-client</artifactId>
@ -272,16 +289,16 @@
<artifactId>logback-classic</artifactId> <artifactId>logback-classic</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.sun.mail</groupId> <groupId>jakarta.mail</groupId>
<artifactId>jakarta.mail</artifactId> <artifactId>jakarta.mail-api</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>jakarta.xml.bind</groupId> <groupId>org.eclipse.angus</groupId>
<artifactId>jakarta.xml.bind-api</artifactId> <artifactId>angus-mail</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>javax.xml.bind</groupId> <groupId>jakarta.xml.bind</groupId>
<artifactId>jaxb-api</artifactId> <artifactId>jakarta.xml.bind-api</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.twilio.sdk</groupId> <groupId>com.twilio.sdk</groupId>
@ -378,40 +395,31 @@
<artifactId>awaitility</artifactId> <artifactId>awaitility</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.testcontainers</groupId> <groupId>org.testcontainers</groupId>
<artifactId>cassandra</artifactId> <artifactId>testcontainers-cassandra</artifactId>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.testcontainers</groupId> <groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId> <artifactId>testcontainers-postgresql</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.testcontainers</groupId> <groupId>org.testcontainers</groupId>
<artifactId>jdbc</artifactId> <artifactId>testcontainers-jdbc</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.thingsboard</groupId> <groupId>org.thingsboard</groupId>
<artifactId>netty-mqtt</artifactId> <artifactId>netty-mqtt</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.8</version>
</dependency>
<dependency> <dependency>
<groupId>org.passay</groupId> <groupId>org.passay</groupId>
<artifactId>passay</artifactId> <artifactId>passay</artifactId>
@ -489,6 +497,12 @@
<dependency> <dependency>
<groupId>dev.langchain4j</groupId> <groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-open-ai-official</artifactId> <artifactId>langchain4j-open-ai-official</artifactId>
<exclusions>
<exclusion>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
</exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>dev.langchain4j</groupId> <groupId>dev.langchain4j</groupId>

1
application/src/main/conf/logback.xml

@ -52,7 +52,6 @@
<appender name="licenseErrorLogAppender" class="ch.qos.logback.core.ConsoleAppender"> <appender name="licenseErrorLogAppender" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target> <target>System.err</target>
<withJansi>true</withJansi>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level> <level>WARN</level>
</filter> </filter>

33
application/src/main/data/json/demo/dashboards/thermostats.json

@ -1303,17 +1303,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}", "label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet", "provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik" "layerType": "OpenStreetMap.Mapnik"
},
{
"label": "{i18n:widgets.maps.layer.satellite}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery"
},
{
"label": "{i18n:widgets.maps.layer.hybrid}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery",
"referenceLayer": "openstreetmap_hybrid"
} }
], ],
"imageSource": null, "imageSource": null,
@ -1561,17 +1550,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}", "label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet", "provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik" "layerType": "OpenStreetMap.Mapnik"
},
{
"label": "{i18n:widgets.maps.layer.satellite}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery"
},
{
"label": "{i18n:widgets.maps.layer.hybrid}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery",
"referenceLayer": "openstreetmap_hybrid"
} }
], ],
"imageSource": null, "imageSource": null,
@ -1820,17 +1798,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}", "label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet", "provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik" "layerType": "OpenStreetMap.Mapnik"
},
{
"label": "{i18n:widgets.maps.layer.satellite}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery"
},
{
"label": "{i18n:widgets.maps.layer.hybrid}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery",
"referenceLayer": "openstreetmap_hybrid"
} }
], ],
"imageSource": null, "imageSource": null,

44
application/src/main/data/json/solutions/fleet_tracking/dashboards/mine_site_monitoring.json

@ -20,21 +20,10 @@
"settings": { "settings": {
"mapType": "geoMap", "mapType": "geoMap",
"layers": [ "layers": [
{
"label": "{i18n:widgets.maps.layer.hybrid}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery",
"referenceLayer": "openstreetmap_hybrid"
},
{ {
"label": "{i18n:widgets.maps.layer.roadmap}", "label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet", "provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik" "layerType": "OpenStreetMap.Mapnik"
},
{
"label": "{i18n:widgets.maps.layer.satellite}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery"
} }
], ],
"imageSource": null, "imageSource": null,
@ -1284,21 +1273,10 @@
"settings": { "settings": {
"mapType": "geoMap", "mapType": "geoMap",
"layers": [ "layers": [
{
"label": "{i18n:widgets.maps.layer.satellite}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery"
},
{ {
"label": "{i18n:widgets.maps.layer.roadmap}", "label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet", "provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik" "layerType": "OpenStreetMap.Mapnik"
},
{
"label": "{i18n:widgets.maps.layer.hybrid}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery",
"referenceLayer": "openstreetmap_hybrid"
} }
], ],
"trips": [ "trips": [
@ -2764,21 +2742,10 @@
"settings": { "settings": {
"mapType": "geoMap", "mapType": "geoMap",
"layers": [ "layers": [
{
"label": "{i18n:widgets.maps.layer.satellite}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery"
},
{ {
"label": "{i18n:widgets.maps.layer.roadmap}", "label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet", "provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik" "layerType": "OpenStreetMap.Mapnik"
},
{
"label": "{i18n:widgets.maps.layer.hybrid}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery",
"referenceLayer": "openstreetmap_hybrid"
} }
], ],
"trips": [ "trips": [
@ -4371,21 +4338,10 @@
"settings": { "settings": {
"mapType": "geoMap", "mapType": "geoMap",
"layers": [ "layers": [
{
"label": "{i18n:widgets.maps.layer.satellite}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery"
},
{ {
"label": "{i18n:widgets.maps.layer.roadmap}", "label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet", "provider": "openstreet",
"layerType": "OpenStreetMap.Mapnik" "layerType": "OpenStreetMap.Mapnik"
},
{
"label": "{i18n:widgets.maps.layer.hybrid}",
"provider": "openstreet",
"layerType": "Esri.WorldImagery",
"referenceLayer": "openstreetmap_hybrid"
} }
], ],
"imageSource": null, "imageSource": null,

2
application/src/main/data/json/system/widget_types/google_map.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/here_map.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/markers_placement___google_maps.json

@ -13,7 +13,7 @@
"templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}", "templateCss": ".error {\n color: red;\n}\n.tb-labels {\n color: #222;\n font: 12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif;\n text-align: center;\n width: 200px;\n white-space: nowrap;\n}",
"controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', false, self.ctx, null, true);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}", "controllerScript": "self.onInit = function() {\n self.ctx.map = new TbMapWidgetV2('google-map', false, self.ctx, null, true);\n}\n\nself.onDataUpdated = function() {\n self.ctx.map.update();\n}\n\nself.onResize = function() {\n self.ctx.map.resize();\n}\n\nself.actionSources = function() {\n return TbMapWidgetV2.actionSources();\n}\n\nself.onDestroy = function() {\n self.ctx.map.destroy();\n}\n\nself.typeParameters = function() {\n return {\n hasDataPageLink: true\n };\n}",
"settingsDirective": "tb-map-widget-settings-legacy", "settingsDirective": "tb-map-widget-settings-legacy",
"defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]},{\"type\":\"function\",\"name\":\"Second point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"fitMapBounds\":true,\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"showLabel\":true,\"label\":\"${entityName}\",\"tooltipPattern\":\"<b>${entityName}</b><br/><br/><b>Latitude:</b> ${latitude:7}<br/><b>Longitude:</b> ${longitude:7}<br/><br/><link-act name='delete'>Delete</link-act>\",\"markerImageSize\":34,\"gmDefaultMapType\":\"roadmap\",\"gmApiKey\":\"AIzaSyDoEx2kaGz3PxwbI9T7ccTSg5xjdw8Nw8Q\",\"useColorFunction\":false,\"markerImages\":[],\"useMarkerImageFunction\":false,\"colorFunction\":\"\\n\",\"color\":\"#fe7569\",\"showTooltip\":true,\"autocloseTooltip\":true,\"defaultCenterPosition\":\"0,0\",\"showTooltipAction\":\"click\",\"polygonKeyName\":\"coordinates\",\"polygonOpacity\":0.5,\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"zoomOnClick\":true,\"defaultZoomLevel\":5,\"provider\":\"google-map\",\"showCoverageOnHover\":true,\"animate\":true,\"maxClusterRadius\":80,\"removeOutsideVisibleBounds\":true,\"mapProvider\":\"HERE.normalDay\",\"draggableMarker\":true,\"editablePolygon\":true,\"mapPageSize\":16384,\"showPolygon\":false,\"polygonTooltipPattern\":\"<b>${entityName}</b><br/><br/><b>TimeStamp:</b> ${coordinates|ts:7}<br/><br/><link-act name='delete_polygon'>Delete</link-act>\",\"showPolygonTooltip\":false},\"title\":\"Markers Placement - Google Maps\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{\"tooltipAction\":[{\"name\":\"delete\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id;\\n });\\n\\nwidgetContext.map.setMarkerLocation(entityDatasource[0], null, null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"8d3c0156-0a14-7a6f-0ddd-0ec16b9ffc91\"},{\"name\":\"delete_polygon\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id\\n });\\n\\nwidgetContext.map.savePolygonLocation(entityDatasource[0], null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"46bf69cd-8906-234c-a879-e2e4c92f5b67\"}]},\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\"}" "defaultConfig": "{\"datasources\":[{\"type\":\"function\",\"name\":\"First point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#2196f3\",\"settings\":{},\"_hash\":0.05427416942713381,\"funcBody\":\"var value = prevValue || 15.833293;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#4caf50\",\"settings\":{},\"_hash\":0.680594833308841,\"funcBody\":\"var value = prevValue || -90.454350;\\nif (time % 5000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]},{\"type\":\"function\",\"name\":\"Second point\",\"dataKeys\":[{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"latitude\",\"color\":\"#f44336\",\"settings\":{},\"_hash\":0.05012157428742059,\"funcBody\":\"var value = prevValue || 14.450463;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"},{\"name\":\"f(x)\",\"type\":\"function\",\"label\":\"longitude\",\"color\":\"#ffc107\",\"settings\":{},\"_hash\":0.6742359401617628,\"funcBody\":\"var value = prevValue || -84.845334;\\nif (time % 4000 < 500) {\\n value += Math.random() * 0.05 - 0.025;\\n}\\nreturn value;\"}]}],\"showTitle\":true,\"backgroundColor\":\"#fff\",\"color\":\"rgba(0, 0, 0, 0.87)\",\"padding\":\"8px\",\"settings\":{\"fitMapBounds\":true,\"latKeyName\":\"latitude\",\"lngKeyName\":\"longitude\",\"showLabel\":true,\"label\":\"${entityName}\",\"tooltipPattern\":\"<b>${entityName}</b><br/><br/><b>Latitude:</b> ${latitude:7}<br/><b>Longitude:</b> ${longitude:7}<br/><br/><link-act name='delete'>Delete</link-act>\",\"markerImageSize\":34,\"gmDefaultMapType\":\"roadmap\",\"gmApiKey\":null,\"useColorFunction\":false,\"markerImages\":[],\"useMarkerImageFunction\":false,\"colorFunction\":\"\\n\",\"color\":\"#fe7569\",\"showTooltip\":true,\"autocloseTooltip\":true,\"defaultCenterPosition\":\"0,0\",\"showTooltipAction\":\"click\",\"polygonKeyName\":\"coordinates\",\"polygonOpacity\":0.5,\"polygonStrokeOpacity\":1,\"polygonStrokeWeight\":1,\"zoomOnClick\":true,\"defaultZoomLevel\":5,\"provider\":\"google-map\",\"showCoverageOnHover\":true,\"animate\":true,\"maxClusterRadius\":80,\"removeOutsideVisibleBounds\":true,\"mapProvider\":\"HERE.normalDay\",\"draggableMarker\":true,\"editablePolygon\":true,\"mapPageSize\":16384,\"showPolygon\":false,\"polygonTooltipPattern\":\"<b>${entityName}</b><br/><br/><b>TimeStamp:</b> ${coordinates|ts:7}<br/><br/><link-act name='delete_polygon'>Delete</link-act>\",\"showPolygonTooltip\":false},\"title\":\"Markers Placement - Google Maps\",\"dropShadow\":true,\"enableFullscreen\":true,\"titleStyle\":{\"fontSize\":\"16px\",\"fontWeight\":400},\"showLegend\":false,\"widgetStyle\":{},\"actions\":{\"tooltipAction\":[{\"name\":\"delete\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id;\\n });\\n\\nwidgetContext.map.setMarkerLocation(entityDatasource[0], null, null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"8d3c0156-0a14-7a6f-0ddd-0ec16b9ffc91\"},{\"name\":\"delete_polygon\",\"icon\":\"more_horiz\",\"type\":\"custom\",\"customFunction\":\"var entityDatasource = widgetContext.map.map.datasources.filter(\\n function(entity) {\\n return entity.entityId === entityId.id\\n });\\n\\nwidgetContext.map.savePolygonLocation(entityDatasource[0], null).subscribe(() => widgetContext.updateAliases());\",\"id\":\"46bf69cd-8906-234c-a879-e2e4c92f5b67\"}]},\"showTitleIcon\":false,\"titleIcon\":\"more_horiz\",\"iconColor\":\"rgba(0, 0, 0, 0.87)\",\"iconSize\":\"24px\",\"titleTooltip\":\"\"}"
}, },
"tags": [ "tags": [
"mapping", "mapping",

2
application/src/main/data/json/system/widget_types/route_map.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/route_map___google.json

File diff suppressed because one or more lines are too long

2
application/src/main/data/json/system/widget_types/trip_map.json

File diff suppressed because one or more lines are too long

12
application/src/main/java/org/thingsboard/server/actors/ruleChain/DefaultTbContext.java

@ -38,6 +38,7 @@ import org.thingsboard.rule.engine.util.TenantIdLoader;
import org.thingsboard.script.api.ScriptType; import org.thingsboard.script.api.ScriptType;
import org.thingsboard.server.actors.ActorSystemContext; import org.thingsboard.server.actors.ActorSystemContext;
import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;
@ -527,7 +528,11 @@ public class DefaultTbContext implements TbContext, TbPeContext {
if (attributes != null) { if (attributes != null) {
attributes.forEach(attributeKvEntry -> JacksonUtil.addKvEntry(entityNode, attributeKvEntry)); attributes.forEach(attributeKvEntry -> JacksonUtil.addKvEntry(entityNode, attributeKvEntry));
} }
return attributesActionMsg(originator, ruleNodeId, scope, ATTRIBUTES_UPDATED, JacksonUtil.toString(entityNode)); TbMsgMetaData tbMsgMetaData = getActionMetaData(ruleNodeId);
// The saved string values that read back as numbers stay strings for the nodes that parse the notification.
List<String> typeCastDisabledKeys = JsonConverter.numericStringKeys(attributes);
tbMsgMetaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
return attributesActionMsg(originator, tbMsgMetaData, scope, ATTRIBUTES_UPDATED, JacksonUtil.toString(entityNode));
} }
@Override @Override
@ -537,11 +542,10 @@ public class DefaultTbContext implements TbContext, TbPeContext {
if (keys != null) { if (keys != null) {
keys.forEach(attrsArrayNode::add); keys.forEach(attrsArrayNode::add);
} }
return attributesActionMsg(originator, ruleNodeId, scope, ATTRIBUTES_DELETED, JacksonUtil.toString(entityNode)); return attributesActionMsg(originator, getActionMetaData(ruleNodeId), scope, ATTRIBUTES_DELETED, JacksonUtil.toString(entityNode));
} }
private TbMsg attributesActionMsg(EntityId originator, RuleNodeId ruleNodeId, String scope, TbMsgType actionMsgType, String msgData) { private TbMsg attributesActionMsg(EntityId originator, TbMsgMetaData tbMsgMetaData, String scope, TbMsgType actionMsgType, String msgData) {
TbMsgMetaData tbMsgMetaData = getActionMetaData(ruleNodeId);
tbMsgMetaData.putValue("scope", scope); tbMsgMetaData.putValue("scope", scope);
HasRuleEngineProfile profile = getRuleEngineProfile(originator); HasRuleEngineProfile profile = getRuleEngineProfile(originator);
return entityActionMsg(originator, tbMsgMetaData, msgData, actionMsgType, profile); return entityActionMsg(originator, tbMsgMetaData, msgData, actionMsgType, profile);

9
application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.config; package org.thingsboard.server.config;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
@ -17,8 +18,8 @@ import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.core.endpoint.PkceParameterNames; import org.springframework.security.oauth2.core.endpoint.PkceParameterNames;
import org.springframework.security.oauth2.core.oidc.OidcScopes; import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames; import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.UrlUtils; import org.springframework.security.web.util.UrlUtils;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponents;
@ -50,7 +51,7 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza
private static final String REGISTRATION_ID_URI_VARIABLE_NAME = "registrationId"; private static final String REGISTRATION_ID_URI_VARIABLE_NAME = "registrationId";
private static final char PATH_DELIMITER = '/'; private static final char PATH_DELIMITER = '/';
private final AntPathRequestMatcher authorizationRequestMatcher = new AntPathRequestMatcher( private final PathPatternRequestMatcher authorizationRequestMatcher = PathPatternRequestMatcher.withDefaults().matcher(
DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/{" + REGISTRATION_ID_URI_VARIABLE_NAME + "}"); DEFAULT_AUTHORIZATION_REQUEST_BASE_URI + "/{" + REGISTRATION_ID_URI_VARIABLE_NAME + "}");
private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder()); private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());
private final StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96); private final StringKeyGenerator secureKeyGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder().withoutPadding(), 96);
@ -212,7 +213,7 @@ public class CustomOAuth2AuthorizationRequestResolver implements OAuth2Authoriza
Map<String, String> uriVariables = new HashMap<>(); Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("registrationId", clientRegistration.getRegistrationId()); uriVariables.put("registrationId", clientRegistration.getRegistrationId());
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)) UriComponents uriComponents = UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request))
.replacePath(request.getContextPath()) .replacePath(request.getContextPath())
.replaceQuery(null) .replaceQuery(null)
.fragment(null) .fragment(null)

7
application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java

@ -1,10 +1,11 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.config; package org.thingsboard.server.config;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterProperties;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
@ -17,7 +18,7 @@ import org.springframework.security.web.SecurityFilterChain;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@EnableMethodSecurity @EnableMethodSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER) @Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
@ConditionalOnExpression("'${service.type:null}'=='tb-rule-engine'") @ConditionalOnExpression("'${service.type:null}'=='tb-rule-engine'")
public class TbRuleEngineSecurityConfiguration { public class TbRuleEngineSecurityConfiguration {

4
application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java

@ -7,7 +7,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -61,7 +61,7 @@ import java.util.stream.Stream;
@Configuration @Configuration
@EnableWebSecurity @EnableWebSecurity
@EnableMethodSecurity @EnableMethodSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER) @Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
@TbCoreComponent @TbCoreComponent
public class ThingsboardSecurityConfiguration { public class ThingsboardSecurityConfiguration {

6
application/src/main/java/org/thingsboard/server/controller/AdminController.java

@ -75,7 +75,9 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.sync.vc.EntitiesVersionControlService; import org.thingsboard.server.service.sync.vc.EntitiesVersionControlService;
import org.thingsboard.server.service.sync.vc.autocommit.DefaultTbAutoCommitSettingsService;
import org.thingsboard.server.service.sync.vc.autocommit.TbAutoCommitSettingsService; import org.thingsboard.server.service.sync.vc.autocommit.TbAutoCommitSettingsService;
import org.thingsboard.server.service.sync.vc.repository.DefaultTbRepositorySettingsService;
import org.thingsboard.server.service.system.SystemInfoService; import org.thingsboard.server.service.system.SystemInfoService;
import org.thingsboard.server.service.update.UpdateService; import org.thingsboard.server.service.update.UpdateService;
@ -166,6 +168,10 @@ public class AdminController extends BaseController {
} else { } else {
accessControlService.checkPermission(getCurrentUser(), Resource.WHITE_LABELING, Operation.WRITE); accessControlService.checkPermission(getCurrentUser(), Resource.WHITE_LABELING, Operation.WRITE);
} }
String key = adminSettings.getKey();
if (DefaultTbRepositorySettingsService.SETTINGS_KEY.equals(key) || DefaultTbAutoCommitSettingsService.SETTINGS_KEY.equals(key)) {
throw new ThingsboardException("Settings with key '" + key + "' can be saved only through the version control API", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
adminSettings = checkNotNull(adminSettingsService.saveAdminSettings(tenantId, adminSettings)); adminSettings = checkNotNull(adminSettingsService.saveAdminSettings(tenantId, adminSettings));
if (adminSettings.getKey().equals(MAIL_SETTINGS_KEY)) { if (adminSettings.getKey().equals(MAIL_SETTINGS_KEY)) {
((ObjectNode) adminSettings.getJsonValue()).remove("refreshToken"); ((ObjectNode) adminSettings.getJsonValue()).remove("refreshToken");

17
application/src/main/java/org/thingsboard/server/controller/AiChatController.java

@ -65,6 +65,15 @@ class AiChatController extends BaseController {
aiChatService.updateChat(chatId, request, user); aiChatService.updateChat(chatId, request, user);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{chatId}/stop")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void stopChat(@PathVariable UUID chatId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
aiChatService.stopChat(chatId, user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping @GetMapping
public JsonNode listChats() throws ThingsboardException { public JsonNode listChats() throws ThingsboardException {
@ -73,6 +82,14 @@ class AiChatController extends BaseController {
return aiChatService.listChats(user); return aiChatService.listChats(user);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/status")
public JsonNode listChatStatuses() throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.READ);
return aiChatService.listChatStatuses(user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/{chatId}/messages") @GetMapping("/{chatId}/messages")
public JsonNode getChatMessages(@PathVariable UUID chatId) throws ThingsboardException { public JsonNode getChatMessages(@PathVariable UUID chatId) throws ThingsboardException {

24
application/src/main/java/org/thingsboard/server/controller/AiSolutionController.java

@ -92,6 +92,14 @@ public class AiSolutionController extends BaseController {
return aiSolutionService.createSolution(solutionId, user); return aiSolutionService.createSolution(solutionId, user);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/stop")
public JsonNode stopSolution(@PathVariable UUID solutionId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
return aiSolutionService.stopSolution(solutionId, user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PutMapping("/{solutionId}/{dataKey}") @PutMapping("/{solutionId}/{dataKey}")
public JsonNode updateData(@PathVariable UUID solutionId, public JsonNode updateData(@PathVariable UUID solutionId,
@ -110,6 +118,22 @@ public class AiSolutionController extends BaseController {
aiSolutionService.clearStep(solutionId, step, user); aiSolutionService.clearStep(solutionId, step, user);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping(value = "/{solutionId}/update", consumes = MediaType.APPLICATION_JSON_VALUE)
public void updateSolution(@PathVariable UUID solutionId, @RequestBody JsonNode request) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.WRITE);
aiSolutionService.updateSolution(solutionId, request, user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/{solutionId}/progress")
public JsonNode getInstallProgress(@PathVariable UUID solutionId) throws ThingsboardException {
SecurityUser user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI, Operation.READ);
return aiSolutionService.getInstallProgress(solutionId, user);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/{solutionId}/install") @PostMapping("/{solutionId}/install")
public JsonNode installSolution(@PathVariable UUID solutionId, public JsonNode installSolution(@PathVariable UUID solutionId,

4
application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java

@ -116,6 +116,10 @@ public class ApiKeyController extends BaseController {
UserId userId = new UserId(toUUID(userIdStr)); UserId userId = new UserId(toUUID(userIdStr));
accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ); accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ);
User user = checkUserId(userId, Operation.READ); User user = checkUserId(userId, Operation.READ);
ApiKeyInfo keyOwner = new ApiKeyInfo();
keyOwner.setTenantId(user.getTenantId());
keyOwner.setUserId(userId);
accessControlService.checkPermission(securityUser, Resource.API_KEY, Operation.READ, null, keyOwner);
return apiKeyService.findApiKeysByUserId(user.getTenantId(), userId, pageLink); return apiKeyService.findApiKeysByUserId(user.getTenantId(), userId, pageLink);
} }

53
application/src/main/java/org/thingsboard/server/controller/BaseController.java

@ -148,6 +148,8 @@ import org.thingsboard.server.common.data.menu.CustomMenuInfo;
import org.thingsboard.server.common.data.mobile.app.MobileApp; import org.thingsboard.server.common.data.mobile.app.MobileApp;
import org.thingsboard.server.common.data.mobile.bundle.MobileAppBundle; import org.thingsboard.server.common.data.mobile.bundle.MobileAppBundle;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget; import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
import org.thingsboard.server.common.data.notification.template.NotificationTemplateConfig;
import org.thingsboard.server.common.data.oauth2.OAuth2Client; import org.thingsboard.server.common.data.oauth2.OAuth2Client;
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;
@ -894,6 +896,49 @@ public abstract class BaseController {
} }
} }
protected void checkReportUser(UserId userId) throws ThingsboardException {
if (!getCurrentUser().getId().equals(userId)) {
checkUserId(userId, Operation.IMPERSONATE);
}
}
protected UserId resolveReportUser(UserId userId, boolean useCurrentUserCredentials) throws ThingsboardException {
SecurityUser currentUser = getCurrentUser();
if (useCurrentUserCredentials && !currentUser.getId().equals(userId) && !canImpersonate(userId)) {
return currentUser.getId();
}
checkReportUser(userId);
return userId;
}
private boolean canImpersonate(UserId userId) throws ThingsboardException {
SecurityUser currentUser = getCurrentUser();
User user = userService.findUserById(currentUser.getTenantId(), userId);
return user != null && currentUser.getTenantId().equals(user.getTenantId()) &&
accessControlService.hasPermission(currentUser, Resource.USER, Operation.IMPERSONATE, userId, user);
}
protected void checkTemplateReportUser(NotificationTemplate notificationTemplate) throws ThingsboardException {
NotificationTemplateConfig configuration = notificationTemplate != null ? notificationTemplate.getConfiguration() : null;
if (configuration != null && configuration.isAttachReport() && configuration.getUserId() != null) {
checkReportUser(configuration.getUserId());
}
}
protected void checkMsgReportUser(JsonNode msg) throws ThingsboardException {
if (msg == null) {
return;
}
checkReportUserIfPresent(msg.path("reportConfig").path("userId"));
checkReportUserIfPresent(msg.path("userId").path("id"));
}
private void checkReportUserIfPresent(JsonNode reportUserId) throws ThingsboardException {
if (reportUserId.isTextual() && StringUtils.isNotBlank(reportUserId.asText())) {
checkReportUser(new UserId(toUUID(reportUserId.asText())));
}
}
UserInfo checkUserInfoId(UserId userId, Operation operation) throws ThingsboardException { UserInfo checkUserInfoId(UserId userId, Operation operation) throws ThingsboardException {
try { try {
validateId(userId, id -> "Incorrect userId " + id); validateId(userId, id -> "Incorrect userId " + id);
@ -1097,7 +1142,11 @@ public abstract class BaseController {
for (EntityId referencedEntityId : calculatedFieldConfig.getReferencedEntities()) { for (EntityId referencedEntityId : calculatedFieldConfig.getReferencedEntities()) {
EntityType refEntityType = referencedEntityId.getEntityType(); EntityType refEntityType = referencedEntityId.getEntityType();
switch (refEntityType) { switch (refEntityType) {
case TENANT -> {} case TENANT -> {
if (!getTenantId().equals(referencedEntityId)) {
throw permissionDenied();
}
}
case CUSTOMER, ASSET, DEVICE -> checkEntityId(referencedEntityId, Operation.READ); case CUSTOMER, ASSET, DEVICE -> checkEntityId(referencedEntityId, Operation.READ);
default -> throw new IllegalArgumentException("Unsupported referenced entity type: '" + refEntityType + "'."); default -> throw new IllegalArgumentException("Unsupported referenced entity type: '" + refEntityType + "'.");
} }
@ -1246,7 +1295,7 @@ public abstract class BaseController {
protected EntityGroupInfo checkEntityGroupId(EntityGroupId entityGroupId, Operation operation) throws ThingsboardException { protected EntityGroupInfo checkEntityGroupId(EntityGroupId entityGroupId, Operation operation) throws ThingsboardException {
try { try {
validateId(entityGroupId, id -> "Incorrect entityGroupId " + id); validateId(entityGroupId, id -> "Incorrect entityGroupId " + id);
EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), entityGroupId); EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId);
checkNotNull(entityGroup, "Entity group with id [" + entityGroupId + "] is not found"); checkNotNull(entityGroup, "Entity group with id [" + entityGroupId + "] is not found");
accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), operation, entityGroup); accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), operation, entityGroup);
return entityGroup; return entityGroup;

10
application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java

@ -29,6 +29,7 @@ import org.thingsboard.server.common.data.id.DashboardId;
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.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.subscription.PlatformFeature; import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
@ -61,6 +62,7 @@ public class DashboardReportController extends BaseController {
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
public static final String DASHBOARD_ID = "dashboardId"; public static final String DASHBOARD_ID = "dashboardId";
public static final String USER_ID = "userId";
@ApiOperation(value = "Download dashboard report (downloadDashboardReport)", @ApiOperation(value = "Download dashboard report (downloadDashboardReport)",
notes = "Generate and download a report from the specified dashboard. " + notes = "Generate and download a report from the specified dashboard. " +
@ -125,6 +127,14 @@ public class DashboardReportController extends BaseController {
DashboardId dashboardId = new DashboardId(toUUID(strDashboardId)); DashboardId dashboardId = new DashboardId(toUUID(strDashboardId));
checkDashboardInfoId(dashboardId, Operation.READ); checkDashboardInfoId(dashboardId, Operation.READ);
String strUserId = reportConfig.getUserId();
checkParameter(USER_ID, strUserId);
UserId reportUserId = resolveReportUser(new UserId(toUUID(strUserId)), reportConfig.isUseCurrentUserCredentials());
reportConfig.setUserId(reportUserId.toString());
if (Authority.CUSTOMER_USER.equals(getCurrentUser().getAuthority())) {
reportsServerEndpointUrl = null;
}
dashboardReportService.generateReport(getTenantId(), reportConfig, reportsServerEndpointUrl, onSuccess(result), result::setErrorResult); dashboardReportService.generateReport(getTenantId(), reportConfig, reportsServerEndpointUrl, onSuccess(result), result::setErrorResult);
} catch (Exception e) { } catch (Exception e) {
result.setErrorResult(e); result.setErrorResult(e);

80
application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java

@ -57,6 +57,7 @@ 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.permission.ShareGroupRequest; import org.thingsboard.server.common.data.permission.ShareGroupRequest;
import org.thingsboard.server.common.data.role.Role; import org.thingsboard.server.common.data.role.Role;
import org.thingsboard.server.common.data.role.RoleType;
import org.thingsboard.server.common.data.security.Authority; import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.owner.OwnerService; import org.thingsboard.server.dao.owner.OwnerService;
@ -210,9 +211,8 @@ public class EntityGroupController extends AutoCommitController {
@RequestBody EntityGroup entityGroup) throws Exception { @RequestBody EntityGroup entityGroup) throws Exception {
SecurityUser currentUser = getCurrentUser(); SecurityUser currentUser = getCurrentUser();
checkEntityGroupType(entityGroup.getType()); checkEntityGroupType(entityGroup.getType());
Operation operation = entityGroup.getId() == null ? Operation.CREATE : Operation.WRITE;
EntityId parentEntityId = entityGroup.getOwnerId(); EntityId parentEntityId = entityGroup.getOwnerId();
if (operation == Operation.CREATE) { if (entityGroup.getId() == null) {
if (parentEntityId == null || parentEntityId.isNullUid()) { if (parentEntityId == null || parentEntityId.isNullUid()) {
parentEntityId = currentUser.getOwnerId(); parentEntityId = currentUser.getOwnerId();
} else { } else {
@ -221,14 +221,12 @@ public class EntityGroupController extends AutoCommitController {
"Invalid entity group ownerId!", ThingsboardErrorCode.PERMISSION_DENIED); "Invalid entity group ownerId!", ThingsboardErrorCode.PERMISSION_DENIED);
} }
} }
EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId));
accessControlService.checkEntityGroupInfoPermission(currentUser, Operation.CREATE, entityGroupInfo);
} else { } else {
validateEntityId(parentEntityId, id -> "Incorrect entity group ownerId " + id); parentEntityId = checkEntityGroupId(entityGroup.getId(), Operation.WRITE).getOwnerId();
} }
EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId));
accessControlService.checkEntityGroupInfoPermission(currentUser, operation, entityGroupInfo);
return tbEntityGroupService.save(getTenantId(), parentEntityId, entityGroup, getCurrentUser()); return tbEntityGroupService.save(getTenantId(), parentEntityId, entityGroup, getCurrentUser());
} }
@ -967,7 +965,11 @@ public class EntityGroupController extends AutoCommitController {
for (String strEntityGroupId : strEntityGroupIds) { for (String strEntityGroupId : strEntityGroupIds) {
entityGroupIds.add(new EntityGroupId(toUUID(strEntityGroupId))); entityGroupIds.add(new EntityGroupId(toUUID(strEntityGroupId)));
} }
return checkNotNull(entityGroupService.findEntityGroupEntityInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData()); List<EntityGroupInfo> entityGroups = checkNotNull(
entityGroupService.findEntityGroupInfosByIds(tenantId, entityGroupIds, new PageLink(Integer.MAX_VALUE)).getData());
return filterEntityGroupsByReadPermission(entityGroups).stream()
.map(entityGroup -> new EntityInfo(entityGroup.getId(), entityGroup.getName()))
.toList();
} }
@ApiOperation(value = "Get Owners (getOwners)", @ApiOperation(value = "Get Owners (getOwners)",
@ -1145,7 +1147,8 @@ public class EntityGroupController extends AutoCommitController {
@ApiOperation(value = "Share the Entity Group (shareEntityGroup)", @ApiOperation(value = "Share the Entity Group (shareEntityGroup)",
notes = "Share the entity group with certain user group based on the provided Share Group Request. " + notes = "Share the entity group with certain user group based on the provided Share Group Request. " +
"The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature." "The request is quite flexible and processing of the request involves multiple security checks using platform RBAC feature. " +
"Each role in 'roleIds' must be a group role readable by the current user, and each of its operations must be granted to the current user for the entity group or its entities."
+ TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_GROUP_WRITE_CHECK) + TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH + RBAC_GROUP_WRITE_CHECK)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')") @PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/entityGroup/{entityGroupId}/share") @PostMapping(value = "/entityGroup/{entityGroupId}/share")
@ -1165,21 +1168,25 @@ public class EntityGroupController extends AutoCommitController {
EntityGroupInfo userGroup; EntityGroupInfo userGroup;
if (shareGroupRequest.isAllUserGroup()) { if (shareGroupRequest.isAllUserGroup()) {
Optional<EntityGroupInfo> userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), Optional<EntityGroupInfo> userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId());
EntityType.USER, EntityGroup.GROUP_ALL_NAME);
if (userGroupOptional.isPresent()) { if (userGroupOptional.isPresent()) {
userGroup = userGroupOptional.get(); userGroup = userGroupOptional.get();
} else { } else {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
} }
} else { } else {
userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId()); userGroup = checkNotNull(entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()));
} }
accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup); accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup);
List<RoleId> roleIds; List<Role> roles;
if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) { if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) {
roleIds = shareGroupRequest.getRoleIds(); roles = new ArrayList<>();
for (RoleId roleId : shareGroupRequest.getRoleIds()) {
Role role = checkRoleId(roleId, Operation.READ);
checkGroupRoleAllowedForShare(role, entityGroup);
roles.add(role);
}
} else { } else {
Role role; Role role;
if (shareGroupRequest.isReadElseWrite()) { if (shareGroupRequest.isReadElseWrite()) {
@ -1187,15 +1194,15 @@ public class EntityGroupController extends AutoCommitController {
} else { } else {
role = roleService.findOrCreateWriteEntityGroupRole(getTenantId(), getCurrentUser().getCustomerId()); role = roleService.findOrCreateWriteEntityGroupRole(getTenantId(), getCurrentUser().getCustomerId());
} }
roleIds = Collections.singletonList(role.getId()); roles = Collections.singletonList(role);
} }
for (RoleId roleId : roleIds) { for (Role role : roles) {
GroupPermission groupPermission = new GroupPermission(); GroupPermission groupPermission = new GroupPermission();
groupPermission.setTenantId(getTenantId()); groupPermission.setTenantId(getTenantId());
groupPermission.setEntityGroupId(entityGroup.getId()); groupPermission.setEntityGroupId(entityGroup.getId());
groupPermission.setEntityGroupType(entityGroup.getType()); groupPermission.setEntityGroupType(entityGroup.getType());
groupPermission.setRoleId(roleId); groupPermission.setRoleId(role.getId());
groupPermission.setUserGroupId(userGroup.getId()); groupPermission.setUserGroupId(userGroup.getId());
GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission)); GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission));
@ -1246,7 +1253,7 @@ public class EntityGroupController extends AutoCommitController {
checkParameter("userGroupId", strUserGroupId); checkParameter("userGroupId", strUserGroupId);
checkParameter("roleId", strRoleId); checkParameter("roleId", strRoleId);
EntityGroupId userGroupId = new EntityGroupId(toUUID(strUserGroupId)); EntityGroupId userGroupId = new EntityGroupId(toUUID(strUserGroupId));
EntityGroup userGroup = entityGroupService.findEntityGroupById(getTenantId(), userGroupId); EntityGroup userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), userGroupId);
if (userGroup == null) { if (userGroup == null) {
throw new ThingsboardException("User group with requested id: " + userGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); throw new ThingsboardException("User group with requested id: " + userGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
} }
@ -1299,7 +1306,7 @@ public class EntityGroupController extends AutoCommitController {
private EntityGroup resolveEntityGroup(UUID entityGroupUuid) throws ThingsboardException { private EntityGroup resolveEntityGroup(UUID entityGroupUuid) throws ThingsboardException {
EntityGroupId entityGroupId = new EntityGroupId(entityGroupUuid); EntityGroupId entityGroupId = new EntityGroupId(entityGroupUuid);
EntityGroup entityGroup = entityGroupService.findEntityGroupById(getTenantId(), entityGroupId); EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId);
if (entityGroup == null) { if (entityGroup == null) {
throw new ThingsboardException("Entity group with requested id: " + entityGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); throw new ThingsboardException("Entity group with requested id: " + entityGroupId + " wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
} }
@ -1309,15 +1316,14 @@ public class EntityGroupController extends AutoCommitController {
private EntityGroupInfo resolveUserGroup(ShareGroupRequest shareGroupRequest) throws ThingsboardException { private EntityGroupInfo resolveUserGroup(ShareGroupRequest shareGroupRequest) throws ThingsboardException {
EntityGroupInfo userGroup; EntityGroupInfo userGroup;
if (shareGroupRequest.isAllUserGroup()) { if (shareGroupRequest.isAllUserGroup()) {
Optional<EntityGroupInfo> userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(), Optional<EntityGroupInfo> userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId());
EntityType.USER, EntityGroup.GROUP_ALL_NAME);
if (userGroupOptional.isPresent()) { if (userGroupOptional.isPresent()) {
userGroup = userGroupOptional.get(); userGroup = userGroupOptional.get();
} else { } else {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
} }
} else { } else {
userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId()); userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId());
} }
if (userGroup == null) { if (userGroup == null) {
throw new ThingsboardException("Specified user group wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND); throw new ThingsboardException("Specified user group wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
@ -1325,6 +1331,12 @@ public class EntityGroupController extends AutoCommitController {
return userGroup; return userGroup;
} }
private Optional<EntityGroupInfo> findAllUserGroup(EntityId ownerId) throws ThingsboardException {
TenantId tenantId = getTenantId();
return entityGroupService.findEntityGroupInfoByTypeAndName(tenantId, ownerId, EntityType.USER, EntityGroup.GROUP_ALL_NAME)
.map(group -> entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, group.getId()));
}
private List<Role> resolveRoles(ShareGroupRequest shareGroupRequest) throws ThingsboardException { private List<Role> resolveRoles(ShareGroupRequest shareGroupRequest) throws ThingsboardException {
List<Role> roles = new ArrayList<>(1); List<Role> roles = new ArrayList<>(1);
if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) { if (shareGroupRequest.getRoleIds() != null && !shareGroupRequest.getRoleIds().isEmpty()) {
@ -1504,9 +1516,29 @@ public class EntityGroupController extends AutoCommitController {
} }
} }
private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set<Operation> mergedOperations) throws ThingsboardException { private void checkGroupRoleAllowedForShare(Role role, EntityGroup entityGroup) throws ThingsboardException {
if (role.getType() == RoleType.GENERIC) {
throw new ThingsboardException("Can't assign Generic Role to entity group!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
MergedUserPermissions userPermissions = getCurrentUser().getUserPermissions();
Resource groupResource = Resource.groupResourceFromGroupType(entityGroup.getType());
Resource entityResource = Resource.resourceFromEntityType(entityGroup.getType());
for (Operation operation : toRoleOperations(role)) {
if (!userPermissions.hasGenericPermission(groupResource, operation)
&& !userPermissions.hasGenericPermission(entityResource, operation)
&& !userPermissions.hasGroupPermissions(entityGroup.getId(), operation)) {
throw permissionDenied();
}
}
}
private List<Operation> toRoleOperations(Role role) {
CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class); CollectionType collectionType = TypeFactory.defaultInstance().constructCollectionType(List.class, Operation.class);
List<Operation> roleOperations = JacksonUtil.readValue(role.getPermissions().toString(), collectionType); return JacksonUtil.readValue(role.getPermissions().toString(), collectionType);
}
private void shareGroup(Role role, EntityGroup userGroup, EntityGroup entityGroup, Set<Operation> mergedOperations) throws ThingsboardException {
List<Operation> roleOperations = toRoleOperations(role);
if (!mergedOperations.isEmpty() && (mergedOperations.contains(Operation.ALL) || mergedOperations.containsAll(roleOperations))) { if (!mergedOperations.isEmpty() && (mergedOperations.contains(Operation.ALL) || mergedOperations.containsAll(roleOperations))) {
GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false)); GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false));
userPermissionsService.onGroupPermissionUpdated(savedGroupPermission); userPermissionsService.onGroupPermissionUpdated(savedGroupPermission);

13
application/src/main/java/org/thingsboard/server/controller/EntityViewController.java

@ -48,6 +48,7 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
@ -132,6 +133,11 @@ public class EntityViewController extends BaseController {
SecurityUser user = getCurrentUser(); SecurityUser user = getCurrentUser();
return saveGroupEntity(entityView, strEntityGroupId, strEntityGroupIds, (entityView1, entityGroups) -> { return saveGroupEntity(entityView, strEntityGroupId, strEntityGroupIds, (entityView1, entityGroups) -> {
try { try {
EntityView existingEntityView = entityView1.getId() == null ? null :
entityViewService.findEntityViewById(user.getTenantId(), entityView1.getId());
if (existingEntityView == null || !hasSameSourceData(existingEntityView, entityView1)) {
checkEntityId(entityView1.getEntityId(), Operation.READ);
}
return tbEntityViewService.save(entityView1, entityGroups, new NameConflictStrategy(nameConflictPolicy, uniquifySeparator, uniquifyStrategy), user); return tbEntityViewService.save(entityView1, entityGroups, new NameConflictStrategy(nameConflictPolicy, uniquifySeparator, uniquifyStrategy), user);
} catch (Exception e) { } catch (Exception e) {
throw handleException(e); throw handleException(e);
@ -451,4 +457,11 @@ public class EntityViewController extends BaseController {
return checkNotNull(entityViewTypes.get()); return checkNotNull(entityViewTypes.get());
} }
private static boolean hasSameSourceData(EntityView existing, EntityView entityView) {
return Objects.equals(existing.getEntityId(), entityView.getEntityId())
&& Objects.equals(existing.getKeys(), entityView.getKeys())
&& existing.getStartTimeMs() == entityView.getStartTimeMs()
&& existing.getEndTimeMs() == entityView.getEndTimeMs();
}
} }

43
application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java

@ -19,6 +19,7 @@ import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.audit.ActionType; import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
import org.thingsboard.server.common.data.id.EntityGroupId; import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.GroupPermissionId; import org.thingsboard.server.common.data.id.GroupPermissionId;
@ -116,6 +117,7 @@ public class GroupPermissionController extends BaseController {
.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.CREATE, null, groupPermission); .checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.CREATE, null, groupPermission);
} else { } else {
oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE); oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE);
checkGroupPermissionManageable(oldGroupPermission);
} }
if (groupPermission.isPublic()) { if (groupPermission.isPublic()) {
@ -168,17 +170,7 @@ public class GroupPermissionController extends BaseController {
try { try {
GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId)); GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId));
GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE); GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE);
if (groupPermission.isPublic()) { checkGroupPermissionManageable(groupPermission);
throw permissionDenied();
}
checkRoleId(groupPermission.getRoleId(), Operation.READ);
if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE);
}
if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE);
}
groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId); groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId);
userPermissionsService.onGroupPermissionDeleted(groupPermission); userPermissionsService.onGroupPermissionDeleted(groupPermission);
@ -218,7 +210,8 @@ public class GroupPermissionController extends BaseController {
@RequestBody List<GroupPermission> permissions) throws ThingsboardException, ExecutionException, InterruptedException { @RequestBody List<GroupPermission> permissions) throws ThingsboardException, ExecutionException, InterruptedException {
TenantId tenantId = getCurrentUser().getTenantId(); TenantId tenantId = getCurrentUser().getTenantId();
accessControlService.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.READ); accessControlService.checkPermission(getCurrentUser(), Resource.GROUP_PERMISSION, Operation.READ);
List<GroupPermissionInfo> permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, permissions).get(); List<GroupPermission> readablePermissions = permissions.stream().filter(this::isReadableEntityGroup).toList();
List<GroupPermissionInfo> permissionInfoList = groupPermissionService.loadUserGroupPermissionInfoListAsync(tenantId, readablePermissions).get();
return applyPermissionInfo(permissionInfoList); return applyPermissionInfo(permissionInfoList);
} }
@ -255,6 +248,32 @@ public class GroupPermissionController extends BaseController {
return groupPermissions; return groupPermissions;
} }
private void checkGroupPermissionManageable(GroupPermission groupPermission) throws ThingsboardException {
if (groupPermission.isPublic()) {
throw permissionDenied();
}
checkRoleId(groupPermission.getRoleId(), Operation.READ);
if (groupPermission.getUserGroupId() != null && !groupPermission.getUserGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getUserGroupId(), Operation.WRITE);
}
if (groupPermission.getEntityGroupId() != null && !groupPermission.getEntityGroupId().isNullUid()) {
checkEntityGroupId(groupPermission.getEntityGroupId(), Operation.WRITE);
}
}
private boolean isReadableEntityGroup(GroupPermission groupPermission) {
EntityGroupId entityGroupId = groupPermission.getEntityGroupId();
if (entityGroupId == null || entityGroupId.isNullUid()) {
return true;
}
try {
EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId);
return entityGroup != null && accessControlService.hasEntityGroupInfoPermission(getCurrentUser(), Operation.READ, entityGroup);
} catch (ThingsboardException e) {
return false;
}
}
private boolean isAlreadyAssigned(TenantId tenantId, GroupPermission groupPermission) { private boolean isAlreadyAssigned(TenantId tenantId, GroupPermission groupPermission) {
if (groupPermission.getEntityGroupId() != null) { if (groupPermission.getEntityGroupId() != null) {
return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupIdAndUserGroupIdAndRoleId(tenantId, return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupIdAndUserGroupIdAndRoleId(tenantId,

46
application/src/main/java/org/thingsboard/server/controller/IotHubController.java

@ -31,7 +31,6 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
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.dao.device.DeviceConnectivityHostSource; import org.thingsboard.server.dao.device.DeviceConnectivityHostSource;
import org.thingsboard.server.dao.device.DeviceConnectivityService; import org.thingsboard.server.dao.device.DeviceConnectivityService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService; import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
@ -39,9 +38,9 @@ import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.system.ResolvedBaseUrl; import org.thingsboard.server.service.security.system.ResolvedBaseUrl;
import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.iot_hub.DevicePackageEntityState; import org.thingsboard.server.service.iot_hub.DevicePackageEntityState;
import org.thingsboard.server.service.iot_hub.DevicePackageUpdateService; import org.thingsboard.server.service.iot_hub.DevicePackageService;
import org.thingsboard.server.service.iot_hub.DeviceUpdateRequest; import org.thingsboard.server.service.iot_hub.DevicePackageRequest;
import org.thingsboard.server.service.iot_hub.DeviceUpdateResult; import org.thingsboard.server.service.iot_hub.DevicePackageResult;
import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities; import org.thingsboard.server.service.iot_hub.InstalledItemKeptEntities;
import org.thingsboard.server.service.iot_hub.InstallItemVersionResult; import org.thingsboard.server.service.iot_hub.InstallItemVersionResult;
import org.thingsboard.server.service.iot_hub.InstallPlan; import org.thingsboard.server.service.iot_hub.InstallPlan;
@ -58,7 +57,7 @@ import org.thingsboard.server.service.iot_hub.IotHubService;
public class IotHubController extends BaseController { public class IotHubController extends BaseController {
private final IotHubService iotHubService; private final IotHubService iotHubService;
private final DevicePackageUpdateService devicePackageUpdateService; private final DevicePackageService devicePackageService;
private final IotHubInstalledItemService iotHubInstalledItemService; private final IotHubInstalledItemService iotHubInstalledItemService;
private final DeviceConnectivityService deviceConnectivityService; private final DeviceConnectivityService deviceConnectivityService;
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
@ -103,21 +102,29 @@ public class IotHubController extends BaseController {
return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor); return iotHubService.registerDeviceInstall(getCurrentUser(), versionId, descriptor);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/device/install")
@ResponseBody
public DevicePackageResult installDevicePackage(@RequestBody DevicePackageRequest request) throws ThingsboardException {
checkAllPermissions();
return devicePackageService.install(getCurrentUser(), request);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/{installedItemId}/deviceUpdate/check") @GetMapping("/installedItems/{installedItemId}/deviceUpdate/check")
@ResponseBody @ResponseBody
public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException { public List<DevicePackageEntityState> checkDeviceUpdate(@PathVariable UUID installedItemId) throws ThingsboardException {
checkAllPermissions(); checkAllPermissions();
return devicePackageUpdateService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId)); return devicePackageService.check(getCurrentUser(), new IotHubInstalledItemId(installedItemId));
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/{installedItemId}/deviceUpdate") @PostMapping("/installedItems/{installedItemId}/deviceUpdate")
@ResponseBody @ResponseBody
public DeviceUpdateResult updateDevicePackage(@PathVariable UUID installedItemId, public DevicePackageResult updateDevicePackage(@PathVariable UUID installedItemId,
@RequestBody DeviceUpdateRequest request) throws ThingsboardException { @RequestBody DevicePackageRequest request) throws ThingsboardException {
checkAllPermissions(); checkAllPermissions();
return devicePackageUpdateService.apply(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request); return devicePackageService.update(getCurrentUser(), new IotHubInstalledItemId(installedItemId), request);
} }
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@ -146,6 +153,25 @@ public class IotHubController extends BaseController {
return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink); return iotHubInstalledItemService.findByTenantId(getTenantId(), itemTypes, itemId, pageLink);
} }
/**
* The installed items with an update in IoT Hub. The body is what the browser got from IoT Hub on Check for updates:
* the published version id by item id. A POST, as the map of a tenant with many items doesn't fit in a URL.
*/
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/installedItems/withUpdates")
@ResponseBody
public PageData<IotHubInstalledItem> getInstalledItemsWithUpdates(@RequestParam int pageSize,
@RequestParam int page,
@RequestParam(required = false) String textSearch,
@RequestParam(required = false) String sortProperty,
@RequestParam(required = false) String sortOrder,
@RequestParam(required = false) List<String> itemTypes,
@RequestBody Map<UUID, UUID> publishedVersionIds) throws ThingsboardException {
checkAllPermissions();
PageLink pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
return iotHubInstalledItemService.findByTenantIdWithUpdates(getTenantId(), itemTypes, publishedVersionIds, pageLink);
}
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping("/installedItems/count") @GetMapping("/installedItems/count")
@ResponseBody @ResponseBody
@ -197,7 +223,7 @@ public class IotHubController extends BaseController {
} }
private void checkAllPermissions() throws ThingsboardException { private void checkAllPermissions() throws ThingsboardException {
if (!getCurrentUser().getUserPermissions().hasGenericPermission(Resource.ALL, Operation.ALL)) { if (!getCurrentUser().getUserPermissions().hasGenericPermissionExceptAi(Operation.ALL)) {
throw new ThingsboardException("You don't have permissions to use solution templates!", throw new ThingsboardException("You don't have permissions to use solution templates!",
ThingsboardErrorCode.PERMISSION_DENIED); ThingsboardErrorCode.PERMISSION_DENIED);
} }

59
application/src/main/java/org/thingsboard/server/controller/NotificationController.java

@ -22,6 +22,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.rule.engine.api.NotificationCenter; import org.thingsboard.rule.engine.api.NotificationCenter;
import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.Tenant;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
@ -38,6 +39,7 @@ import org.thingsboard.server.common.data.notification.NotificationRequestPrevie
import org.thingsboard.server.common.data.notification.NotificationType; import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.common.data.notification.info.AddonAccessErrorNotificationInfo; import org.thingsboard.server.common.data.notification.info.AddonAccessErrorNotificationInfo;
import org.thingsboard.server.common.data.notification.info.AddonAccessRequestNotificationInfo; import org.thingsboard.server.common.data.notification.info.AddonAccessRequestNotificationInfo;
import org.thingsboard.server.common.data.notification.info.AiCreditsLimitIncreaseRequestNotificationInfo;
import org.thingsboard.server.common.data.notification.info.EntitiesLimitIncreaseRequestNotificationInfo; import org.thingsboard.server.common.data.notification.info.EntitiesLimitIncreaseRequestNotificationInfo;
import org.thingsboard.server.common.data.notification.info.NotificationInfo; import org.thingsboard.server.common.data.notification.info.NotificationInfo;
import org.thingsboard.server.common.data.notification.info.PlanUpgradeRequestNotificationInfo; import org.thingsboard.server.common.data.notification.info.PlanUpgradeRequestNotificationInfo;
@ -72,15 +74,20 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.service.translation.TranslationService; import org.thingsboard.server.service.translation.TranslationService;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Comparator; import java.util.Comparator;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
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;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION; import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION;
@ -114,6 +121,8 @@ public class NotificationController extends BaseController {
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
private final SubscriptionService subscriptionService; private final SubscriptionService subscriptionService;
private final Map<String, Long> aiCreditsRequests = new ConcurrentHashMap<>();
@ApiOperation(value = "Get notifications (getNotifications)", @ApiOperation(value = "Get notifications (getNotifications)",
notes = "Returns the page of notifications for current user." + NEW_LINE + notes = "Returns the page of notifications for current user." + NEW_LINE +
PAGE_DATA_PARAMETERS + PAGE_DATA_PARAMETERS +
@ -274,6 +283,9 @@ public class NotificationController extends BaseController {
} }
notificationRequest.setTenantId(user.getTenantId()); notificationRequest.setTenantId(user.getTenantId());
checkEntity(notificationRequest.getId(), notificationRequest, NOTIFICATION); checkEntity(notificationRequest.getId(), notificationRequest, NOTIFICATION);
checkTemplateReportUser(notificationRequest.getTemplateId() != null ?
notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRequest.getTemplateId()) :
notificationRequest.getTemplate());
List<NotificationTargetId> targets = notificationRequest.getTargets().stream() List<NotificationTargetId> targets = notificationRequest.getTargets().stream()
.map(NotificationTargetId::new) .map(NotificationTargetId::new)
.toList(); .toList();
@ -496,6 +508,53 @@ public class NotificationController extends BaseController {
} }
} }
@ApiOperation(value = "Send AI credits limit increase request notification to System administrators (sendAiCreditsLimitIncreaseRequest)",
notes = "Send AI credits limit increase request notification by Tenant Administrator to System administrators. " +
"TENANT asks for a higher monthly limit of the tenant, POOL for more AI credits for the whole installation. " +
"A request for the same limit is sent once a month." + TENANT_AUTHORITY_PARAGRAPH)
@PostMapping("/notification/aiCreditsLimitIncreaseRequest")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
public void sendAiCreditsLimitIncreaseRequest(@Parameter(description = "Limit to increase", schema = @Schema(allowableValues = {"TENANT", "POOL"}))
@RequestParam(defaultValue = "TENANT") String limitType,
@AuthenticationPrincipal SecurityUser user,
HttpServletRequest request) throws Exception {
boolean pool = "POOL".equals(limitType);
if (!pool && !"TENANT".equals(limitType)) {
throw new IllegalArgumentException("Unsupported limit type: " + limitType);
}
long month = ZonedDateTime.now(ZoneOffset.UTC).truncatedTo(ChronoUnit.DAYS).withDayOfMonth(1).toInstant().toEpochMilli();
String requestKey = user.getTenantId().getId() + ":" + limitType;
if (Objects.equals(aiCreditsRequests.put(requestKey, month), month)) {
return;
}
try {
NotificationTarget sysAdmins = notificationTargetService.findNotificationTargetsByTenantIdAndUsersFilterType(TenantId.SYS_TENANT_ID, UsersFilterType.SYSTEM_ADMINISTRATORS)
.stream().findFirst()
.orElseThrow(() -> new IllegalArgumentException("Notification target for 'System administrators' not found"));
String baseUrl = systemSecurityService.getBaseUrl(TenantId.SYS_TENANT_ID, new CustomerId(EntityId.NULL_UUID), request);
Tenant tenant = tenantService.findTenantById(user.getTenantId());
String limitDescription;
if (pool) {
limitDescription = "all AI credits of this installation's license";
} else {
long limit = tenantProfileCache.get(user.getTenantId()).getDefaultProfileConfiguration().getMaxAiCredits();
limitDescription = String.format("its monthly limit of %,d AI credits", limit);
}
NotificationInfo info = AiCreditsLimitIncreaseRequestNotificationInfo.builder()
.userEmail(user.getEmail())
.tenantName(tenant != null ? tenant.getName() : user.getTenantId().toString())
.limitDescription(limitDescription)
.increaseLimitActionLabel(pool ? "Add credits" : "Set new limit")
.increaseLimitLink(pool ? "/license" : "/tenants/" + user.getTenantId())
.baseUrl(baseUrl)
.build();
notificationCenter.sendSystemNotification(TenantId.SYS_TENANT_ID, sysAdmins.getId(), NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST, info);
} catch (Exception e) {
aiCreditsRequests.remove(requestKey, month);
throw e;
}
}
@ApiOperation(value = "Get notification request preview (getNotificationRequestPreview)", @ApiOperation(value = "Get notification request preview (getNotificationRequestPreview)",
notes = "Returns preview for notification request." + NEW_LINE + notes = "Returns preview for notification request." + NEW_LINE +
"`processedTemplates` shows how the notifications for each delivery method will look like " + "`processedTemplates` shows how the notifications for each delivery method will look like " +

17
application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java

@ -20,17 +20,21 @@ import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.NotificationRuleId; import org.thingsboard.server.common.data.id.NotificationRuleId;
import org.thingsboard.server.common.data.id.NotificationTargetId;
import org.thingsboard.server.common.data.notification.rule.NotificationRule; import org.thingsboard.server.common.data.notification.rule.NotificationRule;
import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo; import org.thingsboard.server.common.data.notification.rule.NotificationRuleInfo;
import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType; import org.thingsboard.server.common.data.notification.rule.trigger.config.NotificationRuleTriggerType;
import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
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.permission.Operation; import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.config.annotations.ApiOperation; import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.dao.notification.NotificationRuleService; import org.thingsboard.server.dao.notification.NotificationRuleService;
import org.thingsboard.server.dao.notification.NotificationTemplateService;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List;
import java.util.UUID; import java.util.UUID;
import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION; import static org.thingsboard.server.common.data.permission.Resource.NOTIFICATION;
@ -52,6 +56,7 @@ import static org.thingsboard.server.controller.ControllerConstants.SYSTEM_OR_TE
public class NotificationRuleController extends BaseController { public class NotificationRuleController extends BaseController {
private final NotificationRuleService notificationRuleService; private final NotificationRuleService notificationRuleService;
private final NotificationTemplateService notificationTemplateService;
@ApiOperation(value = "Save notification rule (saveNotificationRule)", @ApiOperation(value = "Save notification rule (saveNotificationRule)",
notes = "Creates or updates notification rule. " + NEW_LINE + notes = "Creates or updates notification rule. " + NEW_LINE +
@ -106,11 +111,23 @@ public class NotificationRuleController extends BaseController {
@AuthenticationPrincipal SecurityUser user) throws Exception { @AuthenticationPrincipal SecurityUser user) throws Exception {
notificationRule.setTenantId(user.getTenantId()); notificationRule.setTenantId(user.getTenantId());
checkEntity(notificationRule.getId(), notificationRule, NOTIFICATION); checkEntity(notificationRule.getId(), notificationRule, NOTIFICATION);
if (notificationRule.getTemplateId() != null) {
checkTemplateReportUser(notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId()));
}
NotificationRuleTriggerType triggerType = notificationRule.getTriggerType(); NotificationRuleTriggerType triggerType = notificationRule.getTriggerType();
if ((user.isTenantAdmin() && !triggerType.isTenantLevel()) || (user.isSystemAdmin() && triggerType.isTenantLevel())) { if ((user.isTenantAdmin() && !triggerType.isTenantLevel()) || (user.isSystemAdmin() && triggerType.isTenantLevel())) {
throw new IllegalArgumentException("Trigger type " + triggerType + " is not available"); throw new IllegalArgumentException("Trigger type " + triggerType + " is not available");
} }
NotificationTemplate template = notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId());
if (template == null || !(template.getTenantId().equals(user.getTenantId()) || template.getTenantId().isSysTenantId())) {
throw new IllegalArgumentException("Notification template not found");
}
for (List<UUID> targets : notificationRule.getRecipientsConfig().getTargetsTable().values()) {
for (UUID targetId : targets) {
checkNotificationTargetId(new NotificationTargetId(targetId), Operation.READ);
}
}
return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule); return doSaveAndLog(EntityType.NOTIFICATION_RULE, notificationRule, notificationRuleService::saveNotificationRule);
} }

1
application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java

@ -106,6 +106,7 @@ public class NotificationTemplateController extends BaseController {
public NotificationTemplate saveNotificationTemplate(@RequestBody @Valid NotificationTemplate notificationTemplate) throws Exception { public NotificationTemplate saveNotificationTemplate(@RequestBody @Valid NotificationTemplate notificationTemplate) throws Exception {
notificationTemplate.setTenantId(getTenantId()); notificationTemplate.setTenantId(getTenantId());
checkEntity(notificationTemplate.getId(), notificationTemplate, NOTIFICATION); checkEntity(notificationTemplate.getId(), notificationTemplate, NOTIFICATION);
checkTemplateReportUser(notificationTemplate);
return doSaveAndLog(EntityType.NOTIFICATION_TEMPLATE, notificationTemplate, notificationTemplateService::saveNotificationTemplate); return doSaveAndLog(EntityType.NOTIFICATION_TEMPLATE, notificationTemplate, notificationTemplateService::saveNotificationTemplate);
} }

8
application/src/main/java/org/thingsboard/server/controller/ReportController.java

@ -248,9 +248,10 @@ public class ReportController extends BaseController {
public ResponseEntity<ByteArrayResource> testReportAndDownload(@RequestBody ReportRequest reportRequest) throws Exception { public ResponseEntity<ByteArrayResource> testReportAndDownload(@RequestBody ReportRequest reportRequest) throws Exception {
checkFeatureAllowed(PlatformFeature.REPORTING); checkFeatureAllowed(PlatformFeature.REPORTING);
SecurityUser currentUser = getCurrentUser(); SecurityUser currentUser = getCurrentUser();
UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(UUID.fromString(reportRequest.getUserId())) : getCurrentUser().getId(); UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(toUUID(reportRequest.getUserId())) : currentUser.getId();
EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId); checkReportUser(userId);
checkUserOwnerPermission(currentUser, userId); checkUserOwnerPermission(currentUser, userId);
EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId);
AccessJwtToken accessToken = systemSecurityService.createUserAccessToken(currentUser.getTenantId(), userId); AccessJwtToken accessToken = systemSecurityService.createUserAccessToken(currentUser.getTenantId(), userId);
ReportTemplateConfig configuration = reportRequest.getReportTemplateConfig(); ReportTemplateConfig configuration = reportRequest.getReportTemplateConfig();
if (configuration == null) { if (configuration == null) {
@ -301,7 +302,8 @@ public class ReportController extends BaseController {
SecurityUser currentUser = getCurrentUser(); SecurityUser currentUser = getCurrentUser();
UserId userId; UserId userId;
if (StringUtils.isNotEmpty(reportRequest.getUserId())) { if (StringUtils.isNotEmpty(reportRequest.getUserId())) {
userId = new UserId(UUID.fromString(reportRequest.getUserId())); userId = new UserId(toUUID(reportRequest.getUserId()));
checkReportUser(userId);
checkUserOwnerPermission(currentUser, userId); checkUserOwnerPermission(currentUser, userId);
} else { } else {
userId = currentUser.getId(); userId = currentUser.getId();

3
application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java

@ -158,8 +158,7 @@ public class RuleEngineController extends BaseController {
} else { } else {
entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr); entityId = EntityIdFactory.getByTypeAndId(entityType, entityIdStr);
} }
//Check that this is a valid JSON checkMsgReportUser(JacksonUtil.toJsonNode(requestBody));
JacksonUtil.toJsonNode(requestBody);
final DeferredResult<ResponseEntity> response = new DeferredResult<>(); final DeferredResult<ResponseEntity> response = new DeferredResult<>();
accessValidator.validate(currentUser, Operation.WRITE, entityId, new HttpValidationCallback(response, new FutureCallback<DeferredResult<ResponseEntity>>() { accessValidator.validate(currentUser, Operation.WRITE, entityId, new HttpValidationCallback(response, new FutureCallback<DeferredResult<ResponseEntity>>() {
@Override @Override

24
application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller; package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.ArraySchema;
@ -21,7 +22,9 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.edge.Edge; import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EdgeId; import org.thingsboard.server.common.data.id.EdgeId;
@ -161,11 +164,26 @@ public class SchedulerEventController extends BaseController {
private void checkEventConfigPermissions(SchedulerEvent schedulerEvent) throws ThingsboardException { private void checkEventConfigPermissions(SchedulerEvent schedulerEvent) throws ThingsboardException {
if (GENERATE_REPORT.equals(schedulerEvent.getType())) { if (GENERATE_REPORT.equals(schedulerEvent.getType())) {
SecurityUser currentUser = getCurrentUser(); SecurityUser currentUser = getCurrentUser();
ReportConfig reportConfig = checkNotNull(JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class), ReportConfig reportConfig = JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class);
"Report scheduler event configuration should be specified!"); if (reportConfig == null) {
throw new ThingsboardException("Report scheduler event configuration should be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
checkReportTemplateId(reportConfig.getReportTemplateId(), Operation.READ); checkReportTemplateId(reportConfig.getReportTemplateId(), Operation.READ);
UserId reportUserId = checkNotNull(reportConfig.getUserId(), "Report user must be specified!"); UserId reportUserId = reportConfig.getUserId();
if (reportUserId == null) {
throw new ThingsboardException("Report user must be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
checkReportUser(reportUserId);
checkUserOwnerPermission(currentUser, reportUserId); checkUserOwnerPermission(currentUser, reportUserId);
} else if (schedulerEvent.getConfiguration() != null) {
if (schedulerEvent.getConfiguration().path("msgBody").path("reportConfig") instanceof ObjectNode reportConfig
&& reportConfig.path("useCurrentUserCredentials").asBoolean(false)
&& reportConfig.path("userId").isTextual()
&& StringUtils.isNotBlank(reportConfig.get("userId").asText())) {
UserId reportUserId = resolveReportUser(new UserId(toUUID(reportConfig.get("userId").asText())), true);
reportConfig.put("userId", reportUserId.toString());
}
checkMsgReportUser(schedulerEvent.getConfiguration().path("msgBody"));
} }
} }

3
application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java

@ -64,6 +64,9 @@ public class SelfRegistrationController extends BaseController {
if (selfRegistrationParams.getNotificationRecipient() != null) { if (selfRegistrationParams.getNotificationRecipient() != null) {
checkNotificationTargetId(selfRegistrationParams.getNotificationRecipient(), Operation.READ); checkNotificationTargetId(selfRegistrationParams.getNotificationRecipient(), Operation.READ);
} }
if (selfRegistrationParams.getDomainId() != null) {
checkDomainId(selfRegistrationParams.getDomainId(), Operation.READ);
}
if (Authority.TENANT_ADMIN.equals(authority)) { if (Authority.TENANT_ADMIN.equals(authority)) {
savedSelfRegistrationParams = whiteLabelingService.saveTenantSelfRegistrationParams(getTenantId(), selfRegistrationParams); savedSelfRegistrationParams = whiteLabelingService.saveTenantSelfRegistrationParams(getTenantId(), selfRegistrationParams);
JsonNode privacyPolicyNode = whiteLabelingService.getTenantPrivacyPolicy(securityUser.getTenantId()); JsonNode privacyPolicyNode = whiteLabelingService.getTenantPrivacyPolicy(securityUser.getTenantId());

41
application/src/main/java/org/thingsboard/server/controller/SignUpController.java

@ -79,7 +79,6 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.UserPrincipal; import org.thingsboard.server.service.security.model.UserPrincipal;
import org.thingsboard.server.service.security.model.token.JwtTokenFactory; import org.thingsboard.server.service.security.model.token.JwtTokenFactory;
import org.thingsboard.server.service.security.system.SystemSecurityService; import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.utils.MiscUtils;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
@ -209,7 +208,7 @@ public class SignUpController extends BaseController {
UserCredentials savedUserCredentials = saveUserCredentials(savedUser, signUpRequest); UserCredentials savedUserCredentials = saveUserCredentials(savedUser, signUpRequest);
try { try {
sendEmailVerification(tenantId, request, savedUserCredentials, email, null, signUpRequest.getPkgName(), signUpRequest.getPlatform()); sendEmailVerification(tenantId, request, savedUser, savedUserCredentials, email, signUpRequest.getPkgName(), signUpRequest.getPlatform());
} catch (ThingsboardException e) { } catch (ThingsboardException e) {
customerService.deleteCustomer(tenantId, savedCustomer.getId()); customerService.deleteCustomer(tenantId, savedCustomer.getId());
throw e; throw e;
@ -227,11 +226,9 @@ public class SignUpController extends BaseController {
return SignUpResult.SUCCESS; return SignUpResult.SUCCESS;
} }
private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, UserCredentials userCredentials, private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, User user, UserCredentials userCredentials,
String targetEmail, String baseUrl, String pkgName, PlatformType platformType) throws ThingsboardException { String targetEmail, String pkgName, PlatformType platformType) throws ThingsboardException {
if (baseUrl == null) { String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request);
baseUrl = MiscUtils.constructBaseUrl(request);
}
String activationLink = String.format("%s/api/noauth/activateEmail?emailCode=%s", baseUrl, userCredentials.getActivateToken()); String activationLink = String.format("%s/api/noauth/activateEmail?emailCode=%s", baseUrl, userCredentials.getActivateToken());
if (!StringUtils.isEmpty(pkgName)) { if (!StringUtils.isEmpty(pkgName)) {
checkNotNull(platformType); checkNotNull(platformType);
@ -265,7 +262,7 @@ public class SignUpController extends BaseController {
} }
@ApiOperation(value = "Resend Activation Email (resendEmailActivation)", @ApiOperation(value = "Resend Activation Email (resendEmailActivation)",
notes = "Request to resend the activation email for the user. Checks that user was not activated yet.") notes = "Request to resend the activation email for a user who signed up through this domain or mobile application and has not verified the email yet.")
@PostMapping(value = "/noauth/resendEmailActivation") @PostMapping(value = "/noauth/resendEmailActivation")
public void resendEmailActivation( public void resendEmailActivation(
@Parameter(description = "Email of the user.", required = true, example = "john.doe@company.com") @Parameter(description = "Email of the user.", required = true, example = "john.doe@company.com")
@ -285,19 +282,17 @@ public class SignUpController extends BaseController {
} }
User existingUser = userService.findUserByEmail(TenantId.SYS_TENANT_ID, email); User existingUser = userService.findUserByEmail(TenantId.SYS_TENANT_ID, email);
if (existingUser != null) { if (existingUser == null || !tenantId.equals(existingUser.getTenantId())) {
UserCredentials credentials = userService.findUserCredentialsByUserId(existingUser.getTenantId(), existingUser.getId());
if (credentials.isEnabled()) {
throw new DataValidationException("User with email '" + existingUser.getEmail() + "' "
+ " is already active!");
} else {
credentials = userService.checkUserActivationToken(tenantId, credentials);
sendEmailVerification(tenantId, request, credentials, email, null, pkgName, platform);
}
} else {
throw new DataValidationException("User with email '" + email + "' " throw new DataValidationException("User with email '" + email + "' "
+ " is not registered!"); + " is not registered!");
} }
UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, existingUser.getId());
if (credentials.isEnabled() || credentials.getActivateToken() == null || credentials.getPassword() == null) {
throw new DataValidationException("User with email '" + existingUser.getEmail() + "' "
+ " is already active!");
}
credentials = userService.checkUserActivationToken(tenantId, credentials);
sendEmailVerification(tenantId, request, existingUser, credentials, email, pkgName, platform);
} }
@ApiOperation(value = "Activate User using code from Email (activateEmail)", @ApiOperation(value = "Activate User using code from Email (activateEmail)",
@ -395,16 +390,19 @@ public class SignUpController extends BaseController {
if (userCredentials.getPassword() == null) { if (userCredentials.getPassword() == null) {
throw new ThingsboardException("Unable to activate user!", ThingsboardErrorCode.PERMISSION_DENIED); throw new ThingsboardException("Unable to activate user!", ThingsboardErrorCode.PERMISSION_DENIED);
} }
User user = userService.findUserById(TenantId.SYS_TENANT_ID, userCredentials.getUserId());
if (user == null || !tenantId.equals(user.getTenantId())) {
throw new ThingsboardException("Invalid email code!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
String encodedPassword = userCredentials.getPassword(); String encodedPassword = userCredentials.getPassword();
UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword); UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword);
User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
long acceptedTs = System.currentTimeMillis(); long acceptedTs = System.currentTimeMillis();
user.setPrivacyPolicyAccepted(acceptedTs); user.setPrivacyPolicyAccepted(acceptedTs);
user.setTermsOfUseAccepted(acceptedTs); user.setTermsOfUseAccepted(acceptedTs);
user = userService.saveUser(tenantId, user); user = userService.saveUser(tenantId, user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail()); UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false)); SecurityUser securityUser = new SecurityUser(user, credentials.isEnabled(), principal, getMergedUserPermissions(user, false));
String baseUrl = MiscUtils.constructBaseUrl(request); String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request);
String loginUrl; String loginUrl;
if (!StringUtils.isEmpty(pkgName)) { if (!StringUtils.isEmpty(pkgName)) {
loginUrl = UriComponentsBuilder.fromUriString(baseUrl).path("/api/noauth/login") loginUrl = UriComponentsBuilder.fromUriString(baseUrl).path("/api/noauth/login")
@ -574,10 +572,11 @@ public class SignUpController extends BaseController {
List<GroupPermission> permissions = selfRegistrationParams.getPermissions(); List<GroupPermission> permissions = selfRegistrationParams.getPermissions();
for (GroupPermission permission : permissions) { for (GroupPermission permission : permissions) {
permission.setId(null);
permission.setTenantId(tenantId); permission.setTenantId(tenantId);
permission.setUserGroupId(usersEntityGroup.getId()); permission.setUserGroupId(usersEntityGroup.getId());
if (permission.getEntityGroupId() != null) { if (permission.getEntityGroupId() != null) {
EntityGroup entityGroup = entityGroupService.findEntityGroupById(tenantId, permission.getEntityGroupId()); EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, permission.getEntityGroupId());
if (entityGroup != null) { if (entityGroup != null) {
permission.setEntityGroupType(entityGroup.getType()); permission.setEntityGroupType(entityGroup.getType());
groupPermissionService.saveGroupPermission(tenantId, permission); groupPermissionService.saveGroupPermission(tenantId, permission);

3
application/src/main/java/org/thingsboard/server/controller/UsageInfoController.java

@ -12,7 +12,6 @@ import org.springframework.web.bind.annotation.RestController;
import org.thingsboard.server.common.data.UsageInfo; import org.thingsboard.server.common.data.UsageInfo;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
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.dao.usage.UsageInfoService; import org.thingsboard.server.dao.usage.UsageInfoService;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
@ -30,7 +29,7 @@ public class UsageInfoController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')") @PreAuthorize("hasAuthority('TENANT_ADMIN')")
@GetMapping(value = "/usage") @GetMapping(value = "/usage")
public UsageInfo getTenantUsageInfo() throws ThingsboardException { public UsageInfo getTenantUsageInfo() throws ThingsboardException {
if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermission(Resource.ALL, Operation.READ)) { if (!getMergedUserPermissions(getCurrentUser(), false).hasGenericPermissionExceptAi(Operation.READ)) {
throw new ThingsboardException("You don't have permission to read UsageInfo!", PERMISSION_DENIED); throw new ThingsboardException("You don't have permission to read UsageInfo!", PERMISSION_DENIED);
} }
return checkNotNull(usageInfoService.getUsageInfo(getCurrentUser().getTenantId())); return checkNotNull(usageInfoService.getUsageInfo(getCurrentUser().getTenantId()));

4
application/src/main/java/org/thingsboard/server/controller/UserController.java

@ -292,7 +292,7 @@ public class UserController extends BaseController {
HttpServletRequest request) throws ThingsboardException { HttpServletRequest request) throws ThingsboardException {
SecurityUser securityUser = getCurrentUser(); SecurityUser securityUser = getCurrentUser();
User user = checkNotNull(userService.findUserByEmail(securityUser.getTenantId(), email)); User user = checkNotNull(userService.findUserByEmail(securityUser.getTenantId(), email));
accessControlService.checkPermission(securityUser, Resource.USER, Operation.READ, user.getId(), user); accessControlService.checkPermission(securityUser, Resource.USER, Operation.WRITE, user.getId(), user);
UserActivationLink activationLink = tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), user.getId(), request); UserActivationLink activationLink = tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), user.getId(), request);
try { try {
@ -323,7 +323,7 @@ public class UserController extends BaseController {
HttpServletRequest request) throws ThingsboardException { HttpServletRequest request) throws ThingsboardException {
checkParameter(USER_ID, strUserId); checkParameter(USER_ID, strUserId);
UserId userId = new UserId(toUUID(strUserId)); UserId userId = new UserId(toUUID(strUserId));
checkUserId(userId, Operation.READ); checkUserId(userId, Operation.WRITE);
SecurityUser securityUser = getCurrentUser(); SecurityUser securityUser = getCurrentUser();
return tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), userId, request); return tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), userId, request);
} }

20
application/src/main/java/org/thingsboard/server/exception/AiCreditsExceededException.java

@ -0,0 +1,20 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.exception;
import lombok.Getter;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
@Getter
public class AiCreditsExceededException extends ThingsboardRuntimeException {
public static final String TENANT_LIMIT = "TENANT";
private final String limitType;
public AiCreditsExceededException(String limitType) {
super("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS);
this.limitType = limitType;
}
}

28
application/src/main/java/org/thingsboard/server/exception/ThingsboardAiCreditsExceededResponse.java

@ -0,0 +1,28 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.exception;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.http.HttpStatus;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
@Schema
public class ThingsboardAiCreditsExceededResponse extends ThingsboardErrorResponse {
private final String aiCreditsLimit;
protected ThingsboardAiCreditsExceededResponse(String message, String aiCreditsLimit) {
super(message, ThingsboardErrorCode.TOO_MANY_REQUESTS, HttpStatus.TOO_MANY_REQUESTS);
this.aiCreditsLimit = aiCreditsLimit;
}
public static ThingsboardAiCreditsExceededResponse of(String message, String aiCreditsLimit) {
return new ThingsboardAiCreditsExceededResponse(message, aiCreditsLimit);
}
@Schema(description = "Which AI credits limit is used up: TENANT for the tenant's monthly limit", accessMode = Schema.AccessMode.READ_ONLY)
public String getAiCreditsLimit() {
return aiCreditsLimit;
}
}

9
application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java

@ -12,7 +12,7 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hibernate.exception.ConstraintViolationException; import org.hibernate.exception.ConstraintViolationException;
import org.springframework.boot.web.servlet.error.ErrorController; import org.springframework.boot.webmvc.error.ErrorController;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -93,6 +93,7 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand
errorCodeToStatusMap.put(ThingsboardErrorCode.ENTITIES_LIMIT_EXCEEDED, HttpStatus.FORBIDDEN); errorCodeToStatusMap.put(ThingsboardErrorCode.ENTITIES_LIMIT_EXCEEDED, HttpStatus.FORBIDDEN);
errorCodeToStatusMap.put(ThingsboardErrorCode.VERSION_CONFLICT, HttpStatus.CONFLICT); errorCodeToStatusMap.put(ThingsboardErrorCode.VERSION_CONFLICT, HttpStatus.CONFLICT);
errorCodeToStatusMap.put(ThingsboardErrorCode.SETUP_INCOMPLETE, HttpStatus.LOCKED); errorCodeToStatusMap.put(ThingsboardErrorCode.SETUP_INCOMPLETE, HttpStatus.LOCKED);
errorCodeToStatusMap.put(ThingsboardErrorCode.SERVICE_UNAVAILABLE, HttpStatus.SERVICE_UNAVAILABLE);
} }
private static ThingsboardErrorCode statusToErrorCode(HttpStatus status) { private static ThingsboardErrorCode statusToErrorCode(HttpStatus status) {
@ -198,6 +199,12 @@ public class ThingsboardErrorResponseHandler extends ResponseEntityExceptionHand
} }
private void handleThingsboardRuntimeException(ThingsboardRuntimeException thingsboardRuntimeException, HttpServletResponse response) throws IOException { private void handleThingsboardRuntimeException(ThingsboardRuntimeException thingsboardRuntimeException, HttpServletResponse response) throws IOException {
if (thingsboardRuntimeException instanceof AiCreditsExceededException aiCreditsExceeded) {
response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
JacksonUtil.writeValue(response.getWriter(),
ThingsboardAiCreditsExceededResponse.of(aiCreditsExceeded.getMessage(), aiCreditsExceeded.getLimitType()));
return;
}
ThingsboardErrorCode errorCode = thingsboardRuntimeException.getErrorCode(); ThingsboardErrorCode errorCode = thingsboardRuntimeException.getErrorCode();
HttpStatus status = errorCodeToStatus(errorCode); HttpStatus status = errorCodeToStatus(errorCode);
response.setStatus(status.value()); response.setStatus(status.value());

2
application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java

@ -226,7 +226,7 @@ public class ThingsboardInstallService {
} catch (EntityCapExceededException e) { } catch (EntityCapExceededException e) {
// A deliberate pre-flight refusal: report the plain policy message, not an unexpected failure. // A deliberate pre-flight refusal: report the plain policy message, not an unexpected failure.
throw new ThingsboardInstallException(e.getMessage(), e); throw new ThingsboardInstallException(e.getMessage(), e);
} catch (Exception e) { } catch (Throwable e) {
log.error("Unexpected error during ThingsBoard installation!", e); log.error("Unexpected error during ThingsBoard installation!", e);
throw new ThingsboardInstallException("Unexpected error during ThingsBoard installation!", e); throw new ThingsboardInstallException("Unexpected error during ThingsBoard installation!", e);
} finally { } finally {

9
application/src/main/java/org/thingsboard/server/service/ai/DefaultTbAiService.java

@ -17,6 +17,7 @@ import org.thingsboard.server.common.data.ApiUsageRecordKey;
import org.thingsboard.server.common.data.User; import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.stats.TbApiUsageReportClient; import org.thingsboard.server.common.stats.TbApiUsageReportClient;
import org.thingsboard.server.exception.AiCreditsExceededException;
import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException; import org.thingsboard.server.service.ai.transport.TbAiChannelRejectedException;
@ -152,9 +153,9 @@ class DefaultTbAiService implements TbAiService {
private static String toUserFriendlyMessage(Throwable e) { private static String toUserFriendlyMessage(Throwable e) {
if (e instanceof TimeoutException) { if (e instanceof TimeoutException) {
return "Request timed out"; return TbAiOperations.TIMED_OUT_MESSAGE;
} else if (e instanceof TbAiChannelUnavailableException) { } else if (e instanceof TbAiChannelUnavailableException) {
return "Service unavailable"; return TbAiOperations.UNAVAILABLE_MESSAGE;
} else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) { } else if (e instanceof TbAiChannelRejectedException || e instanceof ThingsboardRuntimeException) {
return e.getMessage(); return e.getMessage();
} }
@ -176,13 +177,15 @@ class DefaultTbAiService implements TbAiService {
case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND; case 404 -> ThingsboardErrorCode.ITEM_NOT_FOUND;
case 409 -> ThingsboardErrorCode.VERSION_CONFLICT; case 409 -> ThingsboardErrorCode.VERSION_CONFLICT;
case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS; case 429 -> ThingsboardErrorCode.TOO_MANY_REQUESTS;
case 401, 403 -> ThingsboardErrorCode.PERMISSION_DENIED;
case 502, 503, 504 -> ThingsboardErrorCode.SERVICE_UNAVAILABLE;
default -> ThingsboardErrorCode.GENERAL; default -> ThingsboardErrorCode.GENERAL;
}; };
} }
private void checkApiUsage(SecurityUser user) { private void checkApiUsage(SecurityUser user) {
if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) { if (!apiUsageStateService.getApiUsageState(user.getTenantId()).isAiEnabled()) {
throw new ThingsboardRuntimeException("Out of AI credits", ThingsboardErrorCode.TOO_MANY_REQUESTS); throw new AiCreditsExceededException(AiCreditsExceededException.TENANT_LIMIT);
} }
} }

4
application/src/main/java/org/thingsboard/server/service/ai/chat/AiChatService.java

@ -15,8 +15,12 @@ public interface AiChatService {
void updateChat(UUID chatId, JsonNode request, SecurityUser user); void updateChat(UUID chatId, JsonNode request, SecurityUser user);
void stopChat(UUID chatId, SecurityUser user);
JsonNode listChats(SecurityUser user); JsonNode listChats(SecurityUser user);
JsonNode listChatStatuses(SecurityUser user);
JsonNode getChatMessages(UUID chatId, SecurityUser user); JsonNode getChatMessages(UUID chatId, SecurityUser user);
void deleteChat(UUID chatId, SecurityUser user); void deleteChat(UUID chatId, SecurityUser user);

26
application/src/main/java/org/thingsboard/server/service/ai/chat/DefaultAiChatService.java

@ -9,6 +9,8 @@ import org.springframework.stereotype.Service;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.ChatOperationRequest; import org.thingsboard.ai.common.channel.ChatOperationRequest;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.cache.limits.RateLimitService;
import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperation;
@ -27,15 +29,17 @@ import java.util.UUID;
class DefaultAiChatService implements AiChatService { class DefaultAiChatService implements AiChatService {
private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true); private static final JsonNode TOOL_CARDS = JacksonUtil.newObjectNode().put("toolCards", true);
static final String RATE_LIMITED = "RATE_LIMITED";
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiTransport tbAiTransport; private final TbAiTransport tbAiTransport;
private final TbAiOperations operations; private final TbAiOperations operations;
private final RateLimitService rateLimitService;
@Override @Override
public JsonNode createChat(JsonNode request, SecurityUser user) { public JsonNode createChat(JsonNode request, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute( return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, false); new TbAiOperation(ChannelProtocol.CHAT_CREATE, new ChatOperationRequest(null, request)), user, tokenProvider), user, true);
} }
@Override @Override
@ -50,12 +54,24 @@ class DefaultAiChatService implements AiChatService {
new TbAiOperation(ChannelProtocol.CHAT_LIST, null), user, tokenProvider), user, false); new TbAiOperation(ChannelProtocol.CHAT_LIST, null), user, tokenProvider), user, false);
} }
@Override
public JsonNode listChatStatuses(SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_STATUS, null), user, tokenProvider), user, false);
}
@Override @Override
public JsonNode getChatMessages(UUID chatId, SecurityUser user) { public JsonNode getChatMessages(UUID chatId, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute( return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false); new TbAiOperation(ChannelProtocol.CHAT_MESSAGES, new ChatOperationRequest(chatId, TOOL_CARDS)), user, tokenProvider), user, false);
} }
@Override
public void stopChat(UUID chatId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.CHAT_STOP, new ChatOperationRequest(chatId, null)), user, tokenProvider), user, false);
}
@Override @Override
public void deleteChat(UUID chatId, SecurityUser user) { public void deleteChat(UUID chatId, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute( tbAiService.process(tokenProvider -> operations.execute(
@ -67,6 +83,14 @@ class DefaultAiChatService implements AiChatService {
UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin, UUID chatId, JsonNode request, String tbAccessToken, String acceptLanguage, String clientOrigin,
SecurityUser user SecurityUser user
) { ) {
if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) {
return Flux.just(ServerSentEvent.<String>builder()
.event("error")
.data(JacksonUtil.toString(JacksonUtil.newObjectNode()
.put("message", "Rate limit exceeded")
.put("code", RATE_LIMITED)))
.build());
}
var link = new TbAiTurnLink(); var link = new TbAiTurnLink();
return tbAiService.processStream(chatId, tokenProvider -> { return tbAiService.processStream(chatId, tokenProvider -> {
var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin); var context = new TbAiTurnContext(user, tbAccessToken, acceptLanguage, tokenProvider, clientOrigin);

6
application/src/main/java/org/thingsboard/server/service/ai/solution/AiSolutionService.java

@ -25,10 +25,16 @@ public interface AiSolutionService {
void clearStep(UUID solutionId, SolutionStep step, SecurityUser user); void clearStep(UUID solutionId, SolutionStep step, SecurityUser user);
JsonNode stopSolution(UUID solutionId, SecurityUser user);
JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user); JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user); JsonNode uninstallSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user);
void deleteSolution(UUID solutionId, SecurityUser user); void deleteSolution(UUID solutionId, SecurityUser user);
void updateSolution(UUID solutionId, JsonNode request, SecurityUser user);
JsonNode getInstallProgress(UUID solutionId, SecurityUser user);
} }

27
application/src/main/java/org/thingsboard/server/service/ai/solution/DefaultAiSolutionService.java

@ -10,12 +10,15 @@ import org.thingsboard.ai.common.data.solution.SolutionStep;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.exception.ThingsboardRuntimeException; import org.thingsboard.server.exception.ThingsboardRuntimeException;
import org.thingsboard.server.common.data.util.CollectionsUtil; import org.thingsboard.server.common.data.util.CollectionsUtil;
import org.thingsboard.server.cache.limits.RateLimitService;
import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.SolutionChatRequest; import org.thingsboard.ai.common.channel.SolutionChatRequest;
import org.thingsboard.ai.common.channel.SolutionDataRequest; import org.thingsboard.ai.common.channel.SolutionDataRequest;
import org.thingsboard.ai.common.channel.SolutionOperationRequest; import org.thingsboard.ai.common.channel.SolutionOperationRequest;
import org.thingsboard.ai.common.channel.SolutionStepRequest; import org.thingsboard.ai.common.channel.SolutionStepRequest;
import org.thingsboard.ai.common.channel.SolutionUpdateRequest;
import org.thingsboard.server.service.ai.TbAiService; import org.thingsboard.server.service.ai.TbAiService;
import org.thingsboard.server.service.ai.transport.TbAiOperation; import org.thingsboard.server.service.ai.transport.TbAiOperation;
import org.thingsboard.server.service.ai.transport.TbAiOperations; import org.thingsboard.server.service.ai.transport.TbAiOperations;
@ -32,11 +35,12 @@ public class DefaultAiSolutionService implements AiSolutionService {
private final TbAiService tbAiService; private final TbAiService tbAiService;
private final TbAiOperations operations; private final TbAiOperations operations;
private final RateLimitService rateLimitService;
@Override @Override
public JsonNode startNew(SecurityUser user) { public JsonNode startNew(SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute( return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user, false); new TbAiOperation(ChannelProtocol.SOLUTION_START, null), user, tokenProvider), user);
} }
@Override @Override
@ -58,6 +62,9 @@ public class DefaultAiSolutionService implements AiSolutionService {
if (StringUtils.isBlank(text) && attached == null) { if (StringUtils.isBlank(text) && attached == null) {
throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS); throw new ThingsboardRuntimeException("Message cannot be blank", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
} }
if (!rateLimitService.checkRateLimit(LimitedApi.AI_CHAT_REQUESTS, user.getTenantId())) {
throw new ThingsboardRuntimeException("Rate limit exceeded", ThingsboardErrorCode.TOO_MANY_REQUESTS);
}
return tbAiService.process(tokenProvider -> operations.execute( return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user); new TbAiOperation(ChannelProtocol.SOLUTION_CHAT, new SolutionChatRequest(solutionId, step, text, attached)), user, tokenProvider), user);
} }
@ -80,6 +87,12 @@ public class DefaultAiSolutionService implements AiSolutionService {
new TbAiOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step)), user, tokenProvider), user, false); new TbAiOperation(ChannelProtocol.SOLUTION_STEP_CLEAR, new SolutionStepRequest(solutionId, step)), user, tokenProvider), user, false);
} }
@Override
public JsonNode stopSolution(UUID solutionId, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_STOP, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
}
@Override @Override
public JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) { public JsonNode installSolution(UUID solutionId, String tbAccessToken, String clientOrigin, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute( return tbAiService.process(tokenProvider -> operations.execute(
@ -100,4 +113,16 @@ public class DefaultAiSolutionService implements AiSolutionService {
new TbAiOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false); new TbAiOperation(ChannelProtocol.SOLUTION_DELETE, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
} }
@Override
public void updateSolution(UUID solutionId, JsonNode request, SecurityUser user) {
tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_UPDATE, new SolutionUpdateRequest(solutionId, request)), user, tokenProvider), user, false);
}
@Override
public JsonNode getInstallProgress(UUID solutionId, SecurityUser user) {
return tbAiService.process(tokenProvider -> operations.execute(
new TbAiOperation(ChannelProtocol.SOLUTION_PROGRESS, new SolutionOperationRequest(solutionId)), user, tokenProvider), user, false);
}
} }

12
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiOperations.java

@ -52,7 +52,7 @@ class ChannelTbAiOperations {
} catch (NotStartedException e) { } catch (NotStartedException e) {
if (attempt >= 2) { if (attempt >= 2) {
log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage()); log.warn("AI channel operation '{}' was refused twice: {}", operation.type(), e.getMessage());
return failure("Service unavailable"); return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE);
} }
log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage()); log.debug("AI channel operation '{}' was not started ({}), retrying on a new channel", operation.type(), e.getMessage());
fresh = true; fresh = true;
@ -76,8 +76,8 @@ class ChannelTbAiOperations {
} }
} }
static TbAiResponse failure(String message) { static TbAiResponse failure(HttpStatus status, String message) {
return TbAiResponse.builder().success(false).error(message).build(); return TbAiResponse.builder().success(false).status(status.value()).error(message).build();
} }
static TbAiResponse toResponse(OperationResult result) { static TbAiResponse toResponse(OperationResult result) {
@ -136,15 +136,15 @@ class ChannelTbAiOperations {
return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); return result.get(OPERATION_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException e) { } catch (InterruptedException e) {
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
return failure("Request interrupted"); return failure(HttpStatus.SERVICE_UNAVAILABLE, "Request interrupted");
} catch (TimeoutException e) { } catch (TimeoutException e) {
return failure("Request timed out"); return failure(HttpStatus.GATEWAY_TIMEOUT, TbAiOperations.TIMED_OUT_MESSAGE);
} catch (ExecutionException e) { } catch (ExecutionException e) {
if (e.getCause() instanceof NotStartedException notStarted) { if (e.getCause() instanceof NotStartedException notStarted) {
throw notStarted; throw notStarted;
} }
log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e)); log.warn("AI channel operation '{}' failed: {}", operation.type(), ExceptionUtils.getRootCauseMessage(e));
return failure("Service unavailable"); return failure(HttpStatus.SERVICE_UNAVAILABLE, TbAiOperations.UNAVAILABLE_MESSAGE);
} finally { } finally {
finish(); finish();
} }

4
application/src/main/java/org/thingsboard/server/service/ai/transport/ChannelTbAiTransport.java

@ -25,7 +25,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or * Runs a chat turn on a pooled channel and re-emits its events as SSE. A turn the channel did not start (refused, or
* closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails * closed with 1001 before any frame for it) is retried once on a new channel; a channel that cannot be opened fails
* the turn with "Service unavailable". * the turn with {@link TbAiOperations#UNAVAILABLE_MESSAGE}.
*/ */
@Slf4j @Slf4j
@Component @Component
@ -166,7 +166,7 @@ class ChannelTbAiTransport implements TbAiTransport {
end(null); end(null);
} else { } else {
log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason); log.warn("[{}] AI channel closed during the turn [{}] {}", chatId, code, reason);
end(errorEvent("Service unavailable")); end(errorEvent(TbAiOperations.UNAVAILABLE_MESSAGE));
} }
} }

38
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelPool.java

@ -2,6 +2,8 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport; package org.thingsboard.server.service.ai.transport;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakeException;
import jakarta.annotation.PreDestroy; import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -13,6 +15,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.channel.ChannelProtocol; import org.thingsboard.ai.common.channel.ChannelProtocol;
import org.thingsboard.ai.common.channel.TbAiChannelClient; import org.thingsboard.ai.common.channel.TbAiChannelClient;
import org.thingsboard.ai.common.client.TbAiClaims;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiHeaders; import org.thingsboard.ai.common.client.TbAiHeaders;
import org.thingsboard.common.util.ThingsBoardThreadFactory; import org.thingsboard.common.util.ThingsBoardThreadFactory;
@ -120,11 +123,17 @@ class TbAiChannelPool {
PoolKey key = new PoolKey(context.tenantId(), context.userId()); PoolKey key = new PoolKey(context.tenantId(), context.userId());
CompletableFuture<TbAiPooledConnection> pending = null; CompletableFuture<TbAiPooledConnection> pending = null;
if (!fresh) { if (!fresh) {
String limits = limitsOf(currentToken(context));
Group group = groups.computeIfAbsent(key, k -> new Group()); Group group = groups.computeIfAbsent(key, k -> new Group());
synchronized (group) { synchronized (group) {
long now = nanoClock.getAsLong(); long now = nanoClock.getAsLong();
for (int i = group.connections.size() - 1; i >= 0; i--) { for (int i = group.connections.size() - 1; i >= 0; i--) {
TbAiPooledConnection connection = group.connections.get(i); TbAiPooledConnection connection = group.connections.get(i);
if (connection.isStaleFor(limits)) {
log.debug("[{}] Retiring an AI channel opened with other limits", key);
connection.retire();
continue;
}
if (connection.tryReserve(now)) { if (connection.tryReserve(now)) {
return CompletableFuture.completedFuture(connection); return CompletableFuture.completedFuture(connection);
} }
@ -185,7 +194,9 @@ class TbAiChannelPool {
private CompletableFuture<TbAiPooledConnection> connect(TbAiTurnContext context, PoolKey key, boolean pooled) { private CompletableFuture<TbAiPooledConnection> connect(TbAiTurnContext context, PoolKey key, boolean pooled) {
var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled, var connection = new TbAiPooledConnection(key, context.clientOrigin(), pooled,
maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong()); maxOperationsPerConnection, channelClient.codec(), this, nanoClock.getAsLong());
channelClient.connect(handshakeTokenProvider(context), connection) String token = currentToken(context);
connection.handshakeLimits(limitsOf(token));
channelClient.connect(handshakeTokenProvider(context, token), connection)
.subscribeOn(Schedulers.boundedElastic()) .subscribeOn(Schedulers.boundedElastic())
.subscribe(connection::opened, error -> connection.failed(toConnectError(error))); .subscribe(connection::opened, error -> connection.failed(toConnectError(error)));
return connection.ready() return connection.ready()
@ -298,13 +309,32 @@ class TbAiChannelPool {
return true; return true;
} }
private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context) { private static String currentToken(TbAiTurnContext context) {
try {
return context.tokenProvider() != null ? context.tokenProvider().getToken() : null;
} catch (RuntimeException e) {
return null;
}
}
static String limitsOf(String token) {
if (token == null) {
return null;
}
try {
return JWT.decode(token).getClaim(TbAiClaims.PROFILE_CONFIG).asString();
} catch (JWTDecodeException e) {
return null;
}
}
private TbAiClient.TokenProvider handshakeTokenProvider(TbAiTurnContext context, String token) {
TbAiClient.TokenProvider delegate = context.tokenProvider(); TbAiClient.TokenProvider delegate = context.tokenProvider();
String acceptLanguage = context.acceptLanguage(); String acceptLanguage = context.acceptLanguage();
return new TbAiClient.TokenProvider() { return new TbAiClient.TokenProvider() {
@Override @Override
public String getToken() { public String getToken() {
return delegate.getToken(); return token != null ? token : delegate.getToken();
} }
@Override @Override
@ -324,7 +354,7 @@ class TbAiChannelPool {
if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) { if (cause instanceof WebSocketClientHandshakeException handshake && handshake.response() != null) {
int status = handshake.response().status().code(); int status = handshake.response().status().code();
if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) { if (status == HttpStatus.UNAUTHORIZED.value() || status == HttpStatus.FORBIDDEN.value()) {
return new TbAiChannelRejectedException(HttpStatus.valueOf(status).getReasonPhrase()); return new TbAiChannelRejectedException(HttpStatus.valueOf(status));
} }
} }
if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) { if (cause instanceof TbAiChannelRejectedException || cause instanceof TbAiChannelUnavailableException) {

11
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiChannelRejectedException.java

@ -2,13 +2,20 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai.transport; package org.thingsboard.server.service.ai.transport;
import lombok.Getter;
import org.springframework.http.HttpStatus;
/** /**
* TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user. * TB AI refused the channel handshake with 401 or 403; the reason phrase is shown to the user.
*/ */
@Getter
public class TbAiChannelRejectedException extends RuntimeException { public class TbAiChannelRejectedException extends RuntimeException {
public TbAiChannelRejectedException(String reason) { private final HttpStatus status;
super(reason);
public TbAiChannelRejectedException(HttpStatus status) {
super(status.getReasonPhrase());
this.status = status;
} }
} }

8
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiOperations.java

@ -4,6 +4,7 @@ package org.thingsboard.server.service.ai.transport;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.thingsboard.ai.common.client.TbAiClient; import org.thingsboard.ai.common.client.TbAiClient;
import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse; import org.thingsboard.ai.common.client.TbAiClient.TbAiResponse;
@ -17,6 +18,9 @@ import org.thingsboard.server.service.security.system.SystemSecurityService;
@RequiredArgsConstructor @RequiredArgsConstructor
public class TbAiOperations { public class TbAiOperations {
public static final String UNAVAILABLE_MESSAGE = "The AI service is unavailable. Try again.";
public static final String TIMED_OUT_MESSAGE = "The AI service did not answer in time. Try again.";
private final ChannelTbAiOperations channelOperations; private final ChannelTbAiOperations channelOperations;
private final SystemSecurityService systemSecurityService; private final SystemSecurityService systemSecurityService;
@ -33,9 +37,9 @@ public class TbAiOperations {
return channelOperations.execute(operation, context); return channelOperations.execute(operation, context);
} catch (TbAiChannelUnavailableException e) { } catch (TbAiChannelUnavailableException e) {
log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage()); log.warn("[{}][{}] AI channel unavailable for '{}': {}", context.tenantId(), context.userId(), operation.type(), e.getMessage());
return ChannelTbAiOperations.failure("Service unavailable"); return ChannelTbAiOperations.failure(HttpStatus.SERVICE_UNAVAILABLE, UNAVAILABLE_MESSAGE);
} catch (TbAiChannelRejectedException e) { } catch (TbAiChannelRejectedException e) {
return ChannelTbAiOperations.failure(e.getMessage()); return ChannelTbAiOperations.failure(e.getStatus(), e.getMessage());
} }
} }

17
application/src/main/java/org/thingsboard/server/service/ai/transport/TbAiPooledConnection.java

@ -32,7 +32,7 @@ final class TbAiPooledConnection implements ChannelFrameListener {
// Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell // Protocol version 1 is the baseline. A later feature that this ThingsBoard handles goes here, so TB AI can tell
// before using it that this ThingsBoard understands it. // before using it that this ThingsBoard understands it.
static final List<String> CLIENT_CAPABILITIES = List.of(); static final List<String> CLIENT_CAPABILITIES = List.of(ChannelProtocol.CHAT_KIT_CAPABILITY);
private final TbAiChannelPool.PoolKey key; private final TbAiChannelPool.PoolKey key;
private final String origin; private final String origin;
@ -54,6 +54,7 @@ final class TbAiPooledConnection implements ChannelFrameListener {
private volatile ChannelSession session; private volatile ChannelSession session;
private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES; private volatile int maxFrameBytes = TbAiChannelClient.DEFAULT_MAX_FRAME_BYTES;
private volatile List<String> serverCapabilities = List.of(); private volatile List<String> serverCapabilities = List.of();
private volatile String handshakeLimits;
/** /**
* Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot * Created with one reservation for the caller that opens it, so callers waiting on the same handshake cannot
@ -198,6 +199,20 @@ final class TbAiPooledConnection implements ChannelFrameListener {
} }
} }
void handshakeLimits(String limits) {
this.handshakeLimits = limits;
}
/**
* True when the channel shook hands with other limits than the caller's current token carries (the tenant
* profile's rate limits among them): its view of the user is out of date, so it should take no new work. Claims
* that change on every signing, such as the client address or the issue time, do not count.
*/
boolean isStaleFor(String currentLimits) {
String limits = handshakeLimits;
return currentLimits != null && limits != null && !limits.equals(currentLimits);
}
void retire() { void retire() {
boolean close; boolean close;
synchronized (lock) { synchronized (lock) {

6
application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java

@ -6,6 +6,7 @@ package org.thingsboard.server.service.edge;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.client5.http.impl.classic.HttpClients;
@ -134,7 +135,6 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(createConnectionManager(true)).build(); httpClient = HttpClientBuilder.create().useSystemProperties().setConnectionManager(createConnectionManager(true)).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient); factory.setHttpClient(httpClient);
factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory); return new RestTemplate(factory);
} else if (proxyEnabled) { } else if (proxyEnabled) {
log.warn("Going to use Proxy Server: [{}:{}]", System.getProperty("tb.proxy.host"), System.getProperty("tb.proxy.port")); log.warn("Going to use Proxy Server: [{}:{}]", System.getProperty("tb.proxy.host"), System.getProperty("tb.proxy.port"));
@ -143,13 +143,11 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
.setProxy(new HttpHost("https", System.getProperty("tb.proxy.host"), Integer.parseInt(System.getProperty("tb.proxy.port")))).build(); .setProxy(new HttpHost("https", System.getProperty("tb.proxy.host"), Integer.parseInt(System.getProperty("tb.proxy.port")))).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient); factory.setHttpClient(httpClient);
factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory); return new RestTemplate(factory);
} else { } else {
httpClient = HttpClients.custom().setConnectionManager(createConnectionManager(false)).build(); httpClient = HttpClients.custom().setConnectionManager(createConnectionManager(false)).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient); factory.setHttpClient(httpClient);
factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory); return new RestTemplate(factory);
} }
} }
@ -157,8 +155,10 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
private HttpClientConnectionManager createConnectionManager(boolean systemProperties) { private HttpClientConnectionManager createConnectionManager(boolean systemProperties) {
var socketFactory = systemProperties ? SSLConnectionSocketFactory.getSystemSocketFactory() : SSLConnectionSocketFactory.getSocketFactory(); var socketFactory = systemProperties ? SSLConnectionSocketFactory.getSystemSocketFactory() : SSLConnectionSocketFactory.getSocketFactory();
var socketConfig = SocketConfig.custom().setSoTimeout(Timeout.of(READ_TIMEOUT, TimeUnit.MILLISECONDS)).build(); var socketConfig = SocketConfig.custom().setSoTimeout(Timeout.of(READ_TIMEOUT, TimeUnit.MILLISECONDS)).build();
var connectionConfig = ConnectionConfig.custom().setConnectTimeout(Timeout.of(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)).build();
return PoolingHttpClientConnectionManagerBuilder.create() return PoolingHttpClientConnectionManagerBuilder.create()
.setDefaultSocketConfig(socketConfig) .setDefaultSocketConfig(socketConfig)
.setDefaultConnectionConfig(connectionConfig)
.setSSLSocketFactory(socketFactory).build(); .setSSLSocketFactory(socketFactory).build();
} }

2
application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java

@ -193,7 +193,7 @@ public abstract class BaseTelemetryProcessor extends BaseEdgeProcessor {
} }
} }
case ENTITY_GROUP -> { case ENTITY_GROUP -> {
EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, new EntityGroupId(entityId.getId())); EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, new EntityGroupId(entityId.getId()));
if (entityGroup != null) { if (entityGroup != null) {
metaData.putValue("entityGroupName", entityGroup.getName()); metaData.putValue("entityGroupName", entityGroup.getName());
metaData.putValue("entityGroupType", entityGroup.getType().name()); metaData.putValue("entityGroupType", entityGroup.getType().name());

5
application/src/main/java/org/thingsboard/server/service/entitiy/user/DefaultTbUserSettingsService.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.entitiy.user; package org.thingsboard.server.service.entitiy.user;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
@ -39,7 +40,7 @@ import java.util.stream.Collectors;
@Slf4j @Slf4j
public class DefaultTbUserSettingsService implements TbUserSettingsService { public class DefaultTbUserSettingsService implements TbUserSettingsService {
private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 10; private static final int MAX_DASHBOARD_INFO_LIST_SIZE = 50;
private static final Predicate<HasTitle> EMPTY_TITLE = i -> StringUtils.isEmpty(i.getTitle()); private static final Predicate<HasTitle> EMPTY_TITLE = i -> StringUtils.isEmpty(i.getTitle());
private final UserSettingsService settingsService; private final UserSettingsService settingsService;

41
application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_2_0Migration.java

@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.install.lts;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.dao.notification.DefaultNotifications;
import org.thingsboard.server.dao.notification.NotificationSettingsService;
import org.thingsboard.server.queue.util.TbCoreComponent;
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
public class V4_4_2_0Migration implements Migration {
private final NotificationSettingsService notificationSettingsService;
private final DefaultNotifications defaultNotifications;
@Override
public String getVersion() {
return "4.4.2.0";
}
@Override
public void apply() {
createAiCreditsLimitIncreaseRequestTemplate();
}
private void createAiCreditsLimitIncreaseRequestTemplate() {
if (notificationSettingsService.isNotificationConfigured(TenantId.SYS_TENANT_ID, NotificationType.AI_CREDITS_LIMIT_INCREASE_REQUEST)) {
log.debug("The AI credits limit increase request notification template already exists");
return;
}
defaultNotifications.create(TenantId.SYS_TENANT_ID, DefaultNotifications.aiCreditsLimitIncreaseRequest);
log.info("Created the AI credits limit increase request notification template");
}
}

2
application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java

@ -31,7 +31,7 @@ class EntityViewGroupAllUpdater extends EntityGroupAllPaginatedUpdater<EntityVie
@Override @Override
protected void unassignFromCustomer(EntityView entity) { protected void unassignFromCustomer(EntityView entity) {
entity.setCustomerId(new CustomerId(CustomerId.NULL_UUID)); entity.setCustomerId(new CustomerId(CustomerId.NULL_UUID));
entityViewService.saveEntityView(entity); entityViewService.saveEntityView(entity, false);
} }
@Override @Override

26
application/src/main/java/org/thingsboard/server/service/integration/DefaultPlatformIntegrationService.java

@ -93,6 +93,7 @@ import org.thingsboard.server.service.profile.DefaultTbAssetProfileCache;
import org.thingsboard.server.service.profile.DefaultTbDeviceProfileCache; import org.thingsboard.server.service.profile.DefaultTbDeviceProfileCache;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -200,11 +201,11 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
IntegrationCallback<Void> compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback; IntegrationCallback<Void> compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback;
if (hasTelemetry) { if (hasTelemetry) {
process(sessionInfo, data.getPostTelemetryMsg(), compositeCallback); process(sessionInfo, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), compositeCallback);
} }
if (hasAttributes) { if (hasAttributes) {
process(sessionInfo, data.getPostAttributesMsg(), compositeCallback); process(sessionInfo, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), compositeCallback);
} }
}; };
} }
@ -226,11 +227,11 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
IntegrationCallback<Void> compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback; IntegrationCallback<Void> compositeCallback = operationCount > 1 ? new CompositeCallback(operationCount, callback) : callback;
if (hasTelemetry) { if (hasTelemetry) {
process(asset, data.getPostTelemetryMsg(), compositeCallback); process(asset, data.getPostTelemetryMsg(), data.getTelemetryTypeCastDisabledKeysList(), compositeCallback);
} }
if (hasAttributes) { if (hasAttributes) {
process(asset, data.getPostAttributesMsg(), compositeCallback); process(asset, data.getPostAttributesMsg(), data.getAttributesTypeCastDisabledKeysList(), compositeCallback);
} }
}; };
} }
@ -363,6 +364,11 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
@Override @Override
public void process(SessionInfoProto sessionInfo, PostTelemetryMsg msg, IntegrationCallback<Void> callback) { public void process(SessionInfoProto sessionInfo, PostTelemetryMsg msg, IntegrationCallback<Void> callback) {
process(sessionInfo, msg, Collections.emptySet(), callback);
}
// typeCastDisabledKeys: the keys whose string values the converter kept as strings, passed to the rule engine in the metadata.
void process(SessionInfoProto sessionInfo, PostTelemetryMsg msg, Collection<String> typeCastDisabledKeys, IntegrationCallback<Void> callback) {
try { try {
if (msg.getTsKvListCount() == 0) { if (msg.getTsKvListCount() == 0) {
callback.onSuccess(null); callback.onSuccess(null);
@ -381,6 +387,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
metaData.putValue("deviceName", sessionInfo.getDeviceName()); metaData.putValue("deviceName", sessionInfo.getDeviceName());
metaData.putValue("deviceType", sessionInfo.getDeviceType()); metaData.putValue("deviceType", sessionInfo.getDeviceType());
metaData.putValue("ts", tsKv.getTs() + ""); metaData.putValue("ts", tsKv.getTs() + "");
metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList()); JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList());
sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback); sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback);
} }
@ -391,6 +398,10 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
@Override @Override
public void process(SessionInfoProto sessionInfo, PostAttributeMsg msg, IntegrationCallback<Void> callback) { public void process(SessionInfoProto sessionInfo, PostAttributeMsg msg, IntegrationCallback<Void> callback) {
process(sessionInfo, msg, Collections.emptySet(), callback);
}
void process(SessionInfoProto sessionInfo, PostAttributeMsg msg, Collection<String> typeCastDisabledKeys, IntegrationCallback<Void> callback) {
try { try {
TenantId tenantId = TenantId.fromUUID(new UUID(sessionInfo.getTenantIdMSB(), sessionInfo.getTenantIdLSB())); TenantId tenantId = TenantId.fromUUID(new UUID(sessionInfo.getTenantIdMSB(), sessionInfo.getTenantIdLSB()));
DeviceId deviceId = new DeviceId(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB())); DeviceId deviceId = new DeviceId(new UUID(sessionInfo.getDeviceIdMSB(), sessionInfo.getDeviceIdLSB()));
@ -399,6 +410,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
TbMsgMetaData metaData = new TbMsgMetaData(); TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("deviceName", sessionInfo.getDeviceName()); metaData.putValue("deviceName", sessionInfo.getDeviceName());
metaData.putValue("deviceType", sessionInfo.getDeviceType()); metaData.putValue("deviceType", sessionInfo.getDeviceType());
metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST, sendToRuleEngine(tenantId, deviceId, sessionInfo, json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST,
new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(tenantId, getCustomerId(sessionInfo), msg.getKvList().size(), callback))); new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(tenantId, getCustomerId(sessionInfo), msg.getKvList().size(), callback)));
} catch (Exception e) { } catch (Exception e) {
@ -717,7 +729,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
return metaData; return metaData;
} }
private void process(Asset asset, PostTelemetryMsg msg, IntegrationCallback<Void> callback) { private void process(Asset asset, PostTelemetryMsg msg, Collection<String> typeCastDisabledKeys, IntegrationCallback<Void> callback) {
try { try {
if (msg.getTsKvListCount() == 0) { if (msg.getTsKvListCount() == 0) {
callback.onSuccess(null); callback.onSuccess(null);
@ -733,6 +745,7 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
metaData.putValue("assetName", asset.getName()); metaData.putValue("assetName", asset.getName());
metaData.putValue("assetType", asset.getType()); metaData.putValue("assetType", asset.getType());
metaData.putValue("ts", tsKv.getTs() + ""); metaData.putValue("ts", tsKv.getTs() + "");
metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList()); JsonObject json = JsonUtils.getJsonObject(tsKv.getKvList());
sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(), sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(),
asset.getCustomerId(), json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback); asset.getCustomerId(), json, metaData, TbMsgType.POST_TELEMETRY_REQUEST, packCallback);
@ -742,12 +755,13 @@ public class DefaultPlatformIntegrationService extends IntegrationActivityManage
} }
} }
private void process(Asset asset, PostAttributeMsg msg, IntegrationCallback<Void> callback) { private void process(Asset asset, PostAttributeMsg msg, Collection<String> typeCastDisabledKeys, IntegrationCallback<Void> callback) {
try { try {
JsonObject json = JsonUtils.getJsonObject(msg.getKvList()); JsonObject json = JsonUtils.getJsonObject(msg.getKvList());
TbMsgMetaData metaData = new TbMsgMetaData(); TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("assetName", asset.getName()); metaData.putValue("assetName", asset.getName());
metaData.putValue("assetType", asset.getType()); metaData.putValue("assetType", asset.getType());
metaData.putTypeCastDisabledKeys(typeCastDisabledKeys);
sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(), sendToRuleEngine(asset.getTenantId(), asset.getId(), asset.getAssetProfileId(),
asset.getCustomerId(), json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST, asset.getCustomerId(), json, metaData, TbMsgType.POST_ATTRIBUTES_REQUEST,
new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(asset.getTenantId(), asset.getCustomerId(), msg.getKvList().size(), callback))); new IntegrationTbQueueCallback(new ApiStatsProxyCallback<>(asset.getTenantId(), asset.getCustomerId(), msg.getKvList().size(), callback)));

417
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageUpdateService.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultDevicePackageService.java

@ -9,6 +9,8 @@ import com.fasterxml.jackson.databind.node.TextNode;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestClientException;
@ -16,10 +18,13 @@ import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.AttributesSaveRequest; import org.thingsboard.rule.engine.api.AttributesSaveRequest;
import org.thingsboard.server.common.adaptor.JsonConverter; import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard; import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.GroupEntity;
import org.thingsboard.server.common.data.HasCustomerId;
import org.thingsboard.server.common.data.HasName; import org.thingsboard.server.common.data.HasName;
import org.thingsboard.server.common.data.HasTenantId; import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.HasVersion; import org.thingsboard.server.common.data.HasVersion;
@ -30,14 +35,17 @@ import org.thingsboard.server.common.data.exception.EntityVersionMismatchExcepti
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode; import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.ConverterId; import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DashboardId; import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId; import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId; import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IntegrationId; import org.thingsboard.server.common.data.id.IntegrationId;
import org.thingsboard.server.common.data.id.IotHubInstalledItemId; import org.thingsboard.server.common.data.id.IotHubInstalledItemId;
import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.integration.Integration; import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.DeviceInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem; import org.thingsboard.server.common.data.iot_hub.IotHubInstalledItem;
@ -63,9 +71,12 @@ import org.thingsboard.server.dao.subscription.PlatformFeature;
import org.thingsboard.server.dao.subscription.SubscriptionService; import org.thingsboard.server.dao.subscription.SubscriptionService;
import org.thingsboard.server.exception.DataValidationException; import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.exception.EntitiesLimitExceededException;
import org.thingsboard.server.exception.ThingsboardEntitiesLimitExceededResponse;
import org.thingsboard.server.exception.ThingsboardErrorResponse;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.entitiy.integration.TbIntegrationService; import org.thingsboard.server.service.entitiy.integration.TbIntegrationService;
import org.thingsboard.server.service.install.ProjectInfo;
import org.thingsboard.server.service.rule.TbRuleChainService; import org.thingsboard.server.service.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService; import org.thingsboard.server.service.telemetry.TelemetrySubscriptionService;
@ -86,18 +97,17 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
/** /**
* Applies an update of an installed device package in one transaction. The install wizard resolves the templates * Installs a device package, or updates an installed one, in one transaction. The install wizard resolves the
* of the new version (the same way it installs them) and sends the entity of each step; this service checks the * templates of the version and sends the entity of each step; this service checks the plan, saves every entity
* plan, saves every entity and the new version of the installed item together, and rolls all of it back on a * and the installed item together, and rolls all of it back on a failure. The side effects of the saves (actors,
* failure. The side effects of the saves (actors, integration restart, edge, caches) run after commit, so a * integration restart, edge, caches) run after commit, so a rollback leaves no trace; the audit log, version control
* rollback leaves no trace; the audit log, version control and the attributes, which aren't transactional, * and the attributes, which aren't transactional, are written after commit too.
* are written after commit too.
*/ */
@Service @Service
@TbCoreComponent @TbCoreComponent
@Slf4j @Slf4j
@RequiredArgsConstructor @RequiredArgsConstructor
public class DefaultDevicePackageUpdateService extends AbstractTbEntityService implements DevicePackageUpdateService { public class DefaultDevicePackageService extends AbstractTbEntityService implements DevicePackageService {
// Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id} // Step type of the package -> the alias its templates refer to it by, e.g. ${deviceProfile.id}
private static final Map<String, String> STEP_ALIASES = Map.of( private static final Map<String, String> STEP_ALIASES = Map.of(
@ -110,7 +120,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
"DOWNLINK_CONVERTER", "downlinkConverter", "DOWNLINK_CONVERTER", "downlinkConverter",
"INTEGRATION", "integration"); "INTEGRATION", "integration");
private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}"); private static final Pattern ENTITY_PLACEHOLDER = Pattern.compile("\\$\\{([A-Za-z]+)\\.([A-Za-z]+)}");
private static final String UNEXPECTED_ERROR = "Failed to update the device package"; private static final String UNEXPECTED_ERROR = "Failed to save the device package";
private final IotHubInstalledItemService installedItemService; private final IotHubInstalledItemService installedItemService;
private final IotHubRestClient iotHubRestClient; private final IotHubRestClient iotHubRestClient;
@ -129,6 +139,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private final AttributesService attributesService; private final AttributesService attributesService;
private final TelemetrySubscriptionService telemetryService; private final TelemetrySubscriptionService telemetryService;
private final TransactionTemplate transactionTemplate; private final TransactionTemplate transactionTemplate;
private final ProjectInfo projectInfo;
@Override @Override
public List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId) { public List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId) {
@ -162,33 +173,168 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
@Override @Override
public DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request) { public DevicePackageResult install(SecurityUser user, DevicePackageRequest request) {
TenantId tenantId = user.getTenantId();
log.info("[{}] Installing device package version {}", tenantId, request.getVersionId());
DevicePackageResult result = apply(user, "install of version " + request.getVersionId(), () -> {
if (request.getVersionId() == null || request.getFromVersionId() != null || toUuid(request.getVersionId()) == null) {
throw new IllegalArgumentException("Invalid install request");
}
Placement placement = placement(tenantId, request);
JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId());
if (versionInfo == null) {
throw new IllegalArgumentException("Failed to get version info from IoT Hub");
}
// The package owns nothing yet, so overwriting an entity the tenant has needs a confirmation
DeviceInstalledItemDescriptor previous = new DeviceInstalledItemDescriptor();
validateInstallSteps(request);
validate(tenantId, previous, request);
return transactionTemplate.execute(status -> {
Applied applied = applySteps(tenantId, previous, request, null, placement);
IotHubInstalledItem installedItem = new IotHubInstalledItem();
installedItem.setTenantId(tenantId);
installedItem.setItemId(UUID.fromString(versionInfo.get("itemId").asText()));
installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
installedItem.setItemName(versionInfo.get("name").asText());
installedItem.setItemType("DEVICE");
installedItem.setVersion(versionInfo.get("version").asText());
installedItem.setDescriptor(applied.descriptor());
installedItemService.save(tenantId, installedItem);
return applied;
});
});
if (result.isSuccess()) {
reportInstall(user, request.getVersionId());
log.info("[{}] Installed device package version {}", tenantId, request.getVersionId());
}
return result;
}
@Override
public DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request) {
TenantId tenantId = user.getTenantId(); TenantId tenantId = user.getTenantId();
log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId()); log.info("[{}] Updating device package {} to version {}", tenantId, installedItemId, request.getVersionId());
Applied applied; DevicePackageResult result = apply(user, "update of " + installedItemId, () -> {
try {
DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId); DevicePackage devicePackage = findDevicePackage(tenantId, installedItemId);
JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId()); JsonNode versionInfo = iotHubRestClient.getVersionInfo(request.getVersionId());
if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) { if (versionInfo == null || !devicePackage.installedItem().getItemId().toString().equals(versionInfo.path("itemId").asText())) {
throw new IllegalArgumentException("The version belongs to another item"); throw new IllegalArgumentException("The version belongs to another item");
} }
validatePlan(devicePackage, request); validate(tenantId, devicePackage.descriptor(), request);
checkFeatures(tenantId, request); return transactionTemplate.execute(status -> {
validateIntegrations(tenantId, request); IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request);
applied = transactionTemplate.execute(status -> applySteps(tenantId, devicePackage, request, versionInfo)); Applied applied = applySteps(tenantId, devicePackage.descriptor(), request, installedItem.getItemVersionId(), Placement.NONE);
installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
installedItem.setItemName(versionInfo.get("name").asText());
installedItem.setVersion(versionInfo.get("version").asText());
installedItem.setDescriptor(applied.descriptor());
installedItemService.save(tenantId, installedItem);
return applied;
});
});
if (result.isSuccess()) {
log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId());
}
return result;
}
/** Runs the planned change and, once it committed, what isn't transactional; a failure leaves nothing changed. */
private DevicePackageResult apply(SecurityUser user, String operation, PackageChange change) {
TenantId tenantId = user.getTenantId();
Applied applied;
try {
applied = change.apply();
} catch (StepFailure e) { } catch (StepFailure e) {
log.warn("[{}] Device package update of {} failed on step [{}], nothing was changed", tenantId, installedItemId, e.stepKey, e.getCause()); log.warn("[{}] Device package {} failed on step [{}], nothing was changed", tenantId, operation, e.stepKey, e.getCause());
return DeviceUpdateResult.error(userMessage(e.getCause()), e.stepKey); return DevicePackageResult.error(userMessage(e.getCause()), e.stepKey, limitOf(e.getCause()));
} catch (RestClientException e) { } catch (RestClientException e) {
log.error("[{}] IoT Hub request failed while updating device package {}", tenantId, installedItemId, e); log.error("[{}] IoT Hub request failed during the device package {}", tenantId, operation, e);
return DeviceUpdateResult.error("IoT Hub is unavailable. Try again later.", null); return DevicePackageResult.error("IoT Hub is unavailable. Try again later.", null);
} catch (Exception e) { } catch (Exception e) {
log.warn("[{}] Device package update of {} failed, nothing was changed", tenantId, installedItemId, e); log.warn("[{}] Device package {} failed, nothing was changed", tenantId, operation, e);
return DeviceUpdateResult.error(userMessage(e), null); return DevicePackageResult.error(userMessage(e), null);
} }
afterCommit(user, tenantId, applied); afterCommit(user, tenantId, applied);
log.info("[{}] Updated device package {} to version {}", tenantId, installedItemId, request.getVersionId()); return DevicePackageResult.success(applied.descriptor(), applied.outputs());
return DeviceUpdateResult.success(applied.descriptor(), applied.outputs()); }
/** Counts the install on the Hub; the package is installed whether or not the Hub hears of it. */
private void reportInstall(SecurityUser user, String versionId) {
TenantId tenantId = user.getTenantId();
try {
InstallReport report = DefaultIotHubService.buildInstallReport(tenantId.getId(), user.getId().getId(),
projectInfo.getProjectVersion(), projectInfo.getProductType());
iotHubRestClient.reportVersionInstalled(versionId, report);
} catch (Exception e) {
log.warn("[{}] Failed to report install for version {}: {}", tenantId, versionId, e.getMessage());
}
}
/**
* At install a kept entity is one the user chose to use as it is: the package doesn't own it. An existing device or
* gateway is never overwritten: its credentials are what its firmware uses.
*/
private static void validateInstallSteps(DevicePackageRequest request) {
if (request.getSteps() == null) {
return;
}
for (DevicePackageRequest.Step step : request.getSteps()) {
boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
if ((step.getAction() == DevicePackageRequest.Action.KEEP && !"use-existing".equals(step.getResolution()))
|| (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway)) {
throw new IllegalArgumentException("Invalid install step: " + step.getName());
}
}
}
/**
* The customer and the device group the install was opened from; each must be the tenant's. The group's own
* permission isn't checked again: the endpoint's checkAllPermissions already requires ALL operations on ALL resources.
*/
private Placement placement(TenantId tenantId, DevicePackageRequest request) {
CustomerId customerId = request.getCustomerId() != null && !CustomerId.NULL_UUID.equals(request.getCustomerId())
? new CustomerId(request.getCustomerId()) : null;
if (customerId != null && !isTenantsCustomer(tenantId, customerId)) {
throw new IllegalArgumentException("Invalid install request");
}
if (request.getEntityGroupId() == null) {
return new Placement(customerId, customerId, null);
}
EntityGroup group = entityGroupService.findEntityGroupById(tenantId, new EntityGroupId(request.getEntityGroupId()));
EntityId owner = group != null ? group.getOwnerId() : null;
boolean tenants = owner != null && (tenantId.equals(owner)
|| (owner.getEntityType() == EntityType.CUSTOMER && isTenantsCustomer(tenantId, new CustomerId(owner.getId()))));
if (group == null || group.getType() != EntityType.DEVICE || !tenants) {
throw new IllegalArgumentException("Invalid install request");
}
// As a device saved into a group: with no customer given, a new one goes to the group's customer
CustomerId deviceCustomerId = customerId == null && owner.getEntityType() == EntityType.CUSTOMER ? new CustomerId(owner.getId()) : customerId;
return new Placement(customerId, deviceCustomerId, group);
}
private boolean isTenantsCustomer(TenantId tenantId, CustomerId customerId) {
Customer customer = customerService.findCustomerById(tenantId, customerId);
return customer != null && tenantId.equals(customer.getTenantId());
}
/**
* Puts the entity in the customer the install was opened from. An overwrite never changes the owner, with or without
* a customer: the dao would move the entity past the owner change, leaving its groups and the owner cache stale.
*/
private static void assignCustomer(GroupEntity<?> entity, CustomerId customerId, GroupEntity<?> current, DevicePackageRequest.Step step) {
if (customerId != null) {
entity.setOwnerId(customerId);
}
if (current != null && !current.getOwnerId().equals(entity.getOwnerId())) {
throw new IllegalArgumentException(step.getName() + " belongs to another owner");
}
}
/** What is checked before the transaction: the plan, the tenant's plan features and the integrations' configuration. */
private void validate(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request) throws Exception {
validatePlan(ownedIds(previous), request);
checkFeatures(tenantId, request);
validateIntegrations(tenantId, request);
} }
private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) { private DevicePackage findDevicePackage(TenantId tenantId, IotHubInstalledItemId installedItemId) {
@ -201,50 +347,49 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
/** /**
* The update may only change what the package owns, or what the user confirmed. The device and the gateway, * The device package may only change what it owns, or what the user confirmed. Its own device and gateway,
* whose credentials the firmware uses, are never changed. * whose credentials the firmware uses, are never changed.
*/ */
private void validatePlan(DevicePackage devicePackage, DeviceUpdateRequest request) { private void validatePlan(Set<UUID> ownedIds, DevicePackageRequest request) {
if (request.getSteps() == null || request.getSteps().isEmpty()) { if (request.getSteps() == null || request.getSteps().isEmpty()) {
throw new IllegalArgumentException("The update has no steps"); throw new IllegalArgumentException("The device package has no steps");
} }
Set<UUID> ownedIds = ownedIds(devicePackage.descriptor());
// A form's values are saved under its key too, so an entity step may not share it // A form's values are saved under its key too, so an entity step may not share it
Set<String> stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>(); Set<String> stateKeys = request.getInstallState() != null ? new HashSet<>(request.getInstallState().keySet()) : new HashSet<>();
for (DeviceUpdateRequest.Step step : request.getSteps()) { for (DevicePackageRequest.Step step : request.getSteps()) {
if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) { if (step.getName() == null || step.getAction() == null || !isKnownType(step.getType())) {
throw new IllegalArgumentException("Invalid update step: " + step.getName()); throw new IllegalArgumentException("Invalid step: " + step.getName());
} }
if (!stateKeys.add(step.stateKey())) { if (!stateKeys.add(step.stateKey())) {
throw new IllegalArgumentException("Duplicate update step: " + step.stateKey()); throw new IllegalArgumentException("Duplicate step: " + step.stateKey());
} }
boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType()); boolean deviceOrGateway = "DEVICE".equals(step.getType()) || "GATEWAY".equals(step.getType());
switch (step.getAction()) { switch (step.getAction()) {
case KEEP, OVERWRITE -> { case KEEP, OVERWRITE -> {
if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) { if (step.getEntityId() == null && !"GATEWAY_CONNECTOR".equals(step.getType())) {
throw new IllegalArgumentException("No entity for update step: " + step.getName()); throw new IllegalArgumentException("No entity for step: " + step.getName());
} }
boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId()); boolean owned = step.getEntityId() != null && ownedIds.contains(step.getEntityId());
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && !owned && !step.isConfirmed() if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && !owned && !step.isConfirmed()
&& !"GATEWAY_CONNECTOR".equals(step.getType())) { && !"GATEWAY_CONNECTOR".equals(step.getType())) {
throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName()); throw new IllegalArgumentException("Overwriting an entity of another package needs a confirmation: " + step.getName());
} }
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE && deviceOrGateway && owned) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE && deviceOrGateway && owned) {
throw new IllegalArgumentException("The device and its credentials don't change on update"); throw new IllegalArgumentException("The device and its credentials don't change on update");
} }
} }
case CREATE -> { case CREATE -> {
} }
} }
if (step.getAction() != DeviceUpdateRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) { if (step.getAction() != DevicePackageRequest.Action.KEEP && (step.getEntity() == null || !step.getEntity().isObject())) {
throw new IllegalArgumentException("No entity data for update step: " + step.getName()); throw new IllegalArgumentException("No entity data for step: " + step.getName());
} }
} }
} }
/** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */ /** Integrations and converters are saved as through their API, which needs the feature in the tenant's plan. */
private void checkFeatures(TenantId tenantId, DeviceUpdateRequest request) { private void checkFeatures(TenantId tenantId, DevicePackageRequest request) {
boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DeviceUpdateRequest.Action.KEEP boolean savesIntegrations = request.getSteps().stream().anyMatch(step -> step.getAction() != DevicePackageRequest.Action.KEEP
&& ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER"))); && ("INTEGRATION".equals(step.getType()) || step.getType().endsWith("_CONVERTER")));
if (savesIntegrations) { if (savesIntegrations) {
subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS); subscriptionService.checkFeatureAllowed(tenantId, PlatformFeature.INTEGRATIONS);
@ -252,13 +397,13 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
/** The configuration of an integration is checked by a remote call, so before the transaction. */ /** The configuration of an integration is checked by a remote call, so before the transaction. */
private void validateIntegrations(TenantId tenantId, DeviceUpdateRequest request) throws Exception { private void validateIntegrations(TenantId tenantId, DevicePackageRequest request) throws Exception {
for (DeviceUpdateRequest.Step step : request.getSteps()) { for (DevicePackageRequest.Step step : request.getSteps()) {
if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DeviceUpdateRequest.Action.KEEP) { if (!"INTEGRATION".equals(step.getType()) || step.getAction() == DevicePackageRequest.Action.KEEP) {
continue; continue;
} }
ObjectNode body = step.getEntity().deepCopy(); ObjectNode body = step.getEntity().deepCopy();
// Converters this update creates have no id yet; the configuration doesn't depend on them // Converters the request creates have no id yet; the configuration doesn't depend on them
body.remove(List.of("id", "defaultConverterId", "downlinkConverterId")); body.remove(List.of("id", "defaultConverterId", "downlinkConverterId"));
Integration integration = JacksonUtil.treeToValue(body, Integration.class); Integration integration = JacksonUtil.treeToValue(body, Integration.class);
integration.setTenantId(tenantId); integration.setTenantId(tenantId);
@ -274,9 +419,12 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
} }
private Applied applySteps(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request, JsonNode versionInfo) { /**
IotHubInstalledItem installedItem = lockInstalledItem(tenantId, devicePackage, request); * Saves the entities of the steps and builds the descriptor of the installed item, which the caller saves in the
DeviceInstalledItemDescriptor previous = devicePackage.descriptor(); * same transaction. previous is what the package had: on install an empty descriptor, and installedVersionId null.
*/
private Applied applySteps(TenantId tenantId, DeviceInstalledItemDescriptor previous, DevicePackageRequest request, UUID installedVersionId,
Placement placement) {
Set<UUID> ownedIds = ownedIds(previous); Set<UUID> ownedIds = ownedIds(previous);
Map<String, ObjectNode> aliasOutputs = new HashMap<>(); Map<String, ObjectNode> aliasOutputs = new HashMap<>();
Map<String, ObjectNode> outputs = new LinkedHashMap<>(); Map<String, ObjectNode> outputs = new LinkedHashMap<>();
@ -289,23 +437,25 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}); });
} }
List<EntityId> stepEntityIds = new ArrayList<>(); List<EntityId> stepEntityIds = new ArrayList<>();
Map<UUID, EntityId> usedExistingIds = usedExistingIds(previous); Map<UUID, EntityId> usedExistingIds = new LinkedHashMap<>();
previous.getUsedExistingEntityIdsIncludingLegacy().forEach(id -> usedExistingIds.put(id.getId(), id));
List<SavedEntity> saved = new ArrayList<>(); List<SavedEntity> saved = new ArrayList<>();
List<DeviceUpdateRequest.Step> connectorSteps = new ArrayList<>(); List<SavedEntity> grouped = new ArrayList<>();
List<DevicePackageRequest.Step> connectorSteps = new ArrayList<>();
List<StepAttributes> attributes = new ArrayList<>(); List<StepAttributes> attributes = new ArrayList<>();
DashboardId dashboardId = null; DashboardId dashboardId = null;
for (DeviceUpdateRequest.Step step : request.getSteps()) { for (DevicePackageRequest.Step step : request.getSteps()) {
try { try {
if ("GATEWAY_CONNECTOR".equals(step.getType())) { if ("GATEWAY_CONNECTOR".equals(step.getType())) {
// A connector lives in the gateway's attributes, which aren't transactional: saved after commit // A connector lives in the gateway's attributes, which aren't transactional: saved after commit
if (step.getAction() != DeviceUpdateRequest.Action.KEEP) { if (step.getAction() != DevicePackageRequest.Action.KEEP) {
connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs))); connectorSteps.add(copyWithEntity(step, resolvePlaceholders(step.getEntity(), aliasOutputs)));
} }
continue; continue;
} }
JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null; JsonNode entity = step.getEntity() != null ? resolvePlaceholders(step.getEntity(), aliasOutputs) : null;
StepResult result = applyStep(tenantId, step, entity); StepResult result = applyStep(tenantId, step, entity, placement);
ObjectNode output = result.output(); ObjectNode output = result.output();
aliasOutputs.put(STEP_ALIASES.get(step.getType()), output); aliasOutputs.put(STEP_ALIASES.get(step.getType()), output);
outputs.put(step.stateKey(), output); outputs.put(step.stateKey(), output);
@ -317,7 +467,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
state.put("resolution", resolution); state.put("resolution", resolution);
// A kept entity keeps the checksum of what the package left: the current one would take the // A kept entity keeps the checksum of what the package left: the current one would take the
// user's changes for the package's, and the next update would overwrite them without a warning // user's changes for the package's, and the next update would overwrite them without a warning
String checksum = step.getAction() == DeviceUpdateRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum(); String checksum = step.getAction() == DevicePackageRequest.Action.KEEP ? previousChecksum(previous, step.getEntityId()) : result.checksum();
if (checksum != null) { if (checksum != null) {
state.put("checksum", checksum); state.put("checksum", checksum);
} }
@ -343,8 +493,15 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if (result.saved() != null) { if (result.saved() != null) {
saved.add(result.saved()); saved.add(result.saved());
} }
if (step.getAction() != DeviceUpdateRequest.Action.KEEP && !"use-existing".equals(resolution)) { if (placement.entityGroup() != null && result.saved() != null && result.saved().created()
// As at install, the step's attributes go with the entity it saved; written after commit && result.entityId().getEntityType() == EntityType.DEVICE) {
entityGroupService.addEntityToEntityGroup(tenantId, placement.entityGroup().getId(), result.entityId());
grouped.add(result.saved());
}
// The step's attributes go with the entity it saved; at install also onto an entity the user chose to
// use, as the install always did. Written after commit
boolean install = installedVersionId == null;
if (install || (step.getAction() != DevicePackageRequest.Action.KEEP && !"use-existing".equals(resolution))) {
attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes())); attributes.add(new StepAttributes(step.getName(), result.entityId(), step.getServerAttributes(), step.getSharedAttributes()));
} }
} catch (StepFailure e) { } catch (StepFailure e) {
@ -356,7 +513,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
// An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps // An update to the installed version itself, e.g. of ThingsBoard's default converter only, sends just the steps
// it changes: the other steps and the forms keep their install state // it changes: the other steps and the forms keep their install state
if (UUID.fromString(request.getVersionId()).equals(installedItem.getItemVersionId()) && previous.getInstallState() != null) { if (UUID.fromString(request.getVersionId()).equals(installedVersionId) && previous.getInstallState() != null) {
previous.getInstallState().forEach((key, value) -> { previous.getInstallState().forEach((key, value) -> {
if (value instanceof ObjectNode state) { if (value instanceof ObjectNode state) {
installState.putIfAbsent(key, state); installState.putIfAbsent(key, state);
@ -376,15 +533,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
carryMetadataStates(previous, tracked, state); carryMetadataStates(previous, tracked, state);
descriptor.setInstallState(state); descriptor.setInstallState(state);
installedItem.setItemVersionId(UUID.fromString(request.getVersionId()));
installedItem.setItemName(versionInfo.get("name").asText());
installedItem.setVersion(versionInfo.get("version").asText());
installedItem.setDescriptor(descriptor);
installedItemService.save(tenantId, installedItem);
// Resolved once every entity is saved: attributes may refer to a later step's entity // Resolved once every entity is saved: attributes may refer to a later step's entity
List<StepAttributes> resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(), List<StepAttributes> resolvedAttributes = attributes.stream().map(a -> new StepAttributes(a.stepName(), a.entityId(),
resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList(); resolvePlaceholders(a.server(), aliasOutputs), resolvePlaceholders(a.shared(), aliasOutputs))).toList();
return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs); return new Applied(descriptor, outputs, saved, connectorSteps, resolvedAttributes, aliasOutputs, placement.entityGroup(), grouped);
} }
/** The checksums the installed device packages recorded, by entity. */ /** The checksums the installed device packages recorded, by entity. */
@ -422,7 +574,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then * Another update of the package, e.g. a second click or another tab, waits here until this one commits, and then
* fails: the plan was made for the version installed before. Without it both would create the new entities. * fails: the plan was made for the version installed before. Without it both would create the new entities.
*/ */
private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DeviceUpdateRequest request) { private IotHubInstalledItem lockInstalledItem(TenantId tenantId, DevicePackage devicePackage, DevicePackageRequest request) {
IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId()); IotHubInstalledItem installedItem = installedItemService.findByIdForUpdate(tenantId, devicePackage.installedItem().getId());
UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId(); UUID planned = request.getFromVersionId() != null ? request.getFromVersionId() : devicePackage.installedItem().getItemVersionId();
if (installedItem == null || !planned.equals(installedItem.getItemVersionId()) if (installedItem == null || !planned.equals(installedItem.getItemVersionId())
@ -432,11 +584,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return installedItem; return installedItem;
} }
private StepResult applyStep(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { private StepResult applyStep(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) throws ThingsboardException {
return switch (step.getType()) { return switch (step.getType()) {
case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity); case "DEVICE_PROFILE" -> saveDeviceProfile(tenantId, step, entity);
case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity); case "DEVICE", "GATEWAY" -> saveDevice(tenantId, step, entity, placement);
case "DASHBOARD" -> saveDashboard(tenantId, step, entity); case "DASHBOARD" -> saveDashboard(tenantId, step, entity, placement);
case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity); case "RULE_CHAIN" -> saveRuleChain(tenantId, step, entity);
case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity); case "UPLINK_CONVERTER", "DOWNLINK_CONVERTER" -> saveConverter(tenantId, step, entity);
case "INTEGRATION" -> saveIntegration(tenantId, step, entity); case "INTEGRATION" -> saveIntegration(tenantId, step, entity);
@ -444,16 +596,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
}; };
} }
private StepResult saveDeviceProfile(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { private StepResult saveDeviceProfile(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) {
DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null; DeviceProfileId id = step.getEntityId() != null ? new DeviceProfileId(step.getEntityId()) : null;
DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null; DeviceProfile current = id != null ? deviceProfileService.findDeviceProfileById(tenantId, id) : null;
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step); existing(tenantId, current, step);
return kept(id, current.getName()); return kept(id, current.getName());
} }
DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class); DeviceProfile profile = JacksonUtil.treeToValue(entity, DeviceProfile.class);
profile.setTenantId(tenantId); profile.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(profile, id, current, step); prepareOverwrite(profile, id, current, step);
// The tenant's default profile stays the default one // The tenant's default profile stays the default one
@ -466,31 +618,34 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
} }
private StepResult saveDevice(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { private StepResult saveDevice(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) {
DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null; DeviceId id = step.getEntityId() != null ? new DeviceId(step.getEntityId()) : null;
Device device; Device device;
boolean created = false; boolean created = false;
if (step.getAction() == DeviceUpdateRequest.Action.CREATE) { if (step.getAction() == DevicePackageRequest.Action.CREATE) {
Device template = JacksonUtil.treeToValue(entity, Device.class); Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId); template.setTenantId(tenantId);
template.setId(null); template.setId(null);
template.setVersion(null); template.setVersion(null);
assignCustomer(template, placement.deviceCustomerId(), null, step);
device = deviceService.saveDevice(template); device = deviceService.saveDevice(template);
created = true; created = true;
} else { } else {
Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null; Device current = id != null ? deviceService.findDeviceById(tenantId, id) : null;
device = existing(tenantId, current, step); device = existing(tenantId, current, step);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
// Another device the user chose to overwrite; the package's own device never changes // On update, another device the user chose to overwrite; it keeps its credentials. The package's own
// device never changes, and an install never overwrites one
Device template = JacksonUtil.treeToValue(entity, Device.class); Device template = JacksonUtil.treeToValue(entity, Device.class);
template.setTenantId(tenantId); template.setTenantId(tenantId);
prepareOverwrite(template, id, current, step); prepareOverwrite(template, id, current, step);
assignCustomer(template, placement.customerId(), current, step);
device = deviceService.saveDevice(template); device = deviceService.saveDevice(template);
created = true; created = true;
} }
} }
DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId()); DeviceCredentials credentials = deviceCredentialsService.findDeviceCredentialsByDeviceId(tenantId, device.getId());
if (created && step.getCredentials() != null && step.getCredentials().isObject()) { if (step.getAction() == DevicePackageRequest.Action.CREATE && step.getCredentials() != null && step.getCredentials().isObject()) {
credentials = applyCredentials(tenantId, credentials, step.getCredentials()); credentials = applyCredentials(tenantId, credentials, step.getCredentials());
} }
ObjectNode output = output(device.getId(), device.getName()); ObjectNode output = output(device.getId(), device.getName());
@ -500,7 +655,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
if ("GATEWAY".equals(step.getType())) { if ("GATEWAY".equals(step.getType())) {
output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download"); output.put("dockerComposeUrl", "/api/device-connectivity/gateway-launch/" + device.getId().getId() + "/docker-compose/download");
} }
SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DeviceUpdateRequest.Action.CREATE) : null; SavedEntity saved = created ? new SavedEntity(device.getId(), device, step.getAction() == DevicePackageRequest.Action.CREATE) : null;
return new StepResult(device.getId(), output, null, saved); return new StepResult(device.getId(), output, null, saved);
} }
@ -520,16 +675,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials); return deviceCredentialsService.updateDeviceCredentials(tenantId, credentials);
} }
private StepResult saveDashboard(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { private StepResult saveDashboard(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity, Placement placement) {
DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null; DashboardId id = step.getEntityId() != null ? new DashboardId(step.getEntityId()) : null;
Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null; Dashboard current = id != null ? dashboardService.findDashboardById(tenantId, id) : null;
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step); existing(tenantId, current, step);
return kept(id, current.getTitle()); return kept(id, current.getTitle());
} }
Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class); Dashboard dashboard = JacksonUtil.treeToValue(entity, Dashboard.class);
dashboard.setTenantId(tenantId); dashboard.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(dashboard, id, current, step); prepareOverwrite(dashboard, id, current, step);
// The dashboard keeps its owner and the customers it is assigned to // The dashboard keeps its owner and the customers it is assigned to
@ -537,25 +692,27 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
dashboard.setCustomerId(current.getCustomerId()); dashboard.setCustomerId(current.getCustomerId());
} }
dashboard.setAssignedCustomers(current.getAssignedCustomers()); dashboard.setAssignedCustomers(current.getAssignedCustomers());
assignCustomer(dashboard, placement.customerId(), current, step);
} else { } else {
dashboard.setId(null); dashboard.setId(null);
dashboard.setVersion(null); dashboard.setVersion(null);
assignCustomer(dashboard, placement.customerId(), null, step);
} }
Dashboard result = dashboardService.saveDashboard(dashboard); Dashboard result = dashboardService.saveDashboard(dashboard);
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle())); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getTitle()));
} }
private StepResult saveRuleChain(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) throws ThingsboardException { private StepResult saveRuleChain(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) throws ThingsboardException {
RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null; RuleChainId id = step.getEntityId() != null ? new RuleChainId(step.getEntityId()) : null;
RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null; RuleChain current = id != null ? ruleChainService.findRuleChainById(tenantId, id) : null;
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step); existing(tenantId, current, step);
return kept(id, current.getName()); return kept(id, current.getName());
} }
JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity; JsonNode ruleChainJson = entity.has("ruleChain") ? entity.get("ruleChain") : entity;
RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class); RuleChain ruleChain = JacksonUtil.treeToValue(ruleChainJson, RuleChain.class);
ruleChain.setTenantId(tenantId); ruleChain.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(ruleChain, id, current, step); prepareOverwrite(ruleChain, id, current, step);
// A rule chain the tenant made its root one stays the root // A rule chain the tenant made its root one stays the root
@ -578,17 +735,17 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
} }
private StepResult saveConverter(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { private StepResult saveConverter(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) {
ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null; ConverterId id = step.getEntityId() != null ? new ConverterId(step.getEntityId()) : null;
Converter current = id != null ? converterService.findConverterById(tenantId, id) : null; Converter current = id != null ? converterService.findConverterById(tenantId, id) : null;
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step); existing(tenantId, current, step);
return kept(id, current.getName()); return kept(id, current.getName());
} }
Converter converter = JacksonUtil.treeToValue(entity, Converter.class); Converter converter = JacksonUtil.treeToValue(entity, Converter.class);
converter.setTenantId(tenantId); converter.setTenantId(tenantId);
converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK); converter.setType("UPLINK_CONVERTER".equals(step.getType()) ? ConverterType.UPLINK : ConverterType.DOWNLINK);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(converter, id, current, step); prepareOverwrite(converter, id, current, step);
} else { } else {
@ -599,10 +756,10 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName())); return savedResult(tenantId, result.getId(), result, step, output(result.getId(), result.getName()));
} }
private StepResult saveIntegration(TenantId tenantId, DeviceUpdateRequest.Step step, JsonNode entity) { private StepResult saveIntegration(TenantId tenantId, DevicePackageRequest.Step step, JsonNode entity) {
IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null; IntegrationId id = step.getEntityId() != null ? new IntegrationId(step.getEntityId()) : null;
Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null; Integration current = id != null ? integrationService.findIntegrationById(tenantId, id) : null;
if (step.getAction() == DeviceUpdateRequest.Action.KEEP) { if (step.getAction() == DevicePackageRequest.Action.KEEP) {
existing(tenantId, current, step); existing(tenantId, current, step);
Integration merged = withMergedMetadata(current, step.getMetadata()); Integration merged = withMergedMetadata(current, step.getMetadata());
if (merged != null) { if (merged != null) {
@ -613,7 +770,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
Integration integration = JacksonUtil.treeToValue(entity, Integration.class); Integration integration = JacksonUtil.treeToValue(entity, Integration.class);
integration.setTenantId(tenantId); integration.setTenantId(tenantId);
if (step.getAction() == DeviceUpdateRequest.Action.OVERWRITE) { if (step.getAction() == DevicePackageRequest.Action.OVERWRITE) {
existing(tenantId, current, step); existing(tenantId, current, step);
prepareOverwrite(integration, id, current, step); prepareOverwrite(integration, id, current, step);
// The devices keep sending to the same endpoint // The devices keep sending to the same endpoint
@ -668,7 +825,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
/** /**
* A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing. * A copy of the integration with the step's metadata entries merged into its metadata; null when that changes nothing.
* A copy: the integration may be the cache's own instance, which a rolled back update must not change. * A copy: the integration may be the cache's own instance, which a rolled back install or update must not change.
*/ */
private static Integration withMergedMetadata(Integration integration, JsonNode entries) { private static Integration withMergedMetadata(Integration integration, JsonNode entries) {
if (entries == null || !entries.isObject() || entries.isEmpty()) { if (entries == null || !entries.isObject() || entries.isEmpty()) {
@ -698,7 +855,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* The overwritten entity keeps its id and its current name (the user may have renamed it). The version the * The overwritten entity keeps its id and its current name (the user may have renamed it). The version the
* user reviewed makes the save fail if someone changed the entity since. * user reviewed makes the save fail if someone changed the entity since.
*/ */
private void prepareOverwrite(Object entity, EntityId id, Object current, DeviceUpdateRequest.Step step) { private void prepareOverwrite(Object entity, EntityId id, Object current, DevicePackageRequest.Step step) {
switch (entity) { switch (entity) {
case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); } case DeviceProfile p -> { p.setId((DeviceProfileId) id); p.setName(((DeviceProfile) current).getName()); }
case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); } case Device d -> { d.setId((DeviceId) id); d.setName(((Device) current).getName()); }
@ -715,9 +872,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
((HasVersion) entity).setVersion(currentVersion); ((HasVersion) entity).setVersion(currentVersion);
} }
private <T> T existing(TenantId tenantId, T current, DeviceUpdateRequest.Step step) { private <T> T existing(TenantId tenantId, T current, DevicePackageRequest.Step step) {
if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) { if (current == null || !tenantId.equals(((HasTenantId) current).getTenantId())) {
throw new IllegalArgumentException(step.getName() + " was deleted. Check the update again."); throw new IllegalArgumentException(step.getName() + " was deleted meanwhile. Check the package again.");
} }
return current; return current;
} }
@ -745,9 +902,9 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* transaction may come from the cache, which is evicted only after commit. A rule chain is read back with * transaction may come from the cache, which is evicted only after commit. A rule chain is read back with
* its metadata, which isn't cached. * its metadata, which isn't cached.
*/ */
private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DeviceUpdateRequest.Step step, ObjectNode output) { private StepResult savedResult(TenantId tenantId, EntityId id, Object entity, DevicePackageRequest.Step step, ObjectNode output) {
String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity); String checksum = entity instanceof RuleChain ? packageEntities.checksum(tenantId, id) : EntityChecksum.of(entity);
return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DeviceUpdateRequest.Action.CREATE)); return new StepResult(id, output, checksum, new SavedEntity(id, entity, step.getAction() == DevicePackageRequest.Action.CREATE));
} }
private static ObjectNode output(EntityId id, String name) { private static ObjectNode output(EntityId id, String name) {
@ -775,7 +932,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
} }
/** Replaces ${<alias>.<property>} of entities this update has saved, e.g. the id of a converter it created. */ /** Replaces ${<alias>.<property>} of entities the request has saved, e.g. the id of a converter it created. */
static JsonNode resolvePlaceholders(JsonNode node, Map<String, ObjectNode> aliasOutputs) { static JsonNode resolvePlaceholders(JsonNode node, Map<String, ObjectNode> aliasOutputs) {
if (node == null) { if (node == null) {
return null; return null;
@ -834,17 +991,29 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null; return id != null && dashboardService.findDashboardById(tenantId, id) != null ? id : null;
} }
/** What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the update. */ /**
* What isn't transactional: the audit log, version control and attributes. A failure here doesn't undo the install
* or update.
*/
private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) { private void afterCommit(SecurityUser user, TenantId tenantId, Applied applied) {
for (SavedEntity saved : applied.saved()) { for (SavedEntity saved : applied.saved()) {
try { try {
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), CustomerId customerId = saved.entity() instanceof HasCustomerId owned ? owned.getCustomerId() : null;
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), customerId,
saved.created() ? ActionType.ADDED : ActionType.UPDATED, user); saved.created() ? ActionType.ADDED : ActionType.UPDATED, user);
if (saved.id().getEntityType() != EntityType.DEVICE) { if (saved.id().getEntityType() != EntityType.DEVICE) {
autoCommit(user, saved.id()); autoCommit(user, saved.id());
} }
} catch (Exception e) { } catch (Exception e) {
log.warn("[{}] Failed to log the device package update of {}", tenantId, saved.id(), e); log.warn("[{}] Failed to log the device package change of {}", tenantId, saved.id(), e);
}
}
for (SavedEntity saved : applied.grouped()) {
try {
logEntityActionService.logEntityAction(tenantId, saved.id(), (HasName) saved.entity(), ((HasCustomerId) saved.entity()).getCustomerId(),
ActionType.ADDED_TO_ENTITY_GROUP, user, saved.id().toString(), applied.entityGroup().getId().toString(), applied.entityGroup().getName());
} catch (Exception e) {
log.warn("[{}] Failed to log adding {} to its entity group", tenantId, saved.id(), e);
} }
} }
for (StepAttributes step : applied.attributes()) { for (StepAttributes step : applied.attributes()) {
@ -855,7 +1024,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e); log.warn("[{}] Failed to save the attributes of device package step [{}]", tenantId, step.stepName(), e);
} }
} }
for (DeviceUpdateRequest.Step step : applied.connectorSteps()) { for (DevicePackageRequest.Step step : applied.connectorSteps()) {
try { try {
saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity()); saveConnector(tenantId, applied.aliasOutputs().get("gateway"), step.getEntity());
} catch (Exception e) { } catch (Exception e) {
@ -903,9 +1072,20 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
* The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database * The message the wizard shows: the ones validation and limits give, as they are; anything else, e.g. a database
* error, as a common message, with the details in the log. * error, as a common message, with the details in the log.
*/ */
static JsonNode limitOf(Throwable e) {
SubscriptionException subscription = ExceptionUtils.throwableOfType(e, SubscriptionException.class);
if (subscription != null) {
return JacksonUtil.valueToTree(ThingsboardErrorResponse.ofSubscriptionViolation(subscription.getMessage(), subscription.getErrorCode(),
subscription.getEntry(), subscription.getValue(), HttpStatus.FORBIDDEN));
}
EntitiesLimitExceededException entities = ExceptionUtils.throwableOfType(e, EntitiesLimitExceededException.class);
return entities == null ? null
: JacksonUtil.valueToTree(ThingsboardEntitiesLimitExceededResponse.of(entities.getMessage(), entities.getEntityType(), entities.getLimit()));
}
static String userMessage(Throwable e) { static String userMessage(Throwable e) {
if (e instanceof EntityVersionMismatchException) { if (e instanceof EntityVersionMismatchException) {
return "Someone changed it while you were reviewing the update. Check the update again."; return "Someone changed it meanwhile. Check the package again.";
} }
if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException if (e instanceof DataValidationException || e instanceof EntitiesLimitExceededException || e instanceof IllegalArgumentException
|| e instanceof SubscriptionException) { || e instanceof SubscriptionException) {
@ -927,29 +1107,7 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
*/ */
private static Set<UUID> ownedIds(DeviceInstalledItemDescriptor descriptor) { private static Set<UUID> ownedIds(DeviceInstalledItemDescriptor descriptor) {
Set<UUID> ids = new HashSet<>(createdIds(descriptor).keySet()); Set<UUID> ids = new HashSet<>(createdIds(descriptor).keySet());
ids.removeAll(usedExistingIds(descriptor).keySet()); descriptor.getUsedExistingEntityIdsIncludingLegacy().forEach(id -> ids.remove(id.getId()));
return ids;
}
/**
* The entities the user chose to use as they were. An install made before the descriptor kept them has them only in
* its install state, which the first update carries over into the descriptor.
*/
private static Map<UUID, EntityId> usedExistingIds(DeviceInstalledItemDescriptor descriptor) {
Map<UUID, EntityId> ids = new LinkedHashMap<>();
if (descriptor.getUsedExistingEntityIds() != null) {
descriptor.getUsedExistingEntityIds().forEach(id -> ids.put(id.getId(), id));
return ids;
}
Map<UUID, EntityId> createdIds = createdIds(descriptor);
if (descriptor.getInstallState() != null) {
descriptor.getInstallState().values().forEach(state -> {
UUID id = toUuid(state.path("entityOutput").path("id").asText());
if (id != null && "use-existing".equals(state.path("resolution").asText()) && createdIds.containsKey(id)) {
ids.put(id, createdIds.get(id));
}
});
}
return ids; return ids;
} }
@ -961,8 +1119,8 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
return ids; return ids;
} }
private static DeviceUpdateRequest.Step copyWithEntity(DeviceUpdateRequest.Step step, JsonNode entity) { private static DevicePackageRequest.Step copyWithEntity(DevicePackageRequest.Step step, JsonNode entity) {
DeviceUpdateRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DeviceUpdateRequest.Step.class); DevicePackageRequest.Step copy = JacksonUtil.treeToValue(JacksonUtil.valueToTree(step), DevicePackageRequest.Step.class);
if (entity != null) { if (entity != null) {
copy.setEntity(entity); copy.setEntity(entity);
} }
@ -972,6 +1130,11 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) { private record DevicePackage(IotHubInstalledItem installedItem, DeviceInstalledItemDescriptor descriptor) {
} }
@FunctionalInterface
private interface PackageChange {
Applied apply() throws Exception;
}
private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) { private record StepResult(EntityId entityId, ObjectNode output, String checksum, SavedEntity saved) {
} }
@ -982,8 +1145,16 @@ public class DefaultDevicePackageUpdateService extends AbstractTbEntityService i
} }
private record Applied(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs, List<SavedEntity> saved, private record Applied(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs, List<SavedEntity> saved,
List<DeviceUpdateRequest.Step> connectorSteps, List<StepAttributes> attributes, List<DevicePackageRequest.Step> connectorSteps, List<StepAttributes> attributes,
Map<String, ObjectNode> aliasOutputs) { Map<String, ObjectNode> aliasOutputs, EntityGroup entityGroup, List<SavedEntity> grouped) {
}
/**
* Where an install opened from a customer's or a device group's page puts its entities. A new device follows the
* group's customer when no customer is given, as a device saved into a group does; an update has none.
*/
private record Placement(CustomerId customerId, CustomerId deviceCustomerId, EntityGroup entityGroup) {
static final Placement NONE = new Placement(null, null, null);
} }
/** A step that failed: the transaction rolls back, and the wizard shows which step it was. */ /** A step that failed: the transaction rolls back, and the wizard shows which step it was. */

223
application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java

@ -8,15 +8,22 @@ import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.thingsboard.common.util.ExceptionUtil; import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer; import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile; import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.HasTenantId;
import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.AssetProfile; import org.thingsboard.server.common.data.asset.AssetProfile;
import org.thingsboard.server.common.data.cf.CalculatedField; import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.CalculatedFieldType; import org.thingsboard.server.common.data.cf.CalculatedFieldType;
import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.exception.ThingsboardException; import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.group.EntityGroup; import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo; import org.thingsboard.server.common.data.group.EntityGroupInfo;
@ -43,6 +50,7 @@ import org.thingsboard.server.common.data.iot_hub.RuleChainInstalledItemDescript
import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.SolutionTemplateInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor; import org.thingsboard.server.common.data.iot_hub.WidgetInstalledItemDescriptor;
import org.thingsboard.server.common.data.subscription.SubscriptionException; import org.thingsboard.server.common.data.subscription.SubscriptionException;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.exception.EntitiesLimitExceededException; import org.thingsboard.server.exception.EntitiesLimitExceededException;
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;
@ -91,8 +99,11 @@ import java.util.HexFormat;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service @Service
@TbCoreComponent @TbCoreComponent
@ -251,7 +262,7 @@ public class DefaultIotHubService implements IotHubService {
} }
private EntityGroupInfo checkEntityGroup(SecurityUser user, EntityGroupId entityGroupId) throws ThingsboardException { private EntityGroupInfo checkEntityGroup(SecurityUser user, EntityGroupId entityGroupId) throws ThingsboardException {
EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoById(user.getTenantId(), entityGroupId); EntityGroupInfo entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(user.getTenantId(), entityGroupId);
if (entityGroup == null) { if (entityGroup == null) {
throw new IllegalArgumentException("Entity group with id [" + entityGroupId + "] is not found"); throw new IllegalArgumentException("Entity group with id [" + entityGroupId + "] is not found");
} }
@ -268,6 +279,7 @@ public class DefaultIotHubService implements IotHubService {
} }
calculatedField.setId(null); calculatedField.setId(null);
calculatedField.setTenantId(tenantId); calculatedField.setTenantId(tenantId);
mapTenantReferences(calculatedField, tenantId);
if (data != null && data.has("entityId")) { if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class); EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
calculatedField.setEntityId(entityId); calculatedField.setEntityId(entityId);
@ -292,6 +304,7 @@ public class DefaultIotHubService implements IotHubService {
} }
alarmRule.setId(null); alarmRule.setId(null);
alarmRule.setTenantId(tenantId); alarmRule.setTenantId(tenantId);
mapTenantReferences(alarmRule, tenantId);
if (data != null && data.has("entityId")) { if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class); EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
alarmRule.setEntityId(entityId); alarmRule.setEntityId(entityId);
@ -421,7 +434,7 @@ public class DefaultIotHubService implements IotHubService {
String itemType = installedItem.getItemType(); String itemType = installedItem.getItemType();
if ("DEVICE".equals(itemType)) { if ("DEVICE".equals(itemType)) {
// Updated in one transaction from the install wizard of the new version, see DevicePackageUpdateService // Updated in one transaction from the install wizard of the new version, see DevicePackageService
throw new IllegalArgumentException("A device package is updated by the install wizard of the new version"); throw new IllegalArgumentException("A device package is updated by the install wizard of the new version");
} }
IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor(); IotHubInstalledItemDescriptor descriptor = installedItem.getDescriptor();
@ -531,6 +544,7 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName()); existing.setName(newCf.getName());
existing.setType(newCf.getType()); existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration()); existing.setConfiguration(newCf.getConfiguration());
mapTenantReferences(existing, tenantId);
tbCalculatedFieldService.save(existing, user); tbCalculatedFieldService.save(existing, user);
} }
@ -551,9 +565,26 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName()); existing.setName(newCf.getName());
existing.setType(newCf.getType()); existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration()); existing.setConfiguration(newCf.getConfiguration());
mapTenantReferences(existing, tenantId);
tbCalculatedFieldService.save(existing, user); tbCalculatedFieldService.save(existing, user);
} }
private void mapTenantReferences(CalculatedField calculatedField, TenantId tenantId) {
if (calculatedField.getConfiguration() instanceof GeofencingCalculatedFieldConfiguration geofencingCfg) {
geofencingCfg.getZoneGroups().values().forEach(zoneGroupConfiguration -> {
if (zoneGroupConfiguration.getRefEntityId() != null && zoneGroupConfiguration.getRefEntityId().getEntityType() == EntityType.TENANT) {
zoneGroupConfiguration.setRefEntityId(tenantId);
}
});
} else if (calculatedField.getConfiguration() instanceof ArgumentsBasedCalculatedFieldConfiguration argBasedConfig) {
argBasedConfig.getArguments().values().forEach(argument -> {
if (argument.getRefEntityId() != null && argument.getRefEntityId().getEntityType() == EntityType.TENANT) {
argument.setRefEntityId(tenantId);
}
});
}
}
private void updateRuleChain(TenantId tenantId, RuleChainInstalledItemDescriptor descriptor, byte[] fileData) throws Exception { private void updateRuleChain(TenantId tenantId, RuleChainInstalledItemDescriptor descriptor, byte[] fileData) throws Exception {
JsonNode json = JacksonUtil.toJsonNode(new String(fileData)); JsonNode json = JacksonUtil.toJsonNode(new String(fileData));
RuleChainMetaData metadata; RuleChainMetaData metadata;
@ -674,6 +705,8 @@ public class DefaultIotHubService implements IotHubService {
UUID itemId = UUID.fromString(versionInfo.get("itemId").asText()); UUID itemId = UUID.fromString(versionInfo.get("itemId").asText());
String version = versionInfo.get("version").asText(); String version = versionInfo.get("version").asText();
validateDevicePackageEntities(tenantId, descriptor);
IotHubInstalledItem installedItem = new IotHubInstalledItem(); IotHubInstalledItem installedItem = new IotHubInstalledItem();
installedItem.setTenantId(tenantId); installedItem.setTenantId(tenantId);
installedItem.setItemId(itemId); installedItem.setItemId(itemId);
@ -720,7 +753,9 @@ public class DefaultIotHubService implements IotHubService {
/** /**
* Deletes what a device package created, except the entities another installed device package * Deletes what a device package created, except the entities another installed device package
* also uses (e.g. an integration it took over with Overwrite): deleting those would break that package, * also uses (e.g. an integration it took over with Overwrite): deleting those would break that package,
* and the ones the user had before and the package took as they were (use existing). * and the ones the user had before and the package took as they were (use existing). A device profile that devices
* still use stays too, e.g. with the devices a LoRaWAN integration created, and any kept profile keeps what it refers
* to: TB deletes neither.
* A kept integration loses the metadata entries the package added. * A kept integration loses the metadata entries the package added.
*/ */
private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId, private void deleteDevicePackageEntities(TenantId tenantId, IotHubInstalledItemId installedItemId,
@ -729,7 +764,7 @@ public class DefaultIotHubService implements IotHubService {
if (createdEntityIds == null || createdEntityIds.isEmpty()) { if (createdEntityIds == null || createdEntityIds.isEmpty()) {
return; return;
} }
Set<UUID> usedExisting = usedExistingIds(descriptor); Set<UUID> usedExisting = descriptor.getUsedExistingEntityIdsIncludingLegacy().stream().map(EntityId::getId).collect(Collectors.toSet());
List<DeviceInstalledItemDescriptor> otherPackages = new ArrayList<>(); List<DeviceInstalledItemDescriptor> otherPackages = new ArrayList<>();
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, otherPackages); Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, otherPackages);
// An entity goes before what it refers to: a device before its profile, a profile before its default dashboard // An entity goes before what it refers to: a device before its profile, a profile before its default dashboard
@ -737,22 +772,42 @@ public class DefaultIotHubService implements IotHubService {
List<EntityId> ordered = new ArrayList<>(createdEntityIds); List<EntityId> ordered = new ArrayList<>(createdEntityIds);
Collections.reverse(ordered); Collections.reverse(ordered);
ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size()))); ordered.sort(Comparator.comparingInt(id -> DELETE_ORDER.getOrDefault(id.getEntityType(), DELETE_ORDER.size())));
// What a kept profile refers to: its default rule chain and dashboard, which come after it in the order
Set<UUID> referencedByKeptProfiles = new HashSet<>();
for (EntityId entityId : ordered) { for (EntityId entityId : ordered) {
if (usedExisting.contains(entityId.getId())) { if (usedExisting.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId()); log.info("[{}] Kept {} {}: the package took it as it was", tenantId, entityId.getEntityType(), entityId.getId());
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue; continue;
} }
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId()); Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
if (usedBy != null) { if (usedBy != null) {
log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy); log.info("[{}] Kept {} {}: installed device packages {} use it", tenantId, entityId.getEntityType(), entityId.getId(), usedBy);
removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages); removeIntegrationMetadata(tenantId, entityId, descriptor, otherPackages);
profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue;
}
if (referencedByKeptProfiles.contains(entityId.getId())) {
log.info("[{}] Kept {} {}: a kept device profile refers to it", tenantId, entityId.getEntityType(), entityId.getId());
continue;
}
// The package's own devices are deleted by now; the ones left came from elsewhere, e.g. a LoRaWAN integration
long devices = countProfileDevices(tenantId, entityId, Set.of());
if (devices > 0) {
log.info("[{}] Kept device profile {}: devices use it ({})", tenantId, entityId.getId(), devices);
profileReferences(tenantId, entityId).forEach(reference -> referencedByKeptProfiles.add(reference.getId()));
continue; continue;
} }
try { try {
deleteDevicePackageEntity(tenantId, entityId, user); deleteDevicePackageEntity(tenantId, entityId, user);
} catch (Exception e) { } catch (Exception e) {
log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e); // A reference the package doesn't know of, e.g. a profile the user made later with the package's rule chain
if (ExceptionUtils.indexOfType(e, DataValidationException.class) >= 0) {
log.info("[{}] Kept {} {}: {}", tenantId, entityId.getEntityType(), entityId.getId(), ExceptionUtils.getRootCauseMessage(e));
} else {
log.error("[{}] Failed to delete device package entity: {}", tenantId, entityId, e);
}
} }
} }
} }
@ -773,8 +828,8 @@ public class DefaultIotHubService implements IotHubService {
return; return;
} }
try { try {
Integration integration = integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId())); // Only an integration of this tenant: the id comes from the stored descriptor
if (integration == null || !(integration.getConfiguration() != null if (!(findDevicePackageEntity(tenantId, entityId) instanceof Integration integration) || !(integration.getConfiguration() != null
&& integration.getConfiguration().get("metadata") instanceof ObjectNode metadata) && integration.getConfiguration().get("metadata") instanceof ObjectNode metadata)
|| keys.stream().noneMatch(metadata::has)) { || keys.stream().noneMatch(metadata::has)) {
return; return;
@ -811,16 +866,26 @@ public class DefaultIotHubService implements IotHubService {
throw new IllegalArgumentException("Installed item not found"); throw new IllegalArgumentException("Installed item not found");
} }
List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>(); List<InstalledItemKeptEntities.KeptEntity> kept = new ArrayList<>();
List<InstalledItemKeptEntities.KeptEntity> referenced = new ArrayList<>();
Set<IotHubInstalledItemId> usedByItems = new HashSet<>(); Set<IotHubInstalledItemId> usedByItems = new HashSet<>();
int usedExistingCount = 0; int usedExistingCount = 0;
if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) { if (installedItem.getDescriptor() instanceof DeviceInstalledItemDescriptor dd && dd.getCreatedEntityIds() != null) {
Set<UUID> usedExisting = usedExistingIds(dd); Set<UUID> usedExisting = dd.getUsedExistingEntityIdsIncludingLegacy().stream().map(EntityId::getId).collect(Collectors.toSet());
Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>()); Map<UUID, Set<IotHubInstalledItemId>> usedByOtherPackages = findEntitiesOfOtherDevicePackages(tenantId, installedItemId, new ArrayList<>());
// The delete removes these before the profiles, so they don't keep a profile; a kept device does
Set<UUID> deletedDevices = new HashSet<>();
dd.getCreatedEntityIds().stream()
.filter(id -> id.getEntityType() == EntityType.DEVICE && !usedExisting.contains(id.getId()) && !usedByOtherPackages.containsKey(id.getId()))
.forEach(id -> deletedDevices.add(id.getId()));
Set<UUID> created = new HashSet<>();
dd.getCreatedEntityIds().forEach(id -> created.add(id.getId()));
Set<UUID> keptIds = new HashSet<>();
for (EntityId entityId : dd.getCreatedEntityIds()) { for (EntityId entityId : dd.getCreatedEntityIds()) {
Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId()); Set<IotHubInstalledItemId> usedBy = usedByOtherPackages.get(entityId.getId());
boolean taken = usedExisting.contains(entityId.getId()); boolean taken = usedExisting.contains(entityId.getId());
if (usedBy != null || taken) { if (usedBy != null || taken) {
kept.add(new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null))); kept.add(keptEntity(tenantId, entityId));
keptIds.add(entityId.getId());
} }
if (usedBy != null) { if (usedBy != null) {
usedByItems.addAll(usedBy); usedByItems.addAll(usedBy);
@ -829,17 +894,65 @@ public class DefaultIotHubService implements IotHubService {
usedExistingCount++; usedExistingCount++;
} }
} }
for (EntityId entityId : dd.getCreatedEntityIds()) {
if (!keptIds.contains(entityId.getId()) && countProfileDevices(tenantId, entityId, deletedDevices) > 0) {
referenced.add(keptEntity(tenantId, entityId));
keptIds.add(entityId.getId());
}
}
// A kept profile, for whatever reason, keeps what it refers to
for (EntityId entityId : dd.getCreatedEntityIds()) {
if (!keptIds.contains(entityId.getId())) {
continue;
}
for (EntityId reference : profileReferences(tenantId, entityId)) {
if (created.contains(reference.getId()) && keptIds.add(reference.getId())) {
referenced.add(keptEntity(tenantId, reference));
}
}
}
} }
return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount); return new InstalledItemKeptEntities(kept, usedByItems.size(), usedExistingCount, referenced);
} }
/** The entities the package took as they were at install (use existing); none for installs before 4.4.1 kept them. */ private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) {
private static Set<UUID> usedExistingIds(DeviceInstalledItemDescriptor descriptor) { String name = findDevicePackageEntity(tenantId, entityId) != null
Set<UUID> ids = new HashSet<>(); ? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null;
if (descriptor.getUsedExistingEntityIds() != null) { return new InstalledItemKeptEntities.KeptEntity(entityId, name);
descriptor.getUsedExistingEntityIds().forEach(id -> ids.add(id.getId())); }
/** The default rule chains and dashboard of a device profile, which TB doesn't delete while it refers to them; none for another entity. */
private List<EntityId> profileReferences(TenantId tenantId, EntityId profileId) {
List<EntityId> references = new ArrayList<>();
if (profileId.getEntityType() != EntityType.DEVICE_PROFILE) {
return references;
}
DeviceProfile profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(profileId.getId()));
if (profile != null) {
Stream.of(profile.getDefaultRuleChainId(), profile.getDefaultEdgeRuleChainId(), profile.getDefaultDashboardId())
.filter(Objects::nonNull)
.forEach(references::add);
}
return references;
}
/**
* How many devices use the device profile {@code entityId}, apart from {@code excludedDevices}; 0 for another entity.
* TB doesn't delete a profile that devices use.
*/
private long countProfileDevices(TenantId tenantId, EntityId entityId, Set<UUID> excludedDevices) {
if (entityId.getEntityType() != EntityType.DEVICE_PROFILE) {
return 0;
} }
return ids; DeviceProfileId profileId = new DeviceProfileId(entityId.getId());
long count = deviceService.findDeviceIdsByTenantIdAndDeviceProfileId(tenantId, profileId, new PageLink(1)).getTotalElements();
for (UUID deviceId : excludedDevices) {
Device device = deviceService.findDeviceById(tenantId, new DeviceId(deviceId));
if (device != null && profileId.equals(device.getDeviceProfileId())) {
count--;
}
}
return Math.max(count, 0);
} }
/** The other installed device packages' entities, by id; the packages' descriptors go to {@code otherPackages}. */ /** The other installed device packages' entities, by id; the packages' descriptors go to {@code otherPackages}. */
@ -864,36 +977,56 @@ public class DefaultIotHubService implements IotHubService {
return usedBy; return usedBy;
} }
private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException { private void validateDevicePackageEntities(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) {
switch (entityId.getEntityType()) { if (descriptor == null) {
case DEVICE -> { throw new IllegalArgumentException("Device package descriptor is required");
var device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId())); }
if (device != null) tbDeviceService.delete(device, user); List<EntityId> entityIds = new ArrayList<>();
} if (descriptor.getCreatedEntityIds() != null) {
case DEVICE_PROFILE -> { entityIds.addAll(descriptor.getCreatedEntityIds());
var profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId())); }
if (profile != null) tbDeviceProfileService.delete(profile, user); if (descriptor.getDashboardId() != null) {
} entityIds.add(descriptor.getDashboardId());
case DASHBOARD -> { }
var dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId())); if (descriptor.getUsedExistingEntityIds() != null) {
if (dashboard != null) tbDashboardService.delete(dashboard, user); entityIds.addAll(descriptor.getUsedExistingEntityIds());
} }
case RULE_CHAIN -> { for (EntityId entityId : entityIds) {
var ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId())); if (entityId == null || findDevicePackageEntity(tenantId, entityId) == null) {
if (ruleChain != null) tbRuleChainService.delete(ruleChain, user); throw new IllegalArgumentException("Device package entity not found: " + entityId);
}
case INTEGRATION -> {
IntegrationId integrationId = new IntegrationId(entityId.getId());
var integration = integrationService.findIntegrationById(tenantId, integrationId);
if (integration != null) {
integrationService.deleteIntegration(tenantId, integrationId);
}
}
case CONVERTER -> {
var converter = converterService.findConverterById(tenantId, new ConverterId(entityId.getId()));
if (converter != null) tbConverterService.delete(converter, user);
} }
default -> log.warn("[{}] Unsupported entity type for device package delete: {}", tenantId, entityId.getEntityType()); }
}
private HasTenantId findDevicePackageEntity(TenantId tenantId, EntityId entityId) {
HasTenantId entity = switch (entityId.getEntityType()) {
case DEVICE -> deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId()));
case DEVICE_PROFILE -> deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId()));
case DASHBOARD -> dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId()));
case RULE_CHAIN -> ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId()));
case INTEGRATION -> integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId()));
case CONVERTER -> converterService.findConverterById(tenantId, new ConverterId(entityId.getId()));
default -> null;
};
return entity != null && tenantId.equals(entity.getTenantId()) ? entity : null;
}
private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException {
HasTenantId entity = findDevicePackageEntity(tenantId, entityId);
if (entity instanceof Device device) {
tbDeviceService.delete(device, user);
} else if (entity instanceof DeviceProfile profile) {
tbDeviceProfileService.delete(profile, user);
} else if (entity instanceof Dashboard dashboard) {
tbDashboardService.delete(dashboard, user);
} else if (entity instanceof RuleChain ruleChain) {
tbRuleChainService.delete(ruleChain, user);
} else if (entity instanceof Integration integration) {
integrationService.deleteIntegration(tenantId, integration.getId());
} else if (entity instanceof Converter converter) {
tbConverterService.delete(converter, user);
} else {
log.warn("[{}] Skipped device package entity {}: not found", tenantId, entityId);
} }
} }

30
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateRequest.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageRequest.java

@ -10,28 +10,33 @@ import java.util.Map;
import java.util.UUID; import java.util.UUID;
/** /**
* The update of an installed device package as the install wizard planned it: the entity of each install step * The install or update of a device package as the install wizard planned it: the entity of each install step
* of the new version, already resolved from its template, and what to do with it. The server applies all of it * of the version being installed, already resolved from its template, and what to do with it. The server applies
* in one transaction, together with the new version of the installed item, or nothing. * all of it in one transaction, together with the installed item, or nothing.
*/ */
@Data @Data
public class DeviceUpdateRequest { public class DevicePackageRequest {
private String versionId; private String versionId;
// The version installed when the wizard planned the update; the update fails if the package changed since // Update only: the version installed when the wizard planned the update, which fails if the package changed since
private UUID fromVersionId; private UUID fromVersionId;
// The install method of the new version's steps; the installed one when not set // The install method of the steps; an update without it keeps the installed one
private String selectedInstallMethod; private String selectedInstallMethod;
// The form values of the install state, by step: the server adds the entities to it // The form values of the install state, by step: the server adds the entities to it
private Map<String, JsonNode> installState; private Map<String, JsonNode> installState;
// Install only, from a customer's or a device group's page: the customer the device, the gateway and the dashboard
// go to, and the group the created device or gateway is added to. An update ignores them
private UUID customerId;
private UUID entityGroupId;
private List<Step> steps; private List<Step> steps;
public enum Action { public enum Action {
// Taken as it is: the new version doesn't change it, or the user kept an entity they had // Taken as it is: an update's new version doesn't change it, or the user kept an entity they had
KEEP, KEEP,
// Takes the entity from the step // Takes the entity from the step
OVERWRITE, OVERWRITE,
// A new entity: new in this version, deleted since install, or a copy next to one with the same name // A new entity: one the package installs, a step new in this version or deleted since install, or a copy
// next to one with the same name
CREATE CREATE
} }
@ -51,13 +56,13 @@ public class DeviceUpdateRequest {
private Long expectedVersion; private Long expectedVersion;
// The user confirmed overwriting an entity of another package or one they didn't install with this package // The user confirmed overwriting an entity of another package or one they didn't install with this package
private boolean confirmed; private boolean confirmed;
// OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity this // OVERWRITE and CREATE: the entity resolved from the template. ${<alias>.<property>} of an entity the
// update creates is left for the server, which knows its id only once it is created. // request creates is left for the server, which knows its id only once it is created.
private JsonNode entity; private JsonNode entity;
// DEVICE and GATEWAY: the credentials template, if any // DEVICE and GATEWAY: the credentials template, if any
private JsonNode credentials; private JsonNode credentials;
// OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity, // OVERWRITE and CREATE: the attributes of the saved entity, written after the transaction. Like the entity,
// they may keep ${<alias>.<property>} of an entity this update creates. // they may keep ${<alias>.<property>} of an entity the request creates.
private JsonNode serverAttributes; private JsonNode serverAttributes;
private JsonNode sharedAttributes; private JsonNode sharedAttributes;
// The resolution the install state records for it // The resolution the install state records for it
@ -65,7 +70,8 @@ public class DeviceUpdateRequest {
// INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the // INTEGRATION: the step's metadata entries, which the package's converter reads. A KEEP merges them into the
// integration, e.g. one the package took as it was; null removes an entry // integration, e.g. one the package took as it was; null removes an entry
private JsonNode metadata; private JsonNode metadata;
// UPLINK_CONVERTER: the step takes ThingsBoard's default converter, which the install state records for the update check // UPLINK_CONVERTER: the step takes ThingsBoard's default converter. The install state records it, so that a later
// update checks that converter against ThingsBoard's default one
private boolean defaultConverter; private boolean defaultConverter;
/** /**

17
application/src/main/java/org/thingsboard/server/service/iot_hub/DeviceUpdateResult.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageResult.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1 // SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.iot_hub; package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
@ -17,7 +18,7 @@ import java.util.Map;
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class DeviceUpdateResult { public class DevicePackageResult {
private boolean success; private boolean success;
private String errorMessage; private String errorMessage;
@ -25,13 +26,19 @@ public class DeviceUpdateResult {
private DeviceInstalledItemDescriptor descriptor; private DeviceInstalledItemDescriptor descriptor;
// By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token} // By install state key of the step: what the install instructions resolve, e.g. ${integration.httpEndpoint}, ${device.token}
private Map<String, ObjectNode> outputs; private Map<String, ObjectNode> outputs;
// When a step failed on an entity or subscription limit: the same body ThingsBoard answers such a request with (403)
private JsonNode limit;
public static DeviceUpdateResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) { public static DevicePackageResult success(DeviceInstalledItemDescriptor descriptor, Map<String, ObjectNode> outputs) {
return new DeviceUpdateResult(true, null, null, descriptor, outputs); return new DevicePackageResult(true, null, null, descriptor, outputs, null);
} }
public static DeviceUpdateResult error(String errorMessage, String failedStep) { public static DevicePackageResult error(String errorMessage, String failedStep) {
return new DeviceUpdateResult(false, errorMessage, failedStep, null, null); return error(errorMessage, failedStep, null);
}
public static DevicePackageResult error(String errorMessage, String failedStep, JsonNode limit) {
return new DevicePackageResult(false, errorMessage, failedStep, null, null, limit);
} }
} }

9
application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageUpdateService.java → application/src/main/java/org/thingsboard/server/service/iot_hub/DevicePackageService.java

@ -7,13 +7,16 @@ import org.thingsboard.server.service.security.model.SecurityUser;
import java.util.List; import java.util.List;
/** Updates an installed device package to another version of its item. */ /** Installs a device package, or updates an installed one to another version of its item. */
public interface DevicePackageUpdateService { public interface DevicePackageService {
/** The package's entities as they are now: whether they still exist, changed since, or are shared. */ /** The package's entities as they are now: whether they still exist, changed since, or are shared. */
List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId); List<DevicePackageEntityState> check(SecurityUser user, IotHubInstalledItemId installedItemId);
/** Installs the version in one transaction, together with its installed item, or nothing. */
DevicePackageResult install(SecurityUser user, DevicePackageRequest request);
/** Applies the update in one transaction, together with the new version of the installed item, or nothing. */ /** Applies the update in one transaction, together with the new version of the installed item, or nothing. */
DeviceUpdateResult apply(SecurityUser user, IotHubInstalledItemId installedItemId, DeviceUpdateRequest request); DevicePackageResult update(SecurityUser user, IotHubInstalledItemId installedItemId, DevicePackageRequest request);
} }

8
application/src/main/java/org/thingsboard/server/service/iot_hub/InstalledItemKeptEntities.java

@ -9,7 +9,10 @@ import org.thingsboard.server.common.data.id.EntityId;
import java.util.List; import java.util.List;
/** What deleting an installed item keeps: what other installed items use too, and what the user had before it. */ /**
* What deleting an installed item keeps: what other installed items use too, what the user had before it, and what other
* tenant entities refer to (a LoRaWAN integration creates its devices on the first uplink, not the package).
*/
@Data @Data
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
@ -20,6 +23,9 @@ public class InstalledItemKeptEntities {
private int usedByItemsCount; private int usedByItemsCount;
// How many of the kept entities the user had before and the package took as they were (use existing) // How many of the kept entities the user had before and the package took as they were (use existing)
private int usedExistingCount; private int usedExistingCount;
// What other tenant entities refer to: the package's device profiles that devices use, and the default rule chains and
// dashboard of a kept profile. Apart from entities, which an update reads as shared with other packages
private List<KeptEntity> referencedEntities;
@Data @Data
@NoArgsConstructor @NoArgsConstructor

5
application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java

@ -1,12 +1,13 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.iot_hub; package org.thingsboard.server.service.iot_hub;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import jakarta.annotation.PostConstruct; import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.http.HttpMethod; import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;

2
application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java

@ -106,6 +106,8 @@ public class TbMailSender extends JavaMailSenderImpl {
} }
} }
javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", enableTls); javaMailProperties.put(MAIL_PROP + protocol + ".starttls.enable", enableTls);
// Angus Mail checks the server identity unless this is set
javaMailProperties.put(MAIL_PROP + protocol + ".ssl.checkserveridentity", "false");
if (enableTls && jsonConfig.has("tlsVersion") && !jsonConfig.get("tlsVersion").isNull()) { if (enableTls && jsonConfig.has("tlsVersion") && !jsonConfig.get("tlsVersion").isNull()) {
String tlsVersion = jsonConfig.get("tlsVersion").asText(); String tlsVersion = jsonConfig.get("tlsVersion").asText();
if (StringUtils.isNoneEmpty(tlsVersion)) { if (StringUtils.isNoneEmpty(tlsVersion)) {

9
application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java

@ -114,6 +114,9 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
NotificationTemplate notificationTemplate; NotificationTemplate notificationTemplate;
if (request.getTemplateId() != null) { if (request.getTemplateId() != null) {
notificationTemplate = notificationTemplateService.findNotificationTemplateById(tenantId, request.getTemplateId()); notificationTemplate = notificationTemplateService.findNotificationTemplateById(tenantId, request.getTemplateId());
if (notificationTemplate != null && !isTenantOrSystem(tenantId, notificationTemplate.getTenantId())) {
notificationTemplate = null;
}
} else { } else {
notificationTemplate = request.getTemplate(); notificationTemplate = request.getTemplate();
} }
@ -126,7 +129,7 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
List<NotificationTarget> targets = new ArrayList<>(); List<NotificationTarget> targets = new ArrayList<>();
for (UUID targetId : request.getTargets()) { for (UUID targetId : request.getTargets()) {
NotificationTarget target = notificationTargetService.findNotificationTargetById(tenantId, new NotificationTargetId(targetId)); NotificationTarget target = notificationTargetService.findNotificationTargetById(tenantId, new NotificationTargetId(targetId));
if (target != null) { if (target != null && tenantId.equals(target.getTenantId())) {
targets.add(target); targets.add(target);
} else { } else {
log.debug("Unknown notification target {} in request {}", targetId, request); log.debug("Unknown notification target {} in request {}", targetId, request);
@ -516,6 +519,10 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
return "notification"; return "notification";
} }
private static boolean isTenantOrSystem(TenantId tenantId, TenantId ownerId) {
return tenantId.equals(ownerId) || ownerId.isSysTenantId();
}
@Autowired @Autowired
public void setChannels(List<NotificationChannel> channels, NotificationCenter webNotificationChannel) { public void setChannels(List<NotificationChannel> channels, NotificationCenter webNotificationChannel) {
this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c)); this.channels = channels.stream().collect(Collectors.toMap(NotificationChannel::getDeliveryMethod, c -> c));

2
application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java

@ -10,7 +10,7 @@ import lombok.RequiredArgsConstructor;
import lombok.Setter; import lombok.Setter;
import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;

8
application/src/main/java/org/thingsboard/server/service/notification/provider/DefaultFirebaseService.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.notification.provider; package org.thingsboard.server.service.notification.provider;
import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Cache;
@ -52,8 +53,11 @@ public class DefaultFirebaseService implements FirebaseService {
} }
}); });
// mutable-content lets the iOS app's notification service extension
// add the template icon to the push before iOS shows it
Aps.Builder apsConfig = Aps.builder() Aps.Builder apsConfig = Aps.builder()
.setSound("default"); .setSound("default")
.setMutableContent(true);
if (badge != null) { if (badge != null) {
apsConfig.setBadge(badge); apsConfig.setBadge(badge);
} }

17
application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java

@ -26,6 +26,7 @@ import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.widget.WidgetTypeDetails; import org.thingsboard.server.common.data.widget.WidgetTypeDetails;
import org.thingsboard.server.dao.resource.ImageService; import org.thingsboard.server.dao.resource.ImageService;
import org.thingsboard.server.dao.resource.ResourceService; import org.thingsboard.server.dao.resource.ResourceService;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.queue.util.TbCoreComponent; import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService; import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
@ -57,6 +58,22 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements
@Override @Override
public TbResourceInfo save(TbResource resource, SecurityUser user) throws ThingsboardException { public TbResourceInfo save(TbResource resource, SecurityUser user) throws ThingsboardException {
if (resource.getId() != null) {
TbResourceInfo existing = checkNotNull(resourceService.findResourceInfoById(resource.getTenantId(), resource.getId()));
if ((resource.getResourceType() != null && resource.getResourceType() != existing.getResourceType()) ||
(resource.getResourceSubType() != null && resource.getResourceSubType() != existing.getResourceSubType())) {
throw new DataValidationException("Resource type can't be changed");
}
resource.setTenantId(existing.getTenantId());
resource.setCustomerId(existing.getCustomerId());
resource.setResourceType(existing.getResourceType());
resource.setResourceSubType(existing.getResourceSubType());
resource.setResourceKey(existing.getResourceKey());
resource.setCreatedTime(existing.getCreatedTime());
if (resource.getData() == null) {
resource.setEtag(existing.getEtag());
}
}
if (resource.getResourceType() == ResourceType.IMAGE) { if (resource.getResourceType() == ResourceType.IMAGE) {
throw new IllegalArgumentException("Image resource type is not supported"); throw new IllegalArgumentException("Image resource type is not supported");
} }

2
application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java

@ -274,7 +274,7 @@ public class DefaultSchedulerService extends AbstractPartitionBasedService<Tenan
deviceService.saveDevice(device); deviceService.saveDevice(device);
break; break;
case ENTITY_GROUP: case ENTITY_GROUP:
EntityGroup deviceGroup = entityGroupService.findEntityGroupById(tenantId, (EntityGroupId) originatorId); EntityGroup deviceGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, (EntityGroupId) originatorId);
if (deviceGroup == null) { if (deviceGroup == null) {
throw new RuntimeException("Failed to process event: Device group with id [" + originatorId + "] not found!"); throw new RuntimeException("Failed to process event: Device group with id [" + originatorId + "] not found!");
} }

2
application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java

@ -647,7 +647,7 @@ public class AccessValidator {
if (currentUser.isSystemAdmin()) { if (currentUser.isSystemAdmin()) {
callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION)); callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
} else { } else {
ListenableFuture<EntityGroupInfo> entityGroupFuture = entityGroupService.findEntityGroupInfoByIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId())); ListenableFuture<EntityGroupInfo> entityGroupFuture = entityGroupService.findEntityGroupInfoByTenantIdAndIdAsync(currentUser.getTenantId(), new EntityGroupId(entityId.getId()));
Futures.addCallback(entityGroupFuture, getCallback(callback, entityGroup -> { Futures.addCallback(entityGroupFuture, getCallback(callback, entityGroup -> {
if (entityGroup == null) { if (entityGroup == null) {
return ValidationResult.entityNotFound("Entity group with requested id wasn't found!"); return ValidationResult.entityNotFound("Entity group with requested id wasn't found!");

8
application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java

@ -1,11 +1,15 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth; package org.thingsboard.server.service.security.auth;
import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.token.RawAccessJwtToken; import org.thingsboard.server.service.security.model.token.RawAccessJwtToken;
import java.util.Collection;
public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticationToken { public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = -6212297506742428406L; private static final long serialVersionUID = -6212297506742428406L;
@ -14,7 +18,7 @@ public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticat
private SecurityUser securityUser; private SecurityUser securityUser;
public AbstractJwtAuthenticationToken(RawAccessJwtToken unsafeToken) { public AbstractJwtAuthenticationToken(RawAccessJwtToken unsafeToken) {
super(null); super((Collection<? extends GrantedAuthority>) null);
this.rawAccessToken = unsafeToken; this.rawAccessToken = unsafeToken;
this.setAuthenticated(false); this.setAuthenticated(false);
} }

7
application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java

@ -4,7 +4,7 @@
package org.thingsboard.server.service.security.auth.jwt; package org.thingsboard.server.service.security.auth.jwt;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -19,8 +19,9 @@ public class SkipPathRequestMatcher implements RequestMatcher {
public SkipPathRequestMatcher(List<String> pathsToSkip, List<String> pathsToProcess) { public SkipPathRequestMatcher(List<String> pathsToSkip, List<String> pathsToProcess) {
Assert.notNull(pathsToSkip, "List of paths to skip is required."); Assert.notNull(pathsToSkip, "List of paths to skip is required.");
List<RequestMatcher> skip = pathsToSkip.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList()); PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults();
List<RequestMatcher> process = pathsToProcess.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList()); List<RequestMatcher> skip = pathsToSkip.stream().<RequestMatcher>map(builder::matcher).collect(Collectors.toList());
List<RequestMatcher> process = pathsToProcess.stream().<RequestMatcher>map(builder::matcher).collect(Collectors.toList());
skipMatchers = new OrRequestMatcher(skip); skipMatchers = new OrRequestMatcher(skip);
processMatchers = new OrRequestMatcher(process); processMatchers = new OrRequestMatcher(process);
} }

16
application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java

@ -1,11 +1,12 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth.oauth2; package org.thingsboard.server.service.security.auth.oauth2;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
@ -28,7 +29,7 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme
private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token"; private static final String PROVIDER_ACCESS_TOKEN = "provider-access-token";
private RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder(); private final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
@Override @Override
public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client auth2Client) { public SecurityUser getOrCreateUserByClientPrincipal(HttpServletRequest request, OAuth2AuthenticationToken token, String providerAccessToken, OAuth2Client auth2Client) {
@ -37,15 +38,16 @@ public class CustomOAuth2ClientMapper extends AbstractOAuth2ClientMapper impleme
return getOrCreateSecurityUserFromOAuth2User(oauth2User, auth2Client); return getOrCreateSecurityUserFromOAuth2User(oauth2User, auth2Client);
} }
private synchronized OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) { private OAuth2User getOAuth2User(OAuth2AuthenticationToken token, String providerAccessToken, OAuth2CustomMapperConfig custom) {
RestTemplateBuilder builder = restTemplateBuilder;
if (!StringUtils.isEmpty(custom.getUsername()) && !StringUtils.isEmpty(custom.getPassword())) { if (!StringUtils.isEmpty(custom.getUsername()) && !StringUtils.isEmpty(custom.getPassword())) {
restTemplateBuilder = restTemplateBuilder.basicAuthentication(custom.getUsername(), custom.getPassword()); builder = builder.basicAuthentication(custom.getUsername(), custom.getPassword());
} }
if (custom.isSendToken() && !StringUtils.isEmpty(providerAccessToken)) { if (custom.isSendToken() && !StringUtils.isEmpty(providerAccessToken)) {
restTemplateBuilder = restTemplateBuilder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken); builder = builder.defaultHeader(PROVIDER_ACCESS_TOKEN, providerAccessToken);
} }
RestTemplate restTemplate = restTemplateBuilder.build(); RestTemplate restTemplate = builder.build();
String request; String request;
try { try {
request = JacksonUtil.getObjectMapperWithJavaTimeModule().writeValueAsString(token.getPrincipal()); request = JacksonUtil.getObjectMapperWithJavaTimeModule().writeValueAsString(token.getPrincipal());

5
application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth.oauth2; package org.thingsboard.server.service.security.auth.oauth2;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
@ -7,7 +8,7 @@ import lombok.Data;
import lombok.ToString; import lombok.ToString;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;

7
application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java

@ -1,12 +1,15 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.security.auth.pat; package org.thingsboard.server.service.security.auth.pat;
import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.thingsboard.server.service.security.model.SecurityUser; import org.thingsboard.server.service.security.model.SecurityUser;
import org.thingsboard.server.service.security.model.token.ApiKeyAuthRequest; import org.thingsboard.server.service.security.model.token.ApiKeyAuthRequest;
import java.io.Serial; import java.io.Serial;
import java.util.Collection;
public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken { public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
@ -17,7 +20,7 @@ public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
private SecurityUser securityUser; private SecurityUser securityUser;
public ApiKeyAuthenticationToken(ApiKeyAuthRequest apiKeyAuthRequest) { public ApiKeyAuthenticationToken(ApiKeyAuthRequest apiKeyAuthRequest) {
super(null); super((Collection<? extends GrantedAuthority>) null);
this.apiKeyAuthRequest = apiKeyAuthRequest; this.apiKeyAuthRequest = apiKeyAuthRequest;
setAuthenticated(false); setAuthenticated(false);
} }

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

@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.id.HasId;
import org.thingsboard.server.common.data.id.ReportTemplateId; import org.thingsboard.server.common.data.id.ReportTemplateId;
import org.thingsboard.server.common.data.id.TbResourceId; import org.thingsboard.server.common.data.id.TbResourceId;
import org.thingsboard.server.common.data.menu.CustomMenuInfo; import org.thingsboard.server.common.data.menu.CustomMenuInfo;
import org.thingsboard.server.common.data.pat.ApiKeyInfo;
import org.thingsboard.server.common.data.permission.GroupPermission; import org.thingsboard.server.common.data.permission.GroupPermission;
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;
@ -525,6 +526,9 @@ public class CustomerUserPermissions extends AbstractPermissions {
if (!user.getTenantId().equals(entity.getTenantId())) { if (!user.getTenantId().equals(entity.getTenantId())) {
return false; return false;
} }
if (!(entity instanceof ApiKeyInfo apiKeyInfo) || !user.getId().equals(apiKeyInfo.getUserId())) {
return false;
}
// This entity does not have groups, so we are checking only generic level permissions // This entity does not have groups, so we are checking only generic level permissions
return user.getUserPermissions().hasGenericPermission(Resource.API_KEY, operation); return user.getUserPermissions().hasGenericPermission(Resource.API_KEY, operation);
} }

2
application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java

@ -332,7 +332,7 @@ public class DefaultSystemSecurityService implements SystemSecurityService {
@Override @Override
public AccessJwtToken createUserAccessToken(TenantId tenantId, UserId userId) throws ThingsboardException { public AccessJwtToken createUserAccessToken(TenantId tenantId, UserId userId) throws ThingsboardException {
User user = userService.findUserById(tenantId, userId); User user = userService.findUserById(tenantId, userId);
if (user == null) { if (user == null || !user.getTenantId().equals(tenantId)) {
throw new ThingsboardException("Configured user [id: " + userId + "] was not found in system. Please use other user credentials.", ThingsboardErrorCode.BAD_REQUEST_PARAMS); throw new ThingsboardException("Configured user [id: " + userId + "] was not found in system. Please use other user credentials.", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
} }
UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, userId); UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, userId);

8
application/src/main/java/org/thingsboard/server/service/subscription/DefaultTbEntityDataSubscriptionService.java

@ -422,7 +422,13 @@ public class DefaultTbEntityDataSubscriptionService implements TbEntityDataSubsc
List<EntityData> entities = ctx.getEntitiesData(); List<EntityData> entities = ctx.getEntitiesData();
ctx.cancelTasks(); ctx.cancelTasks();
ctx.clearEntitySubscriptions(); ctx.clearEntitySubscriptions();
if (entities.isEmpty()) { if (ctx.isOwnerScoped()) {
ctx.fetchAlarms();
TbAlarmDataSubCtx finalCtx = ctx;
ScheduledFuture<?> task = scheduler.scheduleWithFixedDelay(
() -> refreshAlarmQuery(finalCtx), dynamicPageLinkRefreshInterval, dynamicPageLinkRefreshInterval, TimeUnit.SECONDS);
finalCtx.setRefreshTask(task);
} else if (entities.isEmpty()) {
AlarmDataUpdate update = new AlarmDataUpdate(cmd.getCmdId(), new PageData<>(), null, 0, 0); AlarmDataUpdate update = new AlarmDataUpdate(cmd.getCmdId(), new PageData<>(), null, 0, 0);
ctx.sendWsMsg(update); ctx.sendWsMsg(update);
} else { } else {

4
application/src/main/java/org/thingsboard/server/service/subscription/TbAbstractDataSubCtx.java

@ -66,6 +66,9 @@ public abstract class TbAbstractDataSubCtx<T extends AbstractDataQuery<? extends
return query != null && query.getPageLink().isDynamic(); return query != null && query.getPageLink().isDynamic();
} }
protected void onSameEntities(Map<EntityId, EntityData> newDataMap) {
}
@Override @Override
protected synchronized void update() { protected synchronized void update() {
PageData<EntityData> newData = findEntityData(); PageData<EntityData> newData = findEntityData();
@ -78,6 +81,7 @@ public abstract class TbAbstractDataSubCtx<T extends AbstractDataQuery<? extends
Map<EntityId, EntityData> newDataMap = newData.getData().stream().collect(Collectors.toMap(EntityData::getEntityId, Function.identity(), (a, b) -> a)); Map<EntityId, EntityData> newDataMap = newData.getData().stream().collect(Collectors.toMap(EntityData::getEntityId, Function.identity(), (a, b) -> a));
if (oldDataMap.size() == newDataMap.size() && oldDataMap.keySet().equals(newDataMap.keySet())) { if (oldDataMap.size() == newDataMap.size() && oldDataMap.keySet().equals(newDataMap.keySet())) {
log.trace("[{}][{}] No updates to entity data found", sessionRef.getSessionId(), cmdId); log.trace("[{}][{}] No updates to entity data found", sessionRef.getSessionId(), cmdId);
onSameEntities(newDataMap);
} else { } else {
this.data = newData; this.data = newData;
doUpdate(newDataMap); doUpdate(newDataMap);

45
application/src/main/java/org/thingsboard/server/service/subscription/TbAlarmDataSubCtx.java

@ -101,7 +101,10 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx<AlarmDataQuery> {
return; return;
} }
AlarmDataUpdate update; AlarmDataUpdate update;
if (!entitiesMap.isEmpty()) { if (isOwnerScoped()) {
setAndMergeAlarmsData(findOwnerAlarms());
update = new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0);
} else if (!entitiesMap.isEmpty()) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
PageData<AlarmData> alarms = alarmService.findAlarmDataByQueryForEntities(getTenantId(), PageData<AlarmData> alarms = alarmService.findAlarmDataByQueryForEntities(getTenantId(),
getMergedUserPermissions(), query, getOrderedEntityIds()); getMergedUserPermissions(), query, getOrderedEntityIds());
@ -116,9 +119,39 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx<AlarmDataQuery> {
sendWsMsg(update); sendWsMsg(update);
} }
public boolean isOwnerScoped() {
return query != null && query.getEntityFilter() == null;
}
private PageData<AlarmData> findOwnerAlarms() {
long start = System.currentTimeMillis();
PageData<AlarmData> result = alarmService.findAlarmDataByQuery(getTenantId(), getCustomerId(), getMergedUserPermissions(), query);
stats.getAlarmQueryInvocationCnt().incrementAndGet();
stats.getAlarmQueryTimeSpent().addAndGet(System.currentTimeMillis() - start);
return result;
}
private void refreshOwnerAlarms() {
if (stopped) {
return;
}
PageData<AlarmData> fresh = findOwnerAlarms();
if (alarms != null && alarms.getTotalElements() == fresh.getTotalElements() && alarms.getData().equals(fresh.getData())) {
return;
}
setAndMergeAlarmsData(fresh);
sendWsMsg(new AlarmDataUpdate(cmdId, alarms, null, maxEntitiesPerAlarmSubscription, 0));
}
public void fetchData() { public void fetchData() {
resetInvocationCounter(); resetInvocationCounter();
log.trace("[{}] Fetching data: {}", cmdId, alarmInvocationAttempts); log.trace("[{}] Fetching data: {}", cmdId, alarmInvocationAttempts);
if (isOwnerScoped()) {
data = PageData.emptyPageData();
entitiesMap.clear();
tooManyEntities = false;
return;
}
super.fetchData(); super.fetchData();
entitiesMap.clear(); entitiesMap.clear();
tooManyEntities = data.hasNext(); tooManyEntities = data.hasNext();
@ -232,6 +265,9 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx<AlarmDataQuery> {
} }
public void cleanupOldAlarms() { public void cleanupOldAlarms() {
if (query.getPageLink().getTimeWindow() <= 0) {
return;
}
long expTime = System.currentTimeMillis() - query.getPageLink().getTimeWindow(); long expTime = System.currentTimeMillis() - query.getPageLink().getTimeWindow();
boolean shouldRefresh = false; boolean shouldRefresh = false;
for (AlarmData alarmData : alarms.getData()) { for (AlarmData alarmData : alarms.getData()) {
@ -248,7 +284,7 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx<AlarmDataQuery> {
private boolean filter(Alarm alarm) { private boolean filter(Alarm alarm) {
AlarmDataPageLink filter = query.getPageLink(); AlarmDataPageLink filter = query.getPageLink();
long startTs = System.currentTimeMillis() - filter.getTimeWindow(); long startTs = System.currentTimeMillis() - filter.getTimeWindow();
if (alarm.getCreatedTime() < startTs) { if (filter.getTimeWindow() > 0 && alarm.getCreatedTime() < startTs) {
//Skip update that does not match time window. //Skip update that does not match time window.
return false; return false;
} }
@ -292,6 +328,11 @@ public class TbAlarmDataSubCtx extends TbAbstractDataSubCtx<AlarmDataQuery> {
} }
public synchronized void checkAndResetInvocationCounter() { public synchronized void checkAndResetInvocationCounter() {
if (isOwnerScoped()) {
resetInvocationCounter();
refreshOwnerAlarms();
return;
}
boolean fetchNeeded = this.alarmInvocationAttempts > maxAlarmQueriesPerRefreshInterval; boolean fetchNeeded = this.alarmInvocationAttempts > maxAlarmQueriesPerRefreshInterval;
resetInvocationCounter(); resetInvocationCounter();
if (fetchNeeded) { if (fetchNeeded) {

33
application/src/main/java/org/thingsboard/server/service/subscription/TbEntityDataSubCtx.java

@ -3,6 +3,7 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1 // SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.service.subscription; package org.thingsboard.server.service.subscription;
import java.util.Objects;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@ -177,6 +178,38 @@ public class TbEntityDataSubCtx extends TbAbstractDataSubCtx<EntityDataQuery> {
}); });
} }
@Override
protected void onSameEntities(Map<EntityId, EntityData> newDataMap) {
List<EntityData> changed = new ArrayList<>();
for (EntityData current : data.getData()) {
EntityData fresh = newDataMap.get(current.getEntityId());
Map<String, TsValue> freshFields = fresh != null && fresh.getLatest() != null ? fresh.getLatest().get(EntityKeyType.ENTITY_FIELD) : null;
if (freshFields == null || freshFields.isEmpty() || current.getLatest() == null) {
continue;
}
if (!sameFieldValues(current.getLatest().get(EntityKeyType.ENTITY_FIELD), freshFields)) {
current.getLatest().put(EntityKeyType.ENTITY_FIELD, freshFields);
changed.add(new EntityData(current.getEntityId(), false, false, Map.of(EntityKeyType.ENTITY_FIELD, freshFields), null));
}
}
if (!changed.isEmpty()) {
sendWsMsg(new EntityDataUpdate(cmdId, null, changed, maxEntitiesPerDataSubscription));
}
}
private static boolean sameFieldValues(Map<String, TsValue> current, Map<String, TsValue> fresh) {
if (current == null || current.size() != fresh.size()) {
return false;
}
for (Map.Entry<String, TsValue> entry : fresh.entrySet()) {
TsValue value = current.get(entry.getKey());
if (value == null || !Objects.equals(value.getValue(), entry.getValue().getValue())) {
return false;
}
}
return true;
}
@Override @Override
public synchronized void doUpdate(Map<EntityId, EntityData> newDataMap) { public synchronized void doUpdate(Map<EntityId, EntityData> newDataMap) {
this.updateLatestTsData(this.data); this.updateLatestTsData(this.data);

2
application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java

@ -7,7 +7,7 @@ import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder; import org.springframework.boot.restclient.RestTemplateBuilder;
import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;

20
application/src/main/java/org/thingsboard/server/utils/MiscUtils.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.utils; package org.thingsboard.server.utils;
import com.google.common.hash.HashFunction; import com.google.common.hash.HashFunction;
@ -43,13 +44,20 @@ public class MiscUtils {
getPort(request)); getPort(request));
} }
public static String getScheme(HttpServletRequest request){ public static String getScheme(HttpServletRequest request) {
String scheme = request.getScheme();
String forwardedProto = request.getHeader("x-forwarded-proto"); String forwardedProto = request.getHeader("x-forwarded-proto");
if (forwardedProto != null) { if (isHttpScheme(forwardedProto)) {
scheme = forwardedProto; return forwardedProto.toLowerCase();
}
String scheme = request.getScheme();
if (forwardedProto == null && isHttpScheme(scheme)) {
return scheme.toLowerCase();
} }
return scheme; return request.isSecure() ? "https" : "http";
}
private static boolean isHttpScheme(String scheme) {
return "http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme);
} }
public static String getDomainName(HttpServletRequest request){ public static String getDomainName(HttpServletRequest request){

16
application/src/main/resources/thingsboard.yml

@ -13,6 +13,9 @@ server:
port: "${HTTP_BIND_PORT:8080}" port: "${HTTP_BIND_PORT:8080}"
# Server forward headers strategy. Required for SWAGGER UI when reverse proxy is used # Server forward headers strategy. Required for SWAGGER UI when reverse proxy is used
forward_headers_strategy: "${HTTP_FORWARD_HEADERS_STRATEGY:framework}" forward_headers_strategy: "${HTTP_FORWARD_HEADERS_STRATEGY:framework}"
tomcat:
# Maximum number of GET and POST request parameters Tomcat parses per request
max-parameter-count: "${SERVER_TOMCAT_MAX_PARAMETER_COUNT:10000}"
# Server SSL configuration # Server SSL configuration
ssl: ssl:
# Enable/disable SSL support # Enable/disable SSL support
@ -1205,16 +1208,15 @@ spring.mvc.cors:
allow-credentials: "${TB_CORS_ALLOW_CREDENTIALS:true}" allow-credentials: "${TB_CORS_ALLOW_CREDENTIALS:true}"
# General spring parameters # General spring parameters
# Miscellaneous Spring Boot settings including circular references, Freemarker, async request timeout, path matching strategy, and static resource chain. # Miscellaneous Spring Boot settings including circular references, Freemarker, async request timeout, and path matching strategy.
spring.main.allow-circular-references: "true" # Spring Boot configuration property that controls whether circular dependencies between beans are allowed. spring.main.allow-circular-references: "true" # Spring Boot configuration property that controls whether circular dependencies between beans are allowed.
spring.freemarker.checkTemplateLocation: "false" # spring freemarker configuration spring.freemarker.checkTemplateLocation: "false" # spring freemarker configuration
spring.mvc.async.request-timeout: "${SPRING_MVC_ASYNC_REQUEST_TIMEOUT:30000}" # The default timeout for asynchronous requests in milliseconds spring.mvc.async.request-timeout: "${SPRING_MVC_ASYNC_REQUEST_TIMEOUT:30000}" # The default timeout for asynchronous requests in milliseconds
spring.mvc.pathmatch.matching-strategy: "ANT_PATH_MATCHER" # For endpoints matching in Swagger spring.mvc.pathmatch.matching-strategy: "ANT_PATH_MATCHER" # For endpoints matching in Swagger
spring.resources.chain: spring.http.converters.preferred-json-mapper: "jackson2" # JSON mapper for HTTP message conversion; ThingsBoard uses Jackson 2
compressed: "true" # This property enables or disables support for serving pre-compressed resources (for example, a .gzip or .br file) spring.web.resources.chain:
strategy: enabled: "true" # Enables the Spring resource chain explicitly instead of relying on a webjars locator being on the classpath
content: compressed: "true" # Serve the pre-compressed .br/.gz copies of the UI files built by ui-ngx when the client accepts them
enabled: "true" # This property enables or disables the content Version Strategy. This strategy allows Spring to generate a unique version for static resources, which is based on the content of the resource
spring.servlet.multipart.max-file-size: "${SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE:50MB}" # Total file size cannot exceed 50MB when configuring file uploads spring.servlet.multipart.max-file-size: "${SPRING_SERVLET_MULTIPART_MAX_FILE_SIZE:50MB}" # Total file size cannot exceed 50MB when configuring file uploads
spring.servlet.multipart.max-request-size: "${SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE:50MB}" # Total request size for a multipart/form-data cannot exceed 50MB spring.servlet.multipart.max-request-size: "${SPRING_SERVLET_MULTIPART_MAX_REQUEST_SIZE:50MB}" # Total request size for a multipart/form-data cannot exceed 50MB
@ -2554,7 +2556,7 @@ queue:
# Statistics printing interval for Edge services # Statistics printing interval for Edge services
print-interval-ms: "${TB_QUEUE_EDGE_STATS_PRINT_INTERVAL_MS:60000}" print-interval-ms: "${TB_QUEUE_EDGE_STATS_PRINT_INTERVAL_MS:60000}"
integration: integration:
# Name of hash function used for consistent hash ring in Cluster Mode. See architecture docs for more details. Valid values - murmur3_32, murmur3_128 or sha256 # Number of partitions in each integration queue; there is one queue per integration type. Must match TB_QUEUE_INTEGRATION_PARTITIONS on the Integration Executors, otherwise downlinks, integration validation and Check connection may not reach the executor that runs the integration.
partitions: "${TB_QUEUE_INTEGRATION_PARTITIONS:3}" partitions: "${TB_QUEUE_INTEGRATION_PARTITIONS:3}"
# For high-priority notifications that require minimum latency and processing time # For high-priority notifications that require minimum latency and processing time
notifications_topic: "${TB_QUEUE_INTEGRATION_NOTIFICATIONS_TOPIC:tb_integration_executor.notifications}" notifications_topic: "${TB_QUEUE_INTEGRATION_NOTIFICATIONS_TOPIC:tb_integration_executor.notifications}"

40
application/src/test/java/org/thingsboard/server/actors/rule/DefaultTbContextTest.java

@ -1,5 +1,6 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors // SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-License-Identifier: Apache-2.0 // SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.actors.rule; package org.thingsboard.server.actors.rule;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@ -20,12 +21,18 @@ import org.thingsboard.server.actors.ruleChain.RuleChainOutputMsg;
import org.thingsboard.server.actors.ruleChain.RuleNodeCtx; import org.thingsboard.server.actors.ruleChain.RuleNodeCtx;
import org.thingsboard.server.actors.ruleChain.RuleNodeToRuleChainTellNextMsg; import org.thingsboard.server.actors.ruleChain.RuleNodeToRuleChainTellNextMsg;
import org.thingsboard.server.cluster.TbClusterService; import org.thingsboard.server.cluster.TbClusterService;
import org.thingsboard.server.common.adaptor.JsonConverter;
import org.thingsboard.server.common.data.DataConstants; import org.thingsboard.server.common.data.DataConstants;
import org.thingsboard.server.common.data.debug.DebugSettings; import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.RuleChainId; import org.thingsboard.server.common.data.id.RuleChainId;
import org.thingsboard.server.common.data.id.RuleNodeId; import org.thingsboard.server.common.data.id.RuleNodeId;
import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.kv.AttributeKvEntry;
import org.thingsboard.server.common.data.kv.BaseAttributeKvEntry;
import org.thingsboard.server.common.data.kv.DataType;
import org.thingsboard.server.common.data.kv.LongDataEntry;
import org.thingsboard.server.common.data.kv.StringDataEntry;
import org.thingsboard.server.common.data.msg.TbMsgType; import org.thingsboard.server.common.data.msg.TbMsgType;
import org.thingsboard.server.common.data.msg.TbNodeConnectionType; import org.thingsboard.server.common.data.msg.TbNodeConnectionType;
import org.thingsboard.server.common.data.rule.RuleNode; import org.thingsboard.server.common.data.rule.RuleNode;
@ -41,10 +48,12 @@ import org.thingsboard.server.queue.common.SimpleTbQueueCallback;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
@ -1093,6 +1102,35 @@ class DefaultTbContextTest {
.build(); .build();
} }
@Test
public void givenSavedStringAttributes_whenAttributesUpdatedActionMsg_thenNumericStringsStayStringsWhenParsed() {
List<AttributeKvEntry> attributes = List.of(
new BaseAttributeKvEntry(new StringDataEntry("joinEui", "0000000000000000"), 0L),
new BaseAttributeKvEntry(new StringDataEntry("devEui", "70B3D57ED0012345"), 0L),
new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L));
TbMsg msg = defaultTbContext.attributesUpdatedActionMsg(TENANT_ID, RULE_NODE_ID, DataConstants.CLIENT_SCOPE, attributes);
assertThat(msg.getType()).isEqualTo(TbMsgType.ATTRIBUTES_UPDATED.name());
assertThat(msg.getMetaData().getValue(DataConstants.SCOPE)).isEqualTo(DataConstants.CLIENT_SCOPE);
assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isEqualTo("[\"joinEui\"]");
Map<String, AttributeKvEntry> parsed = JsonConverter.attributesFromMsg(msg).stream()
.collect(Collectors.toMap(AttributeKvEntry::getKey, Function.identity()));
assertThat(parsed.get("joinEui").getDataType()).isEqualTo(DataType.STRING);
assertThat(parsed.get("joinEui").getValue()).isEqualTo("0000000000000000");
assertThat(parsed.get("devEui").getDataType()).isEqualTo(DataType.STRING);
assertThat(parsed.get("fCnt").getDataType()).isEqualTo(DataType.LONG);
}
@Test
public void givenNoNumericStringAttributes_whenAttributesUpdatedActionMsg_thenNoTypeCastDisabledKeys() {
List<AttributeKvEntry> attributes = List.of(new BaseAttributeKvEntry(new LongDataEntry("fCnt", 42L), 0L));
TbMsg msg = defaultTbContext.attributesUpdatedActionMsg(TENANT_ID, RULE_NODE_ID, DataConstants.CLIENT_SCOPE, attributes);
assertThat(msg.getMetaData().getValue(TbMsgMetaData.TYPE_CAST_DISABLED_KEYS)).isNull();
}
private TbMsg getTbMsgWithQueueName() { private TbMsg getTbMsgWithQueueName() {
return TbMsg.newMsg() return TbMsg.newMsg()
.queueName(DataConstants.MAIN_QUEUE_NAME) .queueName(DataConstants.MAIN_QUEUE_NAME)

2
application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java

@ -70,8 +70,8 @@ import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
@Slf4j @Slf4j
@DaoSqlTest @DaoSqlTest

2
application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java

@ -9,10 +9,10 @@ import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.Futures;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test; import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean; import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.TestPropertySource;
import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AttributeScope; import org.thingsboard.server.common.data.AttributeScope;
import org.thingsboard.server.common.data.Device; import org.thingsboard.server.common.data.Device;

57
application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java

@ -0,0 +1,57 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.config;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.thingsboard.server.dao.oauth2.OAuth2ClientService;
import org.thingsboard.server.service.security.model.token.OAuth2AppTokenFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verifyNoInteractions;
@ExtendWith(MockitoExtension.class)
class CustomOAuth2AuthorizationRequestResolverTest {
@Mock
private ClientRegistrationRepository clientRegistrationRepository;
@Mock
private OAuth2ClientService oAuth2ClientService;
@Mock
private OAuth2AppTokenFactory oAuth2AppTokenFactory;
@InjectMocks
private CustomOAuth2AuthorizationRequestResolver resolver;
@Test
void resolvesTheRegistrationIdFromTheAuthorizationPath() {
given(clientRegistrationRepository.findByRegistrationId("abc-123")).willReturn(ClientRegistration.withRegistrationId("abc-123")
.clientId("client")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("{baseUrl}/login/oauth2/code/")
.authorizationUri("https://idp.example.com/authorize")
.tokenUri("https://idp.example.com/token")
.build());
OAuth2AuthorizationRequest request = resolver.resolve(new MockHttpServletRequest("GET", "/oauth2/authorization/abc-123"));
assertThat(request.getAttributes()).containsEntry(OAuth2ParameterNames.REGISTRATION_ID, "abc-123");
assertThat(request.getAuthorizationUri()).isEqualTo("https://idp.example.com/authorize");
}
@Test
void ignoresDeeperPaths() {
assertThat(resolver.resolve(new MockHttpServletRequest("GET", "/oauth2/authorization/abc/extra"))).isNull();
verifyNoInteractions(clientRegistrationRepository);
}
}

40
application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java

@ -0,0 +1,40 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.thingsboard.server.controller.AbstractControllerTest;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@DaoSqlTest
public class JsonMapperWiringTest extends AbstractControllerTest {
@Autowired
private RequestMappingHandlerAdapter handlerAdapter;
@Autowired
private ObjectMapper objectMapper;
@Test
public void mvcUsesJackson2() {
List<HttpMessageConverter<?>> converters = handlerAdapter.getMessageConverters();
assertThat(converters).noneMatch(c -> c.getClass().getName().startsWith("org.springframework.http.converter.json.JacksonJson"));
MappingJackson2HttpMessageConverter json = converters.stream()
.filter(MappingJackson2HttpMessageConverter.class::isInstance)
.map(MappingJackson2HttpMessageConverter.class::cast)
.findFirst().orElseThrow();
assertThat(json.getObjectMapper()).isSameAs(objectMapper);
assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
}
}

117
application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java

@ -0,0 +1,117 @@
// SPDX-FileCopyrightText: Copyright The ThingsBoard Authors
// SPDX-FileCopyrightText: Modifications Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.config;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.http.converter.autoconfigure.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.autoconfigure.DispatcherServletAutoConfiguration;
import org.springframework.boot.webmvc.autoconfigure.WebMvcAutoConfiguration;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.zip.GZIPOutputStream;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.http.HttpHeaders.ACCEPT_ENCODING;
import static org.springframework.http.HttpHeaders.CONTENT_ENCODING;
import static org.springframework.http.HttpHeaders.VARY;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;
/**
* Loads the real thingsboard.yml, so the test fails if its static resource chain keys stop binding again.
*/
@SpringBootTest(classes = StaticResourceCompressionTest.WebMvcConfig.class, properties = "spring.config.name=thingsboard")
public class StaticResourceCompressionTest {
private static final byte[] JS = "console.log('ThingsBoard');\n".repeat(100).getBytes(StandardCharsets.UTF_8);
private static final byte[] JS_GZ = gzip(JS);
private static final byte[] CSS = "@font-face { src: url(font.woff2); }\n".getBytes(StandardCharsets.UTF_8);
@TempDir
static Path webRoot;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
@DynamicPropertySource
static void staticLocations(DynamicPropertyRegistry registry) {
registry.add("spring.web.resources.static-locations", () -> webRoot.toUri().toString());
}
@BeforeAll
static void createStaticFiles() throws IOException {
Files.write(webRoot.resolve("main.js"), JS);
Files.write(webRoot.resolve("main.js.gz"), JS_GZ);
Files.write(webRoot.resolve("styles.css"), CSS);
Files.write(webRoot.resolve("font.woff2"), new byte[]{1, 2, 3});
}
@BeforeEach
void setUpMockMvc() {
mvc = webAppContextSetup(webApplicationContext).build();
}
@Test
public void servesPrebuiltGzipWhenClientAcceptsIt() throws Exception {
mvc.perform(get("/main.js").header(ACCEPT_ENCODING, "gzip, deflate, br"))
.andExpect(status().isOk())
.andExpect(header().string(CONTENT_ENCODING, "gzip"))
.andExpect(header().string(VARY, containsString(ACCEPT_ENCODING)))
.andExpect(content().contentTypeCompatibleWith("text/javascript"))
.andExpect(content().bytes(JS_GZ));
}
@Test
public void servesRawFileWhenClientDoesNotAcceptGzip() throws Exception {
mvc.perform(get("/main.js"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(CONTENT_ENCODING))
.andExpect(content().bytes(JS));
}
@Test
public void servesStylesheetUnchanged() throws Exception {
// the content version strategy would rewrite url(font.woff2) to url(font-<md5>.woff2)
mvc.perform(get("/styles.css").header(ACCEPT_ENCODING, "gzip"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(CONTENT_ENCODING))
.andExpect(content().bytes(CSS));
}
// not @Configuration: @ComponentScan("org.thingsboard.server") in other tests would pick it up
@ImportAutoConfiguration({DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class})
static class WebMvcConfig {
}
private static byte[] gzip(byte[] data) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(out)) {
gzip.write(data);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return out.toByteArray();
}
}

26
application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java

@ -0,0 +1,26 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.config;
import org.junit.jupiter.api.Test;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.ClassPathResource;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class ThingsboardYmlDefaultsTest {
@Test
void tomcatMaxParameterCountDefaultsTo10000() throws IOException {
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load("thingsboard", new ClassPathResource("thingsboard.yml"));
StandardEnvironment environment = new StandardEnvironment();
sources.forEach(environment.getPropertySources()::addLast);
assertThat(environment.getProperty("server.tomcat.max-parameter-count", Integer.class)).isEqualTo(10000);
}
}

5
application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java

@ -7,9 +7,9 @@ import lombok.extern.slf4j.Slf4j;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootContextLoader; import org.springframework.boot.test.context.SpringBootContextLoader;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
@ -63,7 +63,8 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest {
public static final String WS_URL = "ws://localhost:"; public static final String WS_URL = "ws://localhost:";
@LocalServerPort // This class is also the context's configuration bean, which is created before the server port is known
@Value("${local.server.port:0}")
protected int serverPort; protected int serverPort;
protected volatile TbTestWebSocketClient wsClient; // lazy protected volatile TbTestWebSocketClient wsClient; // lazy

11
application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java

@ -46,12 +46,14 @@ import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.AbstractMockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap; import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.MailService; import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.server.actors.DefaultTbActorSystem; import org.thingsboard.server.actors.DefaultTbActorSystem;
@ -334,14 +336,15 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest {
}; };
@Autowired @Autowired
void setConverters(HttpMessageConverter<?>[] converters) { void setConverters(RequestMappingHandlerAdapter handlerAdapter) {
List<HttpMessageConverter<?>> converters = handlerAdapter.getMessageConverters();
this.mappingJackson2HttpMessageConverter = Arrays.stream(converters) this.mappingJackson2HttpMessageConverter = converters.stream()
.filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter) .filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
.findAny() .findAny()
.get(); .get();
this.stringHttpMessageConverter = Arrays.stream(converters) this.stringHttpMessageConverter = converters.stream()
.filter(hmc -> hmc instanceof StringHttpMessageConverter) .filter(hmc -> hmc instanceof StringHttpMessageConverter)
.findAny() .findAny()
.get(); .get();
@ -761,7 +764,7 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest {
doPost("/api/auth/logout").andExpect(status().isOk()); doPost("/api/auth/logout").andExpect(status().isOk());
} }
protected void setJwtToken(MockHttpServletRequestBuilder request) { protected void setJwtToken(AbstractMockHttpServletRequestBuilder<?> request) {
if (this.token != null) { if (this.token != null) {
request.header(ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER, BEARER_HEADER_PREFIX + this.token); request.header(ThingsboardSecurityConfiguration.AUTHORIZATION_HEADER, BEARER_HEADER_PREFIX + this.token);
} }

30
application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java

@ -10,6 +10,7 @@ import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test; import org.junit.Test;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.thingsboard.common.util.JacksonUtil; import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings; import org.thingsboard.server.common.data.AdminSettings;
@ -17,9 +18,11 @@ import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.security.model.JwtSettings; import org.thingsboard.server.common.data.security.model.JwtSettings;
import org.thingsboard.server.dao.secret.SecretConfigurationService; import org.thingsboard.server.dao.secret.SecretConfigurationService;
import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.settings.AdminSettingsService;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Base64; import java.util.Base64;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
@ -44,6 +47,9 @@ public class AdminControllerTest extends AbstractControllerTest {
@MockitoBean @MockitoBean
private SecretConfigurationService secretConfigurationService; private SecretConfigurationService secretConfigurationService;
@Autowired
private AdminSettingsService adminSettingsService;
@Test @Test
public void testFindAdminSettingsByKey() throws Exception { public void testFindAdminSettingsByKey() throws Exception {
loginSysAdmin(); loginSysAdmin();
@ -111,6 +117,30 @@ public class AdminControllerTest extends AbstractControllerTest {
.andExpect(statusReason(containsString("is prohibited"))); .andExpect(statusReason(containsString("is prohibited")));
} }
@Test
public void testSaveAdminSettingsRefusesVersionControlKeys() throws Exception {
loginTenantAdmin();
checkVersionControlKeysRefused(tenantId);
loginSysAdmin();
checkVersionControlKeysRefused(TenantId.SYS_TENANT_ID);
}
private void checkVersionControlKeysRefused(TenantId settingsTenantId) throws Exception {
Map<String, String> values = Map.of(
"entitiesVersionControl", "{\"repositoryUri\":\"repo1\",\"defaultBranch\":\"main\"}",
"autoCommitSettings", "{}");
for (Map.Entry<String, String> entry : values.entrySet()) {
AdminSettings settings = new AdminSettings();
settings.setKey(entry.getKey());
settings.setJsonValue(JacksonUtil.toJsonNode(entry.getValue()));
doPost("/api/admin/settings", settings)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("version control API")));
assertThat(adminSettingsService.findAdminSettingsByTenantIdAndKey(settingsTenantId, entry.getKey())).isNull();
}
}
@Test @Test
public void testMailOAuth2AuthorizationStoresOnlyInAppPrevUri() throws Exception { public void testMailOAuth2AuthorizationStoresOnlyInAppPrevUri() throws Exception {
loginSysAdmin(); loginSysAdmin();

26
application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java

@ -98,6 +98,32 @@ public class AlarmRuleControllerTest extends AbstractControllerTest {
.andExpect(status().isOk()); .andExpect(status().isOk());
} }
@Test
public void testSaveAlarmRuleWithOtherTenantReference() throws Exception {
Device testDevice = createDevice("Test device", "1234567890");
AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature");
alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(tenantId);
doPost("/api/alarm/rule", alarmRule).andExpect(status().isForbidden());
PageData<AlarmRuleDefinition> alarmRules = doGetTypedWithPageLink(
"/api/alarm/rules/" + EntityType.DEVICE + "/" + testDevice.getUuidId() + "?",
new TypeReference<>() {}, new PageLink(10));
assertThat(alarmRules.getData()).isEmpty();
}
@Test
public void testSaveAlarmRuleWithOwnTenantReference() throws Exception {
Device testDevice = createDevice("Test device", "1234567890");
AlarmRuleDefinition alarmRule = createTestAlarmRule(testDevice.getId(), "High Temperature");
alarmRule.getConfiguration().getArguments().get("temperature").setRefEntityId(savedTenant.getId());
AlarmRuleDefinition saved = saveAlarmRule(alarmRule);
assertThat(saved.getId()).isNotNull();
assertThat(saved.getConfiguration().getArguments().get("temperature").getRefEntityId()).isEqualTo(savedTenant.getId());
}
@Test @Test
public void testGetAlarmRuleById() throws Exception { public void testGetAlarmRuleById() throws Exception {
Device testDevice = createDevice("Test device", "1234567890"); Device testDevice = createDevice("Test device", "1234567890");

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

@ -234,6 +234,57 @@ public class ApiKeyControllerTest extends AbstractControllerTest {
doDelete("/api/apiKey/" + savedApiKey.getId().getId()).andExpect(status().isOk()); doDelete("/api/apiKey/" + savedApiKey.getId().getId()).andExpect(status().isOk());
} }
@Test
public void testCustomerUserListsOwnApiKeys() throws Exception {
loginCustomerAdminUser();
ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true);
apiKeyInfo.setUserId(customerAdminUserId);
doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
PageData<ApiKeyInfo> pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerAdminUserId + "?", new TypeReference<>() {}, new PageLink(10, 0));
Assert.assertEquals(1, pageData.getData().size());
Assert.assertEquals(customerAdminUserId, pageData.getData().get(0).getUserId());
}
@Test
public void testTenantAdminListsCustomerUserApiKeys() throws Exception {
ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true);
apiKeyInfo.setUserId(customerUserId);
doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
PageData<ApiKeyInfo> pageData = doGetTypedWithPageLink("/api/apiKeys/" + customerUserId + "?", new TypeReference<>() {}, new PageLink(10, 0));
Assert.assertEquals(1, pageData.getData().size());
Assert.assertEquals(customerUserId, pageData.getData().get(0).getUserId());
}
@Test
public void testCustomerUserCannotListOtherUserApiKeys() throws Exception {
loginCustomerAdminUser();
doGet("/api/user/" + customerUserId).andExpect(status().isOk());
doGet("/api/apiKeys/" + customerUserId + "?pageSize=10&page=0").andExpect(status().isForbidden());
}
@Test
public void testCustomerUserCannotReadOtherUserApiKeyRelations() throws Exception {
ApiKeyInfo apiKeyInfo = constructApiKeyInfo("Test API key description", true);
apiKeyInfo.setUserId(customerUserId);
ApiKey apiKey = doPost("/api/apiKey", apiKeyInfo, ApiKey.class);
loginCustomerAdminUser();
doGet("/api/relations?fromId=" + apiKey.getId().getId() + "&fromType=API_KEY").andExpect(status().isForbidden());
}
@Test
public void testCustomerUserCannotDeleteTenantAdminApiKey() throws Exception {
ApiKey apiKey = doPost("/api/apiKey", constructApiKeyInfo("Test API key description", true), ApiKey.class);
loginCustomerAdminUser();
doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isForbidden());
loginTenantAdmin();
doDelete("/api/apiKey/" + apiKey.getId().getId()).andExpect(status().isOk());
}
private ApiKeyInfo constructApiKeyInfo(String description, boolean enabled) { private ApiKeyInfo constructApiKeyInfo(String description, boolean enabled) {
ApiKeyInfo apiKeyInfo = new ApiKeyInfo(); ApiKeyInfo apiKeyInfo = new ApiKeyInfo();
apiKeyInfo.setDescription(description); apiKeyInfo.setDescription(description);

30
application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java

@ -16,7 +16,11 @@ 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.UserActivationLink; import org.thingsboard.server.common.data.UserActivationLink;
import org.thingsboard.server.common.data.UserInfo; import org.thingsboard.server.common.data.UserInfo;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.UserId; import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.permission.Operation;
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.common.data.security.UserCredentials; import org.thingsboard.server.common.data.security.UserCredentials;
import org.thingsboard.server.common.data.security.model.SecuritySettings; import org.thingsboard.server.common.data.security.model.SecuritySettings;
@ -24,6 +28,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.user.UserCredentialsDao; import org.thingsboard.server.dao.user.UserCredentialsDao;
import org.thingsboard.server.service.security.auth.rest.LoginRequest; import org.thingsboard.server.service.security.auth.rest.LoginRequest;
import org.thingsboard.server.service.security.model.ChangePasswordRequest; import org.thingsboard.server.service.security.model.ChangePasswordRequest;
import org.thingsboard.server.service.security.permission.AccessControlService;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Consumer; import java.util.function.Consumer;
@ -33,6 +38,8 @@ import static org.assertj.core.api.Assertions.within;
import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -43,6 +50,9 @@ public class AuthControllerTest extends AbstractControllerTest {
@MockitoSpyBean @MockitoSpyBean
private UserCredentialsDao userCredentialsDao; private UserCredentialsDao userCredentialsDao;
@MockitoSpyBean
private AccessControlService accessControlService;
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
loginSysAdmin(); loginSysAdmin();
@ -287,6 +297,26 @@ public class AuthControllerTest extends AbstractControllerTest {
assertThat(getUser(user.getId()).getAdditionalInfo().get("userActivated").asBoolean()).isTrue(); assertThat(getUser(user.getId()).getAdditionalInfo().get("userActivated").asBoolean()).isTrue();
} }
@Test
public void testActivationLinkRequiresWritePermissionOnUser() throws Exception {
loginTenantAdmin();
User user = new User();
user.setAuthority(Authority.TENANT_ADMIN);
user.setEmail("pending-user@thingsboard.org");
user = doPost("/api/user", user, User.class);
doThrow(new ThingsboardException("You don't have permission to perform this operation!", ThingsboardErrorCode.PERMISSION_DENIED))
.when(accessControlService).checkPermission(any(), eq(Resource.USER), eq(Operation.WRITE), eq(user.getId()), any());
doGet("/api/user/" + user.getId() + "/activationLinkInfo").andExpect(status().isForbidden());
doGet("/api/user/" + user.getId() + "/activationLink").andExpect(status().isForbidden());
doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isForbidden());
Mockito.reset(accessControlService);
assertThat(getActivationLinkInfo(user).value()).isNotBlank();
doPost("/api/user/sendActivationMail?email=" + user.getEmail()).andExpect(status().isOk());
}
@Test @Test
public void testGetPageWithoutRedirect() throws Exception { public void testGetPageWithoutRedirect() throws Exception {
doGet("/login").andExpect(status().isOk()); doGet("/login").andExpect(status().isOk());

62
application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java

@ -2,6 +2,7 @@
// SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: Apache-2.0
package org.thingsboard.server.controller; package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -41,6 +42,7 @@ import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.service.DaoSqlTest; import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.Comparator; import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -298,6 +300,48 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
doGet("/api/calculatedField/" + savedCalculatedField.getId().getId()).andExpect(status().isNotFound()); doGet("/api/calculatedField/" + savedCalculatedField.getId().getId()).andExpect(status().isNotFound());
} }
@Test
public void testSaveCalculatedFieldWithOtherTenantReference() throws Exception {
Device testDevice = createDevice("Test device", "1234567890");
CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(tenantId)));
doPost("/api/calculatedField", calculatedField).andExpect(status().isForbidden());
PageData<CalculatedField> calculatedFields = doGetTyped("/api/DEVICE/" + testDevice.getId().getId() + "/calculatedFields?pageSize=10&page=0",
new TypeReference<>() {});
assertThat(calculatedFields.getData()).isEmpty();
}
@Test
public void testSaveCalculatedFieldWithOwnTenantReference() throws Exception {
Device testDevice = createDevice("Test device", "1234567890");
CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), Map.of("T", getArgument(savedTenant.getId())));
CalculatedField savedCalculatedField = doPost("/api/calculatedField", calculatedField, CalculatedField.class);
assertThat(savedCalculatedField.getId()).isNotNull();
assertThat(savedCalculatedField.getConfiguration().getReferencedEntities()).containsExactly(savedTenant.getId());
}
@Test
public void testSaveCalculatedFieldChecksEveryReference() throws Exception {
loginTenantAdmin();
Device otherTenantDevice = createDevice("Other device", "0987654321");
login("tenant2@thingsboard.org", "testPassword1");
Device testDevice = createDevice("Test device", "1234567890");
Map<String, Argument> arguments = new LinkedHashMap<>();
arguments.put("T", getArgument(savedTenant.getId()));
arguments.put("H", getArgument(otherTenantDevice.getId()));
CalculatedField calculatedField = getSimpleCalculatedField(testDevice.getId(), arguments);
doPost("/api/calculatedField", calculatedField).andExpect(status().isNotFound());
}
private CalculatedField getSimpleCalculatedField(EntityId entityId, Map<String, Argument> arguments) {
return getCalculatedField(entityId, CalculatedFieldType.SIMPLE, getSimpleCalculatedFieldConfig(arguments));
}
private CalculatedField getSimpleCalculatedField(EntityId entityId) { private CalculatedField getSimpleCalculatedField(EntityId entityId) {
return getCalculatedField(entityId, CalculatedFieldType.SIMPLE); return getCalculatedField(entityId, CalculatedFieldType.SIMPLE);
} }
@ -385,14 +429,13 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
} }
private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig() { private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig() {
SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration(); return getSimpleCalculatedFieldConfig(Map.of("T", getArgument(null)));
}
Argument argument = new Argument(); private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig(Map<String, Argument> arguments) {
argument.setRefEntityId(null); SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
ReferencedEntityKey refEntityKey = new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null);
argument.setRefEntityKey(refEntityKey);
config.setArguments(Map.of("T", argument)); config.setArguments(arguments);
config.setExpression("T - (100 - H) / 5"); config.setExpression("T - (100 - H) / 5");
@ -404,4 +447,11 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
return config; return config;
} }
private Argument getArgument(EntityId refEntityId) {
Argument argument = new Argument();
argument.setRefEntityId(refEntityId);
argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null));
return argument;
}
} }

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save