-
Notifications
You must be signed in to change notification settings - Fork 214
/
HttpPushClientActorTest.java
391 lines (346 loc) · 18.7 KB
/
HttpPushClientActorTest.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*
* Copyright (c) 2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.connectivity.service.messaging.httppush;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.connectivity.api.BaseClientState;
import org.eclipse.ditto.connectivity.model.ClientCertificateCredentials;
import org.eclipse.ditto.connectivity.model.Connection;
import org.eclipse.ditto.connectivity.model.ConnectivityStatus;
import org.eclipse.ditto.connectivity.model.OAuthClientCredentials;
import org.eclipse.ditto.connectivity.model.Target;
import org.eclipse.ditto.connectivity.model.signals.commands.exceptions.ConnectionFailedException;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.CloseConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.OpenConnection;
import org.eclipse.ditto.connectivity.model.signals.commands.modify.TestConnection;
import org.eclipse.ditto.connectivity.service.messaging.AbstractBaseClientActorTest;
import org.eclipse.ditto.connectivity.service.messaging.TestConstants;
import org.eclipse.ditto.connectivity.service.messaging.internal.ssl.SSLContextCreator;
import org.eclipse.ditto.connectivity.service.messaging.monitoring.logs.ConnectionLogger;
import org.eclipse.ditto.internal.utils.pekko.ActorSystemResource;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.protocol.ProtocolFactory;
import org.eclipse.ditto.protocol.adapter.DittoProtocolAdapter;
import org.eclipse.ditto.protocol.adapter.ProtocolAdapter;
import org.eclipse.ditto.things.model.signals.events.ThingModifiedEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValueFactory;
import org.apache.pekko.NotUsed;
import org.apache.pekko.actor.ActorRef;
import org.apache.pekko.actor.ActorSystem;
import org.apache.pekko.actor.Props;
import org.apache.pekko.actor.Status;
import org.apache.pekko.http.javadsl.ConnectionContext;
import org.apache.pekko.http.javadsl.Http;
import org.apache.pekko.http.javadsl.HttpsConnectionContext;
import org.apache.pekko.http.javadsl.ServerBinding;
import org.apache.pekko.http.javadsl.model.ContentTypes;
import org.apache.pekko.http.javadsl.model.HttpHeader;
import org.apache.pekko.http.javadsl.model.HttpMethods;
import org.apache.pekko.http.javadsl.model.HttpRequest;
import org.apache.pekko.http.javadsl.model.HttpResponse;
import org.apache.pekko.http.javadsl.model.StatusCodes;
import org.apache.pekko.stream.SystemMaterializer;
import org.apache.pekko.stream.javadsl.Flow;
import org.apache.pekko.testkit.javadsl.TestKit;
import org.apache.pekko.util.ByteString;
/**
* Tests {@link HttpPushClientActor}.
*/
@RunWith(MockitoJUnitRunner.class)
public final class HttpPushClientActorTest extends AbstractBaseClientActorTest {
private static final ProtocolAdapter ADAPTER = DittoProtocolAdapter.newInstance();
@Rule
public final ActorSystemResource actorSystemResource = ActorSystemResource.newInstance(
TestConstants.CONFIG.withValue(
"ditto.connectivity.connection.http-push.blocked-hostnames",
ConfigValueFactory.fromAnyRef("")
)
);
private ActorSystem actorSystem;
private Flow<HttpRequest, HttpResponse, NotUsed> handler;
private ServerBinding binding;
private Connection connection;
private BlockingQueue<HttpRequest> requestQueue;
private BlockingQueue<HttpResponse> responseQueue;
@Mock
private ConnectionLogger connectionLogger;
@Before
public void createActorSystem() {
// create actor system with deactivated hostname blocklist to connect to localhost
actorSystem = ActorSystem.create(getClass().getSimpleName(),
TestConstants.CONFIG.withValue("ditto.connectivity.connection.http-push.blocked-hostnames",
ConfigValueFactory.fromAnyRef("")));
requestQueue = new LinkedBlockingQueue<>();
responseQueue = new LinkedBlockingQueue<>();
handler = Flow.fromFunction(request -> {
requestQueue.offer(request);
return responseQueue.take();
});
binding = Http.get(actorSystem)
.newServerAt("127.0.0.1", 0)
.bindFlow(handler)
.toCompletableFuture()
.join();
connection = getHttpConnectionBuilderToLocalBinding(false, binding.localAddress().getPort()).build();
}
@After
public void stopActorSystem() {
if (actorSystem != null) {
actorSystem.terminate();
}
}
@Override
protected Connection getConnection(final boolean isSecure) {
return isSecure ? setScheme(connection, "https") : connection;
}
@Override
protected Props createClientActor(final ActorRef proxyActor, final Connection connection) {
return HttpPushClientActor.props(connection, proxyActor, proxyActor, dittoHeaders, ConfigFactory.empty());
}
@Override
protected ActorSystem getActorSystem() {
return actorSystemResource.getActorSystem();
}
@Test
public void connectAndDisconnect() {
new TestKit(actorSystem) {{
final Props props = createClientActor(getRef(), getConnection(false));
final ActorRef underTest = actorSystem.actorOf(props);
underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef());
expectMsg(new Status.Success(BaseClientState.CONNECTED));
underTest.tell(CloseConnection.of(connection.getId(), DittoHeaders.empty()), getRef());
expectMsg(new Status.Success(BaseClientState.DISCONNECTED));
}};
}
@Test
public void testTCPConnection() {
new TestKit(actorSystem) {{
final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
expectMsg(new Status.Success("successfully connected + initialized mapper"));
expectTerminated(underTest);
}};
}
@Test
public void testTCPConnectionFails() {
new TestKit(actorSystem) {{
binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
final Status.Failure failure = expectMsgClass(Status.Failure.class);
assertThat(failure.cause()).isInstanceOf(ConnectionFailedException.class);
expectTerminated(underTest);
}};
}
@Test
public void testTLSConnectionFails() {
// GIVEN: server has a self-signed certificate
connection = getHttpConnectionBuilderToLocalBinding(true, binding.localAddress().getPort()).build();
final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
.clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
.clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
.build();
final SSLContext sslContext =
SSLContextCreator.fromConnection(connection, DittoHeaders.empty(), connectionLogger)
.clientCertificate(credentials);
final HttpsConnectionContext invalidHttpsContext = ConnectionContext.httpsServer(sslContext);
final int port = binding.localAddress().getPort();
binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
binding = Http.get(actorSystem)
.newServerAt("127.0.0.1", port)
.enableHttps(invalidHttpsContext)
.bindFlow(handler)
.toCompletableFuture()
.join();
new TestKit(actorSystem) {{
// WHEN: the connection is tested
final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
// THEN: the test fails
final Status.Failure failure = expectMsgClass(Status.Failure.class);
assertThat(failure.cause()).isInstanceOf(DittoRuntimeException.class);
assertThat(((DittoRuntimeException) failure.cause()).getDescription().orElse(""))
.contains("unable to find valid certification path");
expectTerminated(underTest);
}};
}
@Test
public void testTLSConnection() {
// GIVEN: server has a self-signed certificate
final ClientCertificateCredentials credentials = ClientCertificateCredentials.newBuilder()
.clientKey(TestConstants.Certificates.CLIENT_SELF_SIGNED_KEY)
.clientCertificate(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
.build();
connection = getHttpConnectionBuilderToLocalBinding(true, binding.localAddress().getPort())
.credentials(credentials)
.trustedCertificates(TestConstants.Certificates.CLIENT_SELF_SIGNED_CRT)
.build();
final SSLContext sslContext =
SSLContextCreator.fromConnection(connection, DittoHeaders.empty(), connectionLogger)
.clientCertificate(credentials);
final HttpsConnectionContext httpsContext = ConnectionContext.httpsServer(sslContext);
final int port = binding.localAddress().getPort();
binding.terminate(Duration.ofMillis(1L)).toCompletableFuture().join();
binding = Http.get(actorSystem)
.newServerAt("127.0.0.1", port)
.enableHttps(httpsContext)
.bindFlow(handler)
.toCompletableFuture()
.join();
new TestKit(actorSystem) {{
// WHEN: the connection is tested
final ActorRef underTest = watch(actorSystem.actorOf(createClientActor(getRef(), getConnection(false))));
underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
// THEN: the connection is connected successfully
expectMsg(new Status.Success("successfully connected + initialized mapper"));
expectTerminated(underTest);
}};
}
@Test
public void testInvalidTokenResponse() {
new TestKit(actorSystem) {{
// GIVEN: connection has oauth2 credentials
final var originalConnection = getConnection(false);
final var connection = originalConnection.toBuilder()
.connectionStatus(ConnectivityStatus.CLOSED)
.credentials(OAuthClientCredentials.newBuilder()
.tokenEndpoint(originalConnection.getUri())
.clientId("clientId")
.clientSecret("clientSecret")
.scope("scope")
.build())
.build();
final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), connection));
// GIVEN: token endpoint delivers invalid token response
responseQueue.add(HttpResponse.create().withStatus(404));
// WHEN: a connection test is requested
underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
// THEN: test fails.
final var failure = expectMsgClass(Status.Failure.class);
assertThat(failure.cause()).isInstanceOf(ConnectionFailedException.class);
}};
}
@Test
public void testValidTokenResponse() {
new TestKit(actorSystem) {{
// GIVEN: connection has oauth2 credentials
final var originalConnection = getConnection(false);
final var connection = originalConnection.toBuilder()
.connectionStatus(ConnectivityStatus.CLOSED)
.credentials(OAuthClientCredentials.newBuilder()
.tokenEndpoint(originalConnection.getUri())
.clientId("clientId")
.clientSecret("clientSecret")
.scope("scope")
.build())
.build();
final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), connection));
// GIVEN: token endpoint delivers valid token response
final String accessToken = "ewogICJhbGciOiAiUlMyNTYiLAogICJ0eXAiOiAiSldUIgp9.ewogICJhdWQiOiBbXSwKICAiY2x" +
"pZW50X2lkIjogIm15LWNsaWVudC1pZCIsCiAgImV4cCI6IDMyNTAzNjgwMDAwLAogICJleHQiOiB7fSwKICAiaWF0IjogMC" +
"wKICAiaXNzIjogImh0dHBzOi8vbG9jYWxob3N0LyIsCiAgImp0aSI6ICI3ODVlODBjZC1lNmU2LTQ1MmEtYmU5Ny1hNTljN" +
"TNlZGI0ZDkiLAogICJuYmYiOiAwLAogICJzY3AiOiBbCiAgICAibXktc2NvcGUiCiAgXSwKICAic3ViIjogIm15LXN1Ympl" +
"Y3QiCn0.QUJD";
responseQueue.add(HttpResponse.create()
.withStatus(200)
.withEntity(ContentTypes.APPLICATION_JSON, ByteString.fromString("{\n" +
" \"access_token\": \"" + accessToken + "\",\n" +
" \"expires_in\": 1048576,\n" +
" \"scope\": \"my-scope\",\n" +
" \"token_type\": \"bearer\"\n" +
"}"))
);
// WHEN: a connection test is requested
underTest.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
// THEN: test succeeds
expectMsgClass(Status.Success.class);
}};
}
@Test
public void publishTwinEvent() throws Exception {
new TestKit(actorSystem) {{
// GIVEN: local HTTP connection is connected
final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), getConnection(false)));
underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef());
expectMsg(new Status.Success(BaseClientState.CONNECTED));
final String customHeaderKey = "custom-header";
final String customHeaderValue = "custom-value";
// WHEN: a thing event is sent to a target with header mapping content-type=application/json
final ThingModifiedEvent<?> thingModifiedEvent = TestConstants.thingModified(Collections.emptyList())
.setDittoHeaders(DittoHeaders.newBuilder()
.correlationId("internal-correlation-id")
.readGrantedSubjects(HTTP_TARGET.getAuthorizationContext().getAuthorizationSubjects())
.putHeader(customHeaderKey, customHeaderValue)
.build());
underTest.tell(thingModifiedEvent, getRef());
// THEN: a POST-request is forwarded to the path defined in the target
final HttpRequest thingModifiedRequest = requestQueue.poll(10L, TimeUnit.SECONDS);
assertThat(thingModifiedRequest).isNotNull();
responseQueue.offer(HttpResponse.create().withStatus(StatusCodes.OK));
assertThat(thingModifiedRequest.method()).isEqualTo(HttpMethods.POST);
assertThat(thingModifiedRequest.getUri().getPathString()).isEqualTo("/target/address");
// THEN: only headers in the header mapping are retained
assertThat(thingModifiedRequest.entity().getContentType()).isEqualTo(ContentTypes.APPLICATION_JSON);
assertThat(thingModifiedRequest.getHeader("correlation-id"))
.contains(HttpHeader.parse("correlation-id", "internal-correlation-id"));
assertThat(thingModifiedRequest.getHeader(customHeaderKey)).isEmpty();
// THEN: the payload is the JSON string of the event as a Ditto protocol message
// Remove headers, since the header order can be different.
assertThat(ProtocolFactory.jsonifiableAdaptableFromJson(JsonObject.of(thingModifiedRequest
.entity()
.toStrict(10_000, SystemMaterializer.get(actorSystem).materializer())
.toCompletableFuture()
.join()
.getData()
.utf8String())).setDittoHeaders(DittoHeaders.empty()).toJsonString()).isEqualTo(
ProtocolFactory.wrapAsJsonifiableAdaptable(ADAPTER.toAdaptable(thingModifiedEvent))
.setDittoHeaders(DittoHeaders.empty()).toJsonString());
}};
}
@Test
public void placeholderReplacement() throws Exception {
final Target target = TestConstants.Targets.TARGET_WITH_PLACEHOLDER
.withAddress("PATCH:" + TestConstants.Targets.TARGET_WITH_PLACEHOLDER.getAddress());
connection = connection.toBuilder().setTargets(singletonList(target)).build();
new TestKit(actorSystem) {{
// GIVEN: local HTTP connection is connected
final ActorRef underTest = actorSystem.actorOf(createClientActor(getRef(), connection));
underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), getRef());
expectMsg(new Status.Success(BaseClientState.CONNECTED));
// WHEN: a thing event is sent to a target with header mapping content-type=application/json
final ThingModifiedEvent<?> thingModifiedEvent =
TestConstants.thingModified(target.getAuthorizationContext().getAuthorizationSubjects());
underTest.tell(thingModifiedEvent, getRef());
// THEN: a POST-request is forwarded to the path defined in the target
final HttpRequest thingModifiedRequest = requestQueue.poll(10, TimeUnit.SECONDS);
responseQueue.offer(HttpResponse.create().withStatus(StatusCodes.OK));
assertThat(thingModifiedRequest.getUri().getPathString()).isEqualTo("/target:ditto/thing@twin");
}};
}
}