-
Notifications
You must be signed in to change notification settings - Fork 215
/
ThingCommandEnforcement.java
1105 lines (992 loc) · 56.5 KB
/
ThingCommandEnforcement.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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 java.util.Objects.requireNonNull;
import static org.eclipse.ditto.policies.api.Permission.MIN_REQUIRED_POLICY_PERMISSIONS;
import static org.eclipse.ditto.things.service.enforcement.LiveSignalEnforcement.addEffectedReadSubjectsToThingLiveSignal;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.eclipse.ditto.base.model.auth.AuthorizationContext;
import org.eclipse.ditto.base.model.auth.AuthorizationSubject;
import org.eclipse.ditto.base.model.exceptions.AskException;
import org.eclipse.ditto.base.model.exceptions.DittoJsonException;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.exceptions.EntityNotCreatableException;
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.DittoHeadersSettable;
import org.eclipse.ditto.base.model.headers.LiveChannelTimeoutStrategy;
import org.eclipse.ditto.base.model.headers.contenttype.ContentType;
import org.eclipse.ditto.base.model.json.JsonSchemaVersion;
import org.eclipse.ditto.base.model.namespaces.NamespaceBlockedException;
import org.eclipse.ditto.base.model.signals.FeatureToggle;
import org.eclipse.ditto.base.model.signals.Signal;
import org.eclipse.ditto.base.model.signals.commands.CommandToExceptionRegistry;
import org.eclipse.ditto.base.model.signals.commands.ErrorResponse;
import org.eclipse.ditto.base.model.signals.commands.exceptions.DittoInternalErrorException;
import org.eclipse.ditto.base.model.signals.commands.exceptions.GatewayCommandTimeoutException;
import org.eclipse.ditto.internal.models.signal.CommandHeaderRestoration;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLogger;
import org.eclipse.ditto.internal.utils.cacheloaders.AskWithRetry;
import org.eclipse.ditto.internal.utils.pubsub.LiveSignalPub;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonFieldSelector;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonObjectBuilder;
import org.eclipse.ditto.json.JsonPointer;
import org.eclipse.ditto.json.JsonPointerInvalidException;
import org.eclipse.ditto.json.JsonRuntimeException;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.policies.api.Permission;
import org.eclipse.ditto.policies.api.PoliciesValidator;
import org.eclipse.ditto.policies.enforcement.AbstractEnforcementReloaded;
import org.eclipse.ditto.policies.enforcement.CreationRestrictionEnforcer;
import org.eclipse.ditto.policies.enforcement.LiveResponseAndAcknowledgementForwarder;
import org.eclipse.ditto.policies.enforcement.PolicyEnforcer;
import org.eclipse.ditto.policies.enforcement.PreEnforcer;
import org.eclipse.ditto.policies.enforcement.config.EnforcementConfig;
import org.eclipse.ditto.policies.enforcement.placeholders.references.PolicyIdReferencePlaceholderResolver;
import org.eclipse.ditto.policies.enforcement.placeholders.references.ReferencePlaceholder;
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.Policy;
import org.eclipse.ditto.policies.model.PolicyException;
import org.eclipse.ditto.policies.model.PolicyId;
import org.eclipse.ditto.policies.model.ResourceKey;
import org.eclipse.ditto.policies.model.Subject;
import org.eclipse.ditto.policies.model.SubjectId;
import org.eclipse.ditto.policies.model.enforcers.Enforcer;
import org.eclipse.ditto.policies.model.enforcers.PolicyEnforcers;
import org.eclipse.ditto.policies.model.signals.commands.PolicyErrorResponse;
import org.eclipse.ditto.policies.model.signals.commands.exceptions.PolicyConflictException;
import org.eclipse.ditto.policies.model.signals.commands.exceptions.PolicyNotAccessibleException;
import org.eclipse.ditto.policies.model.signals.commands.exceptions.PolicyUnavailableException;
import org.eclipse.ditto.policies.model.signals.commands.modify.CreatePolicy;
import org.eclipse.ditto.policies.model.signals.commands.modify.CreatePolicyResponse;
import org.eclipse.ditto.policies.model.signals.commands.query.RetrievePolicy;
import org.eclipse.ditto.policies.model.signals.commands.query.RetrievePolicyResponse;
import org.eclipse.ditto.rql.model.ParserException;
import org.eclipse.ditto.rql.model.predicates.ast.RootNode;
import org.eclipse.ditto.rql.parser.RqlPredicateParser;
import org.eclipse.ditto.rql.query.things.FieldNamesPredicateVisitor;
import org.eclipse.ditto.things.model.Thing;
import org.eclipse.ditto.things.model.ThingConstants;
import org.eclipse.ditto.things.model.ThingId;
import org.eclipse.ditto.things.model.signals.commands.ThingCommand;
import org.eclipse.ditto.things.model.signals.commands.ThingCommandResponse;
import org.eclipse.ditto.things.model.signals.commands.exceptions.LiveChannelConditionNotAllowedException;
import org.eclipse.ditto.things.model.signals.commands.exceptions.PolicyIdNotAllowedException;
import org.eclipse.ditto.things.model.signals.commands.exceptions.PolicyInvalidException;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingCommandToAccessExceptionRegistry;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingCommandToModifyExceptionRegistry;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingConditionFailedException;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingConditionInvalidException;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingNotAccessibleException;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingNotCreatableException;
import org.eclipse.ditto.things.model.signals.commands.exceptions.ThingNotModifiableException;
import org.eclipse.ditto.things.model.signals.commands.modify.CreateThing;
import org.eclipse.ditto.things.model.signals.commands.modify.MergeThing;
import org.eclipse.ditto.things.model.signals.commands.modify.ModifyThing;
import org.eclipse.ditto.things.model.signals.commands.modify.ThingModifyCommand;
import org.eclipse.ditto.things.model.signals.commands.query.RetrieveFeature;
import org.eclipse.ditto.things.model.signals.commands.query.RetrieveThing;
import org.eclipse.ditto.things.model.signals.commands.query.ThingQueryCommand;
import org.eclipse.ditto.things.model.signals.commands.query.ThingQueryCommandResponse;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.pattern.AskTimeoutException;
import akka.pattern.Patterns;
/**
* Authorizes {@link ThingCommand}s and filters {@link ThingCommandResponse}s.
*/
public final class ThingCommandEnforcement
extends AbstractEnforcementReloaded<ThingCommand<?>, ThingCommandResponse<?>> {
private static final ThreadSafeDittoLogger LOGGER =
DittoLoggerFactory.getThreadSafeLogger(ThingCommandEnforcement.class);
private static final Map<String, ThreadSafeDittoLogger> NAMESPACE_INSPECTION_LOGGERS = new HashMap<>();
/**
* Label of default policy entry in default policy.
*/
private static final String DEFAULT_POLICY_ENTRY_LABEL = "DEFAULT";
/**
* Json fields that are always shown regardless of authorization.
*/
private static final JsonFieldSelector THING_QUERY_COMMAND_RESPONSE_ALLOWLIST =
JsonFactory.newFieldSelector(Thing.JsonFields.ID);
private final ActorRef ackReceiverActor;
private final ActorRef policiesShardRegion;
private final PreEnforcer preEnforcer;
private final PolicyIdReferencePlaceholderResolver policyIdReferencePlaceholderResolver;
private final CreationRestrictionEnforcer creationRestrictionEnforcer;
private final LiveSignalPub liveSignalPub;
private final ActorSystem actorSystem;
private final EnforcementConfig enforcementConfig;
private final ResponseReceiverCache responseReceiverCache;
/**
* Creates a new instance of the thing command enforcer.
*
* @param actorSystem
* @param ackReceiverActor
* @param policiesShardRegion the policies shard region to load policies from and to use in order to create new
* (inline) policies when creating new things.
* @param creationRestrictionEnforcer the CreationRestrictionEnforcer to apply in order to enforce creation of new
* things based on its config.
* @param enforcementConfig the configuration to apply for this command enforcement implementation.
* @param preEnforcer
* @param liveSignalPub
*/
public ThingCommandEnforcement(final ActorSystem actorSystem,
final ActorRef ackReceiverActor,
final ActorRef policiesShardRegion,
final CreationRestrictionEnforcer creationRestrictionEnforcer,
final EnforcementConfig enforcementConfig,
final PreEnforcer preEnforcer,
final LiveSignalPub liveSignalPub) {
this.actorSystem = actorSystem;
this.ackReceiverActor = requireNonNull(ackReceiverActor);
this.policiesShardRegion = requireNonNull(policiesShardRegion);
this.creationRestrictionEnforcer = creationRestrictionEnforcer;
this.enforcementConfig = enforcementConfig;
enforcementConfig.getSpecialLoggingInspectedNamespaces()
.forEach(loggedNamespace -> NAMESPACE_INSPECTION_LOGGERS.put(
loggedNamespace,
DittoLoggerFactory.getThreadSafeLogger(ThingCommandEnforcement.class.getName() +
".namespace." + loggedNamespace)));
this.preEnforcer = preEnforcer;
policyIdReferencePlaceholderResolver =
PolicyIdReferencePlaceholderResolver.of(policiesShardRegion, enforcementConfig.getAskWithRetryConfig(),
actorSystem.getScheduler(), actorSystem.getDispatcher()); // TODO TJ need to configure different executor?
this.liveSignalPub = liveSignalPub;
responseReceiverCache = ResponseReceiverCache.lookup(actorSystem);
}
/**
* @return the policies shard region which this things specific enforcement received during construction.
*/
public ActorRef getPoliciesShardRegion() {
return policiesShardRegion;
}
@Override
public CompletionStage<ThingCommand<?>> authorizeSignal(final ThingCommand<?> thingCommand,
final PolicyEnforcer enforcer) {
final ThingCommand<?> authorizedCommand;
if (isWotTdRequestingThingQueryCommand(thingCommand)) {
// authorization is not necessary for WoT TD requesting thing query command, this is treated as public
// information:
FeatureToggle.checkWotIntegrationFeatureEnabled(thingCommand.getType(), thingCommand.getDittoHeaders());
// for retrieving the WoT TD, assume that full TD gets returned unfiltered:
authorizedCommand = prepareThingCommandBeforeSendingToPersistence(thingCommand);
} else {
final ThingCommand<?> commandWithReadSubjects = authorizeByPolicyOrThrow(enforcer.getEnforcer(), thingCommand);
if (commandWithReadSubjects instanceof ThingQueryCommand<?> thingQueryCommand) {
authorizedCommand = ensureTwinChannel(thingQueryCommand);
} else if (commandWithReadSubjects.getDittoHeaders().getLiveChannelCondition().isPresent()) {
throw LiveChannelConditionNotAllowedException.newBuilder()
.dittoHeaders(commandWithReadSubjects.getDittoHeaders())
.build();
} else {
authorizedCommand = prepareThingCommandBeforeSendingToPersistence(commandWithReadSubjects);
}
}
return CompletableFuture.completedStage(authorizedCommand);
}
@Override
public CompletionStage<ThingCommand<?>> authorizeSignalWithMissingEnforcer(final ThingCommand<?> signal) {
// Without prior enforcer in cache, enforce CreateThing by self.
// DO NOT use Contextual.askFuture to handle the ask-steps of a CreateThing command! Otherwise
// the query- and modify-commands sent immediately after may be processed before the thing is created.
return enforceCreateThingBySelf(signal)
.thenCompose(this::handleInitialCreateThing)
.exceptionally(throwable -> {
final ThreadSafeDittoLogger l = LOGGER.withCorrelationId(signal);
final var dittoRuntimeException =
DittoRuntimeException.asDittoRuntimeException(throwable, cause -> {
l.warn("Error during thing by itself enforcement - {}: {}",
cause.getClass().getSimpleName(), cause.getMessage());
throw DittoInternalErrorException.newBuilder()
.cause(cause)
.build();
});
l.debug("DittoRuntimeException during enforceThingCommandByNonexistentEnforcer - {}: {}",
dittoRuntimeException.getClass().getSimpleName(), dittoRuntimeException.getMessage());
throw dittoRuntimeException;
});
}
@Override
public CompletionStage<ThingCommandResponse<?>> filterResponse(final ThingCommandResponse<?> commandResponse,
final PolicyEnforcer policyEnforcer) {
if (commandResponse instanceof ThingQueryCommandResponse<?> thingQueryCommandResponse) {
try {
return CompletableFuture.completedStage(
buildJsonViewForThingQueryCommandResponse(thingQueryCommandResponse,
policyEnforcer.getEnforcer())
);
} catch (final RuntimeException e) {
throw reportError("Error after building JsonView", e, commandResponse.getDittoHeaders());
}
} else {
// no filtering required for non ThingQueryCommandResponse:
return CompletableFuture.completedStage(commandResponse);
}
}
private boolean isWotTdRequestingThingQueryCommand(final ThingCommand<?> thingCommand) {
// all listed thingCommand types here must handle "Accept: application/td+json", otherwise access control
// will be bypassed when using the header "Accept: application/td+json"!
return (thingCommand instanceof RetrieveThing || thingCommand instanceof RetrieveFeature) &&
thingCommand.getDittoHeaders().getAccept()
.filter(ContentType.APPLICATION_TD_JSON.getValue()::equals)
.isPresent();
}
/**
* TODO TJ move where? and call from where and when?
* @param command
* @param response
* @param startTime
* @param policyEnforcer
* @return
*/
private CompletionStage<ThingQueryCommandResponse<?>> doSmartChannelSelection(final ThingQueryCommand<?> command,
final ThingQueryCommandResponse<?> response, final Instant startTime, final PolicyEnforcer policyEnforcer) {
final ThingQueryCommandResponse<?> twinResponseWithTwinChannel = setTwinChannel(response);
final ThingQueryCommandResponse<?> twinResponse = CommandHeaderRestoration.restoreCommandConnectivityHeaders(
twinResponseWithTwinChannel, command.getDittoHeaders());
if (!shouldAttemptLiveChannel(command, twinResponse)) {
return CompletableFuture.completedStage(twinResponse);
}
final ThingQueryCommand<?> liveCommand = toLiveCommand(command, policyEnforcer.getEnforcer());
final var pub = liveSignalPub.command();
final var liveResponseForwarder = startLiveResponseForwarder(liveCommand);
if (enforcementConfig.shouldDispatchGlobally(liveCommand)) {
return responseReceiverCache.insertResponseReceiverConflictFreeWithFuture(
liveCommand,
newCommand -> liveResponseForwarder,
(newCommand, forwarder) ->
LiveSignalEnforcement.adjustTimeoutAndFilterLiveQueryResponse(this,
newCommand,
startTime,
pub,
forwarder,
policyEnforcer,
getFallbackResponseCaster(liveCommand, twinResponse)
)
);
} else {
return LiveSignalEnforcement.adjustTimeoutAndFilterLiveQueryResponse(this,
liveCommand,
startTime,
pub,
liveResponseForwarder,
policyEnforcer,
getFallbackResponseCaster(liveCommand, twinResponse)
);
}
}
private ActorRef startLiveResponseForwarder(final ThingQueryCommand<?> signal) {
final var pub = liveSignalPub.command();
final var props = LiveResponseAndAcknowledgementForwarder.props(signal, pub.getPublisher(),
ackReceiverActor);
return actorSystem.actorOf(props); // TODO TJ check if we should really create a root level actor here
}
private Function<Object, CompletionStage<ThingQueryCommandResponse<?>>> getFallbackResponseCaster(
final ThingQueryCommand<?> liveCommand, final ThingQueryCommandResponse<?> twinResponse) {
return response -> {
if (response instanceof ThingQueryCommandResponse) {
return CompletableFuture.completedStage(
setAdditionalHeaders((ThingQueryCommandResponse<?>) response, liveCommand.getDittoHeaders()));
} else if (response instanceof ErrorResponse) {
throw setAdditionalHeaders(((ErrorResponse<?>) response),
liveCommand.getDittoHeaders()).getDittoRuntimeException();
} else if (response instanceof AskException || response instanceof AskTimeoutException) {
return applyTimeoutStrategy(liveCommand, twinResponse);
} else {
final var errorToReport = reportErrorOrResponse(
"before building JsonView for live response via smart channel selection",
response, null, liveCommand.getDittoHeaders());
throw errorToReport;
}
};
}
private static boolean shouldAttemptLiveChannel(final ThingQueryCommand<?> command,
final ThingQueryCommandResponse<?> twinResponse) {
return isLiveChannelConditionMatched(command, twinResponse) || isLiveQueryCommandWithTimeoutStrategy(command);
}
private static boolean isLiveChannelConditionMatched(final ThingQueryCommand<?> command,
final ThingQueryCommandResponse<?> twinResponse) {
return command.getDittoHeaders().getLiveChannelCondition().isPresent() &&
twinResponse.getDittoHeaders().didLiveChannelConditionMatch();
}
static boolean isLiveQueryCommandWithTimeoutStrategy(final Signal<?> command) {
return command instanceof ThingQueryCommand &&
command.getDittoHeaders().getLiveChannelTimeoutStrategy().isPresent() &&
Signal.isChannelLive(command);
}
private static <T extends DittoHeadersSettable<?>> T setAdditionalHeaders(final T settable,
final DittoHeaders commandHeaders) {
final DittoHeaders dittoHeaders = settable.getDittoHeaders();
final DittoHeadersSettable<?> theSettable = settable.setDittoHeaders(dittoHeaders
.toBuilder()
.putHeaders(getAdditionalLiveResponseHeaders(dittoHeaders))
.build());
return (T) CommandHeaderRestoration.restoreCommandConnectivityHeaders(theSettable, commandHeaders);
}
private static CompletionStage<ThingQueryCommandResponse<?>> applyTimeoutStrategy(
final ThingCommand<?> command,
final ThingQueryCommandResponse<?> twinResponse) {
if (isTwinFallbackEnabled(twinResponse)) {
return CompletableFuture.completedStage(twinResponse);
} else {
final var timeout = LiveSignalEnforcement.getLiveSignalTimeout(command);
final GatewayCommandTimeoutException timeoutException = GatewayCommandTimeoutException.newBuilder(timeout)
.dittoHeaders(twinResponse.getDittoHeaders()
.toBuilder()
.channel(Signal.CHANNEL_LIVE)
.putHeaders(getAdditionalLiveResponseHeaders(twinResponse.getDittoHeaders()))
.build())
.build();
final GatewayCommandTimeoutException timeoutExceptionWithConnectivityHeaders =
CommandHeaderRestoration.restoreCommandConnectivityHeaders(timeoutException,
command.getDittoHeaders());
return CompletableFuture.failedStage(timeoutExceptionWithConnectivityHeaders);
}
}
private static boolean isTwinFallbackEnabled(final Signal<?> signal) {
final var liveChannelFallbackStrategy =
signal.getDittoHeaders().getLiveChannelTimeoutStrategy().orElse(LiveChannelTimeoutStrategy.FAIL);
return LiveChannelTimeoutStrategy.USE_TWIN == liveChannelFallbackStrategy;
}
private static ThingQueryCommand<?> toLiveCommand(final ThingQueryCommand<?> command, final Enforcer enforcer) {
final ThingQueryCommand<?> withReadSubjects = addEffectedReadSubjectsToThingLiveSignal(command, enforcer);
return withReadSubjects.setDittoHeaders(withReadSubjects.getDittoHeaders().toBuilder()
.liveChannelCondition(null)
.channel(Signal.CHANNEL_LIVE)
.build());
}
/**
* Query caches again to authorize a {@code CreateThing} command with explicit policy ID and no inline policy.
*
* @param command the command.
* @param policyId the policy ID.
* @return the completionStage of contextual including message and receiver
*/
private CompletionStage<ThingCommand<?>> enforceCreateThingForNonexistentThingWithPolicyId(
final CreateThing command, final PolicyId policyId) {
if (null != policyEnforcerLoader) {
return policyEnforcerLoader.apply(policyId)
.thenCompose(policyEnforcer -> {
if (null != policyEnforcer) {
return authorizeSignal(command, policyEnforcer);
} else {
throw errorForExistingThingWithDeletedPolicy(command, command.getEntityId(), policyId);
}
});
} else {
LOGGER.withCorrelationId(command)
.error("PolicyEnforcerLoader was not present in order to load a PolicyEnforcer.");
throw new IllegalStateException("PolicyEnforcerLoader was absent");
}
}
/**
* Limit view on entity of {@code ThingQueryCommandResponse} by enforcer.
*
* @param response the response.
* @param enforcer the enforcer.
* @return response with view on entity restricted by enforcer.
*/
static <T extends ThingQueryCommandResponse<T>> T buildJsonViewForThingQueryCommandResponse(
final ThingQueryCommandResponse<T> response, final Enforcer enforcer) {
final JsonValue entity = response.getEntity();
if (entity.isObject()) {
final JsonObject filteredView =
getJsonViewForThingQueryCommandResponse(entity.asObject(), response, enforcer);
return response.setEntity(filteredView);
} else {
return response.setEntity(entity);
}
}
/**
* Prepares a passed in {@code authorizedThingCommand} before sending it to the persistence.
*
* @param authorizedThingCommand command to prepare.
* @return the passed in authorizedThingCommand.
*/
private ThingCommand<?> prepareThingCommandBeforeSendingToPersistence(final ThingCommand<?> authorizedThingCommand) {
if (NAMESPACE_INSPECTION_LOGGERS.containsKey(authorizedThingCommand.getEntityId().getNamespace())) {
final ThreadSafeDittoLogger namespaceLogger = NAMESPACE_INSPECTION_LOGGERS
.get(authorizedThingCommand.getEntityId().getNamespace()).withCorrelationId(authorizedThingCommand);
if (authorizedThingCommand instanceof ThingModifyCommand) {
final JsonValue value = ((ThingModifyCommand<?>) authorizedThingCommand).getEntity().orElse(null);
if (null != value) {
final Set<ResourceKey> resourceKeys = calculateLeaves(authorizedThingCommand.getResourcePath(), value);
namespaceLogger.info("Forwarding modify command type <{}> with resourceKeys <{}>",
authorizedThingCommand.getType(),
resourceKeys);
}
}
namespaceLogger
.debug("Forwarding command type <{}>: <{}>", authorizedThingCommand.getType(), authorizedThingCommand);
}
return authorizedThingCommand;
}
/**
* Restrict view on a JSON object by enforcer.
*
* @param responseEntity the JSON object to restrict view on.
* @param response the response containing the object.
* @param enforcer the enforcer.
* @return JSON object with view restricted by enforcer.
*/
private static JsonObject getJsonViewForThingQueryCommandResponse(final JsonObject responseEntity,
final ThingQueryCommandResponse<?> response, final Enforcer enforcer) {
final var resourceKey = ResourceKey.newInstance(ThingConstants.ENTITY_TYPE, response.getResourcePath());
final var authorizationContext = response.getDittoHeaders().getAuthorizationContext();
return enforcer.buildJsonView(resourceKey, responseEntity, authorizationContext,
THING_QUERY_COMMAND_RESPONSE_ALLOWLIST, Permissions.newInstance(Permission.READ));
}
/**
* Create error for commands to an existing thing whose policy is deleted.
*
* @param thingCommand the triggering command.
* @param thingId ID of the thing.
* @param policyId ID of the deleted policy.
* @return an appropriate error.
*/
private static DittoRuntimeException errorForExistingThingWithDeletedPolicy(final ThingCommand<?> thingCommand,
final ThingId thingId, final CharSequence policyId) {
final var message = String.format(
"The Thing with ID '%s' could not be accessed as its Policy with ID '%s' is not or no longer existing.",
thingId, policyId);
final var description = String.format(
"Recreate/create the Policy with ID '%s' in order to get access to the Thing again.",
policyId);
if (thingCommand instanceof ThingModifyCommand) {
return ThingNotModifiableException.newBuilder(thingId)
.message(message)
.description(description)
.dittoHeaders(thingCommand.getDittoHeaders())
.build();
} else {
return ThingNotAccessibleException.newBuilder(thingId)
.message(message)
.description(description)
.dittoHeaders(thingCommand.getDittoHeaders())
.build();
}
}
/**
* Create error due to failing to execute a thing-command in the expected way.
*
* @param thingCommand the command.
* @return the error.
*/
static DittoRuntimeException errorForThingCommand(final ThingCommand<?> thingCommand) {
final CommandToExceptionRegistry<ThingCommand<?>, DittoRuntimeException> registry =
thingCommand instanceof ThingModifyCommand
? ThingCommandToModifyExceptionRegistry.getInstance()
: ThingCommandToAccessExceptionRegistry.getInstance();
return registry.exceptionFrom(thingCommand);
}
/**
* Authorize a thing-command by authorization information contained in itself. Only {@code CreateThing} commands are
* authorized in this manner in the absence of an existing enforcer. {@code ModifyThing} commands are transformed to
* {@code CreateThing} commands before being processed.
*
* @param command the incoming command which needs to be a {@link CreateThing} to be handled in this function.
* @return a CompletionStage of the authorized {@link CreateThing} command extended by read subjects or a failed
* CompletionStage with a DittoRuntimeException as cause.
*/
private CompletionStage<CreateThing> enforceCreateThingBySelf(final ThingCommand<?> command) {
final ThingCommand<?> thingCommand = transformModifyThingToCreateThing(command);
if (thingCommand instanceof CreateThing createThingCommand) {
final var enforcerContext = new CreationRestrictionEnforcer.Context(command.getResourceType(),
command.getEntityId().getNamespace(),
command.getDittoHeaders()
);
if (creationRestrictionEnforcer.canCreate(enforcerContext)) {
return replaceInitialPolicyWithCopiedPolicyIfPresent(createThingCommand)
.thenApply(createThing -> {
final Optional<JsonObject> initialPolicyOptional = createThing.getInitialPolicy();
return initialPolicyOptional.map(initialPolicy ->
enforceCreateThingByOwnInlinedPolicyOrThrow(createThing, initialPolicy)
).orElseGet(() -> enforceCreateThingByAuthorizationContext(createThing));
});
} else {
throw EntityNotCreatableException.newBuilder(createThingCommand.getEntityId())
.dittoHeaders(createThingCommand.getDittoHeaders())
.build();
}
} else {
// Other commands cannot be authorized by policy contained in self.
final DittoRuntimeException error;
if (thingCommand instanceof ThingModifyCommand) {
error = ThingNotModifiableException.newBuilder(thingCommand.getEntityId())
.dittoHeaders(thingCommand.getDittoHeaders())
.build();
} else {
error = ThingNotAccessibleException.newBuilder(thingCommand.getEntityId())
.dittoHeaders(thingCommand.getDittoHeaders())
.build();
}
LOGGER.withCorrelationId(command)
.info("Enforcer was not existing for Thing <{}> and no auth info was inlined, responding with: {} - {}",
thingCommand.getEntityId(), error.getClass().getSimpleName(), error.getMessage());
throw error;
}
}
private CompletionStage<CreateThing> replaceInitialPolicyWithCopiedPolicyIfPresent(final CreateThing createThing) {
return getInitialPolicyOrCopiedPolicy(createThing)
.thenApply(initialPolicyOrCopiedPolicy ->
CreateThing.of(createThing.getThing(), initialPolicyOrCopiedPolicy,
createThing.getDittoHeaders()));
}
private CompletionStage<JsonObject> getInitialPolicyOrCopiedPolicy(final CreateThing createThing) {
final ThreadSafeDittoLogger l = LOGGER.withCorrelationId(createThing);
return createThing.getPolicyIdOrPlaceholder()
.flatMap(ReferencePlaceholder::fromCharSequence)
.map(referencePlaceholder -> {
l.debug("CreateThing command contains a reference placeholder for the policy it wants to copy: {}",
referencePlaceholder);
final var dittoHeadersWithoutPreconditionHeaders = createThing.getDittoHeaders().toBuilder()
.removePreconditionHeaders()
.responseRequired(true)
.build();
return policyIdReferencePlaceholderResolver.resolve(referencePlaceholder,
dittoHeadersWithoutPreconditionHeaders);
})
.orElseGet(() -> CompletableFuture.completedFuture(createThing.getPolicyIdOrPlaceholder().orElse(null)))
.thenCompose(policyId -> {
if (policyId != null) {
l.debug("CreateThing command wants to use a copy of Policy <{}>", policyId);
return retrievePolicyWithEnforcement(createThing.getDittoHeaders(), PolicyId.of(policyId))
.thenApply(policy -> policy.toJson(JsonSchemaVersion.V_2).remove("policyId"));
} else {
l.debug("CreateThing command did not contain a policy that should be copied.");
return CompletableFuture.completedFuture(createThing.getInitialPolicy().orElse(null));
}
});
}
private CompletionStage<Policy> retrievePolicyWithEnforcement(final DittoHeaders dittoHeaders,
final PolicyId policyId) {
final var adjustedHeaders = dittoHeaders.toBuilder()
.removePreconditionHeaders()
.responseRequired(true)
.build();
return AskWithRetry.askWithRetry(policiesShardRegion, RetrievePolicy.of(policyId, adjustedHeaders),
enforcementConfig.getAskWithRetryConfig(), actorSystem.getScheduler(), actorSystem.getDispatcher(), // TODO TJ need to make scheduler and dispatcher configurable?
response -> {
if (response instanceof RetrievePolicyResponse rpr) {
return rpr.getPolicy();
} else if (response instanceof PolicyErrorResponse per) {
throw per.getDittoRuntimeException();
} else if (response instanceof DittoRuntimeException dre) {
throw dre;
} else {
LOGGER.withCorrelationId(adjustedHeaders)
.error("Got an unexpected response while retrieving a Policy that should be copied" +
" during Thing creation: {}", response);
throw DittoInternalErrorException.newBuilder().build();
}
});
}
private static CreateThing enforceCreateThingByAuthorizationContext(final CreateThing createThing) {
// Command without authorization information is authorized by default.
final var dittoHeaders = createThing.getDittoHeaders();
final var authorizationContext = dittoHeaders.getAuthorizationContext();
final Set<AuthorizationSubject> authorizedSubjects = authorizationContext.getFirstAuthorizationSubject()
.map(Collections::singleton)
.orElse(Collections.emptySet());
final Enforcer enforcer = new AuthorizedSubjectsEnforcer(
AuthorizationContext.newInstance(authorizationContext.getType(), authorizedSubjects));
return addEffectedReadSubjectsToThingSignal(createThing, enforcer);
}
private CreateThing enforceCreateThingByOwnInlinedPolicyOrThrow(final CreateThing createThing,
final JsonObject inlinedPolicy) {
final var initialPolicy = getInitialPolicy(createThing, inlinedPolicy);
final var policiesValidator = PoliciesValidator.newInstance(initialPolicy);
if (policiesValidator.isValid()) {
final var initialEnforcer = PolicyEnforcers.defaultEvaluator(initialPolicy);
return authorizeByPolicyOrThrow(initialEnforcer, createThing);
} else {
throw PolicyInvalidException.newBuilder(MIN_REQUIRED_POLICY_PERMISSIONS, createThing.getEntityId())
.dittoHeaders(createThing.getDittoHeaders())
.build();
}
}
@SuppressWarnings("java:S1193")
private Policy getInitialPolicy(final CreateThing createThing, final JsonObject inlinedPolicy) {
try {
// Java doesn't permit conversion of this early return into assignment to final variable.
return PoliciesModelFactory.newPolicy(inlinedPolicy);
} catch (final JsonRuntimeException | DittoJsonException e) {
final var thingId = createThing.getEntityId();
throw PolicyInvalidException.newBuilderForCause(e, thingId)
.dittoHeaders(createThing.getDittoHeaders())
.build();
} catch (final DittoRuntimeException e) {
final var dittoHeaders = createThing.getDittoHeaders();
// PolicyException is an interface!
if (e instanceof PolicyException) {
// user error; no need to log stack trace.
throw e.setDittoHeaders(dittoHeaders);
} else {
throw reportError("Error during creation of inline policy from JSON", e,
createThing.getDittoHeaders());
}
}
}
/**
* Transform a {@code ModifyThing} command sent to nonexistent thing to {@code CreateThing} command if it is sent to
* a nonexistent thing.
*
* @param receivedCommand the command to transform.
* @return {@code CreateThing} command containing the same information if the argument is a {@code ModifyThing}
* command. Otherwise return the command itself.
*/
private static ThingCommand<?> transformModifyThingToCreateThing(final ThingCommand<?> receivedCommand) {
if (receivedCommand instanceof ModifyThing modifyThing) {
final JsonObject initialPolicy = modifyThing.getInitialPolicy().orElse(null);
final String policyIdOrPlaceholder = modifyThing.getPolicyIdOrPlaceholder().orElse(null);
final var newThing = modifyThing.getThing().toBuilder()
.setId(modifyThing.getEntityId())
.build();
return CreateThing.of(newThing, initialPolicy, policyIdOrPlaceholder, modifyThing.getDittoHeaders());
} else {
return receivedCommand;
}
}
/**
* Authorize a thing-command by a policy enforcer.
*
* @param <T> type of the thing-command.
* @param policyEnforcer the policy enforcer.
* @param command the command to authorize.
* @return optionally the authorized command extended by read subjects.
*/
static <T extends ThingCommand<T>> T authorizeByPolicyOrThrow(final Enforcer policyEnforcer,
final ThingCommand<T> command) {
final var thingResourceKey = PoliciesResourceType.thingResource(command.getResourcePath());
final var dittoHeaders = command.getDittoHeaders();
final var authorizationContext = dittoHeaders.getAuthorizationContext();
final boolean commandAuthorized;
if (command instanceof MergeThing mergeThing) {
commandAuthorized = enforceMergeThingCommand(policyEnforcer, mergeThing, thingResourceKey,
authorizationContext);
} else if (command instanceof ThingModifyCommand) {
commandAuthorized = policyEnforcer.hasUnrestrictedPermissions(thingResourceKey, authorizationContext,
Permission.WRITE);
} else {
commandAuthorized =
policyEnforcer.hasPartialPermissions(thingResourceKey, authorizationContext, Permission.READ);
}
final var condition = dittoHeaders.getCondition();
if (!(command instanceof CreateThing) && condition.isPresent()) {
enforceReadPermissionOnCondition(condition.get(), policyEnforcer, dittoHeaders, () ->
ThingConditionFailedException.newBuilderForInsufficientPermission(dittoHeaders).build());
}
final var liveChannelCondition = dittoHeaders.getLiveChannelCondition();
if ((command instanceof ThingQueryCommand) && liveChannelCondition.isPresent()) {
enforceReadPermissionOnCondition(liveChannelCondition.get(), policyEnforcer, dittoHeaders, () ->
ThingConditionFailedException.newBuilderForInsufficientLiveChannelPermission(dittoHeaders).build());
}
if (commandAuthorized) {
return addEffectedReadSubjectsToThingSignal(command, policyEnforcer);
} else {
throw errorForThingCommand(command);
}
}
/**
* Extend a signal by subject headers given with granted and revoked READ access.
* The subjects are provided by the given enforcer for the resource type {@link ThingConstants#ENTITY_TYPE}.
*
* @param signal the signal to extend.
* @param enforcer the enforcer.
* @return the extended signal.
*/
static <T extends Signal<T>> T addEffectedReadSubjectsToThingSignal(final Signal<T> signal,
final Enforcer enforcer) {
final var resourceKey = ResourceKey.newInstance(ThingConstants.ENTITY_TYPE, signal.getResourcePath());
final var authorizationSubjects = enforcer.getSubjectsWithUnrestrictedPermission(resourceKey, Permission.READ);
final var newHeaders = DittoHeaders.newBuilder(signal.getDittoHeaders())
.readGrantedSubjects(authorizationSubjects)
.build();
return signal.setDittoHeaders(newHeaders);
}
private static void enforceReadPermissionOnCondition(final String condition,
final Enforcer policyEnforcer,
final DittoHeaders dittoHeaders,
final Supplier<DittoRuntimeException> exceptionSupplier) {
final var authorizationContext = dittoHeaders.getAuthorizationContext();
final var rootNode = tryParseRqlCondition(condition, dittoHeaders);
final var resourceKeys = determineResourceKeys(rootNode, dittoHeaders);
if (!policyEnforcer.hasUnrestrictedPermissions(resourceKeys, authorizationContext, Permission.READ)) {
throw exceptionSupplier.get();
}
}
private static RootNode tryParseRqlCondition(final String condition, final DittoHeaders dittoHeaders) {
try {
return RqlPredicateParser.getInstance().parse(condition);
} catch (final ParserException e) {
throw ThingConditionInvalidException.newBuilder(condition, e.getMessage())
.dittoHeaders(dittoHeaders)
.build();
}
}
private static Set<ResourceKey> determineResourceKeys(final RootNode rootNode, final DittoHeaders dittoHeaders) {
final var visitor = FieldNamesPredicateVisitor.getNewInstance();
visitor.visit(rootNode);
final var extractedFieldNames = visitor.getFieldNames();
return extractedFieldNames.stream()
.map(fieldName -> tryGetResourceKey(fieldName, dittoHeaders))
.collect(Collectors.toSet());
}
private static ResourceKey tryGetResourceKey(final String fieldName, final DittoHeaders dittoHeaders) {
try {
return PoliciesResourceType.thingResource(fieldName);
} catch (final JsonPointerInvalidException e) {
throw ThingConditionInvalidException.newBuilder(fieldName, e.getDescription().orElse(""))
.dittoHeaders(dittoHeaders)
.build();
}
}
private static boolean enforceMergeThingCommand(final Enforcer policyEnforcer,
final MergeThing command, final ResourceKey thingResourceKey,
final AuthorizationContext authorizationContext) {
if (policyEnforcer.hasUnrestrictedPermissions(thingResourceKey, authorizationContext, Permission.WRITE)) {
// unrestricted permissions at thingResourceKey level
return true;
} else if (policyEnforcer.hasPartialPermissions(thingResourceKey, authorizationContext, Permission.WRITE)) {
// in case of partial permissions at thingResourceKey level check all leaves of merge patch for
// unrestricted permissions
final Set<ResourceKey> resourceKeys = calculateLeaves(command.getPath(), command.getValue());
return policyEnforcer.hasUnrestrictedPermissions(resourceKeys, authorizationContext, Permission.WRITE);
} else {
// not even partial permission
return false;
}
}
private static Set<ResourceKey> calculateLeaves(final JsonPointer path, final JsonValue value) {
if (value.isObject()) {
return value.asObject().stream()
.map(f -> calculateLeaves(path.append(f.getKey().asPointer()), f.getValue()))
.reduce(new HashSet<>(), ThingCommandEnforcement::addAll, ThingCommandEnforcement::addAll);
} else {
return Set.of(PoliciesResourceType.thingResource(path));
}
}
private static Set<ResourceKey> addAll(final Set<ResourceKey> result, final Set<ResourceKey> toBeAdded) {
result.addAll(toBeAdded);
return result;
}
private CompletionStage<ThingCommand<?>> handleInitialCreateThing(final CreateThing createThing) {
final CompletionStage<ThingCommand<?>> result;
if (shouldCreatePolicyForCreateThing(createThing)) {
checkForErrorsInCreateThingWithPolicy(createThing);
result = createPolicyInScopeOfCreateThing(createThing)
.thenApply(this::prepareThingCommandBeforeSendingToPersistence);
} else if (createThing.getThing().getPolicyId().isPresent()) {
final var policyId = createThing.getThing()
.getPolicyId()
.orElseThrow(IllegalStateException::new);
checkForErrorsInCreateThingWithPolicy(createThing);
result = enforceCreateThingForNonexistentThingWithPolicyId(createThing, policyId);
} else {
// nothing to do with policy, simply forward the command
result = CompletableFuture.completedFuture(prepareThingCommandBeforeSendingToPersistence(createThing));
}
return result;
}
private static boolean shouldCreatePolicyForCreateThing(final CreateThing createThing) {
return createThing.getInitialPolicy().isPresent() || createThing.getThing().getPolicyId().isEmpty();
}
private static void checkForErrorsInCreateThingWithPolicy(final CreateThing command) {
validatePolicyIdForCreateThing(command);
}
private static void validatePolicyIdForCreateThing(final CreateThing createThing) {
final var thing = createThing.getThing();
final Optional<String> policyIdOpt = thing.getPolicyId().map(String::valueOf);
final Optional<String> policyIdInPolicyOpt = createThing.getInitialPolicy()
.flatMap(jsonObject -> jsonObject.getValue(Thing.JsonFields.POLICY_ID));
final boolean isValid;
if (policyIdOpt.isPresent()) {
isValid = policyIdInPolicyOpt.isEmpty() || policyIdInPolicyOpt.equals(policyIdOpt);
} else {
isValid = true;
}
if (!isValid) {
throw PolicyIdNotAllowedException.newBuilder(createThing.getEntityId())
.dittoHeaders(createThing.getDittoHeaders())
.build();
}
}
private CompletionStage<CreateThing> createPolicyInScopeOfCreateThing(final CreateThing createThing) {
try {
final Optional<Policy> policy = getInlinedOrDefaultPolicyForCreateThing(createThing);
if (policy.isPresent()) {
final var dittoHeadersForCreatePolicy = DittoHeaders.newBuilder(createThing.getDittoHeaders())
.removePreconditionHeaders()
.responseRequired(true)
.build();
final var createPolicy = CreatePolicy.of(policy.get(), dittoHeadersForCreatePolicy);
return createPolicyAndReturnCreateThing(createPolicy, createThing);
} else {
// cannot create policy.
final var thingId = createThing.getEntityId();
final var message = String.format("The Thing with ID '%s' could not be created with implicit " +
"Policy because no authorization subject is present.", thingId);
throw ThingNotCreatableException.newBuilderForPolicyMissing(thingId, PolicyId.of(thingId))
.message(message)
.description(() -> null)
.dittoHeaders(createThing.getDittoHeaders())
.build();
}
} catch (final RuntimeException error) {
throw reportError("error before creating thing with initial policy", error,
createThing.getDittoHeaders());
}
}
private CompletionStage<CreateThing> createPolicyAndReturnCreateThing(final CreatePolicy createPolicy,
final CreateThing createThingWithoutPolicyId) {
final var createThing = CreateThing.of(
createThingWithoutPolicyId.getThing().setPolicyId(createPolicy.getEntityId()),
null,
createThingWithoutPolicyId.getDittoHeaders());
return preEnforcer.apply(createPolicy)
.thenCompose(msg -> Patterns.ask(policiesShardRegion, msg,
enforcementConfig.getAskWithRetryConfig().getAskTimeout()
.multipliedBy(5L)) // don't retry creating policy (not idempotent!) - but increase default timeout for doing so
.thenApply(policyResponse -> {
handlePolicyResponseForCreateThing(createPolicy, createThing, policyResponse);
return createThing;
})
)
.exceptionally(throwable -> {
if (throwable instanceof AskTimeoutException) {
throw PolicyUnavailableException.newBuilder(createPolicy.getEntityId())
.dittoHeaders(createThing.getDittoHeaders())
.build();
}
throw reportError(String.format("creating initial policy during creation of Thing <%s>",
createThing.getEntityId()), throwable, createThing.getDittoHeaders());
});
}
private void handlePolicyResponseForCreateThing(final CreatePolicy createPolicy, final CreateThing createThing,
final Object policyResponse) {
if (policyResponse instanceof CreatePolicyResponse createPolicyResponse) {
createPolicyResponse.getPolicyCreated().ifPresent(this::injectCreatedPolicy);
} else {
if (shouldReportInitialPolicyCreationFailure(policyResponse)) {
throw reportInitialPolicyCreationFailure(createPolicy.getEntityId(), createThing);
} else if (isAskTimeoutException(policyResponse, null)) {