diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java index 1f276a51ba..c4127f775f 100644 --- a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/ContainerTestSuite.java @@ -119,6 +119,7 @@ public class ContainerTestSuite { new File(targetDir + "advanced/docker-compose.postgres.volumes.yml"), new File(targetDir + "docker-compose.integration.yml"), new File(targetDir + "docker-compose.mosquitto.yml"), + new File(targetDir + "docker-compose.chirpstack.yml"), new File(targetDir + "docker-compose.opc-ua.yml"), new File(targetDir + "advanced/docker-compose.kafka.yml"), new File(targetDir + "advanced/docker-compose.trendz.yml"), @@ -158,6 +159,7 @@ public class ContainerTestSuite { .withExposedService("tb-integration-executor1", 8082) .withExposedService("tb-mqtt-integration", 8082) .withExposedService("broker", 1883) + .withExposedService("chirpstack-rest-api", 8090, Wait.forListeningPort().withStartupTimeout(CONTAINER_STARTUP_TIMEOUT)) .waitingFor("tb-core1", Wait.forLogMessage(TB_CORE_LOG_REGEXP, 1).withStartupTimeout(CONTAINER_STARTUP_TIMEOUT)) .waitingFor("tb-core2", Wait.forLogMessage(TB_CORE_LOG_REGEXP, 1).withStartupTimeout(CONTAINER_STARTUP_TIMEOUT)) .waitingFor("tb-rule-engine1", Wait.forLogMessage(TRANSPORTS_LOG_REGEXP, 1).withStartupTimeout(CONTAINER_STARTUP_TIMEOUT)) diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/TestProperties.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/TestProperties.java index e336ac3528..76f5278252 100644 --- a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/TestProperties.java +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/TestProperties.java @@ -54,6 +54,15 @@ public class TestProperties { return System.getProperty("integrationExecutor.httpUrl", "http://localhost:8082"); } + public static String getChirpStackRestUrl(){ + if (instance.isActive()) { + String host = instance.getTestContainer().getServiceHost("chirpstack-rest-api", 8090); + Integer port = instance.getTestContainer().getServicePort("chirpstack-rest-api", 8090); + return "http://" + host + ":" + port; + } + return System.getProperty("chirpstack.restUrl", "http://localhost:8090"); + } + public static String getMqttBrokerUrl(){ if (instance.isActive()) { String host = instance.getTestContainer().getServiceHost("broker", 1883); diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/ChirpStackIntegrationTest.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/ChirpStackIntegrationTest.java index 99f391fdb3..4abdb8077c 100644 --- a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/ChirpStackIntegrationTest.java +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/ChirpStackIntegrationTest.java @@ -3,18 +3,29 @@ package org.thingsboard.server.msa.integration; import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import lombok.extern.slf4j.Slf4j; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.EntityType; +import org.thingsboard.server.common.data.event.EventType; +import org.thingsboard.server.common.data.id.RuleChainId; +import org.thingsboard.server.common.data.rule.RuleChainMetaData; +import org.thingsboard.server.common.data.rule.RuleNode; +import org.thingsboard.server.msa.TestProperties; import org.thingsboard.server.msa.WsClient; +import org.thingsboard.server.msa.integration.chirpstack.ChirpStackTestClient; +import org.thingsboard.server.msa.integration.chirpstack.ChirpStackTestClient.ProvisionedDevice; +import org.thingsboard.server.msa.integration.chirpstack.LoRaWanUplinkFrameBuilder; import org.thingsboard.server.msa.mapper.WsTelemetryResponse; -import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; +import java.nio.charset.StandardCharsets; +import java.util.HexFormat; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -23,51 +34,85 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.thingsboard.server.common.data.DataConstants.CLIENT_SCOPE; +import static org.thingsboard.server.common.data.DataConstants.SHARED_SCOPE; import static org.thingsboard.server.common.data.integration.IntegrationType.CHIRPSTACK; +/** + * End-to-end ChirpStack integration test: provisions a real ChirpStack v4 server (run by the + * test container suite), publishes a genuine LoRaWAN uplink to ChirpStack's gateway MQTT topic, + * and verifies that ChirpStack decrypts it and forwards it through the ThingsBoard CHIRPSTACK + * HTTP integration into telemetry/attributes. + */ @Slf4j public class ChirpStackIntegrationTest extends AbstractIntegrationTest { private static final String ROUTING_KEY = "routing-key-chirpstack"; private static final String SECRET_KEY = "secret-key-chirpstack"; + // Application payload [0x2a, 0x3f] -> base64 "Kj8=", decoded as temperature 42 / humidity 63. + private static final byte[] UPLINK_PAYLOAD = {0x2a, 0x3f}; + private static final int F_PORT = 1; + + // Downlink converter: reads the shared-attribute body and produces a DownlinkData whose + // metadata (DevEUI, fPort) routes ChirpStackIntegration to POST {applicationServerUrl}/api/ + // devices/{devEui}/queue. The 'data' field is the base64 payload ChirpStack will enqueue. + private static final String DOWNLINK_CONVERTER_ENCODER = + "var result = {\n" + + " contentType: \"TEXT\",\n" + + " data: msg.downlinkData,\n" + + " metadata: {\n" + + " DevEUI: msg.devEui,\n" + + " fPort: \"1\"\n" + + " }\n" + + "};\n" + + "return result;"; + + private ChirpStackTestClient chirpStackClient; + private ProvisionedDevice provisionedDevice; private WsClient wsClient; + @BeforeClass + public void beforeChirpStackClass() { + chirpStackClient = new ChirpStackTestClient(TestProperties.getChirpStackRestUrl()); + } + @AfterMethod public void tearDown() throws Exception { if (wsClient != null) { wsClient.closeBlocking(); + wsClient = null; + } + if (provisionedDevice != null) { + chirpStackClient.deleteApplication(provisionedDevice.getApplicationId()); + provisionedDevice = null; } } @Test public void checkTelemetryUploadedWithLocalIntegration() throws Exception { - JsonNode configConverter = JacksonUtil.toJsonNode(JSON_CONVERTER_CONFIG.replaceAll("DEVICE_NAME", device.getName())); - JsonNode integrationConfig = createChirpStackJsonConfig(); - createIntegration(CHIRPSTACK, integrationConfig, configConverter, null, ROUTING_KEY, SECRET_KEY, false, 2); + provisionedDevice = chirpStackClient.provision(ROUTING_KEY); + createTbChirpStackIntegration(); wsClient = subscribeToWebSocket(device.getId(), "LATEST_TELEMETRY", CmdsType.TS_SUB_CMDS); - ObjectNode payloadMsg = createPayloadMsg(); - - testRestClient.postUplinkPayloadForHttpBasedIntegration(integration.getRoutingKey(), payloadMsg, CHIRPSTACK); + sendUplink(); WsTelemetryResponse actualLatestTelemetry = wsClient.getLastMessage(); assertThat(actualLatestTelemetry.getDataValuesByKey("data").get(1)).isEqualTo("Kj8="); assertThat(actualLatestTelemetry.getDataValuesByKey("temperature").get(1)).isEqualTo("42"); assertThat(actualLatestTelemetry.getDataValuesByKey("humidity").get(1)).isEqualTo("63"); - assertThat(actualLatestTelemetry.getDataValuesByKey("snr").get(1)).isEqualTo("11.5"); + assertThat(actualLatestTelemetry.getDataValuesByKey("snr").get(1)) + .isEqualTo(String.valueOf(LoRaWanUplinkFrameBuilder.SNR)); } @Test public void checkAttributesUploadedWithLocalIntegration() { - JsonNode configConverter = JacksonUtil.toJsonNode(JSON_CONVERTER_CONFIG.replaceAll("DEVICE_NAME", device.getName())); - JsonNode integrationConfig = createChirpStackJsonConfig(); - createIntegration(CHIRPSTACK, integrationConfig, configConverter, null, ROUTING_KEY, SECRET_KEY, false, 2); + provisionedDevice = chirpStackClient.provision(ROUTING_KEY); + createTbChirpStackIntegration(); - ObjectNode payloadMsg = createPayloadMsg(); + sendUplink(); - testRestClient.postUplinkPayloadForHttpBasedIntegration(integration.getRoutingKey(), payloadMsg, CHIRPSTACK); + String expectedEui = HexFormat.of().formatHex(provisionedDevice.getDevEui()); await() .pollInterval(1, TimeUnit.SECONDS) @@ -80,9 +125,60 @@ public class ChirpStackIntegrationTest extends AbstractIntegrationTest { node -> node )); - assertThat(attributeMap.get("rssi").get("value").asInt()).isEqualTo(-130); - assertThat(attributeMap.get("eui").get("value").asText()).isEqualTo("BE7A123456789"); - assertThat(attributeMap.get("fPort").get("value").asInt()).isEqualTo(80); + assertThat(attributeMap.get("rssi").get("value").asInt()).isEqualTo(LoRaWanUplinkFrameBuilder.RSSI); + assertThat(attributeMap.get("eui").get("value").asText()).isEqualTo(expectedEui); + assertThat(attributeMap.get("fPort").get("value").asInt()).isEqualTo(F_PORT); + }); + } + + @Test + public void checkDownlinkEnqueuedInChirpStack() throws Exception { + provisionedDevice = chirpStackClient.provision(ROUTING_KEY); + createTbChirpStackIntegrationWithDownlink(); + + // Re-root the rule chain so ATTRIBUTES_UPDATED messages flow into TbIntegrationDownlinkNode. + RuleChainId ruleChainId = createRootRuleChainWithIntegrationDownlinkNode(integration.getId()); + + String devEuiHex = HexFormat.of().formatHex(provisionedDevice.getDevEui()); + String downlinkDataBase64 = "AQID"; // [0x01, 0x02, 0x03] + + // Trigger the downlink: saving a shared attribute fires ATTRIBUTES_UPDATED whose JSON + // body becomes the converter's `msg`. The converter reads devEui+downlinkData from it. + ObjectNode sharedAttributes = JacksonUtil.newObjectNode(); + sharedAttributes.put("devEui", devEuiHex); + sharedAttributes.put("downlinkData", downlinkDataBase64); + testRestClient.saveEntityAttributes(EntityType.DEVICE.name(), device.getId().toString(), SHARED_SCOPE, sharedAttributes); + + // Wait until the integration's downlink node actually saw the message — surfaces converter + // and HTTP errors as a debug event rather than just a queue that stays empty. + RuleChainMetaData ruleChainMetadata = testRestClient.getRuleChainMetadata(ruleChainId); + RuleNode integrationNode = ruleChainMetadata.getNodes().stream() + .filter(n -> n.getType().equals("org.thingsboard.rule.engine.integration.TbIntegrationDownlinkNode")) + .findFirst() + .orElseThrow(() -> new AssertionError("TbIntegrationDownlinkNode not found in rule chain")); + waitTillRuleNodeReceiveMsg(integrationNode.getId(), EventType.DEBUG_RULE_NODE, integration.getTenantId(), "ATTRIBUTES_UPDATED"); + + // Verify ChirpStack actually accepted the queue item with our payload. + await() + .pollInterval(1, TimeUnit.SECONDS) + .atMost(TIMEOUT, TimeUnit.SECONDS) + .untilAsserted(() -> { + JsonNode queue = chirpStackClient.getDeviceQueue(devEuiHex); + JsonNode result = queue.get("result"); + assertThat(result).as("ChirpStack queue response should contain 'result'").isNotNull(); + boolean matched = false; + for (JsonNode item : result) { + JsonNode data = item.get("data"); + JsonNode fPort = item.get("fPort"); + if (data != null && downlinkDataBase64.equals(data.asText()) + && fPort != null && fPort.asInt() == F_PORT) { + matched = true; + break; + } + } + assertThat(matched) + .as("ChirpStack downlink queue should contain enqueued item with data=%s fPort=%d", downlinkDataBase64, F_PORT) + .isTrue(); }); } @@ -91,24 +187,38 @@ public class ChirpStackIntegrationTest extends AbstractIntegrationTest { return "chirpstack_"; } - private ObjectNode createPayloadMsg() { - ObjectNode payloadMsg = JacksonUtil.newObjectNode(); - - String isoTime = OffsetDateTime.now(ZoneOffset.UTC) - .format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - payloadMsg.put("time", isoTime); - payloadMsg.put("data", "Kj8="); - - ObjectNode deviceInfo = payloadMsg.putObject("deviceInfo"); - deviceInfo.put("devEui", "BE7A123456789"); - payloadMsg.put("fPort", 80); + private void createTbChirpStackIntegration() { + JsonNode configConverter = JacksonUtil.toJsonNode(JSON_CONVERTER_CONFIG.replaceAll("DEVICE_NAME", device.getName())); + createIntegration(CHIRPSTACK, createChirpStackJsonConfig(), configConverter, null, ROUTING_KEY, SECRET_KEY, false, 2); + } - ArrayNode rxInfo = payloadMsg.putArray("rxInfo"); - ObjectNode rxInfoEntry = rxInfo.addObject(); - rxInfoEntry.put("rssi", -130); - rxInfoEntry.put("snr", 11.5); + private void createTbChirpStackIntegrationWithDownlink() { + JsonNode configConverter = JacksonUtil.toJsonNode(JSON_CONVERTER_CONFIG.replaceAll("DEVICE_NAME", device.getName())); + JsonNode downlinkConverter = JacksonUtil.newObjectNode().put("encoder", DOWNLINK_CONVERTER_ENCODER); + createIntegration(CHIRPSTACK, createChirpStackJsonConfig(), configConverter, downlinkConverter, ROUTING_KEY, SECRET_KEY, false, 2); + } - return payloadMsg; + // Builds a real LoRaWAN uplink frame and publishes it to ChirpStack's gateway MQTT event topic. + private void sendUplink() { + String json = LoRaWanUplinkFrameBuilder.buildUplinkFrameJson( + provisionedDevice.getDevAddr(), + provisionedDevice.getNwkSKey(), + provisionedDevice.getAppSKey(), + 0, F_PORT, UPLINK_PAYLOAD, + provisionedDevice.getGatewayId()); + String topic = "eu868/gateway/" + provisionedDevice.getGatewayId() + "/event/up"; + try { + MqttClient client = new MqttClient(TestProperties.getMqttBrokerUrl(), MqttClient.generateClientId(), new MemoryPersistence()); + client.connect(); + try { + client.publish(topic, new MqttMessage(json.getBytes(StandardCharsets.UTF_8))); + } finally { + client.disconnect(); + client.close(); + } + } catch (Exception e) { + throw new RuntimeException("Failed to publish ChirpStack uplink frame", e); + } } private JsonNode createChirpStackJsonConfig() { @@ -117,8 +227,12 @@ public class ChirpStackIntegrationTest extends AbstractIntegrationTest { ObjectNode clientConfigNode = rootNode.putObject("clientConfiguration"); clientConfigNode.put("baseUrl", HTTPS_URL); - clientConfigNode.put("applicationServerUrl", "test_server_url"); - clientConfigNode.put("applicationServerApiToken", "test_api_token"); + // Real in-network ChirpStack REST URL + the seeded admin JWT so the TB integration can + // actually enqueue downlinks. The uplink tests don't read these (uplink path is one-way), + // but having them populated lets the downlink test reuse the same config. + clientConfigNode.put("applicationServerUrl", ChirpStackTestClient.getInNetworkRestUrl()); + clientConfigNode.put("applicationServerAPIToken", chirpStackClient.getToken()); + clientConfigNode.put("useAPI4Plus", true); return rootNode; } diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/TTNIntegrationTest.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/TTNIntegrationTest.java new file mode 100644 index 0000000000..57d20fd1f9 --- /dev/null +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/TTNIntegrationTest.java @@ -0,0 +1,175 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.msa.integration; + +import com.fasterxml.jackson.databind.JsonNode; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.RandomStringUtils; +import org.awaitility.Awaitility; +import org.testng.SkipException; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.common.data.debug.DebugSettings; +import org.thingsboard.server.common.data.integration.Integration; +import org.thingsboard.server.common.data.integration.IntegrationType; +import org.thingsboard.server.msa.WsClient; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.concurrent.TimeUnit; + +import static org.thingsboard.server.msa.prototypes.ConverterPrototypes.uplinkConverterPrototype; + +/** + * Live integration test that exercises ThingsBoard's TTN integration against a real + * The Things Stack Community application. The required cloud credentials are read from + * system properties (-DblackBoxTests.ttn*=...). If any of them is unset, the test is + * skipped — so the class is safe to keep in CI without leaking secrets. + */ +@Slf4j +public class TTNIntegrationTest extends AbstractIntegrationTest { + + private static final String ROUTING_KEY = "routing-key-ttn-integration"; + private static final String SECRET_KEY = "secret-key-ttn-integration"; + + private static final String CONFIG_TEMPLATE = "{\n" + + " \"clientConfiguration\": {\n" + + " \"host\": \"%s\",\n" + + " \"customHost\": true,\n" + + " \"port\": 8883,\n" + + " \"ssl\": true,\n" + + " \"cleanSession\": true,\n" + + " \"connectTimeoutSec\": 10,\n" + + " \"protocolVersion\": \"MQTT_3_1_1\",\n" + + " \"maxBytesInMessage\": 32368,\n" + + " \"credentials\": {\n" + + " \"type\": \"basic\",\n" + + " \"username\": \"%s\",\n" + + " \"password\": \"%s\"\n" + + " }\n" + + " },\n" + + " \"topicFilters\": [ { \"filter\": \"v3/+/devices/+/up\", \"qos\": 0 } ],\n" + + " \"downlinkTopicPattern\": \"v3/%s/devices/${devId}/down/push\",\n" + + " \"metadata\": {}\n" + + "}"; + + private static final String DEVICE_NAME_PLACEHOLDER = "DEVICE_NAME"; + + // TTN delivers an envelope JSON; we ignore the inbound payload entirely and pin every + // uplink to the pre-created test device so the test does not depend on the TTN-side + // device-id matching anything on the TB side. + private static final String UPLINK_CONVERTER_CODE = + "function decodeToString(payload) { return String.fromCharCode.apply(String, payload); }\n" + + "function decodeToJson(payload) { return JSON.parse(decodeToString(payload)); }\n" + + "var data = decodeToJson(payload);\n" + + "var result = {\n" + + " deviceName: '" + DEVICE_NAME_PLACEHOLDER + "',\n" + + " deviceType: 'DEFAULT',\n" + + " telemetry: { temperature: '42' }\n" + + "};\n" + + "return result;"; + + private JsonNode uplinkConverterCode; + private WsClient wsClient; + + @BeforeMethod + public void setUp() { + uplinkConverterCode = JacksonUtil.newObjectNode() + .put("decoder", UPLINK_CONVERTER_CODE.replace(DEVICE_NAME_PLACEHOLDER, device.getName())); + } + + @AfterMethod + public void tearDown() throws Exception { + if (wsClient != null) { + wsClient.closeBlocking(); + } + } + + @Test + public void shouldReceiveSimulatedUplinkFromTheThingsStack() throws Exception { + String region = requireProperty("blackBoxTests.ttnRegion"); + String username = requireProperty("blackBoxTests.ttnUsername"); + String password = requireProperty("blackBoxTests.ttnPassword"); + String appId = requireProperty("blackBoxTests.ttnAppId"); + String deviceId = requireProperty("blackBoxTests.ttnDeviceId"); + + createTtnIntegration(region, username, password); + + wsClient = subscribeToWebSocket(device.getId(), "LATEST_TELEMETRY", CmdsType.TS_SUB_CMDS); + + sendSimulatedUplink(region, password, appId, deviceId); + + Awaitility + .await() + .atMost(TIMEOUT, TimeUnit.SECONDS) + .until(() -> wsClient.getLastMessage().getDataValuesByKey(TELEMETRY_KEY).get(1).equals(TELEMETRY_VALUE)); + } + + private Integration createTtnIntegration(String region, String username, String password) { + String host = region + ".cloud.thethings.network"; + JsonNode config = JacksonUtil.toJsonNode(String.format(CONFIG_TEMPLATE, host, username, password, username)); + + Integration integration = new Integration(); + integration.setConfiguration(config); + + uplinkConverter = testRestClient.postConverter(uplinkConverterPrototype(uplinkConverterCode)); + integration.setDefaultConverterId(uplinkConverter.getId()); + + integration.setName("ttn_" + RandomStringUtils.randomAlphanumeric(7)); + integration.setType(IntegrationType.TTN); + integration.setEnabled(true); + integration.setRemote(false); + integration.setDebugSettings(DebugSettings.all()); + integration.setAllowCreateDevicesOrAssets(true); + integration.setRoutingKey(ROUTING_KEY); + integration.setSecret(SECRET_KEY); + + integration = testRestClient.postIntegration(integration); + waitUntilIntegrationStarted(integration.getId(), integration.getTenantId()); + return this.integration = integration; + } + + private void sendSimulatedUplink(String region, String apiKey, String appId, String deviceId) throws Exception { + String url = String.format("https://%s.cloud.thethings.network/api/v3/as/applications/%s/devices/%s/up/simulate", + region, appId, deviceId); + String frmPayload = Base64.getEncoder().encodeToString("{\"temperature\":42}".getBytes(StandardCharsets.UTF_8)); + String body = "{\"uplink_message\":{" + + "\"f_port\":1," + + "\"frm_payload\":\"" + frmPayload + "\"," + + "\"settings\":{" + + "\"data_rate\":{\"lora\":{\"bandwidth\":125000,\"spreading_factor\":7}}," + + "\"frequency\":\"868000000\"" + + "}}}"; + + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(url)) + .header("Authorization", "Bearer " + apiKey) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(body)) + .build(); + HttpResponse response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() / 100 != 2) { + throw new RuntimeException("TTN simulate-uplink call failed: " + response.statusCode() + " - " + response.body()); + } + } + + private static String requireProperty(String key) { + String value = System.getProperty(key); + if (value == null || value.isBlank()) { + throw new SkipException("Required system property '" + key + "' is not set — skipping TTN live test."); + } + return value; + } + + @Override + protected String getDevicePrototypeSufix() { + return "ttn_"; + } + +} diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/chirpstack/ChirpStackTestClient.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/chirpstack/ChirpStackTestClient.java new file mode 100644 index 0000000000..daee9ba812 --- /dev/null +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/chirpstack/ChirpStackTestClient.java @@ -0,0 +1,336 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.msa.integration.chirpstack; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.awaitility.Awaitility; +import org.awaitility.core.ConditionTimeoutException; +import org.testcontainers.containers.Container; +import org.testcontainers.containers.ContainerState; +import org.thingsboard.common.util.JacksonUtil; +import org.thingsboard.server.msa.ContainerTestSuite; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.Base64; +import java.util.HexFormat; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Provisions a real ChirpStack v4 server (the {@code chirpstack-rest-api} service exposed by + * {@link ContainerTestSuite}) over its REST API so an end-to-end uplink can be produced. + * + *

ChirpStack v4 has no REST login endpoint — the REST API authenticates with a Bearer + * API-key JWT signed with the configured {@code [api] secret}. There is no API key out of the + * box, so we seed one admin {@code api_key} row directly in ChirpStack's PostgreSQL (the table + * only exists after ChirpStack applies its migrations) and mint a matching HS256 token. + */ +@Slf4j +public class ChirpStackTestClient { + + // Must match `secret` in chirpstack/configuration/chirpstack/chirpstack.toml. + private static final String API_SECRET = "black-box-test-secret"; + // Fixed admin api_key id we seed and sign tokens for. + private static final String API_KEY_ID = "11111111-1111-1111-1111-111111111111"; + private static final String POSTGRES_SERVICE = "chirpstack-postgres_1"; + + // In-cluster URL ChirpStack POSTs uplinks to. We hit haproxy on plain HTTP (port 80) because + // (a) it routes /api/v1/integrations/* to the tb-integration-executor backend that actually + // serves local integrations — tb-http-integration is only used for *remote* integrations + // and would return 404 — and (b) HTTPS would force ChirpStack's HTTP client to validate the + // self-signed cert haproxy serves on 443. + private static final String TB_INTEGRATION_BASE_URL = "http://haproxy"; + + // In-cluster URL the TB ChirpStack integration uses to enqueue downlinks. The TB side runs + // inside the compose network and resolves the rest-api container by its service name. + private static final String IN_NETWORK_REST_URL = "http://chirpstack-rest-api:8090"; + + private final String restUrl; + private final String token; + private final HttpClient httpClient = HttpClient.newHttpClient(); + private final SecureRandom random = new SecureRandom(); + + public ChirpStackTestClient(String restUrl) { + this.restUrl = restUrl; + this.token = mintApiKeyToken(); + } + + /** + * Creates a device profile, application, ABP-activated device, gateway and an HTTP + * integration that forwards uplinks to ThingsBoard for the given integration routing key. + */ + public ProvisionedDevice provision(String routingKey) { + seedAdminApiKey(); + String tenantId = getDefaultTenantId(); + + String deviceProfileId = createDeviceProfile(tenantId); + String applicationId = createApplication(tenantId); + + byte[] devEui = randomBytes(8); + byte[] gatewayId = randomBytes(8); + byte[] devAddr = randomBytes(4); + byte[] nwkSKey = randomBytes(16); + byte[] appSKey = randomBytes(16); + String devEuiHex = HexFormat.of().formatHex(devEui); + String gatewayIdHex = HexFormat.of().formatHex(gatewayId); + + createDevice(applicationId, deviceProfileId, devEuiHex); + activateDevice(devEuiHex, devAddr, nwkSKey, appSKey); + createGateway(tenantId, gatewayIdHex); + createHttpIntegration(applicationId, TB_INTEGRATION_BASE_URL + + "/api/v1/integrations/chirpstack/" + routingKey); + + return new ProvisionedDevice(applicationId, devEui, devAddr, nwkSKey, appSKey, gatewayIdHex); + } + + /** The admin API-key JWT used to authenticate REST calls — exposed so the TB integration can use it too. */ + public String getToken() { + return token; + } + + /** In-network base URL for the ChirpStack REST API — used by the TB integration's downlink call. */ + public static String getInNetworkRestUrl() { + return IN_NETWORK_REST_URL; + } + + /** Returns the current ChirpStack downlink queue for the device (GET /api/devices/{devEui}/queue). */ + public JsonNode getDeviceQueue(String devEuiHex) { + return get("/api/devices/" + devEuiHex + "/queue"); + } + + public void deleteApplication(String applicationId) { + try { + delete("/api/applications/" + applicationId); + } catch (Exception e) { + log.warn("Failed to delete ChirpStack application {}", applicationId, e); + } + } + + private String createDeviceProfile(String tenantId) { + ObjectNode dp = JacksonUtil.newObjectNode(); + dp.put("name", "bb-dp-" + HexFormat.of().formatHex(randomBytes(4))); + dp.put("tenantId", tenantId); + dp.put("region", "EU868"); + dp.put("macVersion", "LORAWAN_1_0_3"); + dp.put("regParamsRevision", "A"); + dp.put("supportsOtaa", false); + dp.put("uplinkInterval", 3600); + dp.put("adrAlgorithmId", "default"); + ObjectNode body = JacksonUtil.newObjectNode(); + body.set("deviceProfile", dp); + return post("/api/device-profiles", body).get("id").asText(); + } + + private String createApplication(String tenantId) { + ObjectNode app = JacksonUtil.newObjectNode(); + app.put("name", "bb-app-" + HexFormat.of().formatHex(randomBytes(4))); + app.put("tenantId", tenantId); + ObjectNode body = JacksonUtil.newObjectNode(); + body.set("application", app); + return post("/api/applications", body).get("id").asText(); + } + + private void createDevice(String applicationId, String deviceProfileId, String devEuiHex) { + ObjectNode device = JacksonUtil.newObjectNode(); + device.put("devEui", devEuiHex); + device.put("name", "bb-dev-" + devEuiHex); + device.put("applicationId", applicationId); + device.put("deviceProfileId", deviceProfileId); + device.put("skipFcntCheck", true); + device.put("isDisabled", false); + ObjectNode body = JacksonUtil.newObjectNode(); + body.set("device", device); + post("/api/devices", body); + } + + private void activateDevice(String devEuiHex, byte[] devAddr, byte[] nwkSKey, byte[] appSKey) { + String nwkSKeyHex = HexFormat.of().formatHex(nwkSKey); + ObjectNode activation = JacksonUtil.newObjectNode(); + activation.put("devEui", devEuiHex); + activation.put("devAddr", HexFormat.of().formatHex(devAddr)); + activation.put("appSKey", HexFormat.of().formatHex(appSKey)); + // LoRaWAN 1.0.x uses a single network session key for all three key roles. + activation.put("nwkSEncKey", nwkSKeyHex); + activation.put("sNwkSIntKey", nwkSKeyHex); + activation.put("fNwkSIntKey", nwkSKeyHex); + activation.put("fCntUp", 0); + activation.put("nFCntDown", 0); + activation.put("aFCntDown", 0); + ObjectNode body = JacksonUtil.newObjectNode(); + body.set("deviceActivation", activation); + post("/api/devices/" + devEuiHex + "/activate", body); + } + + private void createGateway(String tenantId, String gatewayIdHex) { + ObjectNode gateway = JacksonUtil.newObjectNode(); + gateway.put("gatewayId", gatewayIdHex); + gateway.put("name", "bb-gw-" + gatewayIdHex); + gateway.put("tenantId", tenantId); + gateway.put("statsInterval", 30); + ObjectNode body = JacksonUtil.newObjectNode(); + body.set("gateway", gateway); + post("/api/gateways", body); + } + + private void createHttpIntegration(String applicationId, String eventEndpointUrl) { + ObjectNode integration = JacksonUtil.newObjectNode(); + integration.put("applicationId", applicationId); + integration.put("encoding", "JSON"); + integration.put("eventEndpointUrl", eventEndpointUrl); + ObjectNode body = JacksonUtil.newObjectNode(); + body.set("integration", integration); + post("/api/applications/" + applicationId + "/integrations/http", body); + } + + private String getDefaultTenantId() { + // Retries until ChirpStack has finished its migrations and the API answers our token. + return Awaitility.await("ChirpStack REST API ready") + .atMost(120, TimeUnit.SECONDS) + .pollInterval(2, TimeUnit.SECONDS) + .until(() -> { + try { + JsonNode result = get("/api/tenants?limit=1").get("result"); + if (result != null && result.size() > 0) { + return result.get(0).get("id").asText(); + } + } catch (Exception e) { + log.debug("ChirpStack not ready yet: {}", e.getMessage()); + } + return null; + }, java.util.Objects::nonNull); + } + + // Inserts a fixed admin api_key row so our minted token validates. Idempotent and retried, + // because the api_key table only exists once ChirpStack has applied its schema migrations. + private void seedAdminApiKey() { + ContainerState postgres = ContainerTestSuite.getInstance().getTestContainer() + .getContainerByServiceName(POSTGRES_SERVICE) + .orElseThrow(() -> new IllegalStateException("ChirpStack postgres container not found")); + String sql = "insert into api_key(id, created_at, name, is_admin, is_read_only) " + + "values ('" + API_KEY_ID + "', now(), 'blackbox', true, false) on conflict (id) do nothing;"; + AtomicReference lastError = new AtomicReference<>("(no attempt recorded)"); + try { + Awaitility.await("Seed ChirpStack admin api_key") + .atMost(120, TimeUnit.SECONDS) + .pollInterval(2, TimeUnit.SECONDS) + .until(() -> { + try { + Container.ExecResult result = postgres.execInContainer( + "psql", "-U", "chirpstack", "-d", "chirpstack", "-v", "ON_ERROR_STOP=1", "-c", sql); + if (result.getExitCode() != 0) { + lastError.set("psql exit=" + result.getExitCode() + " stderr=" + result.getStderr().trim()); + log.debug("api_key seed not ready: {}", lastError.get()); + return false; + } + return true; + } catch (Exception e) { + lastError.set("exec failed: " + e); + log.debug("api_key seed exec failed: {}", e.getMessage()); + return false; + } + }); + } catch (ConditionTimeoutException e) { + throw new IllegalStateException("Failed to seed ChirpStack admin api_key. Last error: " + lastError.get() + + ". This usually means the 'chirpstack' server never applied its schema migrations " + + "(check the chirpstack container logs; it requires the pg_trgm/hstore extensions created by the " + + "postgres initdb script).", e); + } + } + + // ChirpStack api-key JWT: HS256, claims {aud,iss=chirpstack, sub=, typ=key}, no exp. + private static String mintApiKeyToken() { + try { + String header = base64Url("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".getBytes(StandardCharsets.UTF_8)); + String payload = base64Url(("{\"aud\":\"chirpstack\",\"iss\":\"chirpstack\",\"sub\":\"" + + API_KEY_ID + "\",\"typ\":\"key\"}").getBytes(StandardCharsets.UTF_8)); + String signingInput = header + "." + payload; + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(API_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String signature = base64Url(mac.doFinal(signingInput.getBytes(StandardCharsets.UTF_8))); + return signingInput + "." + signature; + } catch (Exception e) { + throw new RuntimeException("Failed to mint ChirpStack API token", e); + } + } + + private static String base64Url(byte[] data) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(data); + } + + private JsonNode post(String path, JsonNode body) { + return send(HttpRequest.newBuilder() + .uri(URI.create(restUrl + path)) + .header("Authorization", "Bearer " + token) + .header("Content-Type", "application/json") + .POST(HttpRequest.BodyPublishers.ofString(JacksonUtil.toString(body))) + .build()); + } + + private JsonNode get(String path) { + return send(HttpRequest.newBuilder() + .uri(URI.create(restUrl + path)) + .header("Authorization", "Bearer " + token) + .GET() + .build()); + } + + private void delete(String path) { + send(HttpRequest.newBuilder() + .uri(URI.create(restUrl + path)) + .header("Authorization", "Bearer " + token) + .DELETE() + .build()); + } + + private JsonNode send(HttpRequest request) { + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() / 100 != 2) { + throw new RuntimeException("ChirpStack API call " + request.method() + " " + request.uri() + + " failed: " + response.statusCode() + " - " + response.body()); + } + return response.body().isEmpty() ? JacksonUtil.newObjectNode() : JacksonUtil.toJsonNode(response.body()); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException("ChirpStack API call failed: " + request.uri(), e); + } + } + + private byte[] randomBytes(int length) { + byte[] bytes = new byte[length]; + random.nextBytes(bytes); + return bytes; + } + + /** Holds the secrets/identifiers needed to craft and publish an uplink for the device. */ + @Getter + public static class ProvisionedDevice { + private final String applicationId; + private final byte[] devEui; + private final byte[] devAddr; + private final byte[] nwkSKey; + private final byte[] appSKey; + private final String gatewayId; + + public ProvisionedDevice(String applicationId, byte[] devEui, byte[] devAddr, + byte[] nwkSKey, byte[] appSKey, String gatewayId) { + this.applicationId = applicationId; + this.devEui = devEui; + this.devAddr = devAddr; + this.nwkSKey = nwkSKey; + this.appSKey = appSKey; + this.gatewayId = gatewayId; + } + } +} diff --git a/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/chirpstack/LoRaWanUplinkFrameBuilder.java b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/chirpstack/LoRaWanUplinkFrameBuilder.java new file mode 100644 index 0000000000..c6ffa0ecc7 --- /dev/null +++ b/msa/black-box-tests/src/test/java/org/thingsboard/server/msa/integration/chirpstack/LoRaWanUplinkFrameBuilder.java @@ -0,0 +1,169 @@ +// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +// SPDX-License-Identifier: BUSL-1.1 +package org.thingsboard.server.msa.integration.chirpstack; + +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.bouncycastle.crypto.engines.AESEngine; +import org.bouncycastle.crypto.macs.CMac; +import org.bouncycastle.crypto.params.KeyParameter; +import org.thingsboard.common.util.JacksonUtil; + +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.util.Base64; + +/** + * Builds a LoRaWAN 1.0.x "unconfirmed data up" PHYPayload (with a valid MIC and + * AES-encrypted FRMPayload) and wraps it into the ChirpStack gateway + * {@code gw.UplinkFrame} JSON that is published to the gateway MQTT event topic + * {@code /gateway//event/up}. ChirpStack validates the MIC, + * decrypts the FRMPayload and forwards the resulting uplink to its application + * integrations — i.e. this produces a genuine uplink, not a faked HTTP POST. + */ +public final class LoRaWanUplinkFrameBuilder { + + private static final int UPLINK_DIRECTION = 0x00; + private static final byte MHDR_UNCONFIRMED_UP = 0x40; + // Standard EU868 SF7BW125 settings; matches one of the region channels. + private static final long FREQUENCY_HZ = 868100000L; + private static final int BANDWIDTH_HZ = 125000; + private static final int SPREADING_FACTOR = 7; + // Gateway-reported radio metadata; exposed so tests can assert the forwarded values. + public static final int RSSI = -130; + public static final double SNR = 11.5; + + private LoRaWanUplinkFrameBuilder() { + } + + /** + * @param devAddr 4-byte device address (big-endian / as displayed) + * @param nwkSKey 16-byte network session key + * @param appSKey 16-byte application session key + * @param fCnt uplink frame counter + * @param fPort frame port (1-223) + * @param payload decrypted application payload bytes + * @param gatewayId 8-byte gateway EUI as a 16-char hex string + */ + public static String buildUplinkFrameJson(byte[] devAddr, byte[] nwkSKey, byte[] appSKey, + int fCnt, int fPort, byte[] payload, String gatewayId) { + byte[] phyPayload = buildPhyPayload(devAddr, nwkSKey, appSKey, fCnt, fPort, payload); + + ObjectNode frame = JacksonUtil.newObjectNode(); + frame.put("phyPayload", Base64.getEncoder().encodeToString(phyPayload)); + + ObjectNode lora = JacksonUtil.newObjectNode(); + lora.put("bandwidth", BANDWIDTH_HZ); + lora.put("spreadingFactor", SPREADING_FACTOR); + lora.put("codeRate", "CR_4_5"); + ObjectNode modulation = JacksonUtil.newObjectNode(); + modulation.set("lora", lora); + ObjectNode txInfo = JacksonUtil.newObjectNode(); + txInfo.put("frequency", FREQUENCY_HZ); + txInfo.set("modulation", modulation); + frame.set("txInfo", txInfo); + + ObjectNode rxInfo = JacksonUtil.newObjectNode(); + rxInfo.put("gatewayId", gatewayId); + rxInfo.put("uplinkId", 1); + rxInfo.put("rssi", RSSI); + rxInfo.put("snr", SNR); + rxInfo.put("channel", 0); + rxInfo.put("context", Base64.getEncoder().encodeToString(new byte[]{0, 0, 0, 1})); + frame.set("rxInfo", rxInfo); + + return JacksonUtil.toString(frame); + } + + static byte[] buildPhyPayload(byte[] devAddr, byte[] nwkSKey, byte[] appSKey, + int fCnt, int fPort, byte[] payload) { + byte[] devAddrLe = reverse(devAddr); + byte[] fCntLe2 = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(fCnt).array(); + + byte[] encryptedPayload = encryptPayload(appSKey, devAddrLe, fCnt, payload); + + // MACPayload = FHDR | FPort | FRMPayload; FHDR = DevAddr(LE) | FCtrl | FCnt(LE, 2 bytes) + ByteArrayOutputStream macPayload = new ByteArrayOutputStream(); + macPayload.writeBytes(devAddrLe); + macPayload.write(0x00); // FCtrl: no ADR, no FOpts + macPayload.write(fCntLe2[0]); + macPayload.write(fCntLe2[1]); + macPayload.write(fPort & 0xFF); + macPayload.writeBytes(encryptedPayload); + + ByteArrayOutputStream msg = new ByteArrayOutputStream(); + msg.write(MHDR_UNCONFIRMED_UP); + msg.writeBytes(macPayload.toByteArray()); + byte[] msgBytes = msg.toByteArray(); + + byte[] mic = computeMic(nwkSKey, devAddrLe, fCnt, msgBytes); + + ByteArrayOutputStream phy = new ByteArrayOutputStream(); + phy.writeBytes(msgBytes); + phy.writeBytes(mic); + return phy.toByteArray(); + } + + // FRMPayload encryption per LoRaWAN spec (AES-128 of S blocks XORed with payload). + private static byte[] encryptPayload(byte[] appSKey, byte[] devAddrLe, int fCnt, byte[] payload) { + byte[] result = new byte[payload.length]; + int blocks = (payload.length + 15) / 16; + for (int i = 1; i <= blocks; i++) { + byte[] a = buildBlock((byte) 0x01, devAddrLe, fCnt, i); + byte[] s = aesEncryptBlock(appSKey, a); + int offset = (i - 1) * 16; + int len = Math.min(16, payload.length - offset); + for (int j = 0; j < len; j++) { + result[offset + j] = (byte) (payload[offset + j] ^ s[j]); + } + } + return result; + } + + // MIC = first 4 bytes of AES-CMAC(nwkSKey, B0 | msg). + private static byte[] computeMic(byte[] nwkSKey, byte[] devAddrLe, int fCnt, byte[] msg) { + byte[] b0 = buildBlock((byte) 0x49, devAddrLe, fCnt, msg.length); + + CMac cmac = new CMac(AESEngine.newInstance()); + cmac.init(new KeyParameter(nwkSKey)); + cmac.update(b0, 0, b0.length); + cmac.update(msg, 0, msg.length); + byte[] out = new byte[cmac.getMacSize()]; + cmac.doFinal(out, 0); + + byte[] mic = new byte[4]; + System.arraycopy(out, 0, mic, 0, 4); + return mic; + } + + // Builds the 16-byte A_i / B_0 block: 00 00 00 00 dir devAddr(LE) fCnt(LE,4) 00 . + // For A_i (encryption) is the block index; for B_0 (MIC) is the message length. + private static byte[] buildBlock(byte prefix, byte[] devAddrLe, int fCnt, int lastByte) { + byte[] fCntLe4 = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(fCnt).array(); + byte[] block = new byte[16]; + block[0] = prefix; + // bytes 1..4 are zero + block[5] = (byte) UPLINK_DIRECTION; + System.arraycopy(devAddrLe, 0, block, 6, 4); + System.arraycopy(fCntLe4, 0, block, 10, 4); + block[14] = 0x00; + block[15] = (byte) lastByte; + return block; + } + + private static byte[] aesEncryptBlock(byte[] key, byte[] block) { + AESEngine engine = (AESEngine) AESEngine.newInstance(); + engine.init(true, new KeyParameter(key)); + byte[] out = new byte[16]; + engine.processBlock(block, 0, out, 0); + return out; + } + + private static byte[] reverse(byte[] in) { + byte[] out = new byte[in.length]; + for (int i = 0; i < in.length; i++) { + out[i] = in[in.length - 1 - i]; + } + return out; + } +} diff --git a/msa/black-box-tests/src/test/resources/chirpstack/configuration/chirpstack/chirpstack.toml b/msa/black-box-tests/src/test/resources/chirpstack/configuration/chirpstack/chirpstack.toml new file mode 100644 index 0000000000..2c3db68997 --- /dev/null +++ b/msa/black-box-tests/src/test/resources/chirpstack/configuration/chirpstack/chirpstack.toml @@ -0,0 +1,50 @@ +# ChirpStack v4 configuration for black-box integration tests. +# Trimmed from the upstream brocaar/chirpstack-docker example: only the EU868 +# region is enabled to speed up startup. Hostnames are injected via the +# environment variables set in docker-compose.chirpstack.yml. + +# Logging. +[logging] + level="info" + + +# PostgreSQL configuration. +[postgresql] + dsn="postgres://chirpstack:chirpstack@$POSTGRESQL_HOST/chirpstack?sslmode=disable" + max_open_connections=10 + min_idle_connections=0 + + +# Redis configuration. +[redis] + servers=[ + "redis://$REDIS_HOST/", + ] + tls_enabled=false + cluster=false + + +# Network related configuration. +[network] + net_id="000000" + enabled_regions=[ + "eu868", + ] + + +# API interface configuration. +[api] + bind="0.0.0.0:8080" + secret="black-box-test-secret" + + +# Application integrations. The MQTT integration is left enabled (as in the +# upstream example) and points at the shared test broker; the per-application +# HTTP integration that forwards uplinks to ThingsBoard is created at runtime +# via the ChirpStack REST API. +[integration] + enabled=["mqtt"] + + [integration.mqtt] + server="tcp://$MQTT_BROKER_HOST:1883/" + json=true diff --git a/msa/black-box-tests/src/test/resources/chirpstack/configuration/chirpstack/region_eu868.toml b/msa/black-box-tests/src/test/resources/chirpstack/configuration/chirpstack/region_eu868.toml new file mode 100644 index 0000000000..c87f268ad1 --- /dev/null +++ b/msa/black-box-tests/src/test/resources/chirpstack/configuration/chirpstack/region_eu868.toml @@ -0,0 +1,280 @@ +# This file contains an example EU868 configuration. +[[regions]] + + # ID is an user-defined identifier for this region. + id="eu868" + + # Description is a short description for this region. + description="EU868" + + # Common-name refers to the common-name of this region as defined by + # the LoRa Alliance. + common_name="EU868" + + + # Gateway configuration. + [regions.gateway] + + # Force gateways as private. + # + # If enabled, gateways can only be used by devices under the same tenant. + force_gws_private=false + + + # Gateway backend configuration. + [regions.gateway.backend] + + # The enabled backend type. + enabled="mqtt" + + # MQTT configuration. + [regions.gateway.backend.mqtt] + + # Topic prefix. + # + # The topic prefix can be used to define the region of the gateway. + # Note, there is no need to add a trailing '/' to the prefix. The trailing + # '/' is automatically added to the prefix if it is configured. + topic_prefix="eu868" + + # MQTT server (e.g. scheme://host:port where scheme is tcp, ssl or ws) + server="tcp://$MQTT_BROKER_HOST:1883" + + # Connect with the given username (optional) + username="" + + # Connect with the given password (optional) + password="" + + # Quality of service level + # + # 0: at most once + # 1: at least once + # 2: exactly once + # + # Note: an increase of this value will decrease the performance. + # For more information: https://www.hivemq.com/blog/mqtt-essentials-part-6-mqtt-quality-of-service-levels + qos=0 + + # Clean session + # + # Set the "clean session" flag in the connect message when this client + # connects to an MQTT broker. By setting this flag you are indicating + # that no messages saved by the broker for this client should be delivered. + clean_session=false + + # Client ID + # + # Set the client id to be used by this client when connecting to the MQTT + # broker. A client id must be no longer than 23 characters. If left blank, + # a random id will be generated by ChirpStack. + client_id="" + + # Keep alive interval. + # + # This defines the maximum time that that should pass without communication + # between the client and server. + keep_alive_interval="30s" + + # CA certificate file (optional) + # + # Use this when setting up a secure connection (when server uses ssl://...) + # but the certificate used by the server is not trusted by any CA certificate + # on the server (e.g. when self generated). + ca_cert="" + + # TLS certificate file (optional) + tls_cert="" + + # TLS key file (optional) + tls_key="" + + + # Gateway channel configuration. + # + # Note: this configuration is only used in case the gateway is using the + # ChirpStack Concentratord daemon. In any other case, this configuration + # is ignored. + [[regions.gateway.channels]] + frequency=868100000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=868300000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=868500000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=867100000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=867300000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=867500000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=867700000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=867900000 + bandwidth=125000 + modulation="LORA" + spreading_factors=[7, 8, 9, 10, 11, 12] + + [[regions.gateway.channels]] + frequency=868300000 + bandwidth=250000 + modulation="LORA" + spreading_factors=[7] + + [[regions.gateway.channels]] + frequency=868800000 + bandwidth=125000 + modulation="FSK" + datarate=50000 + + + # Region specific network configuration. + [regions.network] + + # Installation margin (dB) used by the ADR engine. + # + # A higher number means that the network-server will keep more margin, + # resulting in a lower data-rate but decreasing the chance that the + # device gets disconnected because it is unable to reach one of the + # surrounded gateways. + installation_margin=10 + + # RX window (Class-A). + # + # Set this to: + # 0: RX1 / RX2 + # 1: RX1 only + # 2: RX2 only + rx_window=0 + + # RX1 delay (1 - 15 seconds). + rx1_delay=1 + + # RX1 data-rate offset + rx1_dr_offset=0 + + # RX2 data-rate + rx2_dr=0 + + # RX2 frequency (Hz) + rx2_frequency=869525000 + + # Prefer RX2 on RX1 data-rate less than. + # + # Prefer RX2 over RX1 based on the RX1 data-rate. When the RX1 data-rate + # is smaller than the configured value, then the Network Server will + # first try to schedule the downlink for RX2, failing that (e.g. the gateway + # has already a payload scheduled at the RX2 timing) it will try RX1. + rx2_prefer_on_rx1_dr_lt=0 + + # Prefer RX2 on link budget. + # + # When the link-budget is better for RX2 than for RX1, the Network Server will first + # try to schedule the downlink in RX2, failing that it will try RX1. + rx2_prefer_on_link_budget=false + + # Downlink TX Power (dBm) + # + # When set to -1, the downlink TX Power from the configured band will + # be used. + # + # Please consult the LoRaWAN Regional Parameters and local regulations + # for valid and legal options. Note that the configured TX Power must be + # supported by your gateway(s). + downlink_tx_power=-1 + + # ADR is disabled. + adr_disabled=false + + # Minimum data-rate. + min_dr=0 + + # Maximum data-rate. + max_dr=5 + + + # Rejoin-request configuration (LoRaWAN 1.1) + [regions.network.rejoin_request] + + # Request devices to periodically send rejoin-requests. + enabled=false + + # The device must send a rejoin-request type 0 at least every 2^(max_count_n + 4) + # uplink messages. Valid values are 0 to 15. + max_count_n=0 + + # The device must send a rejoin-request type 0 at least every 2^(max_time_n + 10) + # seconds. Valid values are 0 to 15. + # + # 0 = roughly 17 minutes + # 15 = about 1 year + max_time_n=0 + + + # Class-B configuration. + [regions.network.class_b] + + # Ping-slot data-rate. + ping_slot_dr=3 + + # Ping-slot frequency (Hz) + # + # set this to 0 to use the default frequency plan for the configured region + # (which could be frequency hopping). + ping_slot_frequency=0 + + + # Below is the common set of extra channels. Please make sure that these + # channels are also supported by the gateways. + [[regions.network.extra_channels]] + frequency=867100000 + min_dr=0 + max_dr=5 + + [[regions.network.extra_channels]] + frequency=867300000 + min_dr=0 + max_dr=5 + + [[regions.network.extra_channels]] + frequency=867500000 + min_dr=0 + max_dr=5 + + [[regions.network.extra_channels]] + frequency=867700000 + min_dr=0 + max_dr=5 + + [[regions.network.extra_channels]] + frequency=867900000 + min_dr=0 + max_dr=5 diff --git a/msa/black-box-tests/src/test/resources/chirpstack/configuration/postgresql/initdb/001-chirpstack_extensions.sh b/msa/black-box-tests/src/test/resources/chirpstack/configuration/postgresql/initdb/001-chirpstack_extensions.sh new file mode 100755 index 0000000000..4e96eb8d87 --- /dev/null +++ b/msa/black-box-tests/src/test/resources/chirpstack/configuration/postgresql/initdb/001-chirpstack_extensions.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# +# SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +# SPDX-License-Identifier: BUSL-1.1 +# + +set -e + +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname="$POSTGRES_DB" <<-EOSQL + create extension pg_trgm; + create extension hstore; +EOSQL diff --git a/msa/black-box-tests/src/test/resources/docker-compose.chirpstack.yml b/msa/black-box-tests/src/test/resources/docker-compose.chirpstack.yml new file mode 100644 index 0000000000..fef8c9543a --- /dev/null +++ b/msa/black-box-tests/src/test/resources/docker-compose.chirpstack.yml @@ -0,0 +1,51 @@ +# +# SPDX-FileCopyrightText: Copyright ThingsBoard, Inc. +# SPDX-License-Identifier: BUSL-1.1 +# + +# Real ChirpStack v4 LoRaWAN Network Server used by ChirpStackIntegrationTest. +# It shares the MQTT "broker" (mosquitto) defined in docker-compose.mosquitto.yml +# and lives on the same compose network as tb-http-integration, so ChirpStack +# can forward uplinks to ThingsBoard via its HTTP application integration. + +services: + chirpstack: + image: chirpstack/chirpstack:4 + restart: always + command: -c /etc/chirpstack + # Paths are relative to the compose project directory (docker/advanced), so the + # vendored config copied to /chirpstack is reached via "../chirpstack". + volumes: + - ../chirpstack/configuration/chirpstack:/etc/chirpstack + depends_on: + - chirpstack-postgres + - chirpstack-redis + - broker + environment: + MQTT_BROKER_HOST: broker + REDIS_HOST: chirpstack-redis + POSTGRESQL_HOST: chirpstack-postgres + + chirpstack-rest-api: + image: chirpstack/chirpstack-rest-api:4 + restart: always + command: --server chirpstack:8080 --bind 0.0.0.0:8090 --insecure + ports: + - "8090" + depends_on: + - chirpstack + + chirpstack-postgres: + image: postgres:14-alpine + restart: always + volumes: + - ../chirpstack/configuration/postgresql/initdb:/docker-entrypoint-initdb.d + environment: + POSTGRES_USER: chirpstack + POSTGRES_PASSWORD: chirpstack + POSTGRES_DB: chirpstack + + chirpstack-redis: + image: redis:7-alpine + restart: always + command: redis-server --save "" --appendonly no