-
Notifications
You must be signed in to change notification settings - Fork 215
/
SmartChannelSelectionTest.java
286 lines (258 loc) · 14 KB
/
SmartChannelSelectionTest.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
/*
* Copyright (c) 2022 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.things.service.enforcement;
import static org.assertj.core.api.Assertions.assertThat;
import static org.eclipse.ditto.policies.model.PoliciesResourceType.THING;
import static org.eclipse.ditto.policies.model.SubjectIssuer.GOOGLE;
import java.time.Duration;
import java.util.UUID;
import java.util.function.Consumer;
import org.assertj.core.api.Assertions;
import org.eclipse.ditto.base.model.auth.AuthorizationContext;
import org.eclipse.ditto.base.model.auth.AuthorizationSubject;
import org.eclipse.ditto.base.model.auth.DittoAuthorizationContextType;
import org.eclipse.ditto.base.model.headers.DittoHeaderDefinition;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.headers.DittoHeadersBuilder;
import org.eclipse.ditto.base.model.headers.WithDittoHeaders;
import org.eclipse.ditto.base.model.json.FieldType;
import org.eclipse.ditto.base.model.json.JsonSchemaVersion;
import org.eclipse.ditto.base.model.signals.Signal;
import org.eclipse.ditto.base.model.signals.commands.exceptions.CommandTimeoutException;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonPointer;
import org.eclipse.ditto.policies.api.commands.sudo.SudoRetrievePolicyResponse;
import org.eclipse.ditto.policies.model.Permissions;
import org.eclipse.ditto.policies.model.PoliciesModelFactory;
import org.eclipse.ditto.policies.model.PoliciesResourceType;
import org.eclipse.ditto.policies.model.PolicyId;
import org.eclipse.ditto.things.api.Permission;
import org.eclipse.ditto.things.api.commands.sudo.SudoRetrieveThingResponse;
import org.eclipse.ditto.things.model.ThingIdInvalidException;
import org.eclipse.ditto.things.model.signals.commands.ThingErrorResponse;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingNotAccessibleException;
import org.eclipse.ditto.things.model.signals.commands.query.RetrieveThing;
import org.eclipse.ditto.things.model.signals.commands.query.RetrieveThingResponse;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.typesafe.config.ConfigFactory;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.cluster.pubsub.DistributedPubSubMediator;
import akka.testkit.TestActorRef;
import akka.testkit.javadsl.TestKit;
/**
* Tests {@link ThingCommandEnforcement} in context of an {@code EnforcerActor} for commands requiring smart channel
* selection.
*/
public final class SmartChannelSelectionTest {
private static final String LIVE_COMMANDS_PUB_SUB_TOPIC = "things-live-commands";
@Rule
public final TestName testName = new TestName();
private ActorSystem system;
private MockEntitiesActor mockEntitiesActorInstance;
private ActorRef mockEntitiesActor;
private JsonObject thing;
@Before
public void init() {
system = ActorSystem.create("test", ConfigFactory.load("test"));
final TestActorRef<MockEntitiesActor> testActorRef =
new TestActorRef<>(system, MockEntitiesActor.props(), system.guardian(), UUID.randomUUID().toString());
mockEntitiesActorInstance = testActorRef.underlyingActor();
mockEntitiesActor = testActorRef;
final PolicyId policyId = PolicyId.of("policy:id");
thing = TestSetup.newThingWithPolicyId(policyId);
final JsonObject policy = PoliciesModelFactory.newPolicyBuilder(policyId)
.setRevision(1L)
.forLabel("authorize-self")
.setSubject(GOOGLE, TestSetup.SUBJECT_ID)
.setGrantedPermissions(PoliciesResourceType.thingResource(JsonPointer.empty()),
Permissions.newInstance(Permission.READ, Permission.WRITE))
.build()
.toJson(FieldType.all());
final SudoRetrieveThingResponse sudoRetrieveThingResponse =
SudoRetrieveThingResponse.of(thing, DittoHeaders.empty());
final SudoRetrievePolicyResponse sudoRetrievePolicyResponse =
SudoRetrievePolicyResponse.of(policyId, policy, DittoHeaders.empty());
mockEntitiesActorInstance.setReply(TestSetup.THING_SUDO, sudoRetrieveThingResponse);
mockEntitiesActorInstance.setReply(TestSetup.POLICY_SUDO, sudoRetrievePolicyResponse);
}
@After
public void shutdown() {
if (system != null) {
TestKit.shutdownActorSystem(system);
}
}
@Test
public void thingNotAccessibleAfterEnforcement() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.liveChannelCondition("exists(thingId)"));
mockEntitiesActorInstance.setReply(THING,
ThingNotAccessibleException.newBuilder(retrieveThing.getEntityId())
.dittoHeaders(retrieveThing.getDittoHeaders())
.build());
underTest.tell(retrieveThing, getRef());
TestSetup.fishForMsgClass(this, ThingNotAccessibleException.class);
}};
}
@Test
public void matchLiveChannelCondition() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.liveChannelCondition("exists(thingId)"));
mockEntitiesActorInstance.setReply(THING, getRetrieveThingResponse(retrieveThing, true, b -> {}));
underTest.tell(retrieveThing, getRef());
final var publish = TestSetup.fishForMsgClass(this, DistributedPubSubMediator.Publish.class);
Assertions.assertThat(publish.topic()).isEqualTo(LIVE_COMMANDS_PUB_SUB_TOPIC);
Assertions.assertThat(publish.message()).isInstanceOf(RetrieveThing.class);
assertLiveChannel(RetrieveThing.class, publish.message());
reply(getRetrieveThingResponse(retrieveThing, true, b -> b.channel("live")));
assertLiveChannel(expectMsgClass(RetrieveThingResponse.class));
}};
}
@Test
public void liveChannelTimeoutWithTwinFallback() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.liveChannelCondition("exists(thingId)")
.timeout(Duration.ofMillis(1))
.putHeader(DittoHeaderDefinition.LIVE_CHANNEL_TIMEOUT_STRATEGY.getKey(), "use-twin"));
final var twinResponse = getRetrieveThingResponse(retrieveThing, true, b -> {});
mockEntitiesActorInstance.setReply(THING, twinResponse);
underTest.tell(retrieveThing, getRef());
TestSetup.fishForMsgClass(this, DistributedPubSubMediator.Publish.class);
assertTwinChannel(expectMsgClass(RetrieveThingResponse.class));
}};
}
@Test
public void liveChannelErrorWithTwinFallback() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.liveChannelCondition("exists(thingId)")
.putHeader(DittoHeaderDefinition.LIVE_CHANNEL_TIMEOUT_STRATEGY.getKey(), "use-twin"));
final var twinResponse = getRetrieveThingResponse(retrieveThing, true, b -> {});
mockEntitiesActorInstance.setReply(THING, twinResponse);
underTest.tell(retrieveThing, getRef());
TestSetup.fishForMsgClass(this, DistributedPubSubMediator.Publish.class);
reply(ThingErrorResponse.of(ThingIdInvalidException.newBuilder(retrieveThing.getEntityId())
.dittoHeaders(DittoHeaders.newBuilder().channel("live").build())
.build()));
final var receivedErrorResponse = expectMsgClass(ThingErrorResponse.class);
assertLiveChannel(receivedErrorResponse);
Assertions.assertThat(receivedErrorResponse.getDittoRuntimeException()).isInstanceOf(ThingIdInvalidException.class);
}};
}
@Test
public void liveChannelTimeoutWithoutTwinFallback() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.liveChannelCondition("exists(thingId)")
.timeout(Duration.ofMillis(1)));
final var twinResponse = getRetrieveThingResponse(retrieveThing, true, b -> {});
mockEntitiesActorInstance.setReply(THING, twinResponse);
underTest.tell(retrieveThing, getRef());
TestSetup.fishForMsgClass(this, DistributedPubSubMediator.Publish.class);
assertLiveChannel(expectMsgClass(CommandTimeoutException.class));
}};
}
@Test
public void liveChannelConditionMismatch() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.liveChannelCondition("exists(thingId)")
.timeout(Duration.ofMillis(1)));
final var twinResponse = getRetrieveThingResponse(retrieveThing, false, b -> {});
mockEntitiesActorInstance.setReply(THING, twinResponse);
underTest.tell(retrieveThing, getRef());
final var response = TestSetup.fishForMsgClass(this, RetrieveThingResponse.class);
assertTwinChannel(response);
Assertions.assertThat(response.getDittoHeaders().didLiveChannelConditionMatch()).isFalse();
}};
}
@Test
public void liveCommandTimeoutWithTwinFallback() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.channel("live")
.timeout(Duration.ofMillis(1))
.putHeader(DittoHeaderDefinition.LIVE_CHANNEL_TIMEOUT_STRATEGY.getKey(), "use-twin"));
final var twinResponse = getRetrieveThingResponse(retrieveThing, true, b -> {});
mockEntitiesActorInstance.setReply(THING, twinResponse);
underTest.tell(retrieveThing, getRef());
TestSetup.fishForMsgClass(this, DistributedPubSubMediator.Publish.class);
assertTwinChannel(expectMsgClass(RetrieveThingResponse.class));
}};
}
@Test
public void liveCommandErrorWithTwinFallback() {
new TestKit(system) {{
final ActorRef underTest = newEnforcerActor(getRef());
final var retrieveThing = getRetrieveThing(headers -> headers.channel("live")
.putHeader(DittoHeaderDefinition.LIVE_CHANNEL_TIMEOUT_STRATEGY.getKey(), "use-twin"));
final var twinResponse = getRetrieveThingResponse(retrieveThing, true, b -> {});
mockEntitiesActorInstance.setReply(THING, twinResponse);
underTest.tell(retrieveThing, getRef());
TestSetup.fishForMsgClass(this, DistributedPubSubMediator.Publish.class);
reply(ThingErrorResponse.of(ThingIdInvalidException.newBuilder(retrieveThing.getEntityId())
.dittoHeaders(DittoHeaders.newBuilder().channel("live").build())
.build()));
final var receivedErrorResponse = expectMsgClass(ThingErrorResponse.class);
assertLiveChannel(receivedErrorResponse);
Assertions.assertThat(receivedErrorResponse.getDittoRuntimeException()).isInstanceOf(ThingIdInvalidException.class);
}};
}
private ActorRef newEnforcerActor(final ActorRef testActorRef) {
return TestSetup.newEnforcerActor(system, testActorRef, mockEntitiesActor);
}
private DittoHeaders headers() {
return DittoHeaders.newBuilder()
.authorizationContext(
AuthorizationContext.newInstance(DittoAuthorizationContextType.UNSPECIFIED, TestSetup.SUBJECT,
AuthorizationSubject.newInstance(String.format("%s:%s", GOOGLE, TestSetup.SUBJECT_ID))))
.correlationId(testName.getMethodName())
.schemaVersion(JsonSchemaVersion.V_2)
.build();
}
private RetrieveThing getRetrieveThing(final Consumer<DittoHeadersBuilder<?, ?>> headerModifier) {
final DittoHeadersBuilder<?, ?> builder = headers().toBuilder();
headerModifier.accept(builder);
return RetrieveThing.of(TestSetup.THING_ID, builder.build());
}
private RetrieveThingResponse getRetrieveThingResponse(final RetrieveThing retrieveThing,
final boolean liveChannelConditionMatched, final Consumer<DittoHeadersBuilder<?, ?>> headerModifier) {
final var builder = retrieveThing.getDittoHeaders()
.toBuilder()
.putHeader(DittoHeaderDefinition.LIVE_CHANNEL_CONDITION_MATCHED.getKey(),
String.valueOf(liveChannelConditionMatched));
headerModifier.accept(builder);
return RetrieveThingResponse.of(retrieveThing.getEntityId(), thing, builder.build());
}
private void assertLiveChannel(final Class<? extends WithDittoHeaders> clazz, final Object message) {
assertThat(message).isInstanceOf(clazz);
Assertions.assertThat(Signal.isChannelLive(clazz.cast(message)))
.describedAs("Expect live channel: " + message)
.isTrue();
}
private void assertLiveChannel(final WithDittoHeaders signal) {
assertLiveChannel(WithDittoHeaders.class, signal);
}
private void assertTwinChannel(final Signal<?> signal) {
assertThat(signal.getDittoHeaders().getChannel().orElse("twin"))
.describedAs("Expect twin channel: " + signal)
.isEqualTo("twin");
}
}