/
MqttValidator.java
259 lines (224 loc) · 10.7 KB
/
MqttValidator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/*
* Copyright (c) 2017-2018 Bosch Software Innovations GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/index.php
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.services.connectivity.messaging.mqtt;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.eclipse.ditto.model.base.exceptions.DittoRuntimeException;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.connectivity.Connection;
import org.eclipse.ditto.model.connectivity.ConnectionConfigurationInvalidException;
import org.eclipse.ditto.model.connectivity.ConnectionType;
import org.eclipse.ditto.model.connectivity.Enforcement;
import org.eclipse.ditto.model.connectivity.MqttSource;
import org.eclipse.ditto.model.connectivity.MqttTarget;
import org.eclipse.ditto.model.connectivity.Source;
import org.eclipse.ditto.model.connectivity.Target;
import org.eclipse.ditto.services.connectivity.messaging.validation.AbstractProtocolValidator;
import org.eclipse.ditto.services.models.connectivity.placeholder.EnforcementFactoryFactory;
import org.eclipse.ditto.services.models.connectivity.placeholder.PlaceholderFilter;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import akka.stream.alpakka.mqtt.MqttQoS;
/**
* Connection specification for Mqtt protocol.
*/
@Immutable
public final class MqttValidator extends AbstractProtocolValidator {
private static final String INVALID_TOPIC_FORMAT = "The provided topic ''{0}'' is not valid: {1}";
private static final String QOS = "qos";
private static final Collection<String> ACCEPTED_SCHEMES =
Collections.unmodifiableList(Arrays.asList("tcp", "ssl", "ws", "wss"));
private static final String ERROR_DESCRIPTION = "''{0}'' is not a valid value for mqtt enforcement. Valid" +
" values " +
"are: ''{1}''.";
/**
* Create a new {@code MqttConnectionSpec}.
*
* @return a new instance.
*/
public static MqttValidator newInstance() {
return new MqttValidator();
}
@Override
public ConnectionType type() {
return ConnectionType.MQTT;
}
@Override
public void validate(final Connection connection, final DittoHeaders dittoHeaders) {
validateUriScheme(connection, dittoHeaders, ACCEPTED_SCHEMES, "MQTT 3.1.1");
validateUriByPaho(connection, dittoHeaders);
validateAddresses(connection, dittoHeaders);
validateSourceConfigs(connection, dittoHeaders);
validateTargetConfigs(connection, dittoHeaders);
}
@Override
protected void validateSource(final Source source, final DittoHeaders dittoHeaders,
final Supplier<String> sourceDescription) {
if (!(source instanceof MqttSource)) {
final String message =
MessageFormat.format("Source {0} must be of type MqttSource.", sourceDescription.get());
throw ConnectionConfigurationInvalidException.newBuilder(message)
.dittoHeaders(dittoHeaders)
.build();
}
final MqttSource mqttSource = (MqttSource) source;
validateSourceQoS(mqttSource.getQos(), dittoHeaders, sourceDescription);
validateSourceEnforcement(mqttSource.getEnforcement(), dittoHeaders, sourceDescription);
}
@Override
protected void validateTarget(final Target target, final DittoHeaders dittoHeaders,
final Supplier<String> targetDescription) {
if (!(target instanceof MqttTarget)) {
final String message =
MessageFormat.format("Target {0} must be of type MqttTarget.", targetDescription.get());
throw ConnectionConfigurationInvalidException.newBuilder(message)
.dittoHeaders(dittoHeaders)
.build();
}
final org.eclipse.ditto.model.connectivity.MqttTarget mqttTarget =
(org.eclipse.ditto.model.connectivity.MqttTarget) target;
validateTargetQoS(mqttTarget.getQos(), dittoHeaders, targetDescription);
}
/**
* Retrieve quality of service from a validated specific config with "at-most-once" as default.
*
* @param qos th configured qos value.
* @return quality of service.
*/
static MqttQoS getQoS(final int qos) {
switch (qos) {
case 1:
return MqttQoS.atLeastOnce();
case 2:
return MqttQoS.exactlyOnce();
default:
return MqttQoS.atMostOnce();
}
}
private static void validateSourceEnforcement(@Nullable final Enforcement enforcement,
final DittoHeaders dittoHeaders, final Supplier<String> sourceDescription) {
if (enforcement != null) {
validateEnforcementOrigin(enforcement, sourceDescription);
final String dummyThingId = "namespace:name";
final Map<String, String> filtersMap = PlaceholderFilter.filterAddressesAsMap(enforcement.getFilters(),
dummyThingId, filter -> {
throw invalidValueForConfig(filter, "filters", sourceDescription.get())
.description("Placeholder substitution failed. " +
"Please check the placeholder variables against the documentation.")
.dittoHeaders(dittoHeaders)
.build();
});
filtersMap.forEach((filter, mqttTopic) ->
validateMqttTopic(mqttTopic, true, errorMessage ->
invalidValueForConfig(filter, "filters", sourceDescription.get())
.description(
"The filter is not a valid MQTT topic after placeholder substitution. " +
"Wildcard characters are allowed.")
.dittoHeaders(dittoHeaders)
.build()));
}
}
private static void validateEnforcementOrigin(final Enforcement enforcement,
final Supplier<String> sourceDescription) {
try {
EnforcementFactoryFactory
.newThingIdEnforcementFactory(enforcement, TopicPlaceholder.INSTANCE)
.getFilter("dummyTopic");
} catch (final DittoRuntimeException e) {
throw invalidValueForConfig(enforcement.getInput(), "origin", sourceDescription.get())
.cause(e)
.description(MessageFormat.format(ERROR_DESCRIPTION, enforcement.getInput(),
TopicPlaceholder.VALID_VALUES))
.build();
}
}
/*
* MQTT Source does not support exactly-once delivery.
*/
private static void validateSourceQoS(final int qos,
final DittoHeaders dittoHeaders,
final Supplier<String> errorSiteDescription) {
validateQoS(qos, dittoHeaders, errorSiteDescription, i -> 0 <= i && i <= 2);
}
/*
* MQTT Sink supports quality-of-service 0, 1, 2.
*/
private static void validateTargetQoS(final int qos,
final DittoHeaders dittoHeaders,
final Supplier<String> errorSiteDescription) {
validateQoS(qos, dittoHeaders, errorSiteDescription, i -> 0 <= i && i <= 2);
}
private static void validateQoS(final int qos, final DittoHeaders dittoHeaders,
final Supplier<String> errorSiteDescription, final Predicate<Integer> predicate) {
if (!predicate.test(qos)) {
throw invalidValueForConfig(qos, QOS, errorSiteDescription.get())
.dittoHeaders(dittoHeaders)
.build();
}
}
private static void validateAddresses(final Connection connection, final DittoHeaders dittoHeaders) {
connection.getSources()
.stream()
.flatMap(source -> source.getAddresses().stream())
.forEach(a -> validateAddress(a, true, dittoHeaders));
// no wildcards allowed for publish targets
connection.getTargets()
.stream()
.map(Target::getAddress)
.forEach(a -> validateAddress(a, false, dittoHeaders));
}
private static void validateAddress(final String address, final boolean wildcardAllowed,
final DittoHeaders dittoHeaders) {
validateMqttTopic(address, wildcardAllowed, errorMessage -> {
final String message = MessageFormat.format(INVALID_TOPIC_FORMAT, address, errorMessage);
return ConnectionConfigurationInvalidException.newBuilder(message)
.dittoHeaders(dittoHeaders)
.build();
});
}
private static void validateMqttTopic(final String address, final boolean wildcardAllowed,
final Function<String, DittoRuntimeException> errorProducer) {
try {
MqttTopic.validate(address, wildcardAllowed);
} catch (final IllegalArgumentException e) {
throw errorProducer.apply(e.getMessage());
}
}
private static void validateUriByPaho(final Connection connection, final DittoHeaders dittoHeaders) {
try {
MqttConnectOptions.validateURI(connection.getUri());
} catch (final IllegalArgumentException e) {
final String location = String.format("Connection with ID ''%s''", connection.getId());
final String configName = Connection.JsonFields.URI.getPointer().toString();
final String description =
"Hint: MQTT connection URI may not have trailing '/' or any other path component.";
throw invalidValueForConfig(connection.getUri(), configName, location)
.description(description)
.dittoHeaders(dittoHeaders)
.build();
}
}
private static ConnectionConfigurationInvalidException.Builder invalidValueForConfig(final Object value,
final String configName,
final String location) {
final String message = MessageFormat.format("Invalid value ''{0}'' for configuration ''{1}'' in {2}",
value, configName, location);
return ConnectionConfigurationInvalidException.newBuilder(message);
}
}