Browse Source

Merge branch 'lts-4.4' into feature/ai-chat

pull/16848/head
Igor Kulikov 1 week ago
parent
commit
496cbd9502
  1. 2
      .github/ISSUE_TEMPLATE/---bug-report.md
  2. 2
      .github/ISSUE_TEMPLATE/feature_request.md
  3. 2
      .github/ISSUE_TEMPLATE/question.md
  4. 64
      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. 9
      application/src/main/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolver.java
  15. 7
      application/src/main/java/org/thingsboard/server/config/TbRuleEngineSecurityConfiguration.java
  16. 4
      application/src/main/java/org/thingsboard/server/config/ThingsboardSecurityConfiguration.java
  17. 6
      application/src/main/java/org/thingsboard/server/controller/AdminController.java
  18. 4
      application/src/main/java/org/thingsboard/server/controller/ApiKeyController.java
  19. 53
      application/src/main/java/org/thingsboard/server/controller/BaseController.java
  20. 10
      application/src/main/java/org/thingsboard/server/controller/DashboardReportController.java
  21. 80
      application/src/main/java/org/thingsboard/server/controller/EntityGroupController.java
  22. 13
      application/src/main/java/org/thingsboard/server/controller/EntityViewController.java
  23. 43
      application/src/main/java/org/thingsboard/server/controller/GroupPermissionController.java
  24. 3
      application/src/main/java/org/thingsboard/server/controller/NotificationController.java
  25. 17
      application/src/main/java/org/thingsboard/server/controller/NotificationRuleController.java
  26. 1
      application/src/main/java/org/thingsboard/server/controller/NotificationTemplateController.java
  27. 8
      application/src/main/java/org/thingsboard/server/controller/ReportController.java
  28. 3
      application/src/main/java/org/thingsboard/server/controller/RuleEngineController.java
  29. 24
      application/src/main/java/org/thingsboard/server/controller/SchedulerEventController.java
  30. 3
      application/src/main/java/org/thingsboard/server/controller/SelfRegistrationController.java
  31. 41
      application/src/main/java/org/thingsboard/server/controller/SignUpController.java
  32. 4
      application/src/main/java/org/thingsboard/server/controller/UserController.java
  33. 2
      application/src/main/java/org/thingsboard/server/exception/ThingsboardErrorResponseHandler.java
  34. 2
      application/src/main/java/org/thingsboard/server/install/ThingsboardInstallService.java
  35. 6
      application/src/main/java/org/thingsboard/server/service/edge/DefaultEdgeLicenseService.java
  36. 2
      application/src/main/java/org/thingsboard/server/service/edge/rpc/processor/telemetry/BaseTelemetryProcessor.java
  37. 2
      application/src/main/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdater.java
  38. 115
      application/src/main/java/org/thingsboard/server/service/iot_hub/DefaultIotHubService.java
  39. 5
      application/src/main/java/org/thingsboard/server/service/iot_hub/IotHubRestClient.java
  40. 2
      application/src/main/java/org/thingsboard/server/service/mail/TbMailSender.java
  41. 9
      application/src/main/java/org/thingsboard/server/service/notification/DefaultNotificationCenter.java
  42. 2
      application/src/main/java/org/thingsboard/server/service/notification/channels/MicrosoftTeamsNotificationChannel.java
  43. 17
      application/src/main/java/org/thingsboard/server/service/resource/DefaultTbResourceService.java
  44. 2
      application/src/main/java/org/thingsboard/server/service/scheduler/DefaultSchedulerService.java
  45. 2
      application/src/main/java/org/thingsboard/server/service/security/AccessValidator.java
  46. 8
      application/src/main/java/org/thingsboard/server/service/security/auth/AbstractJwtAuthenticationToken.java
  47. 7
      application/src/main/java/org/thingsboard/server/service/security/auth/jwt/SkipPathRequestMatcher.java
  48. 16
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/CustomOAuth2ClientMapper.java
  49. 5
      application/src/main/java/org/thingsboard/server/service/security/auth/oauth2/GithubOAuth2ClientMapper.java
  50. 7
      application/src/main/java/org/thingsboard/server/service/security/auth/pat/ApiKeyAuthenticationToken.java
  51. 4
      application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
  52. 2
      application/src/main/java/org/thingsboard/server/service/security/system/DefaultSystemSecurityService.java
  53. 2
      application/src/main/java/org/thingsboard/server/service/trendz/TrendzClient.java
  54. 20
      application/src/main/java/org/thingsboard/server/utils/MiscUtils.java
  55. 6
      application/src/main/resources/thingsboard.yml
  56. 2
      application/src/test/java/org/thingsboard/server/cf/AlarmRulesTest.java
  57. 2
      application/src/test/java/org/thingsboard/server/cf/CalculatedFieldIntegrationTest.java
  58. 57
      application/src/test/java/org/thingsboard/server/config/CustomOAuth2AuthorizationRequestResolverTest.java
  59. 40
      application/src/test/java/org/thingsboard/server/config/JsonMapperWiringTest.java
  60. 21
      application/src/test/java/org/thingsboard/server/config/StaticResourceCompressionTest.java
  61. 26
      application/src/test/java/org/thingsboard/server/config/ThingsboardYmlDefaultsTest.java
  62. 5
      application/src/test/java/org/thingsboard/server/controller/AbstractControllerTest.java
  63. 11
      application/src/test/java/org/thingsboard/server/controller/AbstractWebTest.java
  64. 30
      application/src/test/java/org/thingsboard/server/controller/AdminControllerTest.java
  65. 26
      application/src/test/java/org/thingsboard/server/controller/AlarmRuleControllerTest.java
  66. 51
      application/src/test/java/org/thingsboard/server/controller/ApiKeyControllerTest.java
  67. 30
      application/src/test/java/org/thingsboard/server/controller/AuthControllerTest.java
  68. 62
      application/src/test/java/org/thingsboard/server/controller/CalculatedFieldControllerTest.java
  69. 116
      application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java
  70. 195
      application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java
  71. 2
      application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java
  72. 2
      application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java
  73. 473
      application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java
  74. 89
      application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java
  75. 225
      application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java
  76. 2
      application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java
  77. 2
      application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java
  78. 32
      application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java
  79. 35
      application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java
  80. 75
      application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java
  81. 315
      application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java
  82. 166
      application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java
  83. 4
      application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java
  84. 2
      application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java
  85. 2
      application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java
  86. 35
      application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java
  87. 55
      application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java
  88. 64
      application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java
  89. 2
      application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java
  90. 45
      application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java
  91. 2
      application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java
  92. 34
      application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java
  93. 5
      application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java
  94. 17
      application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java
  95. 35
      application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java
  96. 377
      application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java
  97. 16
      application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java
  98. 36
      application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java
  99. 131
      application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java
  100. 95
      application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java

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

@ -3,7 +3,7 @@ name: "\U0001F41E Bug report"
about: Create a report to help us improve
title: "Your title here"
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
title: "Your title here"
labels: ['feature']
assignees: 'Ultrazombie'
assignees: 'mykhailokornieiev'
---

2
.github/ISSUE_TEMPLATE/question.md

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

64
application/pom.xml

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

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

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

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

@ -1303,17 +1303,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"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,
@ -1561,17 +1550,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"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,
@ -1820,17 +1798,6 @@
"label": "{i18n:widgets.maps.layer.roadmap}",
"provider": "openstreet",
"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,

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

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

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

@ -1,5 +1,6 @@
// 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;
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.oidc.OidcScopes;
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.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
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 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 + "}");
private final StringKeyGenerator stateGenerator = new Base64StringKeyGenerator(Base64.getUrlEncoder());
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<>();
uriVariables.put("registrationId", clientRegistration.getRegistrationId());
UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request))
UriComponents uriComponents = UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request))
.replacePath(request.getContextPath())
.replaceQuery(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-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;
import org.springframework.beans.factory.annotation.Autowired;
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.Configuration;
import org.springframework.core.annotation.Order;
@ -17,7 +18,7 @@ import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
@Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
@ConditionalOnExpression("'${service.type:null}'=='tb-rule-engine'")
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.Value;
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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@ -61,7 +61,7 @@ import java.util.stream.Stream;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@Order(SecurityProperties.BASIC_AUTH_ORDER)
@Order(SecurityFilterProperties.BASIC_AUTH_ORDER)
@TbCoreComponent
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.system.SystemSecurityService;
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.repository.DefaultTbRepositorySettingsService;
import org.thingsboard.server.service.system.SystemInfoService;
import org.thingsboard.server.service.update.UpdateService;
@ -166,6 +168,10 @@ public class AdminController extends BaseController {
} else {
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));
if (adminSettings.getKey().equals(MAIL_SETTINGS_KEY)) {
((ObjectNode) adminSettings.getJsonValue()).remove("refreshToken");

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));
accessControlService.checkPermission(securityUser, Resource.API_KEY, 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);
}

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.bundle.MobileAppBundle;
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.page.PageData;
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 {
try {
validateId(userId, id -> "Incorrect userId " + id);
@ -1097,7 +1142,11 @@ public abstract class BaseController {
for (EntityId referencedEntityId : calculatedFieldConfig.getReferencedEntities()) {
EntityType refEntityType = referencedEntityId.getEntityType();
switch (refEntityType) {
case TENANT -> {}
case TENANT -> {
if (!getTenantId().equals(referencedEntityId)) {
throw permissionDenied();
}
}
case CUSTOMER, ASSET, DEVICE -> checkEntityId(referencedEntityId, Operation.READ);
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 {
try {
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");
accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), operation, 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.UserId;
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.dao.subscription.PlatformFeature;
import org.thingsboard.server.queue.util.TbCoreComponent;
@ -61,6 +62,7 @@ public class DashboardReportController extends BaseController {
private final SystemSecurityService systemSecurityService;
public static final String DASHBOARD_ID = "dashboardId";
public static final String USER_ID = "userId";
@ApiOperation(value = "Download dashboard report (downloadDashboardReport)",
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));
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);
} catch (Exception 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.ShareGroupRequest;
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.config.annotations.ApiOperation;
import org.thingsboard.server.dao.owner.OwnerService;
@ -210,9 +211,8 @@ public class EntityGroupController extends AutoCommitController {
@RequestBody EntityGroup entityGroup) throws Exception {
SecurityUser currentUser = getCurrentUser();
checkEntityGroupType(entityGroup.getType());
Operation operation = entityGroup.getId() == null ? Operation.CREATE : Operation.WRITE;
EntityId parentEntityId = entityGroup.getOwnerId();
if (operation == Operation.CREATE) {
if (entityGroup.getId() == null) {
if (parentEntityId == null || parentEntityId.isNullUid()) {
parentEntityId = currentUser.getOwnerId();
} else {
@ -221,14 +221,12 @@ public class EntityGroupController extends AutoCommitController {
"Invalid entity group ownerId!", ThingsboardErrorCode.PERMISSION_DENIED);
}
}
EntityGroupInfo entityGroupInfo = new EntityGroupInfo(entityGroup, ownersCacheService.fetchOwnersHierarchy(getTenantId(), parentEntityId));
accessControlService.checkEntityGroupInfoPermission(currentUser, Operation.CREATE, entityGroupInfo);
} 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());
}
@ -967,7 +965,11 @@ public class EntityGroupController extends AutoCommitController {
for (String strEntityGroupId : strEntityGroupIds) {
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)",
@ -1145,7 +1147,8 @@ public class EntityGroupController extends AutoCommitController {
@ApiOperation(value = "Share the Entity Group (shareEntityGroup)",
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)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping(value = "/entityGroup/{entityGroupId}/share")
@ -1165,21 +1168,25 @@ public class EntityGroupController extends AutoCommitController {
EntityGroupInfo userGroup;
if (shareGroupRequest.isAllUserGroup()) {
Optional<EntityGroupInfo> userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(),
EntityType.USER, EntityGroup.GROUP_ALL_NAME);
Optional<EntityGroupInfo> userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId());
if (userGroupOptional.isPresent()) {
userGroup = userGroupOptional.get();
} else {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
}
} else {
userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId());
userGroup = checkNotNull(entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId()));
}
accessControlService.checkEntityGroupInfoPermission(getCurrentUser(), Operation.WRITE, userGroup);
List<RoleId> roleIds;
List<Role> roles;
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 {
Role role;
if (shareGroupRequest.isReadElseWrite()) {
@ -1187,15 +1194,15 @@ public class EntityGroupController extends AutoCommitController {
} else {
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.setTenantId(getTenantId());
groupPermission.setEntityGroupId(entityGroup.getId());
groupPermission.setEntityGroupType(entityGroup.getType());
groupPermission.setRoleId(roleId);
groupPermission.setRoleId(role.getId());
groupPermission.setUserGroupId(userGroup.getId());
GroupPermission savedGroupPermission = checkNotNull(groupPermissionService.saveGroupPermission(getTenantId(), groupPermission));
@ -1246,7 +1253,7 @@ public class EntityGroupController extends AutoCommitController {
checkParameter("userGroupId", strUserGroupId);
checkParameter("roleId", strRoleId);
EntityGroupId userGroupId = new EntityGroupId(toUUID(strUserGroupId));
EntityGroup userGroup = entityGroupService.findEntityGroupById(getTenantId(), userGroupId);
EntityGroup userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), userGroupId);
if (userGroup == null) {
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 {
EntityGroupId entityGroupId = new EntityGroupId(entityGroupUuid);
EntityGroup entityGroup = entityGroupService.findEntityGroupById(getTenantId(), entityGroupId);
EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), entityGroupId);
if (entityGroup == null) {
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 {
EntityGroupInfo userGroup;
if (shareGroupRequest.isAllUserGroup()) {
Optional<EntityGroupInfo> userGroupOptional = entityGroupService.findEntityGroupInfoByTypeAndName(getTenantId(), shareGroupRequest.getOwnerId(),
EntityType.USER, EntityGroup.GROUP_ALL_NAME);
Optional<EntityGroupInfo> userGroupOptional = findAllUserGroup(shareGroupRequest.getOwnerId());
if (userGroupOptional.isPresent()) {
userGroup = userGroupOptional.get();
} else {
throw new ThingsboardException("Requested item wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
}
} else {
userGroup = entityGroupService.findEntityGroupInfoById(getTenantId(), shareGroupRequest.getUserGroupId());
userGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(getTenantId(), shareGroupRequest.getUserGroupId());
}
if (userGroup == null) {
throw new ThingsboardException("Specified user group wasn't found!", ThingsboardErrorCode.ITEM_NOT_FOUND);
@ -1325,6 +1331,12 @@ public class EntityGroupController extends AutoCommitController {
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 {
List<Role> roles = new ArrayList<>(1);
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);
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))) {
GroupPermission savedGroupPermission = groupPermissionService.saveGroupPermission(getTenantId(), new GroupPermission(getTenantId(), userGroup.getId(), role.getId(), entityGroup.getId(), entityGroup.getId().getEntityType(), false));
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.List;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
@ -132,6 +133,11 @@ public class EntityViewController extends BaseController {
SecurityUser user = getCurrentUser();
return saveGroupEntity(entityView, strEntityGroupId, strEntityGroupIds, (entityView1, entityGroups) -> {
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);
} catch (Exception e) {
throw handleException(e);
@ -451,4 +457,11 @@ public class EntityViewController extends BaseController {
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.exception.ThingsboardErrorCode;
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.EntityId;
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);
} else {
oldGroupPermission = checkGroupPermissionId(groupPermission.getId(), Operation.WRITE);
checkGroupPermissionManageable(oldGroupPermission);
}
if (groupPermission.isPublic()) {
@ -168,17 +170,7 @@ public class GroupPermissionController extends BaseController {
try {
GroupPermissionId groupPermissionId = new GroupPermissionId(toUUID(strGroupPermissionId));
GroupPermission groupPermission = checkGroupPermissionId(groupPermissionId, Operation.DELETE);
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);
}
checkGroupPermissionManageable(groupPermission);
groupPermissionService.deleteGroupPermission(getTenantId(), groupPermissionId);
userPermissionsService.onGroupPermissionDeleted(groupPermission);
@ -218,7 +210,8 @@ public class GroupPermissionController extends BaseController {
@RequestBody List<GroupPermission> permissions) throws ThingsboardException, ExecutionException, InterruptedException {
TenantId tenantId = getCurrentUser().getTenantId();
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);
}
@ -255,6 +248,32 @@ public class GroupPermissionController extends BaseController {
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) {
if (groupPermission.getEntityGroupId() != null) {
return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupIdAndUserGroupIdAndRoleId(tenantId,

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

@ -283,6 +283,9 @@ public class NotificationController extends BaseController {
}
notificationRequest.setTenantId(user.getTenantId());
checkEntity(notificationRequest.getId(), notificationRequest, NOTIFICATION);
checkTemplateReportUser(notificationRequest.getTemplateId() != null ?
notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRequest.getTemplateId()) :
notificationRequest.getTemplate());
List<NotificationTargetId> targets = notificationRequest.getTargets().stream()
.map(NotificationTargetId::new)
.toList();

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.exception.ThingsboardException;
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.NotificationRuleInfo;
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.PageLink;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.config.annotations.ApiOperation;
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.service.security.model.SecurityUser;
import java.util.List;
import java.util.UUID;
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 {
private final NotificationRuleService notificationRuleService;
private final NotificationTemplateService notificationTemplateService;
@ApiOperation(value = "Save notification rule (saveNotificationRule)",
notes = "Creates or updates notification rule. " + NEW_LINE +
@ -106,11 +111,23 @@ public class NotificationRuleController extends BaseController {
@AuthenticationPrincipal SecurityUser user) throws Exception {
notificationRule.setTenantId(user.getTenantId());
checkEntity(notificationRule.getId(), notificationRule, NOTIFICATION);
if (notificationRule.getTemplateId() != null) {
checkTemplateReportUser(notificationTemplateService.findNotificationTemplateById(user.getTenantId(), notificationRule.getTemplateId()));
}
NotificationRuleTriggerType triggerType = notificationRule.getTriggerType();
if ((user.isTenantAdmin() && !triggerType.isTenantLevel()) || (user.isSystemAdmin() && triggerType.isTenantLevel())) {
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);
}

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 {
notificationTemplate.setTenantId(getTenantId());
checkEntity(notificationTemplate.getId(), notificationTemplate, NOTIFICATION);
checkTemplateReportUser(notificationTemplate);
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 {
checkFeatureAllowed(PlatformFeature.REPORTING);
SecurityUser currentUser = getCurrentUser();
UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(UUID.fromString(reportRequest.getUserId())) : getCurrentUser().getId();
EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId);
UserId userId = StringUtils.isNotEmpty(reportRequest.getUserId()) ? new UserId(toUUID(reportRequest.getUserId())) : currentUser.getId();
checkReportUser(userId);
checkUserOwnerPermission(currentUser, userId);
EntityId userOwnerId = ownersCacheService.getOwner(currentUser.getTenantId(), userId);
AccessJwtToken accessToken = systemSecurityService.createUserAccessToken(currentUser.getTenantId(), userId);
ReportTemplateConfig configuration = reportRequest.getReportTemplateConfig();
if (configuration == null) {
@ -301,7 +302,8 @@ public class ReportController extends BaseController {
SecurityUser currentUser = getCurrentUser();
UserId userId;
if (StringUtils.isNotEmpty(reportRequest.getUserId())) {
userId = new UserId(UUID.fromString(reportRequest.getUserId()));
userId = new UserId(toUUID(reportRequest.getUserId()));
checkReportUser(userId);
checkUserOwnerPermission(currentUser, userId);
} else {
userId = currentUser.getId();

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

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

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

@ -2,6 +2,7 @@
// SPDX-License-Identifier: BUSL-1.1
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.Parameter;
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.RestController;
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.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EdgeId;
@ -161,11 +164,26 @@ public class SchedulerEventController extends BaseController {
private void checkEventConfigPermissions(SchedulerEvent schedulerEvent) throws ThingsboardException {
if (GENERATE_REPORT.equals(schedulerEvent.getType())) {
SecurityUser currentUser = getCurrentUser();
ReportConfig reportConfig = checkNotNull(JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class),
"Report scheduler event configuration should be specified!");
ReportConfig reportConfig = JacksonUtil.treeToValue(schedulerEvent.getConfiguration(), ReportConfig.class);
if (reportConfig == null) {
throw new ThingsboardException("Report scheduler event configuration should be specified!", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
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);
} 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) {
checkNotificationTargetId(selfRegistrationParams.getNotificationRecipient(), Operation.READ);
}
if (selfRegistrationParams.getDomainId() != null) {
checkDomainId(selfRegistrationParams.getDomainId(), Operation.READ);
}
if (Authority.TENANT_ADMIN.equals(authority)) {
savedSelfRegistrationParams = whiteLabelingService.saveTenantSelfRegistrationParams(getTenantId(), selfRegistrationParams);
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.token.JwtTokenFactory;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import org.thingsboard.server.utils.MiscUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@ -209,7 +208,7 @@ public class SignUpController extends BaseController {
UserCredentials savedUserCredentials = saveUserCredentials(savedUser, signUpRequest);
try {
sendEmailVerification(tenantId, request, savedUserCredentials, email, null, signUpRequest.getPkgName(), signUpRequest.getPlatform());
sendEmailVerification(tenantId, request, savedUser, savedUserCredentials, email, signUpRequest.getPkgName(), signUpRequest.getPlatform());
} catch (ThingsboardException e) {
customerService.deleteCustomer(tenantId, savedCustomer.getId());
throw e;
@ -227,11 +226,9 @@ public class SignUpController extends BaseController {
return SignUpResult.SUCCESS;
}
private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, UserCredentials userCredentials,
String targetEmail, String baseUrl, String pkgName, PlatformType platformType) throws ThingsboardException {
if (baseUrl == null) {
baseUrl = MiscUtils.constructBaseUrl(request);
}
private void sendEmailVerification(TenantId tenantId, HttpServletRequest request, User user, UserCredentials userCredentials,
String targetEmail, String pkgName, PlatformType platformType) throws ThingsboardException {
String baseUrl = systemSecurityService.getBaseUrl(user.getAuthority(), user.getTenantId(), user.getCustomerId(), request);
String activationLink = String.format("%s/api/noauth/activateEmail?emailCode=%s", baseUrl, userCredentials.getActivateToken());
if (!StringUtils.isEmpty(pkgName)) {
checkNotNull(platformType);
@ -265,7 +262,7 @@ public class SignUpController extends BaseController {
}
@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")
public void resendEmailActivation(
@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);
if (existingUser != null) {
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 {
if (existingUser == null || !tenantId.equals(existingUser.getTenantId())) {
throw new DataValidationException("User with email '" + email + "' "
+ " 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)",
@ -395,16 +390,19 @@ public class SignUpController extends BaseController {
if (userCredentials.getPassword() == null) {
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();
UserCredentials credentials = userService.activateUserCredentials(TenantId.SYS_TENANT_ID, emailCode, encodedPassword);
User user = userService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
long acceptedTs = System.currentTimeMillis();
user.setPrivacyPolicyAccepted(acceptedTs);
user.setTermsOfUseAccepted(acceptedTs);
user = userService.saveUser(tenantId, user);
UserPrincipal principal = new UserPrincipal(UserPrincipal.Type.USER_NAME, user.getEmail());
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;
if (!StringUtils.isEmpty(pkgName)) {
loginUrl = UriComponentsBuilder.fromUriString(baseUrl).path("/api/noauth/login")
@ -574,10 +572,11 @@ public class SignUpController extends BaseController {
List<GroupPermission> permissions = selfRegistrationParams.getPermissions();
for (GroupPermission permission : permissions) {
permission.setId(null);
permission.setTenantId(tenantId);
permission.setUserGroupId(usersEntityGroup.getId());
if (permission.getEntityGroupId() != null) {
EntityGroup entityGroup = entityGroupService.findEntityGroupById(tenantId, permission.getEntityGroupId());
EntityGroup entityGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, permission.getEntityGroupId());
if (entityGroup != null) {
permission.setEntityGroupType(entityGroup.getType());
groupPermissionService.saveGroupPermission(tenantId, permission);

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

@ -292,7 +292,7 @@ public class UserController extends BaseController {
HttpServletRequest request) throws ThingsboardException {
SecurityUser securityUser = getCurrentUser();
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);
try {
@ -323,7 +323,7 @@ public class UserController extends BaseController {
HttpServletRequest request) throws ThingsboardException {
checkParameter(USER_ID, strUserId);
UserId userId = new UserId(toUUID(strUserId));
checkUserId(userId, Operation.READ);
checkUserId(userId, Operation.WRITE);
SecurityUser securityUser = getCurrentUser();
return tbUserService.getActivationLink(securityUser.getTenantId(), securityUser.getCustomerId(), securityUser.getAuthority(), userId, request);
}

2
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 org.apache.commons.lang3.exception.ExceptionUtils;
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.http.HttpHeaders;
import org.springframework.http.HttpStatus;

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

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

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 jakarta.annotation.PostConstruct;
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.HttpClientBuilder;
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();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory);
} else if (proxyEnabled) {
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();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory);
} else {
httpClient = HttpClients.custom().setConnectionManager(createConnectionManager(false)).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setHttpClient(httpClient);
factory.setConnectTimeout(CONNECT_TIMEOUT);
return new RestTemplate(factory);
}
}
@ -157,8 +155,10 @@ public class DefaultEdgeLicenseService implements EdgeLicenseService {
private HttpClientConnectionManager createConnectionManager(boolean systemProperties) {
var socketFactory = systemProperties ? SSLConnectionSocketFactory.getSystemSocketFactory() : SSLConnectionSocketFactory.getSocketFactory();
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()
.setDefaultSocketConfig(socketConfig)
.setDefaultConnectionConfig(connectionConfig)
.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 -> {
EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupById(tenantId, new EntityGroupId(entityId.getId()));
EntityGroup entityGroup = edgeCtx.getEntityGroupService().findEntityGroupInfoByTenantIdAndId(tenantId, new EntityGroupId(entityId.getId()));
if (entityGroup != null) {
metaData.putValue("entityGroupName", entityGroup.getName());
metaData.putValue("entityGroupType", entityGroup.getType().name());

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

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

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

@ -13,12 +13,17 @@ import org.springframework.stereotype.Service;
import org.thingsboard.common.util.ExceptionUtil;
import org.thingsboard.common.util.JacksonUtil;
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.HasTenantId;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.asset.AssetProfile;
import org.thingsboard.server.common.data.cf.CalculatedField;
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.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
@ -257,7 +262,7 @@ public class DefaultIotHubService implements IotHubService {
}
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) {
throw new IllegalArgumentException("Entity group with id [" + entityGroupId + "] is not found");
}
@ -274,6 +279,7 @@ public class DefaultIotHubService implements IotHubService {
}
calculatedField.setId(null);
calculatedField.setTenantId(tenantId);
mapTenantReferences(calculatedField, tenantId);
if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
calculatedField.setEntityId(entityId);
@ -298,6 +304,7 @@ public class DefaultIotHubService implements IotHubService {
}
alarmRule.setId(null);
alarmRule.setTenantId(tenantId);
mapTenantReferences(alarmRule, tenantId);
if (data != null && data.has("entityId")) {
EntityId entityId = JacksonUtil.treeToValue(data.get("entityId"), EntityId.class);
alarmRule.setEntityId(entityId);
@ -537,6 +544,7 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName());
existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration());
mapTenantReferences(existing, tenantId);
tbCalculatedFieldService.save(existing, user);
}
@ -557,9 +565,26 @@ public class DefaultIotHubService implements IotHubService {
existing.setName(newCf.getName());
existing.setType(newCf.getType());
existing.setConfiguration(newCf.getConfiguration());
mapTenantReferences(existing, tenantId);
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 {
JsonNode json = JacksonUtil.toJsonNode(new String(fileData));
RuleChainMetaData metadata;
@ -680,6 +705,8 @@ public class DefaultIotHubService implements IotHubService {
UUID itemId = UUID.fromString(versionInfo.get("itemId").asText());
String version = versionInfo.get("version").asText();
validateDevicePackageEntities(tenantId, descriptor);
IotHubInstalledItem installedItem = new IotHubInstalledItem();
installedItem.setTenantId(tenantId);
installedItem.setItemId(itemId);
@ -801,8 +828,8 @@ public class DefaultIotHubService implements IotHubService {
return;
}
try {
Integration integration = integrationService.findIntegrationById(tenantId, new IntegrationId(entityId.getId()));
if (integration == null || !(integration.getConfiguration() != null
// Only an integration of this tenant: the id comes from the stored descriptor
if (!(findDevicePackageEntity(tenantId, entityId) instanceof Integration integration) || !(integration.getConfiguration() != null
&& integration.getConfiguration().get("metadata") instanceof ObjectNode metadata)
|| keys.stream().noneMatch(metadata::has)) {
return;
@ -889,7 +916,9 @@ public class DefaultIotHubService implements IotHubService {
}
private InstalledItemKeptEntities.KeptEntity keptEntity(TenantId tenantId, EntityId entityId) {
return new InstalledItemKeptEntities.KeptEntity(entityId, entityService.fetchEntityName(tenantId, entityId).orElse(null));
String name = findDevicePackageEntity(tenantId, entityId) != null
? entityService.fetchEntityName(tenantId, entityId).orElse(null) : null;
return new InstalledItemKeptEntities.KeptEntity(entityId, name);
}
/** The default rule chains and dashboard of a device profile, which TB doesn't delete while it refers to them; none for another entity. */
@ -948,36 +977,56 @@ public class DefaultIotHubService implements IotHubService {
return usedBy;
}
private void deleteDevicePackageEntity(TenantId tenantId, EntityId entityId, SecurityUser user) throws ThingsboardException {
switch (entityId.getEntityType()) {
case DEVICE -> {
var device = deviceService.findDeviceById(tenantId, new DeviceId(entityId.getId()));
if (device != null) tbDeviceService.delete(device, user);
}
case DEVICE_PROFILE -> {
var profile = deviceProfileService.findDeviceProfileById(tenantId, new DeviceProfileId(entityId.getId()));
if (profile != null) tbDeviceProfileService.delete(profile, user);
}
case DASHBOARD -> {
var dashboard = dashboardService.findDashboardById(tenantId, new DashboardId(entityId.getId()));
if (dashboard != null) tbDashboardService.delete(dashboard, user);
}
case RULE_CHAIN -> {
var ruleChain = ruleChainService.findRuleChainById(tenantId, new RuleChainId(entityId.getId()));
if (ruleChain != null) tbRuleChainService.delete(ruleChain, user);
}
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);
private void validateDevicePackageEntities(TenantId tenantId, DeviceInstalledItemDescriptor descriptor) {
if (descriptor == null) {
throw new IllegalArgumentException("Device package descriptor is required");
}
List<EntityId> entityIds = new ArrayList<>();
if (descriptor.getCreatedEntityIds() != null) {
entityIds.addAll(descriptor.getCreatedEntityIds());
}
if (descriptor.getDashboardId() != null) {
entityIds.add(descriptor.getDashboardId());
}
if (descriptor.getUsedExistingEntityIds() != null) {
entityIds.addAll(descriptor.getUsedExistingEntityIds());
}
for (EntityId entityId : entityIds) {
if (entityId == null || findDevicePackageEntity(tenantId, entityId) == null) {
throw new IllegalArgumentException("Device package entity not found: " + entityId);
}
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);
}
}

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

@ -1,12 +1,13 @@
// 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;
import com.fasterxml.jackson.databind.JsonNode;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
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.HttpStatus;
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);
// 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()) {
String tlsVersion = jsonConfig.get("tlsVersion").asText();
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;
if (request.getTemplateId() != null) {
notificationTemplate = notificationTemplateService.findNotificationTemplateById(tenantId, request.getTemplateId());
if (notificationTemplate != null && !isTenantOrSystem(tenantId, notificationTemplate.getTenantId())) {
notificationTemplate = null;
}
} else {
notificationTemplate = request.getTemplate();
}
@ -126,7 +129,7 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
List<NotificationTarget> targets = new ArrayList<>();
for (UUID targetId : request.getTargets()) {
NotificationTarget target = notificationTargetService.findNotificationTargetById(tenantId, new NotificationTargetId(targetId));
if (target != null) {
if (target != null && tenantId.equals(target.getTenantId())) {
targets.add(target);
} else {
log.debug("Unknown notification target {} in request {}", targetId, request);
@ -516,6 +519,10 @@ public class DefaultNotificationCenter extends AbstractSubscriptionService imple
return "notification";
}
private static boolean isTenantOrSystem(TenantId tenantId, TenantId ownerId) {
return tenantId.equals(ownerId) || ownerId.isSysTenantId();
}
@Autowired
public void setChannels(List<NotificationChannel> channels, NotificationCenter webNotificationChannel) {
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 org.apache.commons.codec.binary.Base64;
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.HttpHeaders;
import org.springframework.http.MediaType;

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.dao.resource.ImageService;
import org.thingsboard.server.dao.resource.ResourceService;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.entitiy.AbstractTbEntityService;
import org.thingsboard.server.service.security.model.SecurityUser;
@ -57,6 +58,22 @@ public class DefaultTbResourceService extends AbstractTbEntityService implements
@Override
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) {
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);
break;
case ENTITY_GROUP:
EntityGroup deviceGroup = entityGroupService.findEntityGroupById(tenantId, (EntityGroupId) originatorId);
EntityGroup deviceGroup = entityGroupService.findEntityGroupInfoByTenantIdAndId(tenantId, (EntityGroupId) originatorId);
if (deviceGroup == null) {
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()) {
callback.onSuccess(ValidationResult.accessDenied(SYSTEM_ADMINISTRATOR_IS_NOT_ALLOWED_TO_PERFORM_THIS_OPERATION));
} 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 -> {
if (entityGroup == null) {
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-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;
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.token.RawAccessJwtToken;
import java.util.Collection;
public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = -6212297506742428406L;
@ -14,7 +18,7 @@ public abstract class AbstractJwtAuthenticationToken extends AbstractAuthenticat
private SecurityUser securityUser;
public AbstractJwtAuthenticationToken(RawAccessJwtToken unsafeToken) {
super(null);
super((Collection<? extends GrantedAuthority>) null);
this.rawAccessToken = unsafeToken;
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;
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.RequestMatcher;
import org.springframework.util.Assert;
@ -19,8 +19,9 @@ public class SkipPathRequestMatcher implements RequestMatcher {
public SkipPathRequestMatcher(List<String> pathsToSkip, List<String> pathsToProcess) {
Assert.notNull(pathsToSkip, "List of paths to skip is required.");
List<RequestMatcher> skip = pathsToSkip.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
List<RequestMatcher> process = pathsToProcess.stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
PathPatternRequestMatcher.Builder builder = PathPatternRequestMatcher.withDefaults();
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);
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-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;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.http.HttpServletRequest;
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.stereotype.Service;
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 RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
private final RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
@Override
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);
}
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())) {
restTemplateBuilder = restTemplateBuilder.basicAuthentication(custom.getUsername(), custom.getPassword());
builder = builder.basicAuthentication(custom.getUsername(), custom.getPassword());
}
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;
try {
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-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;
import jakarta.servlet.http.HttpServletRequest;
@ -7,7 +8,7 @@ import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
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.stereotype.Service;
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-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;
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.token.ApiKeyAuthRequest;
import java.io.Serial;
import java.util.Collection;
public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
@ -17,7 +20,7 @@ public class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
private SecurityUser securityUser;
public ApiKeyAuthenticationToken(ApiKeyAuthRequest apiKeyAuthRequest) {
super(null);
super((Collection<? extends GrantedAuthority>) null);
this.apiKeyAuthRequest = apiKeyAuthRequest;
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.TbResourceId;
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.Operation;
import org.thingsboard.server.common.data.permission.Resource;
@ -525,6 +526,9 @@ public class CustomerUserPermissions extends AbstractPermissions {
if (!user.getTenantId().equals(entity.getTenantId())) {
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
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
public AccessJwtToken createUserAccessToken(TenantId tenantId, UserId userId) throws ThingsboardException {
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);
}
UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, userId);

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.extern.slf4j.Slf4j;
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.http.HttpEntity;
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-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;
import com.google.common.hash.HashFunction;
@ -43,13 +44,20 @@ public class MiscUtils {
getPort(request));
}
public static String getScheme(HttpServletRequest request){
String scheme = request.getScheme();
public static String getScheme(HttpServletRequest request) {
String forwardedProto = request.getHeader("x-forwarded-proto");
if (forwardedProto != null) {
scheme = forwardedProto;
if (isHttpScheme(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){

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

@ -13,6 +13,9 @@ server:
port: "${HTTP_BIND_PORT:8080}"
# Server forward headers strategy. Required for SWAGGER UI when reverse proxy is used
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
ssl:
# Enable/disable SSL support
@ -1205,11 +1208,12 @@ spring.mvc.cors:
allow-credentials: "${TB_CORS_ALLOW_CREDENTIALS:true}"
# 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.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.pathmatch.matching-strategy: "ANT_PATH_MATCHER" # For endpoints matching in Swagger
spring.http.converters.preferred-json-mapper: "jackson2" # JSON mapper for HTTP message conversion; ThingsBoard uses Jackson 2
spring.web.resources.chain:
enabled: "true" # Enables the Spring resource chain explicitly instead of relying on a webjars locator being on the classpath
compressed: "true" # Serve the pre-compressed .br/.gz copies of the UI files built by ui-ngx when the client accepts them

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 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.testcontainers.shaded.org.awaitility.Awaitility.await;
@Slf4j
@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.google.common.util.concurrent.Futures;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.context.TestPropertySource;
import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AttributeScope;
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();
}
}

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

@ -1,20 +1,22 @@
// 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;
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.autoconfigure.http.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
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;
@ -32,12 +34,12 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
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")
@AutoConfigureMockMvc(addFilters = false)
public class StaticResourceCompressionTest {
private static final byte[] JS = "console.log('ThingsBoard');\n".repeat(100).getBytes(StandardCharsets.UTF_8);
@ -48,6 +50,8 @@ public class StaticResourceCompressionTest {
static Path webRoot;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mvc;
@DynamicPropertySource
@ -63,6 +67,11 @@ public class StaticResourceCompressionTest {
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"))

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.Before;
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.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
@ -63,7 +63,8 @@ public abstract class AbstractControllerTest extends AbstractNotifyEntityTest {
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 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.ResultActions;
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.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.MailService;
import org.thingsboard.server.actors.DefaultTbActorSystem;
@ -334,14 +336,15 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest {
};
@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)
.findAny()
.get();
this.stringHttpMessageConverter = Arrays.stream(converters)
this.stringHttpMessageConverter = converters.stream()
.filter(hmc -> hmc instanceof StringHttpMessageConverter)
.findAny()
.get();
@ -761,7 +764,7 @@ public abstract class AbstractWebTest extends AbstractInMemoryStorageTest {
doPost("/api/auth/logout").andExpect(status().isOk());
}
protected void setJwtToken(MockHttpServletRequestBuilder request) {
protected void setJwtToken(AbstractMockHttpServletRequestBuilder<?> request) {
if (this.token != null) {
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.junit.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.thingsboard.common.util.JacksonUtil;
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.dao.secret.SecretConfigurationService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.settings.AdminSettingsService;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
@ -44,6 +47,9 @@ public class AdminControllerTest extends AbstractControllerTest {
@MockitoBean
private SecretConfigurationService secretConfigurationService;
@Autowired
private AdminSettingsService adminSettingsService;
@Test
public void testFindAdminSettingsByKey() throws Exception {
loginSysAdmin();
@ -111,6 +117,30 @@ public class AdminControllerTest extends AbstractControllerTest {
.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
public void testMailOAuth2AuthorizationStoresOnlyInAppPrevUri() throws Exception {
loginSysAdmin();

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

@ -98,6 +98,32 @@ public class AlarmRuleControllerTest extends AbstractControllerTest {
.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
public void testGetAlarmRuleById() throws Exception {
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());
}
@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) {
ApiKeyInfo apiKeyInfo = new ApiKeyInfo();
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.UserActivationLink;
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.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.UserCredentials;
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.service.security.auth.rest.LoginRequest;
import org.thingsboard.server.service.security.model.ChangePasswordRequest;
import org.thingsboard.server.service.security.permission.AccessControlService;
import java.util.concurrent.TimeUnit;
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.mockito.ArgumentMatchers.any;
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.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -43,6 +50,9 @@ public class AuthControllerTest extends AbstractControllerTest {
@MockitoSpyBean
private UserCredentialsDao userCredentialsDao;
@MockitoSpyBean
private AccessControlService accessControlService;
@After
public void tearDown() throws Exception {
loginSysAdmin();
@ -287,6 +297,26 @@ public class AuthControllerTest extends AbstractControllerTest {
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
public void testGetPageWithoutRedirect() throws Exception {
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
package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -41,6 +42,7 @@ import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@ -298,6 +300,48 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
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) {
return getCalculatedField(entityId, CalculatedFieldType.SIMPLE);
}
@ -385,14 +429,13 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
}
private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig() {
SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
return getSimpleCalculatedFieldConfig(Map.of("T", getArgument(null)));
}
Argument argument = new Argument();
argument.setRefEntityId(null);
ReferencedEntityKey refEntityKey = new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null);
argument.setRefEntityKey(refEntityKey);
private CalculatedFieldConfiguration getSimpleCalculatedFieldConfig(Map<String, Argument> arguments) {
SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
config.setArguments(Map.of("T", argument));
config.setArguments(arguments);
config.setExpression("T - (100 - H) / 5");
@ -404,4 +447,11 @@ public class CalculatedFieldControllerTest extends AbstractControllerTest {
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;
}
}

116
application/src/test/java/org/thingsboard/server/controller/CustomMenuControllerTest.java

@ -5,6 +5,7 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@ -12,7 +13,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.test.web.servlet.MvcResult;
import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntityInfo;
@ -657,6 +657,120 @@ public class CustomMenuControllerTest extends AbstractControllerTest {
assertThat(currentMenu.get("items")).isEmpty();
}
@Test
public void testCustomerUserMenuIgnoresMenuOfOtherTenant() throws Exception {
loginDifferentTenant();
CustomMenu otherTenantMenu = new CustomMenu();
otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10));
otherTenantMenu.setScope(CMScope.CUSTOMER);
otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN);
otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class);
idsToRemove.add(otherTenantMenu.getUuidId());
CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId());
String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl();
loginTenantAdmin();
Customer customer = doGet("/api/customer/" + customerId.getId(), Customer.class);
customer.setCustomMenuId(otherTenantMenu.getId());
doPost("/api/customer", customer).andExpect(status().isOk());
loginCustomerUser();
JsonNode customerUserMenu = doGet("/api/customMenu", JsonNode.class);
assertThat(customerUserMenu.toString()).doesNotContain(otherTenantMenuUrl);
}
@Test
public void testTenantUserMenuIgnoresMenuOfOtherTenant() throws Exception {
loginDifferentTenant();
CustomMenu otherTenantMenu = new CustomMenu();
otherTenantMenu.setName(RandomStringUtils.randomAlphabetic(10));
otherTenantMenu.setScope(CMScope.TENANT);
otherTenantMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN);
otherTenantMenu = doPost("/api/customMenu", otherTenantMenu, CustomMenu.class);
idsToRemove.add(otherTenantMenu.getUuidId());
CustomMenuConfig otherTenantMenuConfig = putRandomMenuConfig(otherTenantMenu.getId());
String otherTenantMenuUrl = ((CustomMenuItem) otherTenantMenuConfig.getItems().get(2)).getUrl();
loginTenantAdmin();
User tenantAdmin = doGet("/api/user/" + tenantAdminUserId.getId(), User.class);
tenantAdmin.setCustomMenuId(otherTenantMenu.getId());
doPost("/api/user", tenantAdmin).andExpect(status().isOk());
assertThat(doGet("/api/user/" + tenantAdminUserId.getId(), User.class).getCustomMenuId()).isEqualTo(otherTenantMenu.getId());
JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class);
assertThat(tenantAdminMenu.toString()).doesNotContain(otherTenantMenuUrl);
}
@Test
public void testCustomMenuAssigneeListContainsOnlyCustomersOfMenuTenant() throws Exception {
loginTenantAdmin();
CustomMenu customerMenu = new CustomMenu();
customerMenu.setName(RandomStringUtils.randomAlphabetic(10));
customerMenu.setScope(CMScope.CUSTOMER);
customerMenu.setAssigneeType(CMAssigneeType.CUSTOMERS);
customerMenu = doPost("/api/customMenu?assignToList=" + customerId, customerMenu, CustomMenu.class);
loginDifferentTenant();
Customer otherTenantCustomer = new Customer();
otherTenantCustomer.setTitle("Other Tenant Customer");
otherTenantCustomer.setCustomMenuId(customerMenu.getId());
otherTenantCustomer = doPost("/api/customer", otherTenantCustomer, Customer.class);
loginTenantAdmin();
List<EntityInfo> assigneeList = doGetTyped("/api/customMenu/" + customerMenu.getId() + "/assigneeList", new TypeReference<>() {});
assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(customerId);
doDelete("/api/customMenu/" + customerMenu.getId() + "?force=true").andExpect(status().isOk());
loginDifferentTenant();
Customer otherTenantCustomerAfterDelete = doGet("/api/customer/" + otherTenantCustomer.getId(), Customer.class);
assertThat(otherTenantCustomerAfterDelete.getCustomMenuId()).isEqualTo(customerMenu.getId());
}
@Test
public void testCustomMenuAssigneeListContainsOnlyUsersOfMenuTenant() throws Exception {
loginTenantAdmin();
CustomMenu userMenu = new CustomMenu();
userMenu.setName(RandomStringUtils.randomAlphabetic(10));
userMenu.setScope(CMScope.TENANT);
userMenu.setAssigneeType(CMAssigneeType.USERS);
userMenu = doPost("/api/customMenu?assignToList=" + tenantAdminUserId, userMenu, CustomMenu.class);
loginDifferentTenant();
User otherTenantUser = new User();
otherTenantUser.setAuthority(Authority.TENANT_ADMIN);
otherTenantUser.setTenantId(differentTenantId);
otherTenantUser.setEmail("othertenantuser@thingsboard.org");
otherTenantUser.setCustomMenuId(userMenu.getId());
otherTenantUser = doPost("/api/user", otherTenantUser, User.class);
assertThat(otherTenantUser.getCustomMenuId()).isEqualTo(userMenu.getId());
loginTenantAdmin();
List<EntityInfo> assigneeList = doGetTyped("/api/customMenu/" + userMenu.getId() + "/assigneeList", new TypeReference<>() {});
assertThat(assigneeList).extracting(EntityInfo::getId).containsExactly(tenantAdminUserId);
doDelete("/api/customMenu/" + userMenu.getId() + "?force=true").andExpect(status().isOk());
loginDifferentTenant();
User otherTenantUserAfterDelete = doGet("/api/user/" + otherTenantUser.getId(), User.class);
assertThat(otherTenantUserAfterDelete.getCustomMenuId()).isEqualTo(userMenu.getId());
}
@Test
public void testTenantUserGetsAssignedSystemMenu() throws Exception {
loginSysAdmin();
CustomMenu systemMenu = new CustomMenu();
systemMenu.setName(RandomStringUtils.randomAlphabetic(10));
systemMenu.setScope(CMScope.TENANT);
systemMenu.setAssigneeType(CMAssigneeType.NO_ASSIGN);
systemMenu = doPost("/api/customMenu", systemMenu, CustomMenu.class);
idsToRemove.add(systemMenu.getUuidId());
CustomMenuConfig systemMenuConfig = putRandomMenuConfig(systemMenu.getId());
doPut("/api/customMenu/" + systemMenu.getId() + "/assign/USERS", List.of(tenantAdminUserId.getId()));
loginTenantAdmin();
JsonNode tenantAdminMenu = doGet("/api/customMenu", JsonNode.class);
assertCustomMenuConfig(tenantAdminMenu, systemMenuConfig);
}
private MvcResult getUserCustomMenu() throws Exception {
return getUserCustomMenu(null);
}

195
application/src/test/java/org/thingsboard/server/controller/DashboardReportControllerTest.java

@ -0,0 +1,195 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.test.web.servlet.ResultActions;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.rule.engine.api.DashboardReportService;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.User;
import org.thingsboard.server.common.data.dashboardreport.DashboardReportConfig;
import org.thingsboard.server.common.data.dashboardreport.DashboardReportData;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.permission.GroupPermission;
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.dao.service.DaoSqlTest;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DaoSqlTest
public class DashboardReportControllerTest extends AbstractControllerTest {
private static final String DASHBOARD_VIEWER_EMAIL = "dashboard.viewer@thingsboard.org";
private static final String DASHBOARD_VIEWER_PASSWORD = "viewer";
private static final String REPORTS_SERVER_URL = "http://localhost:8383";
private static final String REPORT_BASE_URL = "http://localhost:8081";
@MockitoSpyBean
private DashboardReportService dashboardReportService;
private Dashboard dashboard;
@Before
public void beforeTest() throws Exception {
loginSubCustomerAdminUser();
Dashboard dashboard = new Dashboard();
dashboard.setTitle("Sub-customer dashboard");
this.dashboard = doPost("/api/dashboard", dashboard, Dashboard.class);
doAnswer(invocation -> {
Consumer<DashboardReportData> onSuccess = invocation.getArgument(3);
DashboardReportData reportData = new DashboardReportData();
reportData.setData(new byte[]{1});
reportData.setName("report.pdf");
reportData.setContentType("application/pdf");
onSuccess.accept(reportData);
return null;
}).when(dashboardReportService).generateReport(any(), any(), any(), any(), any());
}
@Test
public void testDownloadTestReportRequiresPermissionOverReportUser() throws Exception {
loginDifferentTenant();
UserId otherTenantUserId = savedDifferentTenantUser.getId();
loginDifferentCustomer();
loginCustomerAdminUser();
doPostTestReport(tenantAdminUserId.toString()).andExpect(status().isForbidden());
doPostTestReport(differentCustomerUserId.toString()).andExpect(status().isForbidden());
doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden());
loginSubCustomerAdminUser();
doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden());
loginTenantAdmin();
doPostTestReport(otherTenantUserId.toString()).andExpect(status().isForbidden());
createDashboardViewer();
login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD);
doPostTestReport(customerAdminUserId.toString()).andExpect(status().isForbidden());
doPostTestReport(customerUserId.toString()).andExpect(status().isForbidden());
verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any());
}
@Test
public void testDownloadTestReportAllowedForOwnUser() throws Exception {
loginCustomerAdminUser();
doPostTestReport(customerAdminUserId.toString()).andExpect(status().isOk());
verifyReportGenerated(customerAdminUserId);
UserId dashboardViewerId = createDashboardViewer();
login(DASHBOARD_VIEWER_EMAIL, DASHBOARD_VIEWER_PASSWORD);
doPostTestReport(dashboardViewerId.toString()).andExpect(status().isOk());
verifyReportGenerated(dashboardViewerId);
}
@Test
public void testDownloadTestReportAllowedForOwnedUser() throws Exception {
loginTenantAdmin();
doPostTestReport(customerUserId.toString()).andExpect(status().isOk());
verifyReportGenerated(customerUserId);
loginCustomerAdminUser();
doPostTestReport(subCustomerAdminUserId.toString()).andExpect(status().isOk());
verifyReportGenerated(subCustomerAdminUserId);
doPostTestReport(customerUserId.toString()).andExpect(status().isOk());
}
@Test
public void testDownloadTestReportWithCurrentUserCredentialsUsesCurrentUserWhenReportUserNotAccessible() throws Exception {
loginCustomerAdminUser();
doPostTestReport(tenantAdminUserId.toString(), null, true).andExpect(status().isOk());
verifyReportGenerated(customerAdminUserId);
}
@Test
public void testDownloadTestReportRequiresUserId() throws Exception {
loginCustomerAdminUser();
doPostTestReport(null).andExpect(status().isBadRequest());
doPostTestReport("not-a-uuid").andExpect(status().isBadRequest());
verify(dashboardReportService, never()).generateReport(any(), any(), any(), any(), any());
}
@Test
public void testDownloadTestReportUsesSystemReportServerForCustomerUser() throws Exception {
loginCustomerAdminUser();
doPostTestReport(customerAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk());
verify(dashboardReportService).generateReport(eq(tenantId), any(), isNull(), any(), any());
loginTenantAdmin();
doPostTestReport(tenantAdminUserId.toString(), REPORTS_SERVER_URL).andExpect(status().isOk());
verify(dashboardReportService).generateReport(eq(tenantId), any(), eq(REPORTS_SERVER_URL), any(), any());
}
private UserId createDashboardViewer() throws Exception {
loginTenantAdmin();
Role role = new Role();
role.setTenantId(tenantId);
role.setCustomerId(customerId);
role.setType(RoleType.GENERIC);
role.setName("Dashboard viewer");
role.setPermissions(JacksonUtil.toJsonNode("{\"DASHBOARD\":[\"READ\"]}"));
role = doPost("/api/role", role, Role.class);
EntityGroup userGroup = new EntityGroup();
userGroup.setName("Dashboard viewers");
userGroup.setType(EntityType.USER);
userGroup.setOwnerId(customerId);
userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class);
doPost("/api/groupPermission", new GroupPermission(tenantId, userGroup.getId(), role.getId(), null, null, false), GroupPermission.class);
User user = new User();
user.setAuthority(Authority.CUSTOMER_USER);
user.setTenantId(tenantId);
user.setCustomerId(customerId);
user.setEmail(DASHBOARD_VIEWER_EMAIL);
return createUser(user, DASHBOARD_VIEWER_PASSWORD, userGroup.getId()).getId();
}
private ResultActions doPostTestReport(String userId) throws Exception {
return doPostTestReport(userId, null);
}
private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl) throws Exception {
return doPostTestReport(userId, reportsServerEndpointUrl, false);
}
private ResultActions doPostTestReport(String userId, String reportsServerEndpointUrl, boolean useCurrentUserCredentials) throws Exception {
DashboardReportConfig reportConfig = new DashboardReportConfig();
reportConfig.setBaseUrl(REPORT_BASE_URL);
reportConfig.setDashboardId(dashboard.getId().toString());
reportConfig.setTimezone("UTC");
reportConfig.setNamePattern("report");
reportConfig.setType("pdf");
reportConfig.setUserId(userId);
reportConfig.setUseCurrentUserCredentials(useCurrentUserCredentials);
String url = "/api/report/test";
if (reportsServerEndpointUrl != null) {
url += "?reportsServerEndpointUrl=" + reportsServerEndpointUrl;
}
return doPostAsync(url, reportConfig, TimeUnit.SECONDS.toMillis(30));
}
private void verifyReportGenerated(UserId userId) throws Exception {
verify(dashboardReportService).generateReport(eq(tenantId), argThat(config -> userId.toString().equals(config.getUserId())), any(), any(), any());
}
}

2
application/src/test/java/org/thingsboard/server/controller/DevelopmentNoticeCaptureStampTest.java

@ -62,7 +62,7 @@ public class DevelopmentNoticeCaptureStampTest {
.as("no subscribing call to %s in the capture path to order against", STAMP_METHOD)
.isTrue();
int captured = capture.indexOf("html2canvas(");
int captured = capture.indexOf("domToCanvas(");
int serialised = capture.indexOf("toDataURL");
assertThat(captured).as("no capture call found to order against").isNotNegative();
assertThat(serialised).as("no serialisation call found to order against").isNotNegative();

2
application/src/test/java/org/thingsboard/server/controller/DeviceControllerTest.java

@ -10,6 +10,7 @@ import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
@ -23,7 +24,6 @@ import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.test.context.ContextConfiguration;
import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.ThingsBoardExecutors;
import org.thingsboard.server.common.data.AttributeScope;

473
application/src/test/java/org/thingsboard/server/controller/EntityGroupControllerTest.java

@ -3,40 +3,53 @@
package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.ResultActions;
import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.EntityInfo;
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.edge.Edge;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.IdBased;
import org.thingsboard.server.common.data.id.RoleId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.permission.GroupPermission;
import org.thingsboard.server.common.data.permission.GroupPermissionInfo;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.ShareGroupRequest;
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.dao.grouppermission.GroupPermissionService;
import org.thingsboard.server.dao.role.RoleService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@DaoSqlTest
@ -45,6 +58,12 @@ public class EntityGroupControllerTest extends AbstractControllerTest {
@Autowired
private RoleService roleService;
@Autowired
private GroupPermissionService groupPermissionService;
private static final String GROUP_MANAGER_PERMISSIONS =
"{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}";
private Tenant savedTenant;
private User tenantAdmin;
@ -89,6 +108,300 @@ public class EntityGroupControllerTest extends AbstractControllerTest {
Assert.assertEquals(savedEntityGroup.getName(), foundEntityGroup.getName());
}
@Test
public void testShouldNotChangeEntityGroupOwnerAsGroupOwner() throws Exception {
loginTenantAdmin();
EntityGroup entityGroup = new EntityGroup();
entityGroup.setName("Device Group");
entityGroup.setType(EntityType.DEVICE);
EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
savedEntityGroup.setOwnerId(customerId);
doPost("/api/entityGroup", savedEntityGroup)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Entity group owner can't be changed!")));
assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId);
}
@Test
public void testShouldNotChangeEntityGroupType() throws Exception {
loginTenantAdmin();
EntityGroup entityGroup = new EntityGroup();
entityGroup.setName("Device Group");
entityGroup.setType(EntityType.DEVICE);
EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
savedEntityGroup.setType(EntityType.USER);
doPost("/api/entityGroup", savedEntityGroup)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("Entity group type can't be changed!")));
assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getType()).isEqualTo(EntityType.DEVICE);
}
@Test
public void testShouldNotMoveTenantEntityGroupToCustomerAsCustomerAdmin() throws Exception {
EntityGroup tenantAdministratorsGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, tenantId,
EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME).get();
loginCustomerAdminUser();
EntityGroup movedEntityGroup = new EntityGroup(tenantAdministratorsGroup);
movedEntityGroup.setOwnerId(customerId);
doPost("/api/entityGroup", movedEntityGroup)
.andExpect(status().isForbidden());
assertThat(entityGroupService.findEntityGroupById(tenantId, tenantAdministratorsGroup.getId()).getOwnerId()).isEqualTo(tenantId);
}
@Test
public void testShouldNotMoveEntityGroupSharedWithWriteAccess() throws Exception {
loginTenantAdmin();
EntityGroup entityGroup = new EntityGroup();
entityGroup.setName("Shared Device Group");
entityGroup.setType(EntityType.DEVICE);
EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
var shareGroupRequest = new ShareGroupRequest(customerId, true, null, false, Collections.emptyList());
doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, savedEntityGroup.getId().toString())
.andExpect(status().isOk());
loginCustomerAdminUser();
EntityGroup sharedEntityGroup = doGet("/api/entityGroup/" + savedEntityGroup.getId().getId(), EntityGroup.class);
sharedEntityGroup.setOwnerId(customerId);
doPost("/api/entityGroup", sharedEntityGroup)
.andExpect(status().isForbidden());
assertThat(entityGroupService.findEntityGroupById(tenantId, savedEntityGroup.getId()).getOwnerId()).isEqualTo(tenantId);
}
@Test
public void testShouldNotMoveOtherTenantEntityGroup() throws Exception {
loginDifferentTenant();
EntityGroup entityGroup = new EntityGroup();
entityGroup.setName("Other Tenant Device Group");
entityGroup.setType(EntityType.DEVICE);
EntityGroup otherTenantEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
loginCustomerAdminUser();
otherTenantEntityGroup.setOwnerId(customerId);
doPost("/api/entityGroup", otherTenantEntityGroup)
.andExpect(status().isNotFound());
assertThat(entityGroupService.findEntityGroupById(differentTenantId, otherTenantEntityGroup.getId()).getOwnerId()).isEqualTo(differentTenantId);
}
@Test
public void testGetEntityGroupInfosByIdsReturnsOnlyOwnTenantGroups() throws Exception {
loginTenantAdmin();
EntityGroup ownGroup = new EntityGroup();
ownGroup.setName("Own Device Group");
ownGroup.setType(EntityType.DEVICE);
ownGroup = doPost("/api/entityGroup", ownGroup, EntityGroup.class);
loginDifferentTenant();
EntityGroup otherTenantGroup = new EntityGroup();
otherTenantGroup.setName("Other Tenant Device Group");
otherTenantGroup.setType(EntityType.DEVICE);
otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
loginTenantAdmin();
List<EntityInfo> entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + ownGroup.getId().getId() + "," + otherTenantGroup.getId().getId(),
new TypeReference<>() {});
assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(ownGroup.getId());
}
@Test
public void testGetEntityGroupInfosByIdsReturnsOnlyReadableGroups() throws Exception {
loginTenantAdmin();
EntityGroup tenantGroup = new EntityGroup();
tenantGroup.setName("Tenant Device Group");
tenantGroup.setType(EntityType.DEVICE);
tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class);
loginCustomerAdminUser();
EntityGroup customerGroup = new EntityGroup();
customerGroup.setName("Customer Device Group");
customerGroup.setType(EntityType.DEVICE);
customerGroup.setOwnerId(customerId);
customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class);
List<EntityInfo> entityInfos = doGetTyped("/api/entityGroupInfos?entityGroupIds=" + customerGroup.getId().getId() + "," + tenantGroup.getId().getId(),
new TypeReference<>() {});
assertThat(entityInfos).extracting(EntityInfo::getId).containsExactly(customerGroup.getId());
}
@Test
public void testShareGroupWithUserGroupOfOtherTenantReturnsNotFound() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantUserGroup = new EntityGroup();
otherTenantUserGroup.setName("Other Tenant User Group");
otherTenantUserGroup.setType(EntityType.USER);
otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class);
loginTenantAdmin();
EntityGroup deviceGroup = new EntityGroup();
deviceGroup.setName("Shared Device Group");
deviceGroup.setType(EntityType.DEVICE);
deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null);
doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest)
.andExpect(status().isNotFound())
.andExpect(statusReason(not(containsString(otherTenantUserGroup.getName()))));
}
@Test
public void testShareGroupV2WithUserGroupOfOtherTenantReturnsNotFound() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantUserGroup = new EntityGroup();
otherTenantUserGroup.setName("Other Tenant User Group");
otherTenantUserGroup.setType(EntityType.USER);
otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class);
loginTenantAdmin();
EntityGroup deviceGroup = new EntityGroup();
deviceGroup.setName("Shared Device Group");
deviceGroup.setType(EntityType.DEVICE);
deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, false, otherTenantUserGroup.getId(), true, null);
doPost("/api/v2/entityGroup/" + deviceGroup.getId().getId() + "/share", shareGroupRequest)
.andExpect(status().isNotFound())
.andExpect(statusReason(not(containsString(otherTenantUserGroup.getName()))));
}
@Test
public void testShareGroupWithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception {
loginDifferentTenant();
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null);
doPost("/api/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString())
.andExpect(status().isNotFound())
.andExpect(statusReason(is(msgErrorNotFound)));
ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null);
doPost("/api/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString())
.andExpect(status().isNotFound())
.andExpect(statusReason(is(msgErrorNotFound)));
assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty();
}
@Test
public void testShareGroupWithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception {
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId,
EntityType.USER, EntityGroup.GROUP_ALL_NAME).get();
ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null);
doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString())
.andExpect(status().isOk());
assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId());
}
@Test
public void testShareGroupV2WithAllUsersGroupOfOtherTenantReturnsNotFound() throws Exception {
loginDifferentTenant();
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
ShareGroupRequest unknownOwnerRequest = new ShareGroupRequest(TenantId.fromUUID(UUID.randomUUID()), true, null, true, null);
doPost("/api/v2/entityGroup/{entityGroupId}/share", unknownOwnerRequest, deviceGroup.getId().toString())
.andExpect(status().isNotFound())
.andExpect(statusReason(is(msgErrorNotFound)));
ShareGroupRequest otherTenantRequest = new ShareGroupRequest(differentTenantId, true, null, true, null);
doPost("/api/v2/entityGroup/{entityGroupId}/share", otherTenantRequest, deviceGroup.getId().toString())
.andExpect(status().isNotFound())
.andExpect(statusReason(is(msgErrorNotFound)));
assertThat(findSharedUserGroupIds(deviceGroup)).isEmpty();
}
@Test
public void testShareGroupV2WithAllUsersGroupOfOwnCustomerSharesWithThatGroup() throws Exception {
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Shared Device Group", tenantId);
EntityGroup customerAllUsersGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, customerId,
EntityType.USER, EntityGroup.GROUP_ALL_NAME).get();
ShareGroupRequest shareGroupRequest = new ShareGroupRequest(customerId, true, null, true, null);
doPost("/api/v2/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString())
.andExpect(status().isOk());
assertThat(findSharedUserGroupIds(deviceGroup)).containsExactly(customerAllUsersGroup.getId());
}
@Test
public void testShareGroupToChildOwnerUserGroupWithGroupsOfOtherTenantReturnsNotFound() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantUserGroup = new EntityGroup();
otherTenantUserGroup.setName("Other Tenant User Group");
otherTenantUserGroup.setType(EntityType.USER);
otherTenantUserGroup = doPost("/api/entityGroup", otherTenantUserGroup, EntityGroup.class);
EntityGroup otherTenantDeviceGroup = new EntityGroup();
otherTenantDeviceGroup.setName("Other Tenant Device Group");
otherTenantDeviceGroup.setType(EntityType.DEVICE);
otherTenantDeviceGroup = doPost("/api/entityGroup", otherTenantDeviceGroup, EntityGroup.class);
loginTenantAdmin();
EntityGroup deviceGroup = new EntityGroup();
deviceGroup.setName("Shared Device Group");
deviceGroup.setType(EntityType.DEVICE);
deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
EntityGroup userGroup = new EntityGroup();
userGroup.setName("Own User Group");
userGroup.setType(EntityType.USER);
userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class);
Role role = new Role();
role.setName("Read Group Role");
role.setType(RoleType.GROUP);
role.setPermissions(JacksonUtil.valueToTree(List.of(Operation.READ)));
role = doPost("/api/role", role, Role.class);
doPost("/api/entityGroup/" + deviceGroup.getId().getId() + "/" + otherTenantUserGroup.getId().getId() + "/" + role.getId().getId() + "/share")
.andExpect(status().isNotFound());
doPost("/api/entityGroup/" + otherTenantDeviceGroup.getId().getId() + "/" + userGroup.getId().getId() + "/" + role.getId().getId() + "/share")
.andExpect(status().isNotFound());
}
@Test
public void testGetAttributesOfEntityGroupOfOtherTenantReturnsNotFound() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantGroup = new EntityGroup();
otherTenantGroup.setName("Other Tenant Asset Group");
otherTenantGroup.setType(EntityType.ASSET);
otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
loginTenantAdmin();
doGetAsync("/api/plugins/telemetry/ENTITY_GROUP/" + otherTenantGroup.getId().getId() + "/values/attributes")
.andExpect(status().isNotFound());
}
@Test
public void testGetEntityGroupOfOtherTenantReturnsNotFound() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantGroup = new EntityGroup();
otherTenantGroup.setName("Other Tenant Asset Group");
otherTenantGroup.setType(EntityType.ASSET);
otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
loginTenantAdmin();
doGet("/api/entityGroup/" + otherTenantGroup.getId().getId())
.andExpect(status().isNotFound())
.andExpect(statusReason(not(containsString(otherTenantGroup.getName()))));
}
@Test
public void testShouldNotUpdateNonExistingEntityGroup() throws Exception {
loginTenantAdmin();
EntityGroup entityGroup = new EntityGroup();
entityGroup.setId(new EntityGroupId(UUID.randomUUID()));
entityGroup.setName("Non-existing Device Group");
entityGroup.setType(EntityType.DEVICE);
entityGroup.setOwnerId(tenantId);
doPost("/api/entityGroup", entityGroup)
.andExpect(status().isNotFound());
}
@Test
public void testSaveEntityGroupWithSameName() throws Exception {
EntityGroup entityGroup = new EntityGroup();
@ -314,4 +627,164 @@ public class EntityGroupControllerTest extends AbstractControllerTest {
Assert.assertNotNull(foundDashboard2);
}
@Test
public void testShareEntityGroupWithGroupRole() throws Exception {
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]");
shareWithRoles(deviceGroup, customerId, groupRole.getId())
.andExpect(status().isOk());
assertThat(findSharedRoleIds(deviceGroup)).containsExactly(groupRole.getId());
}
@Test
public void testShareEntityGroupRejectsGenericRole() throws Exception {
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}");
shareWithRoles(deviceGroup, customerId, genericRole.getId())
.andExpect(status().isBadRequest());
assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
}
@Test
public void testShareEntityGroupRequiresReadableRole() throws Exception {
createDifferentTenant();
Role otherTenantRole = createRole(differentTenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]");
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
shareWithRoles(deviceGroup, customerId, otherTenantRole.getId())
.andExpect(status().isForbidden());
assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
}
@Test
public void testShareEntityGroupSavesNothingWhenAnyRoleRejected() throws Exception {
loginTenantAdmin();
EntityGroup deviceGroup = createDeviceGroup("Device Group", tenantId);
Role groupRole = createRole(tenantId, null, "Read role", RoleType.GROUP, "[\"READ\"]");
Role genericRole = createRole(tenantId, null, "Generic role", RoleType.GENERIC, "{\"DEVICE\":[\"READ\"]}");
shareWithRoles(deviceGroup, customerId, groupRole.getId(), genericRole.getId())
.andExpect(status().isBadRequest());
assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
}
@Test
public void testShareEntityGroupRequiresRoleOperationsHeldByUser() throws Exception {
loginTenantAdmin();
User manager = createGroupManager(createCustomerUserGroup(), GROUP_MANAGER_PERMISSIONS);
EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId);
Role readRole = createRole(tenantId, customerId, "Read role", RoleType.GROUP, "[\"READ\"]");
Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]");
login(manager.getEmail(), "manager");
shareWithRoles(deviceGroup, customerId, rpcRole.getId())
.andExpect(status().isForbidden());
assertThat(findSharedRoleIds(deviceGroup)).isEmpty();
shareWithRoles(deviceGroup, customerId, readRole.getId())
.andExpect(status().isOk());
assertThat(findSharedRoleIds(deviceGroup)).containsExactly(readRole.getId());
}
@Test
public void testShareEntityGroupAllowsRoleOperationsHeldOnEntities() throws Exception {
loginTenantAdmin();
User manager = createGroupManager(createCustomerUserGroup(),
"{\"DEVICE_GROUP\":[\"READ\",\"WRITE\"],\"DEVICE\":[\"RPC_CALL\"],\"USER_GROUP\":[\"READ\",\"WRITE\"],\"GROUP_PERMISSION\":[\"CREATE\"],\"ROLE\":[\"READ\"]}");
EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId);
Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]");
login(manager.getEmail(), "manager");
shareWithRoles(deviceGroup, customerId, rpcRole.getId())
.andExpect(status().isOk());
assertThat(findSharedRoleIds(deviceGroup)).containsExactly(rpcRole.getId());
}
@Test
public void testShareEntityGroupAllowsRoleOperationsHeldOnSharedGroup() throws Exception {
loginTenantAdmin();
EntityGroup managers = createCustomerUserGroup();
User manager = createGroupManager(managers, GROUP_MANAGER_PERMISSIONS);
EntityGroup deviceGroup = createDeviceGroup("Customer Device Group", customerId);
Role groupRpcRole = createRole(tenantId, customerId, "RPC role", RoleType.GROUP, "[\"RPC_CALL\"]");
GroupPermission groupRpcPermission = new GroupPermission();
groupRpcPermission.setRoleId(groupRpcRole.getId());
groupRpcPermission.setUserGroupId(managers.getId());
groupRpcPermission.setEntityGroupId(deviceGroup.getId());
groupRpcPermission.setEntityGroupType(deviceGroup.getType());
doPost("/api/groupPermission", groupRpcPermission, GroupPermission.class);
Role rpcRole = createRole(tenantId, customerId, "Read and RPC role", RoleType.GROUP, "[\"READ\",\"RPC_CALL\"]");
login(manager.getEmail(), "manager");
shareWithRoles(deviceGroup, customerId, rpcRole.getId())
.andExpect(status().isOk());
assertThat(findSharedRoleIds(deviceGroup)).contains(rpcRole.getId());
}
private EntityGroup createCustomerUserGroup() throws Exception {
EntityGroup userGroup = new EntityGroup();
userGroup.setType(EntityType.USER);
userGroup.setName("Group managers");
userGroup.setOwnerId(customerId);
return doPost("/api/entityGroup", userGroup, EntityGroup.class);
}
private User createGroupManager(EntityGroup userGroup, String permissions) throws Exception {
Role managerRole = createRole(tenantId, customerId, "Group manager", RoleType.GENERIC, permissions);
GroupPermission managerPermission = new GroupPermission();
managerPermission.setRoleId(managerRole.getId());
managerPermission.setUserGroupId(userGroup.getId());
doPost("/api/groupPermission", managerPermission, GroupPermission.class);
User manager = new User();
manager.setAuthority(Authority.CUSTOMER_USER);
manager.setTenantId(tenantId);
manager.setCustomerId(customerId);
manager.setEmail("groupmanager@thingsboard.org");
return createUser(manager, "manager", userGroup.getId());
}
private EntityGroup createDeviceGroup(String name, EntityId ownerId) throws Exception {
EntityGroup entityGroup = new EntityGroup();
entityGroup.setType(EntityType.DEVICE);
entityGroup.setName(name);
entityGroup.setOwnerId(ownerId);
return doPost("/api/entityGroup", entityGroup, EntityGroup.class);
}
private Role createRole(TenantId roleTenantId, CustomerId roleCustomerId, String name, RoleType type, String permissions) {
Role role = new Role();
role.setTenantId(roleTenantId);
role.setCustomerId(roleCustomerId);
role.setType(type);
role.setName(name);
role.setPermissions(JacksonUtil.toJsonNode(permissions));
return roleService.saveRole(roleTenantId, role);
}
private ResultActions shareWithRoles(EntityGroup entityGroup, CustomerId targetCustomerId, RoleId... roleIds) throws Exception {
var shareGroupRequest = new ShareGroupRequest(targetCustomerId, true, null, false, List.of(roleIds));
return doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, entityGroup.getId().toString());
}
private List<RoleId> findSharedRoleIds(EntityGroup entityGroup) {
return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100))
.getData().stream().map(GroupPermission::getRoleId).collect(Collectors.toList());
}
private List<EntityGroupId> findSharedUserGroupIds(EntityGroup entityGroup) {
return groupPermissionService.findGroupPermissionByTenantIdAndEntityGroupId(tenantId, entityGroup.getId(), new PageLink(100))
.getData().stream().map(GroupPermission::getUserGroupId).collect(Collectors.toList());
}
}

89
application/src/test/java/org/thingsboard/server/controller/EntityViewControllerTest.java

@ -353,6 +353,94 @@ public class EntityViewControllerTest extends AbstractControllerTest {
deleteDifferentTenant();
}
@Test
public void testSaveEntityViewWithEntityOfOtherTenant() throws Exception {
loginDifferentTenant();
String name = "Entity view of other tenant device";
EntityView entityView = createEntityView(name, 0, 0);
doPost("/api/entityView", entityView)
.andExpect(status().is4xxClientError());
doGet("/api/tenant/entityViews?entityViewName=" + name)
.andExpect(status().isNotFound());
deleteDifferentTenant();
}
@Test
public void testUpdateEntityViewByCustomerUserToEntityNotAssignedToCustomer() throws Exception {
EntityView savedView = getNewSavedEntityView("Customer entity view");
doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk());
doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/DEVICE/" + testDevice.getId().getId()).andExpect(status().isOk());
Device otherDevice = new Device();
otherDevice.setName("Device not assigned to customer");
otherDevice.setType("default");
otherDevice = doPost("/api/device", otherDevice, Device.class);
loginCustomerAdminUser();
EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
customerView.setEntityId(otherDevice.getId());
doPost("/api/entityView", customerView)
.andExpect(status().isForbidden());
EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
assertEquals(testDevice.getId(), foundView.getEntityId());
}
@Test
public void testUpdateEntityViewByCustomerUserKeepingEntity() throws Exception {
EntityView savedView = getNewSavedEntityView("Customer entity view");
doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk());
loginCustomerAdminUser();
EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
customerView.setName("Customer entity view renamed");
EntityView updatedView = doPost("/api/entityView", customerView, EntityView.class);
assertEquals("Customer entity view renamed", updatedView.getName());
assertEquals(testDevice.getId(), updatedView.getEntityId());
}
@Test
public void testUpdateEntityViewKeysByCustomerUserWithEntityNotAssignedToCustomer() throws Exception {
EntityView savedView = getNewSavedEntityView("Customer entity view");
doPost("/api/owner/CUSTOMER/" + customerId.getId() + "/ENTITY_VIEW/" + savedView.getId().getId()).andExpect(status().isOk());
loginCustomerAdminUser();
EntityView customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
customerView.setKeys(new TelemetryEntityView(List.of("tsKey1"), new AttributesEntityView()));
doPost("/api/entityView", customerView)
.andExpect(status().isForbidden());
customerView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
customerView.setStartTimeMs(1L);
doPost("/api/entityView", customerView)
.andExpect(status().isForbidden());
EntityView foundView = doGet("/api/entityView/" + savedView.getId().getId(), EntityView.class);
assertEquals(telemetry, foundView.getKeys());
assertEquals(0L, foundView.getStartTimeMs());
}
@Test
public void testFindEntityViewByOldNameAfterRename() throws Exception {
String oldName = "Entity view old name";
EntityView savedView = getNewSavedEntityView(oldName);
doGet("/api/tenant/entityViews?entityViewName=" + oldName)
.andExpect(status().isOk());
savedView.setName("Entity view new name");
doPost("/api/entityView", savedView, EntityView.class);
doGet("/api/tenant/entityViews?entityViewName=" + oldName)
.andExpect(status().isNotFound());
}
@Test
public void testDeleteEntityView() throws Exception {
Customer customer = doPost("/api/customer", getNewCustomer("My customer"), Customer.class);
@ -380,6 +468,7 @@ public class EntityViewControllerTest extends AbstractControllerTest {
public void testSaveEntityViewWithEmptyName() throws Exception {
EntityView entityView = new EntityView();
entityView.setType("default");
entityView.setEntityId(testDevice.getId());
Mockito.reset(tbClusterService, auditLogService);

225
application/src/test/java/org/thingsboard/server/controller/GroupPermissionControllerTest.java

@ -3,23 +3,27 @@
package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.thingsboard.server.common.data.Customer;
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.group.EntityGroup;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.permission.AllowedPermissionsInfo;
import org.thingsboard.server.common.data.permission.GroupPermission;
import org.thingsboard.server.common.data.permission.GroupPermissionInfo;
import org.thingsboard.server.common.data.permission.ShareGroupRequest;
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.dao.grouppermission.GroupPermissionService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.ArrayList;
@ -35,6 +39,9 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@DaoSqlTest
public class GroupPermissionControllerTest extends AbstractControllerTest {
@Autowired
private GroupPermissionService groupPermissionService;
private IdComparator<GroupPermission> idComparator;
private Tenant savedTenant;
private User tenantAdmin;
@ -278,6 +285,222 @@ public class GroupPermissionControllerTest extends AbstractControllerTest {
checkPermissionOwners(loadedGroupPermissionsInfo, List.of(subCustomerId));
}
@Test
public void testLoadUserGroupPermissionInfosReturnsOnlyOwnTenantData() throws Exception {
loginDifferentTenant();
Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class);
EntityGroup otherTenantGroup = new EntityGroup();
otherTenantGroup.setType(EntityType.DEVICE);
otherTenantGroup.setName("Other Tenant Device Group");
otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
loginTenantAdmin();
Role ownRole = doPost("/api/role", newRole("Own Role", RoleType.GROUP), Role.class);
GroupPermission otherTenantRolePermission = new GroupPermission();
otherTenantRolePermission.setRoleId(otherTenantRole.getId());
GroupPermission otherTenantGroupPermission = new GroupPermission();
otherTenantGroupPermission.setRoleId(ownRole.getId());
otherTenantGroupPermission.setEntityGroupId(otherTenantGroup.getId());
List<GroupPermissionInfo> infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info",
List.of(otherTenantRolePermission, otherTenantGroupPermission), new TypeReference<>() {});
assertThat(infos).isEmpty();
}
@Test
public void testLoadUserGroupPermissionInfosReturnsOnlyReadableGroups() throws Exception {
loginTenantAdmin();
Role role = doPost("/api/role", newRole("Group Role", RoleType.GROUP), Role.class);
EntityGroup tenantGroup = new EntityGroup();
tenantGroup.setType(EntityType.DEVICE);
tenantGroup.setName("Tenant Device Group");
tenantGroup = doPost("/api/entityGroup", tenantGroup, EntityGroup.class);
loginCustomerAdminUser();
EntityGroup customerGroup = new EntityGroup();
customerGroup.setType(EntityType.DEVICE);
customerGroup.setName("Customer Device Group");
customerGroup.setOwnerId(customerId);
customerGroup = doPost("/api/entityGroup", customerGroup, EntityGroup.class);
GroupPermission tenantGroupPermission = new GroupPermission();
tenantGroupPermission.setRoleId(role.getId());
tenantGroupPermission.setEntityGroupId(tenantGroup.getId());
GroupPermission customerGroupPermission = new GroupPermission();
customerGroupPermission.setRoleId(role.getId());
customerGroupPermission.setEntityGroupId(customerGroup.getId());
List<GroupPermissionInfo> infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info",
List.of(tenantGroupPermission, customerGroupPermission), new TypeReference<>() {});
assertThat(infos).extracting(GroupPermissionInfo::getEntityGroupId).containsExactly(customerGroup.getId());
}
@Test
public void testLoadUserGroupPermissionInfosKeepsSystemRoles() throws Exception {
loginTenantAdmin();
EntityGroup tenantAdminsGroup = findGroupByOwnerIdTypeAndName(tenantId, EntityType.USER, EntityGroup.GROUP_TENANT_ADMINS_NAME);
List<GroupPermissionInfo> storedInfos = doGetTyped("/api/userGroup/" + tenantAdminsGroup.getId() + "/groupPermissions",
new TypeReference<>() {});
assertThat(storedInfos).isNotEmpty();
assertThat(storedInfos).allSatisfy(info -> assertThat(info.getRole().getTenantId().isSysTenantId()).isTrue());
List<GroupPermission> permissions = storedInfos.stream().map(GroupPermission::new).toList();
List<GroupPermissionInfo> infos = doPostWithTypedResponse("/api/userGroup/groupPermissions/info", permissions, new TypeReference<>() {});
assertThat(infos).hasSameSizeAs(permissions);
assertThat(infos).allSatisfy(info -> assertThat(info.getRole()).isNotNull());
}
@Test
public void testShareGroupWithRoleOfOtherTenantIsRejected() throws Exception {
loginDifferentTenant();
Role otherTenantRole = doPost("/api/role", newRole("Other Tenant Role", RoleType.GROUP), Role.class);
loginTenantAdmin();
EntityGroup deviceGroup = new EntityGroup();
deviceGroup.setType(EntityType.DEVICE);
deviceGroup.setName("Shared Device Group");
deviceGroup = doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
ShareGroupRequest shareGroupRequest = new ShareGroupRequest(tenantId, true, null, false, List.of(otherTenantRole.getId()));
doPost("/api/entityGroup/{entityGroupId}/share", shareGroupRequest, deviceGroup.getId().toString())
.andExpect(status().isForbidden());
assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, otherTenantRole.getId(), new PageLink(10)).getData()).isEmpty();
}
private Role newRole(String roleName, RoleType roleType) {
Role role = new Role();
role.setName(roleName);
role.setType(roleType);
return role;
}
@Test
public void testCustomerAdminCannotUpdateTenantGroupPermission() throws Exception {
loginTenantAdmin();
EntityGroup tenantUserGroup = saveUserGroup("Tenant users");
Role tenantRole = doPost("/api/role", createRole("Tenant role", RoleType.GENERIC), Role.class);
GroupPermission groupPermission = new GroupPermission();
groupPermission.setRoleId(tenantRole.getId());
groupPermission.setUserGroupId(tenantUserGroup.getId());
groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
loginCustomerAdminUser();
Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class);
GroupPermission update = new GroupPermission(groupPermission);
update.setUserGroupId(findCustomerAdminsGroup(customerId).getId());
update.setRoleId(customerRole.getId());
doPost("/api/groupPermission", update).andExpect(status().isForbidden());
loginTenantAdmin();
GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
assertEquals(tenantUserGroup.getId(), stored.getUserGroupId());
assertEquals(tenantRole.getId(), stored.getRoleId());
}
@Test
public void testCustomerAdminCannotMoveGroupPermissionFromTenantUserGroup() throws Exception {
loginCustomerAdminUser();
Role customerRole = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class);
EntityGroup customerUserGroup = saveUserGroup("Customer users");
loginTenantAdmin();
EntityGroup tenantUserGroup = saveUserGroup("Tenant users");
GroupPermission groupPermission = new GroupPermission();
groupPermission.setRoleId(customerRole.getId());
groupPermission.setUserGroupId(tenantUserGroup.getId());
groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
loginCustomerAdminUser();
GroupPermission update = new GroupPermission(groupPermission);
update.setUserGroupId(customerUserGroup.getId());
doPost("/api/groupPermission", update).andExpect(status().isForbidden());
loginTenantAdmin();
GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
assertEquals(tenantUserGroup.getId(), stored.getUserGroupId());
}
@Test
public void testCustomerAdminCannotUpdateGroupPermissionOfTenantEntityGroup() throws Exception {
loginCustomerAdminUser();
Role customerRole = doPost("/api/role", createRole("Customer group role", RoleType.GROUP), Role.class);
EntityGroup customerUserGroup = saveUserGroup("Customer users");
EntityGroup customerDeviceGroup = saveDeviceGroup("Customer devices");
loginTenantAdmin();
EntityGroup tenantDeviceGroup = saveDeviceGroup("Tenant devices");
GroupPermission groupPermission = new GroupPermission();
groupPermission.setRoleId(customerRole.getId());
groupPermission.setUserGroupId(customerUserGroup.getId());
groupPermission.setEntityGroupId(tenantDeviceGroup.getId());
groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
loginCustomerAdminUser();
GroupPermission update = new GroupPermission(groupPermission);
update.setEntityGroupId(customerDeviceGroup.getId());
doPost("/api/groupPermission", update).andExpect(status().isForbidden());
loginTenantAdmin();
GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
assertEquals(tenantDeviceGroup.getId(), stored.getEntityGroupId());
}
@Test
public void testPublicGroupPermissionIsNotUpdatable() throws Exception {
loginTenantAdmin();
EntityGroup deviceGroup = saveDeviceGroup("Public devices");
doPost("/api/entityGroup/" + deviceGroup.getUuidId() + "/makePublic").andExpect(status().isOk());
List<GroupPermissionInfo> permissions = doGetTyped("/api/entityGroup/" + deviceGroup.getUuidId() + "/groupPermissions",
new TypeReference<>() {});
assertEquals(1, permissions.size());
GroupPermission publicPermission = doGet("/api/groupPermission/" + permissions.get(0).getUuidId(), GroupPermission.class);
assertTrue(publicPermission.isPublic());
EntityGroup userGroup = saveUserGroup("Other users");
GroupPermission update = new GroupPermission(publicPermission);
update.setPublic(false);
update.setUserGroupId(userGroup.getId());
doPost("/api/groupPermission", update).andExpect(status().isForbidden());
GroupPermission stored = doGet("/api/groupPermission/" + publicPermission.getUuidId(), GroupPermission.class);
assertTrue(stored.isPublic());
assertEquals(publicPermission.getUserGroupId(), stored.getUserGroupId());
}
@Test
public void testCustomerAdminUpdatesOwnGroupPermission() throws Exception {
loginCustomerAdminUser();
EntityGroup firstUserGroup = saveUserGroup("First customer users");
EntityGroup secondUserGroup = saveUserGroup("Second customer users");
Role role = doPost("/api/role", createRole("Customer role", RoleType.GENERIC), Role.class);
GroupPermission groupPermission = new GroupPermission();
groupPermission.setRoleId(role.getId());
groupPermission.setUserGroupId(firstUserGroup.getId());
groupPermission = doPost("/api/groupPermission", groupPermission, GroupPermission.class);
groupPermission.setUserGroupId(secondUserGroup.getId());
doPost("/api/groupPermission", groupPermission).andExpect(status().isOk());
GroupPermission stored = doGet("/api/groupPermission/" + groupPermission.getUuidId(), GroupPermission.class);
assertEquals(secondUserGroup.getId(), stored.getUserGroupId());
}
private EntityGroup saveUserGroup(String name) throws Exception {
EntityGroup userGroup = new EntityGroup();
userGroup.setType(EntityType.USER);
userGroup.setName(name);
return doPost("/api/entityGroup", userGroup, EntityGroup.class);
}
private EntityGroup saveDeviceGroup(String name) throws Exception {
EntityGroup deviceGroup = new EntityGroup();
deviceGroup.setType(EntityType.DEVICE);
deviceGroup.setName(name);
return doPost("/api/entityGroup", deviceGroup, EntityGroup.class);
}
private void checkPermissionOwners(List<GroupPermissionInfo> groupPermissionsInfos, List<? extends EntityId> ownerIds) {
for (GroupPermissionInfo groupPermissionInfo : groupPermissionsInfos) {
assertTrue(ownerIds.contains(groupPermissionInfo.getUserGroupOwnerId()));

2
application/src/test/java/org/thingsboard/server/controller/ImageControllerTest.java

@ -307,7 +307,7 @@ public class ImageControllerTest extends AbstractControllerTest {
Map<String, String> expectedHeaders = Map.of(
"Baker Street, 221B.png", "attachment; filename=\"Baker Street, 221B.png\"",
"\"Baker Street\", 221B.png", "attachment; filename=\"\\\"Baker Street\\\", 221B.png\"",
"Хрещатик, 22.png", "attachment; filename=\"=?UTF-8?Q?=D0=A5=D1=80=D0=B5=D1=89=D0=B0=D1=82=D0=B8=D0=BA,_22.png?=\"; " +
"Хрещатик, 22.png", "attachment; filename=\"________, 22.png\"; " +
"filename*=UTF-8''%D0%A5%D1%80%D0%B5%D1%89%D0%B0%D1%82%D0%B8%D0%BA%2C%2022.png"
);

2
application/src/test/java/org/thingsboard/server/controller/IntegrationControllerTest.java

@ -5,13 +5,13 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.TestPropertySource;
import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.IntegrationConvertersInfo;

32
application/src/test/java/org/thingsboard/server/controller/ReportControllerTest.java

@ -25,6 +25,7 @@ import org.thingsboard.server.common.data.alarm.Alarm;
import org.thingsboard.server.common.data.alarm.AlarmSeverity;
import org.thingsboard.server.common.data.asset.Asset;
import org.thingsboard.server.common.data.id.ReportTemplateId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.job.Job;
import org.thingsboard.server.common.data.job.JobStatus;
import org.thingsboard.server.common.data.job.JobType;
@ -101,6 +102,8 @@ import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -826,6 +829,35 @@ public class ReportControllerTest extends AbstractControllerTest {
doPost("/api/v2/report/test", request).andExpect(status().isOk());
}
@Test
public void testTestReportRequiresPermissionOverReportUser() throws Exception {
loginDifferentTenant();
UserId otherTenantUserId = savedDifferentTenantUser.getId();
loginTenantAdmin();
ReportRequest request = new ReportRequest();
request.setReportTemplateConfig(buildReportTemplate(TbReportFormat.CSV).getConfiguration());
request.setUserId(otherTenantUserId.toString());
doPost("/api/v2/report/test", request).andExpect(status().isForbidden());
verify(tbReportService, never()).generateTestReport(any());
}
@Test
public void testRequestReportRequiresPermissionOverReportUser() throws Exception {
loginDifferentTenant();
UserId otherTenantUserId = savedDifferentTenantUser.getId();
loginTenantAdmin();
ReportTemplate reportTemplate = doPost("/api/reportTemplate", buildReportTemplate(TbReportFormat.CSV), ReportTemplate.class);
ReportRequest request = new ReportRequest();
request.setReportTemplateId(reportTemplate.getId());
request.setUserId(otherTenantUserId.toString());
doPost("/api/v2/report/request", request).andExpect(status().isForbidden());
assertThat(findJobs(List.of(JobType.REPORT), List.of(reportTemplate.getId().getId()))).isEmpty();
}
private TimeseriesTableComponent buildTimeseriesTableComponent(String devicesAliasId) {
return buildTimeseriesTableComponent(devicesAliasId, buildCurrentDateTimeWindow());
}

35
application/src/test/java/org/thingsboard/server/controller/RuleEngineControllerTest.java

@ -16,6 +16,7 @@ import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.msg.TbMsgType;
import org.thingsboard.server.common.msg.TbMsg;
import org.thingsboard.server.common.msg.TbMsgMetaData;
@ -242,6 +243,32 @@ public class RuleEngineControllerTest extends AbstractControllerTest {
verifyNoInteractions(ruleEngineCallService);
}
@Test
public void testHandleRuleEngineRequestRequiresPermissionOverReportUser() throws Exception {
loginCustomerAdminUser();
doPost("/api/rule-engine/", (Object) reportRequestBody(tenantAdminUserId))
.andExpect(status().isForbidden());
doPost("/api/rule-engine/", (Object) reportConfigRequestBody(tenantAdminUserId))
.andExpect(status().isForbidden());
verifyNoInteractions(ruleEngineCallService);
TbMsg responseMsg = TbMsg.newMsg()
.type(TbMsgType.REST_API_REQUEST)
.originator(customerAdminUserId)
.copyMetaData(TbMsgMetaData.EMPTY)
.data(RESPONSE_BODY)
.build();
mockRestApiCallToRuleEngine(responseMsg);
String ownReportRequestBody = reportRequestBody(customerAdminUserId);
doPostAsyncWithTypedResponse("/api/rule-engine/", ownReportRequestBody, new TypeReference<JsonNode>() {
}, status().isOk());
ArgumentCaptor<TbMsg> requestMsgCaptor = ArgumentCaptor.forClass(TbMsg.class);
verify(ruleEngineCallService).processRestApiCallToRuleEngine(eq(tenantId), any(UUID.class), requestMsgCaptor.capture(), eq(false), any(Consumer.class));
assertThat(requestMsgCaptor.getValue().getData()).isEqualTo(ownReportRequestBody);
}
@Test
public void testHandleRuleEngineRequestUnauthorized() throws Exception {
doPost("/api/rule-engine/", (Object) REQUEST_BODY)
@ -249,6 +276,14 @@ public class RuleEngineControllerTest extends AbstractControllerTest {
.andExpect(statusReason(containsString("Authentication failed")));
}
private String reportRequestBody(UserId userId) {
return "{\"reportConfig\":{\"userId\":\"" + userId.getId() + "\"}}";
}
private String reportConfigRequestBody(UserId userId) {
return "{\"userId\":{\"id\":\"" + userId.getId() + "\"}}";
}
private void mockRestApiCallToRuleEngine(TbMsg responseMsg) {
doAnswer(invocation -> {
Consumer<TbMsg> consumer = invocation.getArgument(4);

75
application/src/test/java/org/thingsboard/server/controller/SchedulerEventControllerTest.java

@ -276,6 +276,48 @@ public class SchedulerEventControllerTest extends AbstractControllerTest {
assertThat(reportInfos.getData()).hasSize(0);
}
@Test
public void testSaveReportEventRequiresPermissionOverReportUser() throws Exception {
ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class);
loginCustomerAdminUser();
doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), tenantAdminUserId)).andExpect(status().isForbidden());
doPost("/api/schedulerEvent", createDashboardReportSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden());
doPost("/api/schedulerEvent", createReportConfigMsgSchedulerEvent(tenantAdminUserId)).andExpect(status().isForbidden());
assertThat(findSchedulerEvents(null, null)).isEmpty();
SchedulerEvent reportEvent = createReportSchedulerEvent(template.getId(), customerAdminUserId);
((ObjectNode) reportEvent.getSchedule()).put("startTime", System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1));
assertThat(saveSchedulerEvent(reportEvent).getId()).isNotNull();
assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId)).getId()).isNotNull();
loginTenantAdmin();
assertThat(saveSchedulerEvent(createDashboardReportSchedulerEvent(customerUserId)).getId()).isNotNull();
}
@Test
public void testSaveDashboardReportEventWithCurrentUserCredentialsUsesSaverWhenReportUserNotAccessible() throws Exception {
loginCustomerAdminUser();
SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(tenantAdminUserId, true));
assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString());
}
@Test
public void testSaveDashboardReportEventWithCurrentUserCredentialsKeepsAccessibleReportUser() throws Exception {
SchedulerEvent saved = saveSchedulerEvent(createDashboardReportSchedulerEvent(customerAdminUserId, true));
assertThat(saved.getConfiguration().get("msgBody").get("reportConfig").get("userId").asText()).isEqualTo(customerAdminUserId.toString());
}
@Test
public void testSaveReportEventRequiresReportUser() throws Exception {
ReportTemplate template = doPost("/api/reportTemplate", buildTemplate("CSV report template", ReportTemplateType.REPORT, TbReportFormat.CSV), ReportTemplate.class);
doPost("/api/schedulerEvent", createReportSchedulerEvent(template.getId(), null)).andExpect(status().isBadRequest());
SchedulerEvent noConfigurationEvent = createReportSchedulerEvent(template.getId(), tenantAdminUserId);
noConfigurationEvent.setConfiguration(null);
doPost("/api/schedulerEvent", noConfigurationEvent).andExpect(status().isBadRequest());
}
private ReportTemplate buildTemplate(String templateName, ReportTemplateType report, TbReportFormat format) {
ReportTemplate template = new ReportTemplate();
template.setName(templateName);
@ -310,6 +352,39 @@ public class SchedulerEventControllerTest extends AbstractControllerTest {
return schedulerEvent;
}
private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId) {
return createDashboardReportSchedulerEvent(userId, false);
}
private SchedulerEvent createDashboardReportSchedulerEvent(UserId userId, boolean useCurrentUserCredentials) {
SchedulerEvent schedulerEvent = createSchedulerEvent();
schedulerEvent.setType("generateDashboardReport");
ObjectNode reportConfig = JacksonUtil.newObjectNode();
reportConfig.put("namePattern", "report-%d{yyyy-MM-dd_HH:mm:ss}");
reportConfig.put("type", "pdf");
reportConfig.put("useCurrentUserCredentials", useCurrentUserCredentials);
reportConfig.put("userId", userId.toString());
ObjectNode msgBody = JacksonUtil.newObjectNode();
msgBody.set("reportConfig", reportConfig);
msgBody.put("sendEmail", false);
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.put("msgType", "generateDashboardReport");
configuration.set("msgBody", msgBody);
schedulerEvent.setConfiguration(configuration);
return schedulerEvent;
}
private SchedulerEvent createReportConfigMsgSchedulerEvent(UserId userId) {
SchedulerEvent schedulerEvent = createSchedulerEvent();
ObjectNode msgBody = JacksonUtil.newObjectNode();
msgBody.set("userId", JacksonUtil.valueToTree(userId));
ObjectNode configuration = JacksonUtil.newObjectNode();
configuration.put("msgType", "Custom Msg");
configuration.set("msgBody", msgBody);
schedulerEvent.setConfiguration(configuration);
return schedulerEvent;
}
private SchedulerEvent saveSchedulerEvent(SchedulerEvent schedulerEvent) {
return doPost("/api/schedulerEvent", schedulerEvent, SchedulerEvent.class);
}

315
application/src/test/java/org/thingsboard/server/controller/SignUpControllerSqlTest.java

@ -4,16 +4,20 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.bean.override.mockito.MockitoSpyBean;
import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.CustomerInfo;
import org.thingsboard.server.common.data.Dashboard;
@ -26,6 +30,7 @@ import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.domain.Domain;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.menu.CMAssigneeType;
import org.thingsboard.server.common.data.menu.CMScope;
import org.thingsboard.server.common.data.menu.CustomMenu;
@ -37,6 +42,12 @@ import org.thingsboard.server.common.data.notification.NotificationDeliveryMetho
import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.common.data.oauth2.PlatformType;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.permission.GroupPermission;
import org.thingsboard.server.common.data.permission.GroupPermissionInfo;
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.UserCredentials;
import org.thingsboard.server.common.data.selfregistration.DefaultDashboardParams;
import org.thingsboard.server.common.data.selfregistration.HomeDashboardParams;
import org.thingsboard.server.common.data.selfregistration.MobileRedirectParams;
@ -47,8 +58,10 @@ import org.thingsboard.server.common.data.selfregistration.V2CaptchaParams;
import org.thingsboard.server.common.data.selfregistration.WebSelfRegistrationParams;
import org.thingsboard.server.common.data.signup.SignUpRequest;
import org.thingsboard.server.common.data.signup.SignUpResult;
import org.thingsboard.server.common.data.wl.WhiteLabelingType;
import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.group.EntityGroupService;
import org.thingsboard.server.dao.grouppermission.GroupPermissionService;
import org.thingsboard.server.dao.menu.CustomMenuDao;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.settings.AdminSettingsService;
@ -57,6 +70,7 @@ import org.thingsboard.server.dao.user.UserService;
import org.thingsboard.server.dao.wl.WhiteLabelingService;
import org.thingsboard.server.service.entitiy.TbLogEntityActionService;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@ -68,10 +82,14 @@ import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -87,6 +105,8 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
public static final String CUSTOMER_TEST_EMAIL = "signup-customer@thingsboard.org";
public static final String CUSTOMER_TITLE_PREFIX = "Prefix-";
public static final String CONFIGURED_BASE_URL = "https://configured.example.com";
public static final String OTHER_HOST = "other.example.com";
private static List<UUID> idsToRemove = new ArrayList<>();
private EntityGroup customerGroup;
@ -116,6 +136,9 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
@Autowired
protected WhiteLabelingService whiteLabelingService;
@Autowired
private GroupPermissionService groupPermissionService;
@Before
public void beforeTest() throws Exception {
loginTenantAdmin();
@ -167,6 +190,41 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
removeCreatedUser(user);
}
@Test
public void testSelfRegisterUserCreatesNewGroupPermissions() throws Exception {
EntityGroup userGroup = new EntityGroup();
userGroup.setType(EntityType.USER);
userGroup.setName("Existing permission users");
userGroup = doPost("/api/entityGroup", userGroup, EntityGroup.class);
Role role = new Role();
role.setName("Existing permission role");
role.setType(RoleType.GENERIC);
role = doPost("/api/role", role, Role.class);
GroupPermission existingPermission = new GroupPermission();
existingPermission.setUserGroupId(userGroup.getId());
existingPermission.setRoleId(role.getId());
existingPermission = doPost("/api/groupPermission", existingPermission, GroupPermission.class);
GroupPermission selfRegistrationPermission = new GroupPermission(existingPermission);
createWebSelfRegistrationSettings(List.of(selfRegistrationPermission));
String email = "signup-permissions@thingsboard.org";
doSignUp(createWebSignUpRequest(email));
GroupPermission storedPermission = doGet("/api/groupPermission/" + existingPermission.getUuidId(), GroupPermission.class);
assertThat(storedPermission.getUserGroupId()).isEqualTo(userGroup.getId());
User user = userService.findUserByEmail(tenantId, email);
EntityGroup selfRegistrationGroup = entityGroupService.findEntityGroupByTypeAndName(tenantId, user.getCustomerId(), EntityType.USER,
"Self Registration Users").orElseThrow();
List<GroupPermissionInfo> selfRegistrationPermissions = doGetTyped("/api/userGroup/" + selfRegistrationGroup.getUuidId() + "/groupPermissions",
new TypeReference<>() {});
assertThat(selfRegistrationPermissions).hasSize(1);
assertThat(selfRegistrationPermissions.get(0).getId()).isNotEqualTo(existingPermission.getId());
assertThat(selfRegistrationPermissions.get(0).getRoleId()).isEqualTo(role.getId());
removeCreatedUser(user);
}
@Test
public void testSelfRegisterUserFromMobileApp() throws Exception {
String appSecret = StringUtils.randomAlphanumeric(24);
@ -320,6 +378,223 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
removeCreatedUser(user);
}
@Test
public void testSelfRegisterUserSkipsPermissionForGroupOfOtherTenant() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantGroup = new EntityGroup();
otherTenantGroup.setName("Other Tenant Device Group");
otherTenantGroup.setType(EntityType.DEVICE);
otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
loginTenantAdmin();
Role role = new Role();
role.setName("Self Registration Group Role");
role.setType(RoleType.GROUP);
role.setPermissions(JacksonUtil.toJsonNode("[\"READ\"]"));
role = doPost("/api/role", role, Role.class);
GroupPermission permission = new GroupPermission();
permission.setRoleId(role.getId());
permission.setEntityGroupId(otherTenantGroup.getId());
createWebSelfRegistrationSettings(List.of(permission));
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
assertThat(groupPermissionService.findGroupPermissionByTenantIdAndRoleId(tenantId, role.getId(), new PageLink(10)).getData()).isEmpty();
removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
}
@Test
public void testResendEmailActivationForPendingSignUpUser() throws Exception {
createWebSelfRegistrationSettings();
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
Mockito.clearInvocations(mailService);
doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isOk());
verify(mailService, times(1)).sendActivationEmail(eq(tenantId), anyString(), anyLong(), eq(CUSTOMER_TEST_EMAIL));
removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
}
@Test
public void testResendEmailActivationSendsNothingForUserOfOtherTenant() throws Exception {
createWebSelfRegistrationSettings();
createDifferentTenant();
User otherUser = new User();
otherUser.setAuthority(Authority.TENANT_ADMIN);
otherUser.setTenantId(differentTenantId);
otherUser.setEmail("other.tenant.user@thingsboard.org");
otherUser = doPost("/api/user?sendActivationMail=false", otherUser, User.class);
UserCredentials credentials = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId());
credentials.setPassword("abcdef123");
credentials = userService.saveUserCredentials(differentTenantId, credentials);
Mockito.clearInvocations(mailService);
doPost("/api/noauth/resendEmailActivation?email=" + otherUser.getEmail()).andExpect(status().isBadRequest());
verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString());
UserCredentials credentialsAfter = userService.findUserCredentialsByUserId(differentTenantId, otherUser.getId());
assertThat(credentialsAfter.getActivateToken()).isEqualTo(credentials.getActivateToken());
assertThat(credentialsAfter.getActivateTokenExpTime()).isEqualTo(credentials.getActivateTokenExpTime());
deleteDifferentTenant();
}
@Test
public void testResendEmailActivationSendsNothingForDisabledActivatedUser() throws Exception {
createWebSelfRegistrationSettings();
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL);
UserCredentials credentials = userService.findUserCredentialsByUserId(tenantId, user.getId());
userService.activateUserCredentials(tenantId, credentials.getActivateToken(), credentials.getPassword());
userService.setUserCredentialsEnabled(tenantId, user.getId(), false);
Mockito.clearInvocations(mailService);
doPost("/api/noauth/resendEmailActivation?email=" + CUSTOMER_TEST_EMAIL).andExpect(status().isBadRequest());
verify(mailService, never()).sendActivationEmail(any(), anyString(), anyLong(), anyString());
assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken()).isNull();
removeCreatedUser(user);
}
@Test
public void testActivationEmailLinkUsesConfiguredBaseUrl() throws Exception {
createWebSelfRegistrationSettings();
AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL);
try {
Mockito.clearInvocations(mailService);
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode=");
} finally {
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
}
removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
}
@Test
public void testActivationEmailLinkUsesRequestBaseUrlWhenGeneralBaseUrlIsMissing() throws Exception {
createWebSelfRegistrationSettings();
AdminSettings generalSettings = setGeneralBaseUrl(null);
try {
Mockito.clearInvocations(mailService);
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
assertThat(captureActivationLink()).startsWith("http://localhost:80/api/noauth/activateEmail?emailCode=");
} finally {
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
}
removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
}
@Test
public void testResendActivationEmailLinkUsesConfiguredBaseUrl() throws Exception {
String appSecret = StringUtils.randomAlphanumeric(24);
String mobilePkgName = "my.test.android.app";
createMobileSelfRegistrationSettings(mobilePkgName, appSecret, PlatformType.ANDROID, createDashboard(), createDashboard());
AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL);
try {
doSignUp(createMobileSignUpRequest(CUSTOMER_TEST_EMAIL, mobilePkgName, appSecret, PlatformType.ANDROID));
Mockito.clearInvocations(mailService);
mockMvc.perform(post("/api/noauth/resendEmailActivation")
.param("email", CUSTOMER_TEST_EMAIL)
.param("pkgName", mobilePkgName)
.param("platform", PlatformType.ANDROID.name())
.header("Host", OTHER_HOST))
.andExpect(status().isOk());
assertThat(captureActivationLink()).startsWith(CONFIGURED_BASE_URL + "/api/noauth/activateEmail?emailCode=");
} finally {
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
}
removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
}
@Test
public void testAccountActivatedEmailLinkUsesConfiguredBaseUrl() throws Exception {
createWebSelfRegistrationSettings();
AdminSettings generalSettings = setGeneralBaseUrl(CONFIGURED_BASE_URL);
User user;
try {
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL);
String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken();
Mockito.clearInvocations(mailService);
doPost("/api/noauth/activateByEmailCode?emailCode=" + activateToken).andExpect(status().isOk());
verify(mailService, times(1)).sendAccountActivatedEmail(eq(tenantId), eq(CONFIGURED_BASE_URL + "/login"), eq(CUSTOMER_TEST_EMAIL));
} finally {
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, generalSettings);
}
removeCreatedUser(user);
}
@Test
public void testActivationEmailLinkUsesHttpSchemeForNonHttpForwardedProto() throws Exception {
createWebSelfRegistrationSettings();
Mockito.clearInvocations(mailService);
mockMvc.perform(post("/api/noauth/signup")
.contentType(contentType)
.content(json(createWebSignUpRequest(CUSTOMER_TEST_EMAIL)))
.header("X-Forwarded-Proto", "ftp"))
.andExpect(status().isOk());
URI activationLink = URI.create(captureActivationLink());
assertThat(activationLink.getScheme()).isEqualTo("http");
assertThat(activationLink.getHost()).isEqualTo("localhost");
removeCreatedUser(userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL));
}
@Test
public void testActivationByEmailCodeOnOtherTenantSettingsIsRejected() throws Exception {
createWebSelfRegistrationSettings();
doSignUp(createWebSignUpRequest(CUSTOMER_TEST_EMAIL));
User user = userService.findUserByEmail(tenantId, CUSTOMER_TEST_EMAIL);
String activateToken = userService.findUserCredentialsByUserId(tenantId, user.getId()).getActivateToken();
createDifferentTenant();
createWebSelfRegistrationParams(OTHER_HOST, Collections.emptyList());
mockMvc.perform(post("/api/noauth/activateByEmailCode")
.param("emailCode", activateToken)
.header("Host", OTHER_HOST))
.andExpect(status().isBadRequest());
assertThat(userService.findUserCredentialsByUserId(tenantId, user.getId()).isEnabled()).isFalse();
deleteDifferentTenant();
removeCreatedUser(user);
}
@Test
public void testSaveSelfRegistrationParamsWithDomainOfOtherTenantIsForbidden() throws Exception {
String domainName = "signup-other-tenant.example.com";
Domain savedDomain = doPost("/api/domain", constructDomain(domainName), Domain.class);
loginDifferentTenant();
WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams();
selfRegistrationParams.setTitle("Please sign up");
selfRegistrationParams.setPrivacyPolicy("Privacy policy");
selfRegistrationParams.setTermsOfUse("Terms of use");
selfRegistrationParams.setDomainId(savedDomain.getId());
selfRegistrationParams.setPermissions(Collections.emptyList());
doPost("/api/selfRegistration/selfRegistrationParams", selfRegistrationParams)
.andExpect(status().isForbidden());
assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.SELF_REGISTRATION)).isNull();
assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.PRIVACY_POLICY)).isNull();
assertThat(whiteLabelingService.findWhiteLabelingByDomainAndType(domainName, WhiteLabelingType.TERMS_OF_USE)).isNull();
}
protected SignUpRequest createWebSignUpRequest(String email) {
var signUpRequest = new SignUpRequest();
signUpRequest.setFields(Map.of(SignUpFieldId.EMAIL, email,
@ -388,8 +663,39 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
Assert.assertNull("Expected that created user is deleted but one found!", found);
}
private String captureActivationLink() throws Exception {
ArgumentCaptor<String> activationLink = ArgumentCaptor.forClass(String.class);
verify(mailService, times(1)).sendActivationEmail(eq(tenantId), activationLink.capture(), anyLong(), eq(CUSTOMER_TEST_EMAIL));
return activationLink.getValue();
}
private AdminSettings setGeneralBaseUrl(String baseUrl) {
AdminSettings generalSettings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "general");
AdminSettings updatedSettings = new AdminSettings(generalSettings);
ObjectNode jsonValue = generalSettings.getJsonValue().deepCopy();
if (baseUrl != null) {
jsonValue.put("baseUrl", baseUrl);
} else {
jsonValue.remove("baseUrl");
}
jsonValue.put("prohibitDifferentUrl", true);
updatedSettings.setJsonValue(jsonValue);
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, updatedSettings);
return generalSettings;
}
private void createWebSelfRegistrationSettings() {
Domain domain = constructDomain("localhost");
createWebSelfRegistrationSettings(Collections.emptyList());
}
private void createWebSelfRegistrationSettings(List<GroupPermission> permissions) {
createWebSelfRegistrationParams("localhost", permissions);
createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB);
createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB);
}
private void createWebSelfRegistrationParams(String domainName, List<GroupPermission> permissions) {
Domain domain = constructDomain(domainName);
Domain savedDomain = doPost("/api/domain", domain, Domain.class);
WebSelfRegistrationParams selfRegistrationParams = new WebSelfRegistrationParams();
@ -402,13 +708,10 @@ public class SignUpControllerSqlTest extends AbstractControllerTest {
selfRegistrationParams.setShowPrivacyPolicy(true);
selfRegistrationParams.setDomainId(savedDomain.getId());
selfRegistrationParams.setNotificationRecipient(createNotificationTarget(currentUserId).getId());
selfRegistrationParams.setPermissions(Collections.emptyList());
selfRegistrationParams.setPermissions(permissions);
doPost("/api/selfRegistration/selfRegistrationParams",
selfRegistrationParams, JsonNode.class);
createNotificationTemplate(NotificationType.USER_ACTIVATED, "User activated", "User ${userEmail} was activated", NotificationDeliveryMethod.WEB);
createNotificationTemplate(NotificationType.USER_REGISTERED, "User registered", "User ${userEmail} was registered", NotificationDeliveryMethod.WEB);
}
private void createMobileSelfRegistrationSettings(String mobilePkgName, String appSecret, PlatformType platformType,

166
application/src/test/java/org/thingsboard/server/controller/TbResourceControllerTest.java

@ -22,6 +22,7 @@ import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.Dashboard;
import org.thingsboard.server.common.data.EntityInfo;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.ResourceSubType;
import org.thingsboard.server.common.data.ResourceType;
import org.thingsboard.server.common.data.StringUtils;
import org.thingsboard.server.common.data.TbResource;
@ -32,6 +33,7 @@ import org.thingsboard.server.common.data.audit.ActionType;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.group.EntityGroupInfo;
import org.thingsboard.server.common.data.id.TbResourceId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.lwm2m.LwM2mObject;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
@ -926,6 +928,160 @@ public class TbResourceControllerTest extends AbstractControllerTest {
assertThat(download(savedResource.getId())).asBase64Encoded().isEqualTo(newData);
}
@Test
public void testUpdateResourceInfoKeepsStoredTenant() throws Exception {
TbResourceInfo savedResource = saveJsModule();
TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
resourceInfo.setTenantId(null);
resourceInfo.setTitle("Updated title");
Mockito.reset(tbClusterService, auditLogService);
TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
assertThat(updatedResource.getTenantId()).isEqualTo(savedTenant.getId());
assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
testNotifyEntityAllOneTimeLogEntityActionEntityEqClass(updatedResource, updatedResource.getId(), updatedResource.getId(),
savedTenant.getId(), tenantAdmin.getCustomerId(), tenantAdmin.getId(), tenantAdmin.getEmail(),
ActionType.UPDATED, ActionType.UPDATED);
resourceInfo = findResourceInfo(savedResource.getId());
assertThat(resourceInfo.getTenantId()).isEqualTo(savedTenant.getId());
assertThat(resourceInfo.getTitle()).isEqualTo("Updated title");
resourceInfo.setTenantId(TenantId.SYS_TENANT_ID);
doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId());
loginDifferentTenant();
login(tenantAdmin.getEmail(), "testPassword1");
resourceInfo.setTenantId(savedDifferentTenant.getId());
doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(savedTenant.getId());
deleteDifferentTenant();
}
@Test
public void testUpdateResourceInfoKeepsStoredKeyAndEtag() throws Exception {
TbResourceInfo savedResource = saveJsModule();
TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
resourceInfo.setTitle("Updated title");
resourceInfo.setResourceKey("other-key");
resourceInfo.setEtag("0");
resourceInfo.setCreatedTime(1);
TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey());
assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag());
assertThat(updatedResource.getCreatedTime()).isEqualTo(savedResource.getCreatedTime());
resourceInfo = findResourceInfo(savedResource.getId());
assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey());
assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag());
}
@Test
public void testUpdateResourceInfoRefusesTypeChange() throws Exception {
TbResourceInfo savedResource = saveJsModule();
TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
resourceInfo.setResourceType(ResourceType.GENERAL);
doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("can't be changed")));
resourceInfo = findResourceInfo(savedResource.getId());
resourceInfo.setResourceSubType(ResourceSubType.MODULE);
doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("can't be changed")));
resourceInfo = findResourceInfo(savedResource.getId());
assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE);
assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION);
resourceInfo.setTitle("Updated title");
ObjectNode request = (ObjectNode) JacksonUtil.valueToTree(resourceInfo);
request.putNull("resourceType");
request.putNull("resourceSubType");
TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", request, TbResourceInfo.class);
assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
resourceInfo = findResourceInfo(savedResource.getId());
assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE);
assertThat(resourceInfo.getResourceSubType()).isEqualTo(ResourceSubType.EXTENSION);
}
@Test
public void testSaveResourceWithIdKeepsStoredTypeKeyAndEtag() throws Exception {
TbResourceInfo savedResource = saveJsModule();
TbResource resource = new TbResource(findResourceInfo(savedResource.getId()));
resource.setResourceType(ResourceType.GENERAL);
doPost("/api/resource", resource)
.andExpect(status().isBadRequest())
.andExpect(statusReason(containsString("can't be changed")));
resource.setResourceType(ResourceType.JS_MODULE);
resource.setTitle("Updated title");
resource.setResourceKey("other-key");
resource.setEtag("0");
TbResourceInfo updatedResource = doPost("/api/resource", resource, TbResourceInfo.class);
assertThat(updatedResource.getTitle()).isEqualTo("Updated title");
assertThat(updatedResource.getResourceKey()).isEqualTo(savedResource.getResourceKey());
assertThat(updatedResource.getEtag()).isEqualTo(savedResource.getEtag());
TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
assertThat(resourceInfo.getResourceType()).isEqualTo(ResourceType.JS_MODULE);
assertThat(resourceInfo.getResourceKey()).isEqualTo(savedResource.getResourceKey());
assertThat(resourceInfo.getEtag()).isEqualTo(savedResource.getEtag());
}
@Test
public void testSysAdminUpdateResourceInfoKeepsSystemTenant() throws Exception {
loginSysAdmin();
TbResourceInfo savedResource = saveJsModule();
assertThat(savedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID);
TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
resourceInfo.setTenantId(savedTenant.getId());
TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
assertThat(updatedResource.getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID);
assertThat(findResourceInfo(savedResource.getId()).getTenantId()).isEqualTo(TenantId.SYS_TENANT_ID);
doDelete("/api/resource/" + savedResource.getUuidId()).andExpect(status().isOk());
}
@Test
public void testUpdateResourceInfoKeepsStoredCustomer() throws Exception {
Customer storedCustomer = saveCustomer("Stored resource customer");
Customer otherCustomer = saveCustomer("Other resource customer");
TbResource resource = new TbResource();
resource.setResourceType(ResourceType.JS_MODULE);
resource.setResourceSubType(ResourceSubType.EXTENSION);
resource.setTitle("Js resource");
resource.setFileName(JS_TEST_FILE_NAME);
resource.setEncodedData(TEST_DATA);
resource.setCustomerId(storedCustomer.getId());
TbResourceInfo savedResource = doPost("/api/resource", resource, TbResourceInfo.class);
assertThat(savedResource.getCustomerId()).isEqualTo(storedCustomer.getId());
TbResourceInfo resourceInfo = findResourceInfo(savedResource.getId());
resourceInfo.setCustomerId(otherCustomer.getId());
TbResourceInfo updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId());
resourceInfo.setCustomerId(null);
updatedResource = doPut("/api/resource/" + savedResource.getUuidId() + "/info", resourceInfo, TbResourceInfo.class);
assertThat(updatedResource.getCustomerId()).isEqualTo(storedCustomer.getId());
assertThat(findResourceInfo(savedResource.getId()).getCustomerId()).isEqualTo(storedCustomer.getId());
}
private Customer saveCustomer(String title) throws Exception {
Customer customer = new Customer();
customer.setTitle(title);
return doPost("/api/customer", customer, Customer.class);
}
@Test
public void testGetLwm2mListObjectsPage() throws Exception {
loginTenantAdmin();
@ -1087,6 +1243,16 @@ public class TbResourceControllerTest extends AbstractControllerTest {
return uploadResource(HttpMethod.POST, "/api/resource/upload", tbResource.getFileName(), tbResource.getResourceType().getMediaType(), data, parts);
}
private TbResourceInfo saveJsModule() throws Exception {
TbResource resource = new TbResource();
resource.setResourceType(ResourceType.JS_MODULE);
resource.setResourceSubType(ResourceSubType.EXTENSION);
resource.setTitle("Js resource");
resource.setFileName(JS_TEST_FILE_NAME);
resource.setEncodedData(TEST_DATA);
return save(resource);
}
private TbResourceInfo findResourceInfo(TbResourceId id) throws Exception {
return doGet("/api/resource/info/" + id, TbResourceInfo.class);
}

4
application/src/test/java/org/thingsboard/server/controller/TrendzApiControllerTest.java

@ -2,11 +2,11 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MvcResult;
import org.testcontainers.shaded.com.fasterxml.jackson.core.type.TypeReference;
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.SortOrder;

2
application/src/test/java/org/thingsboard/server/controller/WhiteLabelingControllerTest.java

@ -4,11 +4,11 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.awaitility.Awaitility;
import org.junit.After;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MvcResult;
import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.AdminSettings;
import org.thingsboard.server.common.data.StringUtils;

2
application/src/test/java/org/thingsboard/server/controller/WidgetTypeControllerTest.java

@ -6,11 +6,11 @@ package org.thingsboard.server.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.testcontainers.shaded.org.apache.commons.lang3.RandomStringUtils;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EntityType;

35
application/src/test/java/org/thingsboard/server/edge/CalculatedFieldEdgeTest.java

@ -20,6 +20,7 @@ import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput;
import org.thingsboard.server.common.data.debug.DebugSettings;
import org.thingsboard.server.common.data.id.CalculatedFieldId;
import org.thingsboard.server.common.data.id.EntityId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.gen.edge.v1.CalculatedFieldRequestMsg;
@ -109,6 +110,40 @@ public class CalculatedFieldEdgeTest extends AbstractEdgeTest {
checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName());
}
@Test
public void testSendCalculatedFieldToCloudSavesItUnderEdgeTenant() throws Exception {
Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();
SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config);
calculatedField.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
UUID uuid = Uuids.timeBased();
UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
checkCalculatedFieldOnCloud(uplinkMsg, uuid, calculatedField.getName());
CalculatedField calculatedFieldFromCloud = doGet("/api/calculatedField/" + uuid, CalculatedField.class);
Assert.assertEquals(tenantId, calculatedFieldFromCloud.getTenantId());
}
@Test
public void testSendCalculatedFieldWithOtherTenantReferenceToCloud() throws Exception {
Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();
SimpleCalculatedFieldConfiguration config = new SimpleCalculatedFieldConfiguration();
CalculatedField calculatedField = createSimpleCalculatedField(savedDevice.getId(), config);
config.getArguments().get("T").setRefEntityId(TenantId.fromUUID(UUID.randomUUID()));
UUID uuid = Uuids.timeBased();
UplinkMsg uplinkMsg = getUplinkMsg(uuid, calculatedField, UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
edgeImitator.expectResponsesAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsg);
Assert.assertTrue(edgeImitator.waitForResponses());
Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess());
doGet("/api/calculatedField/" + uuid).andExpect(status().isNotFound());
}
@Test
public void testSendCalculatedFieldRequestToCloud() throws Exception {
Device savedDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();

55
application/src/test/java/org/thingsboard/server/edge/DeviceEdgeTest.java

@ -679,6 +679,61 @@ public class DeviceEdgeTest extends AbstractEdgeTest {
Assert.assertEquals(deviceName + " Updated", device.getName());
}
@Test
public void testSendDeviceToCloudAddsDeviceOnlyToGroupOfEdgeTenant() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantGroup = new EntityGroup();
otherTenantGroup.setType(EntityType.DEVICE);
otherTenantGroup.setName("Other Tenant Device Group");
otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
loginTenantAdmin();
Device deviceMsg = buildDeviceForUplinkMsg("Edge Device In Group", "test");
UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder();
deviceUpdateMsgBuilder.setIdMSB(deviceMsg.getUuidId().getMostSignificantBits());
deviceUpdateMsgBuilder.setIdLSB(deviceMsg.getUuidId().getLeastSignificantBits());
deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits());
deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits());
deviceUpdateMsgBuilder.setEntity(JacksonUtil.toString(deviceMsg));
deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build());
edgeImitator.expectResponsesAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
Assert.assertTrue(edgeImitator.waitForResponses());
Device device = doGet("/api/device/" + deviceMsg.getId().getId(), Device.class);
Assert.assertNotNull(device);
Assert.assertFalse(entityGroupService.isEntityInGroup(differentTenantId, device.getId(), otherTenantGroup.getId()));
}
@Test
public void testDeleteDeviceFromGroupOnCloudKeepsGroupsOfOtherTenant() throws Exception {
loginDifferentTenant();
EntityGroup otherTenantGroup = new EntityGroup();
otherTenantGroup.setType(EntityType.DEVICE);
otherTenantGroup.setName("Other Tenant Device Group");
otherTenantGroup = doPost("/api/entityGroup", otherTenantGroup, EntityGroup.class);
Device otherTenantDevice = saveDevice("Other Tenant Device", "test", otherTenantGroup.getId());
loginTenantAdmin();
UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
DeviceUpdateMsg.Builder deviceUpdateMsgBuilder = DeviceUpdateMsg.newBuilder();
deviceUpdateMsgBuilder.setIdMSB(otherTenantDevice.getUuidId().getMostSignificantBits());
deviceUpdateMsgBuilder.setIdLSB(otherTenantDevice.getUuidId().getLeastSignificantBits());
deviceUpdateMsgBuilder.setEntityGroupIdMSB(otherTenantGroup.getUuidId().getMostSignificantBits());
deviceUpdateMsgBuilder.setEntityGroupIdLSB(otherTenantGroup.getUuidId().getLeastSignificantBits());
deviceUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_DELETED_RPC_MESSAGE);
uplinkMsgBuilder.addDeviceUpdateMsg(deviceUpdateMsgBuilder.build());
edgeImitator.expectResponsesAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
Assert.assertTrue(edgeImitator.waitForResponses());
Assert.assertTrue(entityGroupService.isEntityInGroup(differentTenantId, otherTenantDevice.getId(), otherTenantGroup.getId()));
}
@Test
public void testRpcCall() throws Exception {
Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge();

64
application/src/test/java/org/thingsboard/server/edge/EntityViewEdgeTest.java

@ -18,6 +18,7 @@ import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.EntityGroupId;
import org.thingsboard.server.common.data.id.EntityViewId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.dao.service.DaoSqlTest;
@ -191,6 +192,69 @@ public class EntityViewEdgeTest extends AbstractEdgeTest {
Assert.assertNotEquals(entityViewOnCloudName, entityView.getName());
}
@Test
public void testEntityViewFromEdgeSavedInEdgeTenant() throws Exception {
Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge();
EntityView entityViewMsg = buildEntityViewForUplinkMsg(device, "Edge EntityView 3");
entityViewMsg.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder();
entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits());
entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits());
entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg));
entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_CREATED_RPC_MESSAGE);
uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build());
edgeImitator.expectResponsesAmount(1);
edgeImitator.expectMessageAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
Assert.assertTrue(edgeImitator.waitForResponses());
Assert.assertTrue(edgeImitator.getLatestResponseMsg().getSuccess());
EntityView entityView = doGet("/api/entityView/" + entityViewMsg.getUuidId(), EntityView.class);
Assert.assertEquals(tenantId, entityView.getTenantId());
}
@Test
public void testEntityViewFromEdgeWithIdOfOtherTenantViewNotSaved() throws Exception {
Device edgeDevice = saveDeviceOnCloudAndVerifyDeliveryToEdge();
loginDifferentTenant();
Device otherTenantDevice = new Device();
otherTenantDevice.setName("Other tenant device");
otherTenantDevice.setType("default");
otherTenantDevice = doPost("/api/device", otherTenantDevice, Device.class);
EntityView otherTenantView = saveEntityView("Other tenant EntityView", otherTenantDevice.getId(), null);
loginTenantAdmin();
EntityView entityViewMsg = buildEntityViewForUplinkMsg(edgeDevice, "Edge EntityView 4");
entityViewMsg.setId(otherTenantView.getId());
UplinkMsg.Builder uplinkMsgBuilder = UplinkMsg.newBuilder();
EntityViewUpdateMsg.Builder entityViewUpdateMsgBuilder = EntityViewUpdateMsg.newBuilder();
entityViewUpdateMsgBuilder.setIdMSB(entityViewMsg.getUuidId().getMostSignificantBits());
entityViewUpdateMsgBuilder.setIdLSB(entityViewMsg.getUuidId().getLeastSignificantBits());
entityViewUpdateMsgBuilder.setEntity(JacksonUtil.toString(entityViewMsg));
entityViewUpdateMsgBuilder.setMsgType(UpdateMsgType.ENTITY_UPDATED_RPC_MESSAGE);
uplinkMsgBuilder.addEntityViewUpdateMsg(entityViewUpdateMsgBuilder.build());
edgeImitator.expectResponsesAmount(1);
edgeImitator.sendUplinkMsg(uplinkMsgBuilder.build());
Assert.assertTrue(edgeImitator.waitForResponses());
Assert.assertFalse(edgeImitator.getLatestResponseMsg().getSuccess());
loginDifferentTenant();
EntityView storedView = doGet("/api/entityView/" + otherTenantView.getUuidId(), EntityView.class);
Assert.assertEquals(differentTenantId, storedView.getTenantId());
Assert.assertEquals("Other tenant EntityView", storedView.getName());
Assert.assertEquals(otherTenantDevice.getId(), storedView.getEntityId());
Assert.assertEquals(otherTenantView.getCustomerId(), storedView.getCustomerId());
Assert.assertEquals(otherTenantView.getOwnerId(), storedView.getOwnerId());
loginTenantAdmin();
}
@Test
public void testSendUnassignEntityViewFromGroupOnEdgeToCloud() throws Exception {
Device device = saveDeviceOnCloudAndVerifyDeliveryToEdge();

2
application/src/test/java/org/thingsboard/server/edge/OtaPackageEdgeTest.java

@ -4,12 +4,12 @@
package org.thingsboard.server.edge;
import com.google.protobuf.AbstractMessage;
import org.awaitility.Awaitility;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.EntityType;

45
application/src/test/java/org/thingsboard/server/edge/TelemetryEdgeTest.java

@ -390,4 +390,49 @@ public class TelemetryEdgeTest extends AbstractEdgeTest {
});
}
@Test
public void testSendEntityGroupAttributesAndTelemetryForGroupOfDifferentTenantToCloud() throws Exception {
loginDifferentTenant();
EntityGroup entityGroup = new EntityGroup();
entityGroup.setType(EntityType.DEVICE);
entityGroup.setName("Different Tenant Device Group");
EntityGroup savedEntityGroup = doPost("/api/entityGroup", entityGroup, EntityGroup.class);
loginTenantAdmin();
EntityDataProto entityData = EntityDataProto.newBuilder()
.setEntityIdMSB(savedEntityGroup.getUuidId().getMostSignificantBits())
.setEntityIdLSB(savedEntityGroup.getUuidId().getLeastSignificantBits())
.setEntityType(EntityType.ENTITY_GROUP.name())
.setAttributesUpdatedMsg(TransportProtos.PostAttributeMsg.newBuilder()
.addKv(TransportProtos.KeyValueProto.newBuilder()
.setKey("groupKey")
.setType(TransportProtos.KeyValueType.STRING_V)
.setStringV("groupValue").build())
.build())
.setPostAttributeScope(DataConstants.SERVER_SCOPE)
.setPostTelemetryMsg(TransportProtos.PostTelemetryMsg.newBuilder()
.addTsKvList(TransportProtos.TsKvListProto.newBuilder()
.setTs(System.currentTimeMillis())
.addKv(TransportProtos.KeyValueProto.newBuilder()
.setKey("groupTemperature")
.setType(TransportProtos.KeyValueType.LONG_V)
.setLongV(25).build())
.build())
.build())
.build();
sendUplinkMsgAndWaitForResponse(uplinkMsgBuilder -> uplinkMsgBuilder.addEntityData(entityData));
loginDifferentTenant();
String keysUrl = "/api/plugins/telemetry/ENTITY_GROUP/" + savedEntityGroup.getUuidId() + "/keys/";
Awaitility.await()
.pollDelay(3, TimeUnit.SECONDS)
.atMost(10, TimeUnit.SECONDS)
.untilAsserted(() -> {
List<String> attributeKeys = doGetAsyncTyped(keysUrl + "attributes/" + DataConstants.SERVER_SCOPE, new TypeReference<>() {});
Assert.assertTrue(attributeKeys.isEmpty());
List<String> timeseriesKeys = doGetAsyncTyped(keysUrl + "timeseries", new TypeReference<>() {});
Assert.assertTrue(timeseriesKeys.isEmpty());
});
}
}

2
application/src/test/java/org/thingsboard/server/edge/UserEdgeTest.java

@ -5,11 +5,11 @@ package org.thingsboard.server.edge;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.protobuf.AbstractMessage;
import org.awaitility.Awaitility;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.testcontainers.shaded.org.awaitility.Awaitility;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Customer;
import org.thingsboard.server.common.data.EdgeUtils;

34
application/src/test/java/org/thingsboard/server/install/ThingsboardInstallServiceTest.java

@ -3,6 +3,10 @@
// SPDX-License-Identifier: Apache-2.0 AND BUSL-1.1
package org.thingsboard.server.install;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -11,6 +15,7 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.thingsboard.server.dao.sql.citus.CitusSchemaService;
@ -26,6 +31,7 @@ import org.thingsboard.server.service.install.TsDatabaseSchemaService;
import org.thingsboard.server.service.install.update.CacheCleanupService;
import org.thingsboard.server.service.install.update.DataUpdateService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.doThrow;
@ -189,6 +195,34 @@ class ThingsboardInstallServiceTest {
verify(databaseEntitiesUpgradeService, never()).upgradeDatabase(anyBoolean());
}
@Test
void anErrorDuringAFreshInstallIsReportedAsAnInstallFailure() throws Exception {
ReflectionTestUtils.setField(installService, "isUpgrade", false);
ExceptionInInitializerError error = new ExceptionInInitializerError("Fontconfig head is null");
doThrow(error).when(systemDataLoaderService).loadSystemWidgets();
Logger logger = (Logger) LoggerFactory.getLogger(ThingsboardInstallService.class);
ListAppender<ILoggingEvent> appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
try {
assertThatThrownBy(() -> installService.performInstall())
.isInstanceOf(ThingsboardInstallException.class)
.hasCause(error);
assertThat(appender.list)
.filteredOn(e -> e.getLevel() == Level.ERROR)
.singleElement()
.satisfies(e -> {
assertThat(e.getFormattedMessage()).isEqualTo("Unexpected error during ThingsBoard installation!");
assertThat(e.getThrowableProxy().getClassName()).isEqualTo(ExceptionInInitializerError.class.getName());
assertThat(e.getThrowableProxy().getMessage()).isEqualTo("Fontconfig head is null");
assertThat(e.getThrowableProxy().getStackTraceElementProxyArray()).isNotEmpty();
});
} finally {
logger.detachAppender(appender);
}
}
@Test
void postgresToCitusUpgradeFailsWhenCitusSchemaServiceMissing() {
ReflectionTestUtils.setField(installService, "isUpgrade", true);

5
application/src/test/java/org/thingsboard/server/service/cf/ctx/state/GeofencingValueArgumentEntryTest.java

@ -1,13 +1,14 @@
// 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.cf.ctx.state;
import io.hypersistence.utils.hibernate.type.json.internal.JacksonUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.common.util.geo.PerimeterDefinition;
import org.thingsboard.server.common.data.id.AssetId;
import org.thingsboard.server.common.data.id.EntityId;

17
application/src/test/java/org/thingsboard/server/service/entitiy/EntityServiceTest.java

@ -2105,6 +2105,7 @@ public class EntityServiceTest extends AbstractControllerTest {
entityView.setCustomerId(customerId);
entityView.setName("test");
entityView.setType("default");
entityView.setEntityId(deviceId);
customerEntityIds.add(entityViewService.saveEntityView(entityView).getId());
EntityGroup entityGroup = new EntityGroup();
@ -3876,12 +3877,18 @@ public class EntityServiceTest extends AbstractControllerTest {
@Test
public void testEntityViewEntityMapping() {
Device device = new Device();
device.setTenantId(tenantId);
device.setName("Device for entity view");
device.setType("default");
device = deviceService.saveDevice(device);
EntityView entityView = new EntityView();
entityView.setTenantId(tenantId);
entityView.setCustomerId(customerId);
entityView.setName("test");
entityView.setType("default");
entityView.setEntityId(new DeviceId(UUID.randomUUID()));
entityView.setEntityId(device.getId());
entityView.setKeys(new TelemetryEntityView(List.of("test"), null));
entityView.setStartTimeMs(124);
entityView.setEndTimeMs(256);
@ -3913,12 +3920,18 @@ public class EntityServiceTest extends AbstractControllerTest {
@Test
public void testFindEntitiesWithEntityViewFilter() {
Device device = new Device();
device.setTenantId(tenantId);
device.setName("Device for entity view");
device.setType("default");
device = deviceService.saveDevice(device);
EntityView entityView = new EntityView();
entityView.setTenantId(tenantId);
entityView.setCustomerId(customerId);
entityView.setName("test");
entityView.setType("default");
entityView.setEntityId(new DeviceId(UUID.randomUUID()));
entityView.setEntityId(device.getId());
entityView.setKeys(new TelemetryEntityView(List.of("test"), null));
entityView.setStartTimeMs(124);
entityView.setEndTimeMs(256);

35
application/src/test/java/org/thingsboard/server/service/install/update/EntityViewGroupAllUpdaterTest.java

@ -0,0 +1,35 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.install.update;
import org.junit.jupiter.api.Test;
import org.thingsboard.server.common.data.EntityView;
import org.thingsboard.server.common.data.group.EntityGroup;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.dao.customer.CustomerService;
import org.thingsboard.server.dao.entityview.EntityViewService;
import org.thingsboard.server.dao.group.EntityGroupService;
import java.util.UUID;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
class EntityViewGroupAllUpdaterTest {
@Test
void testUnassignFromCustomerSavesWithoutValidation() {
EntityViewService entityViewService = mock(EntityViewService.class);
EntityViewGroupAllUpdater updater = new EntityViewGroupAllUpdater(entityViewService, mock(CustomerService.class),
mock(EntityGroupService.class), new EntityGroup(), true);
EntityView entityView = new EntityView();
entityView.setCustomerId(new CustomerId(UUID.randomUUID()));
updater.unassignFromCustomer(entityView);
verify(entityViewService).saveEntityView(entityView, false);
assertThat(entityView.getCustomerId().isNullUid()).isTrue();
}
}

377
application/src/test/java/org/thingsboard/server/service/iot_hub/DefaultIotHubServiceTest.java

@ -21,6 +21,21 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.LoggerFactory;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.cf.CalculatedField;
import org.thingsboard.server.common.data.cf.CalculatedFieldType;
import org.thingsboard.server.common.data.cf.configuration.AlarmCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.Argument;
import org.thingsboard.server.common.data.cf.configuration.ArgumentType;
import org.thingsboard.server.common.data.cf.configuration.ArgumentsBasedCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.CalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.ReferencedEntityKey;
import org.thingsboard.server.common.data.cf.configuration.SimpleCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.TimeSeriesOutput;
import org.thingsboard.server.common.data.cf.configuration.geofencing.EntityCoordinates;
import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingCalculatedFieldConfiguration;
import org.thingsboard.server.common.data.cf.configuration.geofencing.GeofencingReportStrategy;
import org.thingsboard.server.common.data.cf.configuration.geofencing.ZoneGroupConfiguration;
import org.thingsboard.server.common.data.id.CalculatedFieldId;
import org.thingsboard.server.common.data.id.DashboardId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.DeviceProfileId;
@ -32,6 +47,8 @@ import org.thingsboard.server.common.data.rule.RuleChain;
import org.thingsboard.server.exception.DataValidationException;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.integration.Integration;
import org.thingsboard.server.common.data.iot_hub.AlarmRuleInstalledItemDescriptor;
import org.thingsboard.server.common.data.iot_hub.CalculatedFieldInstalledItemDescriptor;
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.RuleChainInstalledItemDescriptor;
@ -40,6 +57,7 @@ import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.converter.Converter;
import org.thingsboard.server.common.data.id.ConverterId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.dao.cf.CalculatedFieldService;
import org.thingsboard.server.dao.dashboard.DashboardService;
import org.thingsboard.server.dao.converter.ConverterService;
import org.thingsboard.server.dao.device.DeviceProfileService;
@ -47,6 +65,7 @@ import org.thingsboard.server.dao.device.DeviceService;
import org.thingsboard.server.dao.entity.EntityService;
import org.thingsboard.server.dao.integration.IntegrationService;
import org.thingsboard.server.dao.iot_hub.IotHubInstalledItemService;
import org.thingsboard.server.service.entitiy.cf.TbCalculatedFieldService;
import org.thingsboard.server.dao.rule.RuleChainService;
import org.thingsboard.server.service.entitiy.dashboard.TbDashboardService;
import org.thingsboard.server.service.entitiy.converter.TbConverterService;
@ -55,6 +74,7 @@ import org.thingsboard.server.service.entitiy.device.profile.TbDeviceProfileServ
import org.thingsboard.server.service.rule.TbRuleChainService;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@ -87,6 +107,10 @@ class DefaultIotHubServiceTest {
@Mock
private IotHubInstalledItemService iotHubInstalledItemService;
@Mock
private TbCalculatedFieldService tbCalculatedFieldService;
@Mock
private CalculatedFieldService calculatedFieldService;
@Mock
private DeviceService deviceService;
@Mock
private EntityService entityService;
@ -107,6 +131,8 @@ class DefaultIotHubServiceTest {
@Mock
private TbConverterService tbConverterService;
@Mock
private DevicePackageEntities devicePackageEntities;
@Mock
private RuleChainService ruleChainService;
@Mock
private TbRuleChainService tbRuleChainService;
@ -474,6 +500,151 @@ class DefaultIotHubServiceTest {
assertThat(result.getErrorMessage()).contains("install failed");
}
@Test
void doInstallVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception {
mockTenant();
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "1.0"));
when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData());
when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0));
when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1));
service.doInstallVersion(user, versionId, null, null);
ArgumentCaptor<CalculatedField> captor = ArgumentCaptor.forClass(CalculatedField.class);
verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
}
@Test
void updateItemVersion_calculatedField_mapsTenantReferencesToInstallingTenant() throws Exception {
mockTenant();
String versionId = UUID.randomUUID().toString();
CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID());
CalculatedFieldInstalledItemDescriptor descriptor = new CalculatedFieldInstalledItemDescriptor();
descriptor.setCalculatedFieldId(calculatedFieldId);
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("CALCULATED_FIELD");
item.setItemVersionId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(anyString()))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "CF", "2.0"));
when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(calculatedFieldFileData());
CalculatedField existing = new CalculatedField(calculatedFieldId);
existing.setTenantId(tenantId);
when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing);
UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null);
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<CalculatedField> captor = ArgumentCaptor.forClass(CalculatedField.class);
verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
}
@Test
void doInstallVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception {
mockTenant();
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "1.0"));
when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData());
when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0));
when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1));
service.doInstallVersion(user, versionId, null, null);
ArgumentCaptor<CalculatedField> captor = ArgumentCaptor.forClass(CalculatedField.class);
verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
}
@Test
void updateItemVersion_alarmRule_mapsTenantReferencesToInstallingTenant() throws Exception {
mockTenant();
String versionId = UUID.randomUUID().toString();
CalculatedFieldId calculatedFieldId = new CalculatedFieldId(UUID.randomUUID());
AlarmRuleInstalledItemDescriptor descriptor = new AlarmRuleInstalledItemDescriptor();
descriptor.setCalculatedFieldId(calculatedFieldId);
IotHubInstalledItem item = installedItem(UUID.randomUUID());
item.setItemType("ALARM_RULE");
item.setItemVersionId(UUID.randomUUID());
item.setDescriptor(descriptor);
when(iotHubInstalledItemService.findById(tenantId, item.getId())).thenReturn(item);
when(iotHubRestClient.getVersionInfo(anyString()))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "ALARM_RULE", "Alarm", "2.0"));
when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(alarmRuleFileData());
CalculatedField existing = new CalculatedField(calculatedFieldId);
existing.setTenantId(tenantId);
when(calculatedFieldService.findById(tenantId, calculatedFieldId)).thenReturn(existing);
UpdateItemVersionResult result = service.updateItemVersion(user, item.getId(), versionId, true, null);
assertThat(result.isSuccess()).isTrue();
ArgumentCaptor<CalculatedField> captor = ArgumentCaptor.forClass(CalculatedField.class);
verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
assertThat(((ArgumentsBasedCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getArguments().get("T").getRefEntityId()).isEqualTo(tenantId);
}
@Test
void doInstallVersion_geofencingCalculatedField_mapsZoneGroupTenantReferencesToInstallingTenant() throws Exception {
mockTenant();
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "CALCULATED_FIELD", "Geofencing", "1.0"));
when(iotHubRestClient.getVersionFileData(versionId)).thenReturn(geofencingFileData());
when(tbCalculatedFieldService.save(any(), eq(user))).thenAnswer(invocation -> invocation.getArgument(0));
when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(invocation -> invocation.getArgument(1));
service.doInstallVersion(user, versionId, null, null);
ArgumentCaptor<CalculatedField> captor = ArgumentCaptor.forClass(CalculatedField.class);
verify(tbCalculatedFieldService).save(captor.capture(), eq(user));
assertThat(((GeofencingCalculatedFieldConfiguration) captor.getValue().getConfiguration()).getZoneGroups().get("zones").getRefEntityId()).isEqualTo(tenantId);
}
private byte[] calculatedFieldFileData() {
SimpleCalculatedFieldConfiguration configuration = new SimpleCalculatedFieldConfiguration();
configuration.setArguments(Map.of("T", otherTenantArgument()));
configuration.setExpression("T");
return fileData(CalculatedFieldType.SIMPLE, configuration);
}
private byte[] alarmRuleFileData() {
AlarmCalculatedFieldConfiguration configuration = new AlarmCalculatedFieldConfiguration();
configuration.setArguments(Map.of("T", otherTenantArgument()));
configuration.setCreateRules(Map.of());
return fileData(CalculatedFieldType.ALARM, configuration);
}
private byte[] geofencingFileData() {
ZoneGroupConfiguration zoneGroup = new ZoneGroupConfiguration("perimeter", GeofencingReportStrategy.REPORT_PRESENCE_STATUS_ONLY, false);
zoneGroup.setRefEntityId(TenantId.fromUUID(UUID.randomUUID()));
GeofencingCalculatedFieldConfiguration configuration = new GeofencingCalculatedFieldConfiguration();
configuration.setEntityCoordinates(new EntityCoordinates("latitude", "longitude"));
configuration.setZoneGroups(Map.of("zones", zoneGroup));
configuration.setOutput(new TimeSeriesOutput());
return fileData(CalculatedFieldType.GEOFENCING, configuration);
}
private Argument otherTenantArgument() {
Argument argument = new Argument();
argument.setRefEntityId(TenantId.fromUUID(UUID.randomUUID()));
argument.setRefEntityKey(new ReferencedEntityKey("temperature", ArgumentType.TS_LATEST, null));
return argument;
}
private byte[] fileData(CalculatedFieldType type, CalculatedFieldConfiguration configuration) {
CalculatedField calculatedField = new CalculatedField();
calculatedField.setEntityId(new DeviceId(UUID.randomUUID()));
calculatedField.setType(type);
calculatedField.setName("CF");
calculatedField.setConfiguration(configuration);
return JacksonUtil.toString(calculatedField).getBytes(StandardCharsets.UTF_8);
}
@Test
void deleteInstalledItem_devicePackage_removesEachEntityBeforeWhatItRefersTo() throws Exception {
mockTenant();
@ -482,6 +653,9 @@ class DefaultIotHubServiceTest {
profile.setDefaultDashboardId(dashboard.getId());
Integration integration = new Integration(new IntegrationId(UUID.randomUUID()));
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
profile.setTenantId(tenantId);
dashboard.setTenantId(tenantId);
integration.setTenantId(tenantId);
converter.setTenantId(tenantId);
// The profile and the integration listed first: in reverse order of creation, the dashboard would go before the
// profile that refers to it, and the converter before the integration that uses it.
@ -516,6 +690,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted, other), 1, 2, false));
Device device = new Device(deviceId);
device.setTenantId(tenantId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
@ -661,6 +836,12 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked, first, second, unrelated), 1, 4, false));
DeviceProfile sharedProfile = new DeviceProfile(sharedProfileId);
sharedProfile.setTenantId(tenantId);
when(deviceProfileService.findDeviceProfileById(tenantId, sharedProfileId)).thenReturn(sharedProfile);
Dashboard sharedDashboard = new Dashboard(sharedDashboardId);
sharedDashboard.setTenantId(tenantId);
when(dashboardService.findDashboardById(tenantId, sharedDashboardId)).thenReturn(sharedDashboard);
when(entityService.fetchEntityName(tenantId, sharedProfileId)).thenReturn(Optional.of("Shared profile"));
when(entityService.fetchEntityName(tenantId, sharedDashboardId)).thenReturn(Optional.of("Shared dashboard"));
@ -683,6 +864,7 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
Device device = new Device(deviceId);
device.setTenantId(tenantId);
when(deviceService.findDeviceById(tenantId, deviceId)).thenReturn(device);
service.deleteInstalledItem(user, deleted.getId());
@ -700,6 +882,9 @@ class DefaultIotHubServiceTest {
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked), 1, 1, false));
Dashboard usersDashboard = new Dashboard(usersDashboardId);
usersDashboard.setTenantId(tenantId);
when(dashboardService.findDashboardById(tenantId, usersDashboardId)).thenReturn(usersDashboard);
when(entityService.fetchEntityName(tenantId, usersDashboardId)).thenReturn(Optional.of("My dashboard"));
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
@ -810,8 +995,13 @@ class DefaultIotHubServiceTest {
@Test
void findKeptEntities_devicePackage_namesTheProfileDevicesUseAndWhatItRefersTo_apartFromTheShared() {
DeviceProfile profile = new DeviceProfile(new DeviceProfileId(UUID.randomUUID()));
RuleChainId ruleChainId = new RuleChainId(UUID.randomUUID());
DashboardId dashboardId = new DashboardId(UUID.randomUUID());
profile.setTenantId(tenantId);
RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID()));
ruleChain.setTenantId(tenantId);
RuleChainId ruleChainId = ruleChain.getId();
Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
dashboard.setTenantId(tenantId);
DashboardId dashboardId = dashboard.getId();
profile.setDefaultRuleChainId(ruleChainId);
profile.setDefaultDashboardId(dashboardId);
// The user's, not the package's: not listed
@ -827,6 +1017,8 @@ class DefaultIotHubServiceTest {
.thenReturn(new PageData<>(List.of(), 3, 3, true));
when(deviceService.findDeviceById(tenantId, packageDevice.getId())).thenReturn(packageDevice);
when(deviceProfileService.findDeviceProfileById(tenantId, profile.getId())).thenReturn(profile);
when(ruleChainService.findRuleChainById(tenantId, ruleChainId)).thenReturn(ruleChain);
when(dashboardService.findDashboardById(tenantId, dashboardId)).thenReturn(dashboard);
when(entityService.fetchEntityName(tenantId, profile.getId())).thenReturn(Optional.of("smartico-l2-lr"));
when(entityService.fetchEntityName(tenantId, ruleChainId)).thenReturn(Optional.of("Smartico L2-LR"));
when(entityService.fetchEntityName(tenantId, dashboardId)).thenReturn(Optional.of("Smartico L2-LR Fleet"));
@ -950,6 +1142,7 @@ class DefaultIotHubServiceTest {
private List<ILoggingEvent> deleteRuleChainFailingWith(Exception failure) throws Exception {
mockTenant();
RuleChain ruleChain = new RuleChain(new RuleChainId(UUID.randomUUID()));
ruleChain.setTenantId(tenantId);
IotHubInstalledItem deleted = devicePackage(ruleChain.getId());
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
@ -986,4 +1179,184 @@ class DefaultIotHubServiceTest {
return item;
}
private Dashboard dashboard(TenantId owner) {
Dashboard dashboard = new Dashboard(new DashboardId(UUID.randomUUID()));
dashboard.setTenantId(owner);
return dashboard;
}
private Device device(TenantId owner) {
Device device = new Device(new DeviceId(UUID.randomUUID()));
device.setTenantId(owner);
return device;
}
private DeviceInstalledItemDescriptor devicePackageDescriptor(EntityId... createdEntityIds) {
DeviceInstalledItemDescriptor descriptor = new DeviceInstalledItemDescriptor();
descriptor.setCreatedEntityIds(List.of(createdEntityIds));
return descriptor;
}
@Test
void registerDeviceInstall_unknownEntity_rejectedAndNotSaved() {
mockTenant();
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
Device knownDevice = device(tenantId);
Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard);
InstallItemVersionResult result = service.registerDeviceInstall(user, versionId,
devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId()));
assertThat(result.isSuccess()).isFalse();
verify(iotHubInstalledItemService, never()).save(any(), any());
verify(tbDeviceService, never()).delete(any(Device.class), any());
verify(tbDashboardService, never()).delete(any(Dashboard.class), any());
}
@Test
void registerDeviceInstall_unknownDashboardId_rejectedAndNotSaved() {
mockTenant();
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard);
DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor();
descriptor.setDashboardId(unknownDashboard.getId());
InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor);
assertThat(result.isSuccess()).isFalse();
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void registerDeviceInstall_knownEntities_saved() {
mockTenant();
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
Device knownDevice = device(tenantId);
Dashboard knownDashboard = dashboard(tenantId);
when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
when(dashboardService.findDashboardById(tenantId, knownDashboard.getId())).thenReturn(knownDashboard);
DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId(), knownDashboard.getId());
descriptor.setDashboardId(knownDashboard.getId());
when(iotHubInstalledItemService.save(eq(tenantId), any())).thenAnswer(inv -> inv.getArgument(1));
InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor);
assertThat(result.isSuccess()).isTrue();
verify(iotHubInstalledItemService).save(eq(tenantId), any(IotHubInstalledItem.class));
}
@Test
void deleteInstalledItem_devicePackage_skipsEntityNotFound() throws Exception {
mockTenant();
Device knownDevice = device(tenantId);
Dashboard unknownDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
when(dashboardService.findDashboardById(tenantId, unknownDashboard.getId())).thenReturn(unknownDashboard);
UUID id = UUID.randomUUID();
IotHubInstalledItem item = installedItem(id);
item.setDescriptor(devicePackageDescriptor(knownDevice.getId(), unknownDashboard.getId()));
when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(item), 1, 1, false));
service.deleteInstalledItem(user, new IotHubInstalledItemId(id));
verify(tbDeviceService).delete(knownDevice, user);
verify(tbDashboardService, never()).delete(any(Dashboard.class), any());
verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id));
}
@Test
void deleteInstalledItem_devicePackage_deletesItsIntegrationAndConverter() throws Exception {
mockTenant();
Integration integration = new Integration(new IntegrationId(UUID.randomUUID()));
integration.setTenantId(tenantId);
Converter converter = new Converter(new ConverterId(UUID.randomUUID()));
converter.setTenantId(tenantId);
Integration unknownIntegration = new Integration(new IntegrationId(UUID.randomUUID()));
unknownIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
when(integrationService.findIntegrationById(tenantId, integration.getId())).thenReturn(integration);
when(integrationService.findIntegrationById(tenantId, unknownIntegration.getId())).thenReturn(unknownIntegration);
when(converterService.findConverterById(tenantId, converter.getId())).thenReturn(converter);
UUID id = UUID.randomUUID();
IotHubInstalledItem item = installedItem(id);
item.setDescriptor(devicePackageDescriptor(converter.getId(), integration.getId(), unknownIntegration.getId()));
when(iotHubInstalledItemService.findById(tenantId, new IotHubInstalledItemId(id))).thenReturn(item);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(item), 1, 1, false));
service.deleteInstalledItem(user, new IotHubInstalledItemId(id));
verify(integrationService).deleteIntegration(tenantId, integration.getId());
verify(integrationService, never()).deleteIntegration(tenantId, unknownIntegration.getId());
verify(tbConverterService).delete(converter, user);
verify(iotHubInstalledItemService).deleteById(tenantId, new IotHubInstalledItemId(id));
}
@Test
void registerDeviceInstall_usedExistingEntityOfAnotherTenant_rejectedAndNotSaved() {
mockTenant();
String versionId = UUID.randomUUID().toString();
when(iotHubRestClient.getVersionInfo(versionId))
.thenReturn(version(versionId, UUID.randomUUID().toString(), "DEVICE", "Pkg", "1.0"));
Device knownDevice = device(tenantId);
when(deviceService.findDeviceById(tenantId, knownDevice.getId())).thenReturn(knownDevice);
Dashboard otherTenantDashboard = dashboard(TenantId.fromUUID(UUID.randomUUID()));
when(dashboardService.findDashboardById(tenantId, otherTenantDashboard.getId())).thenReturn(otherTenantDashboard);
DeviceInstalledItemDescriptor descriptor = devicePackageDescriptor(knownDevice.getId());
descriptor.setUsedExistingEntityIds(List.of(otherTenantDashboard.getId()));
InstallItemVersionResult result = service.registerDeviceInstall(user, versionId, descriptor);
assertThat(result.isSuccess()).isFalse();
verify(iotHubInstalledItemService, never()).save(any(), any());
}
@Test
void deleteInstalledItem_devicePackage_leavesTheIntegrationOfAnotherTenantAsItIs() {
mockTenant();
IntegrationId integrationId = new IntegrationId(UUID.randomUUID());
IotHubInstalledItem deleted = devicePackage(integrationId);
setIntegrationState(deleted, integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
((DeviceInstalledItemDescriptor) deleted.getDescriptor()).setUsedExistingEntityIds(List.of(integrationId));
when(iotHubInstalledItemService.findById(tenantId, deleted.getId())).thenReturn(deleted);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(deleted), 1, 1, false));
Integration otherTenantIntegration = integration(integrationId, Map.of("profile.milesight-iot-am308", "am308-custom"));
otherTenantIntegration.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
when(integrationService.findIntegrationById(tenantId, integrationId)).thenReturn(otherTenantIntegration);
service.deleteInstalledItem(user, deleted.getId());
verify(integrationService, never()).saveIntegration(any());
verify(integrationService, never()).deleteIntegration(any(), any());
}
@Test
void findKeptEntities_devicePackage_namesNoEntityOfAnotherTenant() {
DashboardId otherTenantDashboardId = new DashboardId(UUID.randomUUID());
IotHubInstalledItem checked = devicePackage(new DeviceId(UUID.randomUUID()), otherTenantDashboardId);
((DeviceInstalledItemDescriptor) checked.getDescriptor()).setUsedExistingEntityIds(List.of(otherTenantDashboardId));
when(iotHubInstalledItemService.findById(tenantId, checked.getId())).thenReturn(checked);
when(iotHubInstalledItemService.findByTenantId(eq(tenantId), eq(List.of("DEVICE")), isNull(), any()))
.thenReturn(new PageData<>(List.of(checked), 1, 1, false));
Dashboard otherTenantDashboard = new Dashboard(otherTenantDashboardId);
otherTenantDashboard.setTenantId(TenantId.fromUUID(UUID.randomUUID()));
when(dashboardService.findDashboardById(tenantId, otherTenantDashboardId)).thenReturn(otherTenantDashboard);
InstalledItemKeptEntities kept = service.findKeptEntities(tenantId, checked.getId());
assertThat(kept.getEntities()).containsExactly(new InstalledItemKeptEntities.KeptEntity(otherTenantDashboardId, null));
verify(entityService, never()).fetchEntityName(any(), any());
}
}

16
application/src/test/java/org/thingsboard/server/service/mail/TbMailSenderTest.java

@ -21,6 +21,7 @@ import java.util.Properties;
import java.util.UUID;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
@ -63,6 +64,21 @@ public class TbMailSenderTest {
verify(tbMailSender, times(1)).testConnectionSuper();
}
@Test
public void testServerIdentityCheckIsDisabled() {
var json = JacksonUtil.newObjectNode();
json.put("smtpProtocol", "smtps");
json.put("smtpHost", "10.0.0.1");
json.put("smtpPort", "465");
json.put("timeout", "10000");
json.put("username", "");
json.put("enableTls", true);
TbMailSender sender = new TbMailSender(null, TenantId.SYS_TENANT_ID, json);
assertEquals("false", sender.getJavaMailProperties().getProperty("mail.smtps.ssl.checkserveridentity"));
}
@Test
public void testGiveMailTenantSettings_noFallbackToSystem() {
var json = JacksonUtil.newObjectNode();

36
application/src/test/java/org/thingsboard/server/service/notification/NotificationApiTest.java

@ -1123,6 +1123,42 @@ public class NotificationApiTest extends AbstractNotificationApiTest {
assertThat(getAvailableDeliveryMethods()).doesNotContain(NotificationDeliveryMethod.MOBILE_APP);
}
@Test
public void testNotificationRequest_templateOfOtherTenant_returnsBadRequest() throws Exception {
loginDifferentTenant();
NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB);
loginTenantAdmin();
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
long requestsCount = findNotificationRequests().getTotalElements();
NotificationRequest notificationRequest = NotificationRequest.builder()
.targets(List.of(target.getUuidId()))
.templateId(otherTemplate.getId())
.additionalConfig(new NotificationRequestConfig())
.build();
doPost("/api/notification/request", notificationRequest).andExpect(status().isBadRequest());
assertThat(findNotificationRequests().getTotalElements()).isEqualTo(requestsCount);
}
@Test
public void testNotificationRequest_systemTemplate_isDelivered() throws Exception {
loginSysAdmin();
NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.GENERAL, "Subject", "Text", NotificationDeliveryMethod.WEB);
loginTenantAdmin();
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
NotificationRequest notificationRequest = NotificationRequest.builder()
.tenantId(tenantId)
.templateId(systemTemplate.getId())
.originatorEntityId(tenantAdminUserId)
.targets(List.of(target.getUuidId()))
.build();
NotificationRequestStats stats = submitNotificationRequestAndWait(notificationRequest);
assertThat(stats.getErrors()).isEmpty();
assertThat(stats.getSent().get(NotificationDeliveryMethod.WEB).get()).isOne();
}
private NotificationRequestStats submitNotificationRequestAndWait(NotificationRequest notificationRequest) throws Exception {
SettableFuture<NotificationRequestStats> future = SettableFuture.create();
notificationCenter.processNotificationRequest(notificationRequest.getTenantId(), notificationRequest, new FutureCallback<>() {

131
application/src/test/java/org/thingsboard/server/service/notification/NotificationRuleApiTest.java

@ -46,6 +46,7 @@ import org.thingsboard.server.common.data.device.data.DeviceData;
import org.thingsboard.server.common.data.edge.Edge;
import org.thingsboard.server.common.data.id.AlarmId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.NotificationTemplateId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.limit.LimitedApi;
import org.thingsboard.server.common.data.notification.Notification;
@ -899,6 +900,136 @@ public class NotificationRuleApiTest extends AbstractNotificationApiTest {
});
}
@Test
public void testSaveNotificationRule_templateOfOtherTenant_returnsBadRequest() throws Exception {
loginDifferentTenant();
NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB);
loginTenantAdmin();
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId()));
doPost("/api/notification/rule", rule).andExpect(status().isBadRequest());
assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName());
}
@Test
public void testSaveNotificationRule_targetOfOtherTenant_returnsForbidden() throws Exception {
loginDifferentTenant();
NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId());
loginTenantAdmin();
NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB);
NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(otherTarget.getUuidId()));
doPost("/api/notification/rule", rule).andExpect(status().isForbidden());
NotificationTemplate alarmTemplate = createNotificationTemplate(NotificationType.ALARM, "Alarm", "Alarm", NotificationDeliveryMethod.WEB);
NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId);
NotificationRule alarmRule = new NotificationRule();
alarmRule.setName("Alarm rule " + UUID.randomUUID());
alarmRule.setEnabled(true);
alarmRule.setTemplateId(alarmTemplate.getId());
alarmRule.setTriggerType(NotificationRuleTriggerType.ALARM);
AlarmNotificationRuleTriggerConfig triggerConfig = new AlarmNotificationRuleTriggerConfig();
triggerConfig.setNotifyOn(Set.of(AlarmAction.CREATED));
alarmRule.setTriggerConfig(triggerConfig);
EscalatedNotificationRuleRecipientsConfig recipientsConfig = new EscalatedNotificationRuleRecipientsConfig();
recipientsConfig.setEscalationTable(Map.of(
0, List.of(ownTarget.getUuidId()),
60, List.of(otherTarget.getUuidId())
));
alarmRule.setRecipientsConfig(recipientsConfig);
doPost("/api/notification/rule", alarmRule).andExpect(status().isForbidden());
assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName)
.doesNotContain(rule.getName(), alarmRule.getName());
}
@Test
public void testSaveNotificationRule_systemTemplate_isSaved() throws Exception {
loginSysAdmin();
NotificationTemplate systemTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB);
loginTenantAdmin();
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
NotificationRule rule = saveNotificationRule(newDeviceCreatedRule(systemTemplate.getId(), List.of(target.getUuidId())));
try {
assertThat(rule.getId()).isNotNull();
assertThat(rule.getTemplateId()).isEqualTo(systemTemplate.getId());
} finally {
// the rule references a system template, which afterEach deletes before the tenant
notificationRuleService.deleteNotificationRuleById(tenantId, rule.getId());
}
}
@Test
public void testSaveNotificationRule_nonExistentTarget_returnsNotFound() throws Exception {
NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Created", "Created", NotificationDeliveryMethod.WEB);
NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(UUID.randomUUID()));
doPost("/api/notification/rule", rule).andExpect(status().isNotFound());
assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName());
}
@Test
public void testRuleProcessing_deliversOnlyToTargetsOfRuleTenant() throws Exception {
loginDifferentTenant();
NotificationTarget otherTarget = createNotificationTarget(savedDifferentTenantUser.getId());
loginTenantAdmin();
NotificationTemplate template = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB);
NotificationTarget ownTarget = createNotificationTarget(tenantAdminUserId);
NotificationRule rule = newDeviceCreatedRule(template.getId(), List.of(ownTarget.getUuidId(), otherTarget.getUuidId()));
rule.setTenantId(tenantId);
notificationRuleService.saveNotificationRule(tenantId, rule);
notificationRulesCache.evict(tenantId);
createDevice("Device 1", "default", "111");
await().atMost(TIMEOUT, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).contains("Device created"));
loginDifferentTenant();
await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created"));
}
@Test
public void testRuleProcessing_templateOfOtherTenant_deliversNothing() throws Exception {
loginDifferentTenant();
NotificationTemplate otherTemplate = createNotificationTemplate(NotificationType.ENTITY_ACTION, "Device created", "Device created", NotificationDeliveryMethod.WEB);
loginTenantAdmin();
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
NotificationRule rule = newDeviceCreatedRule(otherTemplate.getId(), List.of(target.getUuidId()));
rule.setTenantId(tenantId);
notificationRuleService.saveNotificationRule(tenantId, rule);
notificationRulesCache.evict(tenantId);
createDevice("Device 1", "default", "111");
await().during(3, TimeUnit.SECONDS).atMost(5, TimeUnit.SECONDS)
.untilAsserted(() -> assertThat(getMyNotifications(false, 100)).extracting(Notification::getSubject).doesNotContain("Device created"));
}
private NotificationRule newDeviceCreatedRule(NotificationTemplateId templateId, List<UUID> targets) {
EntityActionNotificationRuleTriggerConfig triggerConfig = new EntityActionNotificationRuleTriggerConfig();
triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE));
triggerConfig.setCreated(true);
NotificationRule rule = new NotificationRule();
rule.setName("Device created " + UUID.randomUUID());
rule.setEnabled(true);
rule.setTemplateId(templateId);
rule.setTriggerType(NotificationRuleTriggerType.ENTITY_ACTION);
rule.setTriggerConfig(triggerConfig);
DefaultNotificationRuleRecipientsConfig recipientsConfig = DefaultNotificationRuleRecipientsConfig.forTriggerType(NotificationRuleTriggerType.ENTITY_ACTION);
recipientsConfig.setTargets(targets);
rule.setRecipientsConfig(recipientsConfig);
return rule;
}
private <R> R checkNotificationAfter(Callable<R> action, BiConsumer<Notification, R> check) throws Exception {
if (getWsClient().getLastDataUpdate() == null) {
getWsClient().subscribeForUnreadNotifications(10).waitForReply(true);

95
application/src/test/java/org/thingsboard/server/service/notification/NotificationTemplateApiTest.java

@ -9,9 +9,18 @@ import org.junit.Before;
import org.junit.Test;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.thingsboard.server.common.data.EntityType;
import org.thingsboard.server.common.data.id.IdBased;
import org.thingsboard.server.common.data.id.UserId;
import org.thingsboard.server.common.data.notification.NotificationDeliveryMethod;
import org.thingsboard.server.common.data.notification.NotificationRequest;
import org.thingsboard.server.common.data.notification.NotificationRequestConfig;
import org.thingsboard.server.common.data.notification.NotificationType;
import org.thingsboard.server.common.data.notification.rule.DefaultNotificationRuleRecipientsConfig;
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.trigger.config.EntityActionNotificationRuleTriggerConfig;
import org.thingsboard.server.common.data.notification.targets.NotificationTarget;
import org.thingsboard.server.common.data.notification.template.EmailDeliveryMethodNotificationTemplate;
import org.thingsboard.server.common.data.notification.template.NotificationTemplate;
import org.thingsboard.server.common.data.notification.template.NotificationTemplateConfig;
@ -21,6 +30,7 @@ import org.thingsboard.server.dao.service.DaoSqlTest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@ -86,6 +96,91 @@ public class NotificationTemplateApiTest extends AbstractNotificationApiTest {
.containsOnly(generalNotificationTemplate.getId(), alarmNotificationTemplate.getId(), entityActionNotificationTemplate.getId());
}
@Test
public void testSaveTemplateWithReportRequiresPermissionOverReportUser() throws Exception {
UserId otherTenantUserId = getDifferentTenantUserId();
NotificationTemplate notificationTemplate = buildTemplateWithReport(otherTenantUserId);
save(notificationTemplate, status().isForbidden());
notificationTemplate.getConfiguration().setUserId(tenantAdminUserId);
save(notificationTemplate, status().isOk());
}
@Test
public void testNotificationRequestWithReportRequiresPermissionOverReportUser() throws Exception {
UserId otherTenantUserId = getDifferentTenantUserId();
NotificationTarget target = createNotificationTarget(tenantAdminUserId);
NotificationRequest inlineTemplateRequest = NotificationRequest.builder()
.targets(List.of(target.getUuidId()))
.template(buildTemplateWithReport(otherTenantUserId))
.additionalConfig(new NotificationRequestConfig())
.build();
doPost("/api/notification/request", inlineTemplateRequest).andExpect(status().isForbidden());
NotificationTemplate storedTemplate = saveTemplateWithReportUser(otherTenantUserId);
NotificationRequest storedTemplateRequest = NotificationRequest.builder()
.targets(List.of(target.getUuidId()))
.templateId(storedTemplate.getId())
.additionalConfig(new NotificationRequestConfig())
.build();
doPost("/api/notification/request", storedTemplateRequest).andExpect(status().isForbidden());
assertThat(findNotificationRequests().getData()).isEmpty();
}
@Test
public void testSaveRuleWithReportTemplateRequiresPermissionOverReportUser() throws Exception {
UserId otherTenantUserId = getDifferentTenantUserId();
NotificationTemplate storedTemplate = saveTemplateWithReportUser(otherTenantUserId);
EntityActionNotificationRuleTriggerConfig triggerConfig = new EntityActionNotificationRuleTriggerConfig();
triggerConfig.setEntityTypes(Set.of(EntityType.DEVICE));
triggerConfig.setCreated(true);
NotificationRule rule = new NotificationRule();
rule.setName("Device created");
rule.setEnabled(true);
rule.setTemplateId(storedTemplate.getId());
rule.setTriggerType(triggerConfig.getTriggerType());
rule.setTriggerConfig(triggerConfig);
DefaultNotificationRuleRecipientsConfig recipientsConfig = DefaultNotificationRuleRecipientsConfig.forTriggerType(triggerConfig.getTriggerType());
recipientsConfig.setTargets(List.of(createNotificationTarget(tenantAdminUserId).getUuidId()));
rule.setRecipientsConfig(recipientsConfig);
doPost("/api/notification/rule", rule).andExpect(status().isForbidden());
assertThat(findNotificationRules().getData()).extracting(NotificationRuleInfo::getName).doesNotContain(rule.getName());
}
private UserId getDifferentTenantUserId() throws Exception {
loginDifferentTenant();
UserId userId = savedDifferentTenantUser.getId();
loginTenantAdmin();
return userId;
}
private NotificationTemplate buildTemplateWithReport(UserId userId) {
NotificationTemplate notificationTemplate = new NotificationTemplate();
notificationTemplate.setName("Template with report");
notificationTemplate.setNotificationType(NotificationType.GENERAL);
NotificationTemplateConfig config = new NotificationTemplateConfig();
EmailDeliveryMethodNotificationTemplate emailTemplate = new EmailDeliveryMethodNotificationTemplate();
emailTemplate.setEnabled(true);
emailTemplate.setSubject("Report");
emailTemplate.setBody("Report");
config.setDeliveryMethodsTemplates(Map.of(NotificationDeliveryMethod.EMAIL, emailTemplate));
config.setAttachReport(true);
config.setUserId(userId);
notificationTemplate.setConfiguration(config);
return notificationTemplate;
}
private NotificationTemplate saveTemplateWithReportUser(UserId userId) {
NotificationTemplate notificationTemplate = buildTemplateWithReport(userId);
notificationTemplate.setTenantId(tenantId);
return notificationTemplateService.saveNotificationTemplate(tenantId, notificationTemplate);
}
private String saveAndGetError(NotificationTemplate notificationTemplate, ResultMatcher statusMatcher) throws Exception {
return getErrorMessage(save(notificationTemplate, statusMatcher));
}

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

Loading…
Cancel
Save