-
Notifications
You must be signed in to change notification settings - Fork 214
/
ThingCommandEnforcement.java
1453 lines (1300 loc) · 74 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) 2017 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.concierge.service.enforcement;
import static java.util.Objects.requireNonNull;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import static org.eclipse.ditto.concierge.service.enforcement.LiveSignalEnforcement.addEffectedReadSubjectsToThingLiveSignal;
import static org.eclipse.ditto.concierge.service.enforcement.LiveSignalEnforcement.adjustTimeoutAndFilterLiveQueryResponse;
import static org.eclipse.ditto.policies.api.Permission.MIN_REQUIRED_POLICY_PERMISSIONS;
import java.time.Instant;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.eclipse.ditto.base.api.persistence.PersistenceLifecycle;
import org.eclipse.ditto.base.model.auth.AuthorizationContext;
import org.eclipse.ditto.base.model.auth.AuthorizationSubject;
import org.eclipse.ditto.base.model.entity.id.EntityId;
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.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.WithDittoHeaders;
import org.eclipse.ditto.base.model.json.FieldType;
import org.eclipse.ditto.base.model.json.JsonSchemaVersion;
import org.eclipse.ditto.base.model.namespaces.NamespaceBlockedException;
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.GatewayCommandTimeoutException;
import org.eclipse.ditto.base.model.signals.commands.exceptions.GatewayInternalErrorException;
import org.eclipse.ditto.concierge.api.ConciergeMessagingConstants;
import org.eclipse.ditto.concierge.service.actors.LiveResponseAndAcknowledgementForwarder;
import org.eclipse.ditto.concierge.service.common.ConciergeConfig;
import org.eclipse.ditto.concierge.service.common.DittoConciergeConfig;
import org.eclipse.ditto.concierge.service.common.EnforcementConfig;
import org.eclipse.ditto.concierge.service.enforcement.placeholders.references.PolicyIdReferencePlaceholderResolver;
import org.eclipse.ditto.concierge.service.enforcement.placeholders.references.ReferencePlaceholder;
import org.eclipse.ditto.internal.models.signal.CommandHeaderRestoration;
import org.eclipse.ditto.internal.models.signal.SignalInformationPoint;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLogger;
import org.eclipse.ditto.internal.utils.cache.Cache;
import org.eclipse.ditto.internal.utils.cache.entry.Entry;
import org.eclipse.ditto.internal.utils.cacheloaders.AskWithRetry;
import org.eclipse.ditto.internal.utils.cacheloaders.EnforcementCacheKey;
import org.eclipse.ditto.internal.utils.cacheloaders.EnforcementContext;
import org.eclipse.ditto.internal.utils.cacheloaders.PolicyEnforcer;
import org.eclipse.ditto.internal.utils.cluster.DistPubSubAccess;
import org.eclipse.ditto.internal.utils.config.DefaultScopedConfig;
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.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.protocol.TopicPath;
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.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.exceptions.ThingUnavailableException;
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.RetrieveThing;
import org.eclipse.ditto.things.model.signals.commands.query.RetrieveThingResponse;
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;
/**
* Authorize {@code ThingCommand}.
*/
public final class ThingCommandEnforcement
extends AbstractEnforcementWithAsk<ThingCommand<?>, ThingQueryCommandResponse<?>> {
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 thingsShardRegion;
private final ActorRef policiesShardRegion;
private final EnforcerRetriever<Enforcer> thingEnforcerRetriever;
private final EnforcerRetriever<Enforcer> policyEnforcerRetriever;
private final Cache<EnforcementCacheKey, Entry<EnforcementCacheKey>> thingIdCache;
private final Cache<EnforcementCacheKey, Entry<Enforcer>> policyEnforcerCache;
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;
private ThingCommandEnforcement(final Contextual<ThingCommand<?>> data,
final ActorSystem actorSystem,
final ActorRef thingsShardRegion,
final ActorRef policiesShardRegion,
final Cache<EnforcementCacheKey, Entry<EnforcementCacheKey>> thingIdCache,
final Cache<EnforcementCacheKey, Entry<Enforcer>> policyEnforcerCache,
final PreEnforcer preEnforcer,
final CreationRestrictionEnforcer creationRestrictionEnforcer,
final LiveSignalPub liveSignalPub,
final EnforcementConfig enforcementConfig,
final ResponseReceiverCache responseReceiverCache) {
super(data, ThingQueryCommandResponse.class);
this.thingsShardRegion = requireNonNull(thingsShardRegion);
this.policiesShardRegion = requireNonNull(policiesShardRegion);
final ConciergeConfig conciergeConfig = DittoConciergeConfig.of(
DefaultScopedConfig.dittoScoped(actorSystem.settings().config())
);
conciergeConfig.getEnforcementConfig().getSpecialLoggingInspectedNamespaces()
.forEach(loggedNamespace -> NAMESPACE_INSPECTION_LOGGERS.put(
loggedNamespace,
DittoLoggerFactory.getThreadSafeLogger(ThingCommandEnforcement.class.getName() +
".namespace." + loggedNamespace)));
this.thingIdCache = requireNonNull(thingIdCache);
this.policyEnforcerCache = requireNonNull(policyEnforcerCache);
this.preEnforcer = preEnforcer;
this.actorSystem = actorSystem;
this.enforcementConfig = enforcementConfig;
thingEnforcerRetriever = PolicyEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache);
policyEnforcerRetriever = new EnforcerRetriever<>(IdentityCache.INSTANCE, policyEnforcerCache);
policyIdReferencePlaceholderResolver =
PolicyIdReferencePlaceholderResolver.of(conciergeForwarder(), getAskWithRetryConfig(),
context.getScheduler(), context.getExecutor());
this.creationRestrictionEnforcer = creationRestrictionEnforcer;
this.liveSignalPub = liveSignalPub;
this.responseReceiverCache = responseReceiverCache;
}
@Override
public CompletionStage<Contextual<WithDittoHeaders>> enforce() {
return thingEnforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> {
try {
return doEnforce(enforcerKeyEntry, enforcerEntry);
} catch (final RuntimeException e) {
return CompletableFuture.failedStage(e);
}
});
}
private CompletionStage<Contextual<WithDittoHeaders>> doEnforce(
final Entry<EnforcementCacheKey> enforcerKeyEntry, final Entry<Enforcer> enforcerEntry) {
if (enforcerEntry.exists()) {
if (keyEntryForDeletedThing(enforcerKeyEntry)) {
if (isRetrieveCommandForDeletedThing()) {
final EntityId policyId = enforcerKeyEntry.getValueOrThrow().getId();
final Contextual<WithDittoHeaders> enforcementResult = enforceThingCommandByPolicyEnforcer(signal(),
PolicyId.of(policyId),
enforcerEntry.getValueOrThrow());
return CompletableFuture.completedFuture(enforcementResult);
} else {
return enforceThingCommandByNonexistentEnforcer(enforcerKeyEntry);
}
} else {
final EntityId policyId = enforcerKeyEntry.getValueOrThrow().getId();
final Contextual<WithDittoHeaders> enforcementResult = enforceThingCommandByPolicyEnforcer(signal(),
PolicyId.of(policyId),
enforcerEntry.getValueOrThrow());
return CompletableFuture.completedFuture(enforcementResult);
}
} else {
return enforceThingCommandByNonexistentEnforcer(enforcerKeyEntry);
}
}
private boolean isRetrieveCommandForDeletedThing() {
return (signal() instanceof RetrieveThing) && signal().getDittoHeaders().shouldRetrieveDeleted();
}
private boolean keyEntryForDeletedThing(final Entry<EnforcementCacheKey> enforcerKeyEntry) {
return enforcerKeyEntry.exists() && enforcerKeyEntry.getValueOrThrow()
.getCacheLookupContext()
.flatMap(EnforcementContext::getPersistenceLifecycle)
.map(x -> PersistenceLifecycle.DELETED == x)
.orElse(false);
}
/**
* Authorize a thing command in the absence of an enforcer. This happens when the thing did not exist or when the
* policy of the thing does not exist.
*
* @param enforcerKeyEntry cache entry in the entity ID cache for the enforcer cache key.
* @return the completionStage of the contextual including message and receiver
*/
private CompletionStage<Contextual<WithDittoHeaders>> enforceThingCommandByNonexistentEnforcer(
final Entry<EnforcementCacheKey> enforcerKeyEntry) {
if (enforcerKeyEntry.exists() && !keyEntryForDeletedThing(enforcerKeyEntry)) {
// Thing exists but its policy is deleted.
final var thingId = signal().getEntityId();
final EntityId policyId = enforcerKeyEntry.getValueOrThrow().getId();
final DittoRuntimeException error = errorForExistingThingWithDeletedPolicy(signal(), thingId, policyId);
if (LOGGER.isInfoEnabled()) {
LOGGER.withCorrelationId(dittoHeaders())
.info("Enforcer was not existing for Thing <{}>, responding with: {}", thingId,
error.toString());
}
throw error;
} else {
// 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()
.thenCompose(pair ->
handleInitialCreateThing(pair.createThing, pair.enforcer)
.thenApply(create -> create.withReceiver(thingsShardRegion))
)
.exceptionally(throwable -> {
final ThreadSafeDittoLogger l = LOGGER.withCorrelationId(dittoHeaders());
final var dittoRuntimeException =
DittoRuntimeException.asDittoRuntimeException(throwable, cause -> {
l.warn("Error during thing by itself enforcement - {}: {}",
cause.getClass().getSimpleName(), cause.getMessage());
throw GatewayInternalErrorException.newBuilder()
.cause(cause)
.build();
});
l.debug("DittoRuntimeException during enforceThingCommandByNonexistentEnforcer - {}: {}",
dittoRuntimeException.getClass().getSimpleName(), dittoRuntimeException.getMessage());
throw dittoRuntimeException;
});
}
}
private static boolean isResponseRequired(final WithDittoHeaders withDittoHeaders) {
final var dittoHeaders = withDittoHeaders.getDittoHeaders();
return dittoHeaders.isResponseRequired();
}
/**
* Authorize a thing command by policy enforcer with view restriction for query commands.
*
* @param thingCommand the thing command to authorize.
* @param policyId the ID of the thing's policy.
* @param enforcer the policy enforcer.
* @return the contextual including message and receiver
*/
private Contextual<WithDittoHeaders> enforceThingCommandByPolicyEnforcer(
final ThingCommand<?> thingCommand, final PolicyId policyId, final Enforcer enforcer) {
final ThingCommand<?> commandWithReadSubjects = authorizeByPolicyOrThrow(enforcer, thingCommand);
final Contextual<WithDittoHeaders> result;
if (commandWithReadSubjects instanceof ThingQueryCommand) {
final ThingQueryCommand<?> thingQueryCommand = (ThingQueryCommand<?>) commandWithReadSubjects;
final Instant startTime = Instant.now();
if (!isResponseRequired(thingQueryCommand)) {
// drop query command with response-required=false
result = withMessageToReceiver(null, ActorRef.noSender());
} else if (thingQueryCommand instanceof RetrieveThing && shouldRetrievePolicyWithThing(thingQueryCommand)) {
final var retrieveThing = (RetrieveThing) ensureTwinChannel(thingQueryCommand);
result = withMessageToReceiverViaAskFuture(retrieveThing, sender(), () ->
retrieveThingAndPolicy(retrieveThing, policyId, enforcer).thenCompose(response ->
doSmartChannelSelection(thingQueryCommand, response, startTime, enforcer))
);
} else {
final var twinCommand = ensureTwinChannel(thingQueryCommand);
result = withMessageToReceiverViaAskFuture(twinCommand, sender(), () ->
askAndBuildJsonView(thingsShardRegion, thingQueryCommand, enforcer,
context.getScheduler(), context.getExecutor()).thenCompose(response ->
doSmartChannelSelection(thingQueryCommand, response, startTime, enforcer))
);
}
} else if (commandWithReadSubjects.getDittoHeaders().getLiveChannelCondition().isPresent()) {
throw LiveChannelConditionNotAllowedException.newBuilder()
.dittoHeaders(commandWithReadSubjects.getDittoHeaders())
.build();
} else {
result = forwardToThingsShardRegion(commandWithReadSubjects);
}
return result;
}
private CompletionStage<ThingQueryCommandResponse<?>> doSmartChannelSelection(final ThingQueryCommand<?> command,
final ThingQueryCommandResponse<?> response, final Instant startTime, final Enforcer enforcer) {
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, enforcer);
final var pub = liveSignalPub.command();
final var liveResponseForwarder = startLiveResponseForwarder(liveCommand);
if (enforcementConfig.shouldDispatchGlobally(liveCommand)) {
return responseReceiverCache.insertResponseReceiverConflictFreeWithFuture(
liveCommand,
newCommand -> liveResponseForwarder,
(newCommand, forwarder) -> adjustTimeoutAndFilterLiveQueryResponse(this, newCommand,
startTime, pub, forwarder, enforcer, getFallbackResponseCaster(liveCommand, twinResponse))
);
} else {
return adjustTimeoutAndFilterLiveQueryResponse(this, liveCommand, startTime, pub, liveResponseForwarder,
enforcer, getFallbackResponseCaster(liveCommand, twinResponse));
}
}
private ActorRef startLiveResponseForwarder(final ThingQueryCommand<?> signal) {
final var pub = liveSignalPub.command();
final var props = LiveResponseAndAcknowledgementForwarder.props(signal, pub.getPublisher(), sender());
return actorSystem.actorOf(props);
}
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) {
return CompletableFuture.failedStage(
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);
return CompletableFuture.failedStage(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() &&
SignalInformationPoint.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(TopicPath.Channel.LIVE.getName())
.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(TopicPath.Channel.LIVE.getName())
.build());
}
/**
* Retrieve a thing and its policy and combine them into a response.
*
* @param retrieveThing the retrieve-thing command.
* @param policyId the ID of the thing's policy.
* @param enforcer the enforcer for the command.
* @return always {@code true}.
*/
private CompletionStage<ThingQueryCommandResponse<?>> retrieveThingAndPolicy(final RetrieveThing retrieveThing,
final PolicyId policyId, final Enforcer enforcer) {
final var dittoHeadersWithoutPreconditionHeaders =
DittoHeaders.newBuilder(retrieveThing.getDittoHeaders())
.removePreconditionHeaders()
.build();
final Optional<RetrievePolicy> retrievePolicyOptional = PolicyCommandEnforcement.authorizePolicyCommand(
RetrievePolicy.of(policyId, dittoHeadersWithoutPreconditionHeaders), PolicyEnforcer.of(enforcer),
this.creationRestrictionEnforcer);
if (retrievePolicyOptional.isPresent()) {
return retrieveThingBeforePolicy(retrieveThing)
.thenCompose(retrieveThingResponse -> {
if (retrieveThingResponse instanceof RetrieveThingResponse) {
final var retrievePolicy = retrievePolicyOptional.get();
return retrieveInlinedPolicyForThing(retrieveThing, retrievePolicy)
.thenApply(policyResponse -> {
if (policyResponse.isPresent()) {
final RetrievePolicyResponse filteredPolicyResponse =
PolicyCommandEnforcement.buildJsonViewForPolicyQueryCommandResponse(
policyResponse.get(), enforcer);
return reportAggregatedThingAndPolicyResponse(retrieveThing,
(RetrieveThingResponse) retrieveThingResponse,
filteredPolicyResponse, enforcer);
} else {
return retrieveThingResponse;
}
});
} else {
return CompletableFuture.completedFuture(retrieveThingResponse);
}
});
} else {
// sender is not authorized to view the policy, ignore the request to embed policy.
return askAndBuildJsonView(thingsShardRegion, retrieveThing, enforcer, context.getScheduler(),
context.getExecutor());
}
}
/**
* Retrieve a thing before retrieving its inlined policy. Report errors to sender.
*
* @param command the command.
* @return future response from things-shard-region.
*/
private CompletionStage<ThingQueryCommandResponse<?>> retrieveThingBeforePolicy(final RetrieveThing command) {
return ask(thingsShardRegion, command, "retrieving thing before inlined policy", context.getScheduler(),
context.getExecutor());
}
/**
* Retrieve inlined policy after retrieving a thing. Do not report errors.
*
* @param retrieveThing the original command.
* @param retrievePolicy the command to retrieve the thing's policy.
* @return future response from policies-shard-region.
*/
private CompletionStage<Optional<RetrievePolicyResponse>> retrieveInlinedPolicyForThing(
final RetrieveThing retrieveThing, final RetrievePolicy retrievePolicy) {
return preEnforcer.apply(retrievePolicy)
.thenCompose(msg -> AskWithRetry.askWithRetry(policiesShardRegion, msg,
getAskWithRetryConfig(), context.getScheduler(), context.getExecutor(),
response -> {
if (response instanceof RetrievePolicyResponse) {
return Optional.of((RetrievePolicyResponse) response);
} else {
LOGGER.withCorrelationId(getCorrelationIdOrNull(response, retrieveThing))
.info("No authorized response when retrieving inlined policy <{}> for thing <{}>: {}",
retrievePolicy.getEntityId(), retrieveThing.getEntityId(), response);
return Optional.<RetrievePolicyResponse>empty();
}
}
).exceptionally(error -> {
LOGGER.withCorrelationId(getCorrelationIdOrNull(error, retrieveThing))
.error("Retrieving inlined policy after RetrieveThing", error);
return Optional.empty();
}));
}
@Nullable
private static CharSequence getCorrelationIdOrNull(final Object signal, final WithDittoHeaders fallBackSignal) {
final WithDittoHeaders withDittoHeaders;
if (isWithDittoHeaders(signal)) {
withDittoHeaders = (WithDittoHeaders) signal;
} else {
withDittoHeaders = fallBackSignal;
}
final var dittoHeaders = withDittoHeaders.getDittoHeaders();
return dittoHeaders.getCorrelationId().orElse(null);
}
private static boolean isWithDittoHeaders(final Object o) {
return o instanceof WithDittoHeaders;
}
/**
* Put thing and policy together as response to the sender.
*
* @param retrieveThing the original command.
* @param thingResponse response from things-shard-region.
* @param policyResponse response from policies-shard-region.
* @param enforcer enforcer to build the JSON view.
*/
private static RetrieveThingResponse reportAggregatedThingAndPolicyResponse(final RetrieveThing retrieveThing,
final RetrieveThingResponse thingResponse,
final RetrievePolicyResponse policyResponse,
final Enforcer enforcer) {
return reportAggregatedThingAndPolicy(retrieveThing, thingResponse, policyResponse.getPolicy(), enforcer);
}
private static RetrieveThingResponse reportAggregatedThingAndPolicy(final RetrieveThing retrieveThing,
final RetrieveThingResponse retrieveThingResponse,
final Policy policy,
final Enforcer enforcer) {
final RetrieveThingResponse limitedView =
buildJsonViewForThingQueryCommandResponse(retrieveThingResponse, enforcer);
final JsonObject inlinedPolicy =
policy.toInlinedJson(retrieveThing.getImplementedSchemaVersion(), FieldType.notHidden());
final JsonObject thingWithInlinedPolicy = limitedView.getEntity().asObject().toBuilder()
.setAll(inlinedPolicy)
.build();
return limitedView.setEntity(thingWithInlinedPolicy);
}
/**
* Report timeout of {@code ThingQueryCommand}.
*
* @param command the original command.
* @param askTimeout the timeout exception.
*/
@Override
protected DittoRuntimeException handleAskTimeoutForCommand(final ThingCommand<?> command,
final Throwable askTimeout) {
LOGGER.withCorrelationId(dittoHeaders()).error("Timeout before building JsonView", askTimeout);
return ThingUnavailableException.newBuilder(command.getEntityId())
.dittoHeaders(command.getDittoHeaders())
.build();
}
/**
* Mixin-private: report thing query response with view on entity restricted by enforcer.
*
* @param commandResponse response of query.
* @param enforcer the enforcer.
*/
@Override
protected ThingQueryCommandResponse<?> filterJsonView(final ThingQueryCommandResponse<?> commandResponse,
final Enforcer enforcer) {
try {
return buildJsonViewForThingQueryCommandResponse(commandResponse, enforcer);
} catch (final RuntimeException e) {
throw reportError("Error after building JsonView", e);
}
}
/**
* 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<Contextual<WithDittoHeaders>> enforceCreateThingForNonexistentThingWithPolicyId(
final CreateThing command, final PolicyId policyId) {
final var policyCacheKey = EnforcementCacheKey.of(policyId);
return policyEnforcerRetriever.retrieve(policyCacheKey, (policyIdEntry, policyEnforcerEntry) -> {
if (policyEnforcerEntry.exists()) {
final Contextual<WithDittoHeaders> enforcementResult =
enforceThingCommandByPolicyEnforcer(command, policyId, policyEnforcerEntry.getValueOrThrow());
return CompletableFuture.completedFuture(enforcementResult);
} else {
throw errorForExistingThingWithDeletedPolicy(command, command.getEntityId(), policyId);
}
});
}
/**
* 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);
}
}
/**
* Forward a command to things-shard-region.
*
* @param command command to forward.
* @return the contextual including message and receiver
*/
private Contextual<WithDittoHeaders> forwardToThingsShardRegion(final ThingCommand<?> command) {
if (command instanceof ThingModifyCommand && ((ThingModifyCommand<?>) command).changesAuthorization()) {
invalidateThingCaches(command.getEntityId());
}
if (NAMESPACE_INSPECTION_LOGGERS.containsKey(command.getEntityId().getNamespace())) {
final ThreadSafeDittoLogger namespaceLogger = NAMESPACE_INSPECTION_LOGGERS
.get(command.getEntityId().getNamespace()).withCorrelationId(command);
if (command instanceof ThingModifyCommand) {
final JsonValue value = ((ThingModifyCommand<?>) command).getEntity().orElse(null);
if (null != value) {
final Set<ResourceKey> resourceKeys = calculateLeaves(command.getResourcePath(), value);
namespaceLogger.info("Forwarding modify command type <{}> with resourceKeys <{}>",
command.getType(),
resourceKeys);
}
}
namespaceLogger.debug("Forwarding command type <{}>: <{}>", command.getType(), command);
}
return withMessageToReceiver(command, thingsShardRegion);
}
/**
* Whenever a Command changed the authorization, the caches must be invalidated - otherwise a directly following
* Command targeted for the same entity will probably fail as the enforcer was not yet updated.
*
* @param thingId the ID of the Thing to invalidate caches for.
*/
private void invalidateThingCaches(final ThingId thingId) {
final var thingCacheKey = EnforcementCacheKey.of(thingId);
thingIdCache.invalidate(thingCacheKey);
pubSubMediator().tell(DistPubSubAccess.sendToAll(
ConciergeMessagingConstants.ENFORCER_ACTOR_PATH,
InvalidateCacheEntry.of(thingCacheKey),
true),
self());
}
private void invalidatePolicyCache(final PolicyId policyId) {
final var policyCacheKey = EnforcementCacheKey.of(policyId);
policyEnforcerCache.invalidate(policyCacheKey);
pubSubMediator().tell(DistPubSubAccess.sendToAll(
ConciergeMessagingConstants.ENFORCER_ACTOR_PATH,
InvalidateCacheEntry.of(policyCacheKey),
true),
self());
}
/**
* 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.
*
* @return optionally the authorized command extended by read subjects.
*/
private CompletionStage<CreateThingWithEnforcer> enforceCreateThingBySelf() {
final ThingCommand<?> thingCommand = transformModifyThingToCreateThing(signal());
if (thingCommand instanceof CreateThing) {
return replaceInitialPolicyWithCopiedPolicyIfPresent((CreateThing) thingCommand)
.thenApply(createThing -> {
final Optional<JsonObject> initialPolicyOptional = createThing.getInitialPolicy();
return initialPolicyOptional.map(
initialPolicy -> enforceCreateThingByOwnInlinedPolicyOrThrow(createThing,
initialPolicy))
.orElseGet(() -> enforceCreateThingByAuthorizationContext(createThing));
});
} else {
// Other commands cannot be authorized by policy contained in self.
final DittoRuntimeException error = ThingNotAccessibleException.newBuilder(thingCommand.getEntityId())
.dittoHeaders(thingCommand.getDittoHeaders())
.build();
LOGGER.withCorrelationId(dittoHeaders())
.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 = dittoHeaders().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(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 PolicyId policyId) {
final var adjustedHeaders = dittoHeaders().toBuilder()
.removePreconditionHeaders()
.responseRequired(true)
.build();
return AskWithRetry.askWithRetry(conciergeForwarder(), RetrievePolicy.of(policyId, adjustedHeaders),
getAskWithRetryConfig(), context.getScheduler(), context.getExecutor(),
response -> {
if (response instanceof RetrievePolicyResponse) {
return ((RetrievePolicyResponse) response).getPolicy();
} else if (response instanceof PolicyErrorResponse) {
throw ((PolicyErrorResponse) response).getDittoRuntimeException();
} else if (response instanceof DittoRuntimeException) {
throw (DittoRuntimeException) response;
} else {
LOGGER.withCorrelationId(adjustedHeaders)
.error("Got an unexpected response while retrieving a Policy that should be copied" +
" during Thing creation: {}", response);
throw GatewayInternalErrorException.newBuilder().build();
}
});
}
private static CreateThingWithEnforcer 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));
final CreateThing command = AbstractEnforcement.addEffectedReadSubjectsToThingSignal(createThing, enforcer);
return new CreateThingWithEnforcer(command, enforcer);
}
private CreateThingWithEnforcer 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 attachEnforcerOrThrow(createThing, initialEnforcer,
ThingCommandEnforcement::authorizeByPolicyOrThrow);
} 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);
}
}
}
private static CreateThingWithEnforcer attachEnforcerOrThrow(final CreateThing command, final Enforcer enforcer,
final BiFunction<Enforcer, ThingCommand<CreateThing>, CreateThing> authorization) {
final CreateThing authorizedCommand = authorization.apply(enforcer, command);
return new CreateThingWithEnforcer(authorizedCommand, enforcer);
}
/**
* 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) {
final var modifyThing = (ModifyThing) receivedCommand;
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;