/
ThingCommandEnforcement.java
1314 lines (1170 loc) · 63.4 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-2018 Bosch Software Innovations GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/index.php
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.services.concierge.enforcement;
import static java.util.Objects.requireNonNull;
import static org.eclipse.ditto.model.things.Permission.ADMINISTRATE;
import static org.eclipse.ditto.services.models.policies.Permission.MIN_REQUIRED_POLICY_PERMISSIONS;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiFunction;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonFieldSelector;
import org.eclipse.ditto.json.JsonFieldSelectorBuilder;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonObjectBuilder;
import org.eclipse.ditto.json.JsonRuntimeException;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.model.base.auth.AuthorizationContext;
import org.eclipse.ditto.model.base.auth.AuthorizationSubject;
import org.eclipse.ditto.model.base.exceptions.DittoJsonException;
import org.eclipse.ditto.model.base.exceptions.DittoRuntimeException;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.base.headers.WithDittoHeaders;
import org.eclipse.ditto.model.base.json.FieldType;
import org.eclipse.ditto.model.base.json.JsonSchemaVersion;
import org.eclipse.ditto.model.enforcers.AclEnforcer;
import org.eclipse.ditto.model.enforcers.Enforcer;
import org.eclipse.ditto.model.enforcers.PolicyEnforcers;
import org.eclipse.ditto.model.policies.Permissions;
import org.eclipse.ditto.model.policies.PoliciesModelFactory;
import org.eclipse.ditto.model.policies.PoliciesResourceType;
import org.eclipse.ditto.model.policies.Policy;
import org.eclipse.ditto.model.policies.PolicyException;
import org.eclipse.ditto.model.policies.ResourceKey;
import org.eclipse.ditto.model.policies.Subject;
import org.eclipse.ditto.model.policies.SubjectId;
import org.eclipse.ditto.model.policies.SubjectIssuer;
import org.eclipse.ditto.model.things.AccessControlList;
import org.eclipse.ditto.model.things.AclInvalidException;
import org.eclipse.ditto.model.things.AclNotAllowedException;
import org.eclipse.ditto.model.things.AclValidator;
import org.eclipse.ditto.model.things.Thing;
import org.eclipse.ditto.services.concierge.cache.IdentityCache;
import org.eclipse.ditto.services.concierge.enforcement.placeholders.references.PolicyIdReferencePlaceholderResolver;
import org.eclipse.ditto.services.concierge.enforcement.placeholders.references.ReferencePlaceholder;
import org.eclipse.ditto.services.models.concierge.EntityId;
import org.eclipse.ditto.services.models.concierge.cache.Entry;
import org.eclipse.ditto.services.models.policies.Permission;
import org.eclipse.ditto.services.models.policies.PoliciesAclMigrations;
import org.eclipse.ditto.services.models.policies.PoliciesValidator;
import org.eclipse.ditto.services.utils.cache.Cache;
import org.eclipse.ditto.signals.commands.base.CommandToExceptionRegistry;
import org.eclipse.ditto.signals.commands.base.exceptions.GatewayInternalErrorException;
import org.eclipse.ditto.signals.commands.base.exceptions.GatewayServiceTimeoutException;
import org.eclipse.ditto.signals.commands.policies.PolicyCommand;
import org.eclipse.ditto.signals.commands.policies.PolicyErrorResponse;
import org.eclipse.ditto.signals.commands.policies.exceptions.PolicyConflictException;
import org.eclipse.ditto.signals.commands.policies.exceptions.PolicyNotAccessibleException;
import org.eclipse.ditto.signals.commands.policies.exceptions.PolicyUnavailableException;
import org.eclipse.ditto.signals.commands.policies.modify.CreatePolicy;
import org.eclipse.ditto.signals.commands.policies.modify.CreatePolicyResponse;
import org.eclipse.ditto.signals.commands.policies.query.RetrievePolicy;
import org.eclipse.ditto.signals.commands.policies.query.RetrievePolicyResponse;
import org.eclipse.ditto.signals.commands.things.ThingCommand;
import org.eclipse.ditto.signals.commands.things.ThingCommandResponse;
import org.eclipse.ditto.signals.commands.things.ThingErrorResponse;
import org.eclipse.ditto.signals.commands.things.exceptions.PolicyIdNotAllowedException;
import org.eclipse.ditto.signals.commands.things.exceptions.PolicyInvalidException;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingCommandToAccessExceptionRegistry;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingCommandToModifyExceptionRegistry;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingNotAccessibleException;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingNotCreatableException;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingNotModifiableException;
import org.eclipse.ditto.signals.commands.things.exceptions.ThingUnavailableException;
import org.eclipse.ditto.signals.commands.things.modify.CreateThing;
import org.eclipse.ditto.signals.commands.things.modify.ModifyThing;
import org.eclipse.ditto.signals.commands.things.modify.ThingModifyCommand;
import org.eclipse.ditto.signals.commands.things.query.RetrieveThing;
import org.eclipse.ditto.signals.commands.things.query.RetrieveThingResponse;
import org.eclipse.ditto.signals.commands.things.query.ThingQueryCommand;
import org.eclipse.ditto.signals.commands.things.query.ThingQueryCommandResponse;
import akka.actor.ActorRef;
import akka.event.DiagnosticLoggingAdapter;
import akka.pattern.AskTimeoutException;
import akka.pattern.PatternsCS;
/**
* Authorize {@code ThingCommand}.
*/
public final class ThingCommandEnforcement extends AbstractEnforcement<ThingCommand> {
/**
* 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_WHITELIST =
JsonFactory.newFieldSelector(Thing.JsonFields.ID);
private final List<SubjectIssuer> subjectIssuersForPolicyMigration;
private final ActorRef thingsShardRegion;
private final ActorRef policiesShardRegion;
private final EnforcerRetriever thingEnforcerRetriever;
private final EnforcerRetriever policyEnforcerRetriever;
private final Cache<EntityId, Entry<EntityId>> thingIdCache;
private final Cache<EntityId, Entry<Enforcer>> policyEnforcerCache;
private final Cache<EntityId, Entry<Enforcer>> aclEnforcerCache;
private final PolicyIdReferencePlaceholderResolver policyIdReferencePlaceholderResolver;
private ThingCommandEnforcement(final Context data, final ActorRef thingsShardRegion,
final ActorRef policiesShardRegion, final Cache<EntityId, Entry<EntityId>> thingIdCache,
final Cache<EntityId, Entry<Enforcer>> policyEnforcerCache,
final Cache<EntityId, Entry<Enforcer>> aclEnforcerCache,
final List<SubjectIssuer> subjectIssuersForPolicyMigration) {
super(data);
this.thingsShardRegion = requireNonNull(thingsShardRegion);
this.policiesShardRegion = requireNonNull(policiesShardRegion);
this.subjectIssuersForPolicyMigration = requireNonNull(subjectIssuersForPolicyMigration);
this.thingIdCache = requireNonNull(thingIdCache);
this.policyEnforcerCache = requireNonNull(policyEnforcerCache);
this.aclEnforcerCache = requireNonNull(aclEnforcerCache);
thingEnforcerRetriever =
PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache);
policyEnforcerRetriever = new EnforcerRetriever(IdentityCache.INSTANCE, policyEnforcerCache);
policyIdReferencePlaceholderResolver =
PolicyIdReferencePlaceholderResolver.of(conciergeForwarderActor(), getAskTimeout());
}
@Override
public CompletionStage<Void> enforce(final ThingCommand signal, final ActorRef sender,
final DiagnosticLoggingAdapter log) {
return thingEnforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> {
if (!enforcerEntry.exists()) {
enforceThingCommandByNonexistentEnforcer(enforcerKeyEntry, signal, sender);
} else if (isAclEnforcer(enforcerKeyEntry)) {
enforceThingCommandByAclEnforcer(signal, enforcerEntry.getValue(), sender);
} else {
final String policyId = enforcerKeyEntry.getValue().getId();
enforceThingCommandByPolicyEnforcer(signal, policyId, enforcerEntry.getValue(), sender);
}
});
}
/**
* Provides {@link AbstractEnforcement} for commands of type {@link ThingCommand}.
*/
public static final class Provider implements EnforcementProvider<ThingCommand> {
private static final List<SubjectIssuer> DEFAULT_SUBJECT_ISSUERS_FOR_POLICY_MIGRATION =
Collections.singletonList(SubjectIssuer.GOOGLE);
private final ActorRef thingsShardRegion;
private final ActorRef policiesShardRegion;
private final Cache<EntityId, Entry<EntityId>> thingIdCache;
private final Cache<EntityId, Entry<Enforcer>> policyEnforcerCache;
private final Cache<EntityId, Entry<Enforcer>> aclEnforcerCache;
private final List<SubjectIssuer> subjectIssuersForPolicyMigration;
/**
* Constructor.
*
* @param thingsShardRegion the ActorRef to the Things shard region.
* @param policiesShardRegion the ActorRef to the Policies shard region.
* @param thingIdCache the thing-id-cache.
* @param policyEnforcerCache the policy-enforcer cache.
* @param aclEnforcerCache the acl-enforcer cache.
*/
public Provider(final ActorRef thingsShardRegion,
final ActorRef policiesShardRegion, final Cache<EntityId, Entry<EntityId>> thingIdCache,
final Cache<EntityId, Entry<Enforcer>> policyEnforcerCache,
final Cache<EntityId, Entry<Enforcer>> aclEnforcerCache) {
this(thingsShardRegion, policiesShardRegion, thingIdCache, policyEnforcerCache, aclEnforcerCache,
DEFAULT_SUBJECT_ISSUERS_FOR_POLICY_MIGRATION);
}
/**
* Constructor.
*
* @param thingsShardRegion the ActorRef to the Things shard region.
* @param policiesShardRegion the ActorRef to the Policies shard region.
* @param thingIdCache the thing-id-cache.
* @param policyEnforcerCache the policy-enforcer cache.
* @param aclEnforcerCache the acl-enforcer cache.
* @param subjectIssuersForPolicyMigration a list of {@link SubjectIssuer}s for which a {@link Subject} will
* be created per ACL SID. E.g. when {@link SubjectIssuer#GOOGLE} is specified, for the ACL SID "123", a
* {@link Subject} "google:123" will be created.
*/
public Provider(final ActorRef thingsShardRegion,
final ActorRef policiesShardRegion, final Cache<EntityId, Entry<EntityId>> thingIdCache,
final Cache<EntityId, Entry<Enforcer>> policyEnforcerCache,
final Cache<EntityId, Entry<Enforcer>> aclEnforcerCache,
final List<SubjectIssuer> subjectIssuersForPolicyMigration) {
this.thingsShardRegion = requireNonNull(thingsShardRegion);
this.policiesShardRegion = requireNonNull(policiesShardRegion);
this.thingIdCache = requireNonNull(thingIdCache);
this.policyEnforcerCache = requireNonNull(policyEnforcerCache);
this.aclEnforcerCache = requireNonNull(aclEnforcerCache);
this.subjectIssuersForPolicyMigration = requireNonNull(subjectIssuersForPolicyMigration);
}
@Override
public Class<ThingCommand> getCommandClass() {
return ThingCommand.class;
}
@Override
public boolean isApplicable(final ThingCommand command) {
// live commands are not applicable for thing command enforcement
// because they should never be forwarded to things shard region
return !LiveSignalEnforcement.isLiveSignal(command);
}
@Override
public AbstractEnforcement<ThingCommand> createEnforcement(final AbstractEnforcement.Context context) {
return new ThingCommandEnforcement(context, thingsShardRegion, policiesShardRegion, thingIdCache,
policyEnforcerCache, aclEnforcerCache, subjectIssuersForPolicyMigration
);
}
}
/**
* 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.
* @param thingCommand the command to authorize.
* @param sender sender of the command.
*/
private void enforceThingCommandByNonexistentEnforcer(final Entry<EntityId> enforcerKeyEntry,
final ThingCommand thingCommand, final ActorRef sender) {
if (enforcerKeyEntry.exists()) {
// Thing exists but its policy is deleted.
final String thingId = thingCommand.getThingId();
final String policyId = enforcerKeyEntry.getValue().getId();
final DittoRuntimeException error = errorForExistingThingWithDeletedPolicy(thingCommand, thingId, policyId);
log(thingCommand).info("Enforcer was not existing for Thing <{}>, responding with: {}", thingId, error);
replyToSender(error, sender);
} else {
// Without prior enforcer in cache, enforce CreateThing by self.
enforceCreateThingBySelf(thingCommand, sender).ifPresent(pair ->
handleInitialCreateThing(pair.createThing, pair.enforcer, sender));
}
}
/**
* Authorize a thing command by ACL enforcer with special handling for the field "/acl".
*
* @param thingCommand the thing command.
* @param enforcer the ACL enforcer.
* @param sender sender of the command.
*/
private void enforceThingCommandByAclEnforcer(final ThingCommand<?> thingCommand, final Enforcer enforcer,
final ActorRef sender) {
final Optional<? extends ThingCommand> authorizedCommand = authorizeByAcl(enforcer, thingCommand);
if (authorizedCommand.isPresent()) {
final ThingCommand commandWithReadSubjects = authorizedCommand.get();
if (commandWithReadSubjects instanceof RetrieveThing &&
shouldRetrievePolicyWithThing(commandWithReadSubjects)) {
final RetrieveThing retrieveThing = (RetrieveThing) commandWithReadSubjects;
retrieveThingAclAndMigrateToPolicy(retrieveThing, enforcer, sender);
} else {
forwardToThingsShardRegion(commandWithReadSubjects, sender);
}
} else {
respondWithError(thingCommand, sender, self());
}
}
private void retrieveThingAclAndMigrateToPolicy(final RetrieveThing retrieveThing,
final Enforcer enforcer,
final ActorRef sender) {
final JsonFieldSelectorBuilder jsonFieldSelectorBuilder =
JsonFactory.newFieldSelectorBuilder().addFieldDefinition(Thing.JsonFields.ACL);
retrieveThing.getSelectedFields().ifPresent(jsonFieldSelectorBuilder::addPointers);
final DittoHeaders dittoHeaders = retrieveThing
.getDittoHeaders()
.toBuilder()
.schemaVersion(JsonSchemaVersion.V_1)
.build();
final RetrieveThing retrieveThingV1 = RetrieveThing.getBuilder(retrieveThing.getThingId(), dittoHeaders)
.withSelectedFields(jsonFieldSelectorBuilder.build())
.build();
PatternsCS.ask(thingsShardRegion, retrieveThingV1, getAskTimeout().toMillis())
.handleAsync((response, error) -> {
if (response instanceof RetrieveThingResponse) {
final RetrieveThingResponse retrieveThingResponse = (RetrieveThingResponse) response;
final Optional<AccessControlList> aclOptional =
retrieveThingResponse.getThing().getAccessControlList();
if (aclOptional.isPresent()) {
final Policy policy =
PoliciesAclMigrations.accessControlListToPolicyEntries(aclOptional.get(),
retrieveThing.getThingId(), subjectIssuersForPolicyMigration);
reportAggregatedThingAndPolicy(retrieveThing,
retrieveThingResponse.setDittoHeaders(retrieveThing.getDittoHeaders()),
policy, enforcer, sender);
} else {
replyToSender(retrieveThingResponse.setDittoHeaders(retrieveThing.getDittoHeaders()),
sender);
}
} else if (response instanceof WithDittoHeaders) {
final WithDittoHeaders withDittoHeaders = (WithDittoHeaders) response;
replyToSender(withDittoHeaders.setDittoHeaders(retrieveThing.getDittoHeaders()), sender);
} else if (isAskTimeoutException(response, error)) {
reportThingUnavailable(retrieveThing.getThingId(), retrieveThing.getDittoHeaders(), sender);
} else {
reportUnexpectedErrorOrResponse("retrieving thing for ACL migration",
sender, response, error, retrieveThing.getDittoHeaders());
}
return null;
});
}
/**
* Authorize a thing command by policy enforcer with view restriction for query commands.
*
* @param thingCommand the thing command.
* @param policyId Id of the thing's policy.
* @param enforcer the policy enforcer.
* @param sender sender of the command.
*/
private void enforceThingCommandByPolicyEnforcer(final ThingCommand<?> thingCommand,
final String policyId,
final Enforcer enforcer,
final ActorRef sender) {
final boolean authorized = authorizeByPolicy(enforcer, thingCommand)
.map(commandWithReadSubjects -> {
if (commandWithReadSubjects instanceof ThingQueryCommand) {
final ThingQueryCommand thingQueryCommand = (ThingQueryCommand) commandWithReadSubjects;
if (thingQueryCommand instanceof RetrieveThing &&
shouldRetrievePolicyWithThing(thingQueryCommand)) {
final RetrieveThing retrieveThing = (RetrieveThing) thingQueryCommand;
return retrieveThingAndPolicy(retrieveThing, policyId, enforcer, sender);
} else {
return askThingsShardRegionAndBuildJsonView(thingQueryCommand, enforcer, sender);
}
} else {
return forwardToThingsShardRegion(commandWithReadSubjects, sender);
}
})
.isPresent();
if (!authorized) {
respondWithError(thingCommand, sender, self());
}
}
/**
* Responds to the passed {@code sender} with an error based on the type of the passed in {@code thingCommand}.
*
* @param thingCommand the ThingCommand to use for determining which error to send back
* @param sender the sender to send back the error to
* @param self the self reference
*/
static void respondWithError(final ThingCommand thingCommand, final ActorRef sender, final ActorRef self) {
sender.tell(errorForThingCommand(thingCommand), self);
}
/**
* Retrieve for response of a query command and limit the response
* according to a policy
* enforcer.
*
* @param commandWithReadSubjects the command to ask.
* @param enforcer enforcer to build JsonView with.
* @param sender sender of the command.
* @return always {@code true}.
*/
private boolean askThingsShardRegionAndBuildJsonView(
final ThingQueryCommand commandWithReadSubjects,
final Enforcer enforcer,
final ActorRef sender) {
PatternsCS.ask(thingsShardRegion, commandWithReadSubjects, getAskTimeout().toMillis())
.handleAsync((response, error) -> {
if (response instanceof ThingQueryCommandResponse) {
reportJsonViewForThingQuery(sender, (ThingQueryCommandResponse) response, enforcer);
} else if (response instanceof DittoRuntimeException) {
replyToSender(response, sender);
} else if (isAskTimeoutException(response, error)) {
final AskTimeoutException askTimeoutException = error instanceof AskTimeoutException
? (AskTimeoutException) error
: (AskTimeoutException) response;
reportTimeoutForThingQuery(commandWithReadSubjects, sender, askTimeoutException);
} else if (error != null) {
reportUnexpectedError("before building JsonView", sender, error,
commandWithReadSubjects.getDittoHeaders());
} else {
reportUnknownResponse("before building JsonView", sender, response,
commandWithReadSubjects.getDittoHeaders());
}
return null;
});
return true;
}
/**
* Retrieve a thing and its policy and combine them into a response.
*
* @param retrieveThing the retrieve-thing command.
* @param policyId ID of the thing's policy.
* @param enforcer the enforcer for the command.
* @param sender sender of the command.
* @return always {@code true}.
*/
private boolean retrieveThingAndPolicy(
final RetrieveThing retrieveThing,
final String policyId,
final Enforcer enforcer,
final ActorRef sender) {
final DittoHeaders dittoHeadersWithoutPreconditionHeaders = retrieveThing.getDittoHeaders()
.toBuilder()
.removePreconditionHeaders()
.build();
final Optional<RetrievePolicy> retrievePolicyOptional = PolicyCommandEnforcement.authorizePolicyCommand(
RetrievePolicy.of(policyId, dittoHeadersWithoutPreconditionHeaders), enforcer);
if (retrievePolicyOptional.isPresent()) {
retrieveThingBeforePolicy(retrieveThing, sender).thenAccept(thingResponse ->
thingResponse.ifPresent(retrieveThingResponse -> {
final RetrievePolicy retrievePolicy = retrievePolicyOptional.get();
retrieveInlinedPolicyForThing(retrieveThing, retrievePolicy).thenAccept(policyResponse -> {
if (policyResponse.isPresent()) {
final RetrievePolicyResponse filteredPolicyResponse =
PolicyCommandEnforcement.buildJsonViewForPolicyQueryCommandResponse(
policyResponse.get(), enforcer);
reportAggregatedThingAndPolicyResponse(retrieveThing, retrieveThingResponse,
filteredPolicyResponse, enforcer, sender);
} else {
replyToSender(retrieveThingResponse, sender);
}
});
}));
return true;
} else {
// sender is not authorized to view the policy, ignore the request to embed policy.
return askThingsShardRegionAndBuildJsonView(retrieveThing, enforcer, sender);
}
}
/**
* Retrieve a thing before retrieving its inlined policy. Report errors to sender.
*
* @param retrieveThing the command.
* @param sender whom to report errors to.
* @return future response from things-shard-region.
*/
private CompletionStage<Optional<RetrieveThingResponse>> retrieveThingBeforePolicy(
final RetrieveThing retrieveThing,
final ActorRef sender) {
return PatternsCS.ask(thingsShardRegion, retrieveThing, getAskTimeout().toMillis())
.handleAsync((response, error) -> {
if (response instanceof RetrieveThingResponse) {
return Optional.of((RetrieveThingResponse) response);
} else if (response instanceof ThingErrorResponse || response instanceof DittoRuntimeException) {
replyToSender(response, sender);
} else if (isAskTimeoutException(response, error)) {
reportThingUnavailable(retrieveThing.getThingId(), retrieveThing.getDittoHeaders(), sender);
} else {
reportUnexpectedErrorOrResponse("retrieving thing before inlined policy",
sender, response, error, retrieveThing.getDittoHeaders());
}
return Optional.empty();
});
}
private void reportThingUnavailable(final String thingId, final DittoHeaders dittoHeaders, final ActorRef sender) {
final ThingUnavailableException thingUnavailableException =
ThingUnavailableException.newBuilder(thingId).dittoHeaders(dittoHeaders).build();
replyToSender(thingUnavailableException, sender);
}
/**
* 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 PatternsCS.ask(policiesShardRegion, retrievePolicy, getAskTimeout().toMillis())
.handleAsync((response, error) -> {
if (response instanceof RetrievePolicyResponse) {
return Optional.of((RetrievePolicyResponse) response);
} else if (error != null) {
log(error).error(error, "retrieving inlined policy after RetrieveThing");
} else {
log(response).info(
"No authorized response when retrieving inlined policy <{}> for thing <{}>: {}",
retrievePolicy.getId(), retrieveThing.getThingId(), response);
}
return Optional.empty();
});
}
/**
* Put thing and policy together as response to the sender.
*
* @param retrieveThing the original command.
* @param retrieveThingResponse response from things-shard-region.
* @param retrievePolicyResponse response from policies-shard-region.
* @param enforcer enforcer to bulid the Json view.
* @param sender sender of the original command.
*/
private void reportAggregatedThingAndPolicyResponse(
final RetrieveThing retrieveThing,
final RetrieveThingResponse retrieveThingResponse,
final RetrievePolicyResponse retrievePolicyResponse,
final Enforcer enforcer,
final ActorRef sender) {
reportAggregatedThingAndPolicy(retrieveThing, retrieveThingResponse, retrievePolicyResponse.getPolicy(),
enforcer, sender);
}
private void reportAggregatedThingAndPolicy(
final RetrieveThing retrieveThing,
final RetrieveThingResponse retrieveThingResponse,
final Policy policy,
final Enforcer enforcer,
final ActorRef sender) {
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();
replyToSender(limitedView.setEntity(thingWithInlinedPolicy), sender);
}
/**
* Report timeout of {@code ThingQueryCommand}.
*
* @param command the original command.
* @param sender sender of the command.
* @param askTimeoutException the timeout exception.
*/
private void reportTimeoutForThingQuery(
final ThingQueryCommand command,
final ActorRef sender,
final AskTimeoutException askTimeoutException) {
log(command).error(askTimeoutException, "Timeout before building JsonView");
replyToSender(ThingUnavailableException.newBuilder(command.getThingId())
.dittoHeaders(command.getDittoHeaders())
.build(), sender);
}
/**
* Mixin-private: report thing query response with view on entity restricted by enforcer.
*
* @param sender sender of the command.
* @param thingQueryCommandResponse response of query.
* @param enforcer the enforcer.
*/
private void reportJsonViewForThingQuery(final ActorRef sender,
final ThingQueryCommandResponse<?> thingQueryCommandResponse,
final Enforcer enforcer) {
try {
final ThingQueryCommandResponse responseWithLimitedJsonView =
buildJsonViewForThingQueryCommandResponse(thingQueryCommandResponse, enforcer);
replyToSender(responseWithLimitedJsonView, sender);
} catch (final RuntimeException e) {
reportError("Error after building JsonView", sender, e, thingQueryCommandResponse.getDittoHeaders());
}
}
/**
* Query caches again to authorize a {@code CreateThing} command with explicit policy ID and no inline policy.
*
* @param createThing the command.
* @param policyId the policy ID.
* @param sender sender of the command.
*/
private void enforceCreateThingForNonexistentThingWithPolicyId(final CreateThing createThing,
final String policyId,
final ActorRef sender) {
final EntityId policyEntityId = EntityId.of(PolicyCommand.RESOURCE_TYPE, policyId);
policyEnforcerRetriever.retrieve(policyEntityId, (policyIdEntry, policyEnforcerEntry) -> {
if (policyEnforcerEntry.exists()) {
enforceThingCommandByPolicyEnforcer(createThing, policyId, policyEnforcerEntry.getValue(), sender);
} else {
final DittoRuntimeException error =
errorForExistingThingWithDeletedPolicy(createThing, createThing.getThingId(), policyId);
replyToSender(error, sender);
}
});
}
/**
* 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..
*/
private static <T extends ThingQueryCommandResponse> 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.
* Do not call {@code Actor.forward(Object, ActorContext)} because it is not thread-safe.
*
* @param command command to forward.
* @param sender sender of the command.
* @return true.
*/
private boolean forwardToThingsShardRegion(final ThingCommand command, final ActorRef sender) {
thingsShardRegion.tell(command, sender);
if (command instanceof ThingModifyCommand && ((ThingModifyCommand) command).changesAuthorization()) {
invalidateThingCaches(command.getThingId());
}
return true;
}
/**
* 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 String thingId) {
final EntityId entityId = EntityId.of(ThingCommand.RESOURCE_TYPE, thingId);
thingIdCache.invalidate(entityId);
aclEnforcerCache.invalidate(entityId);
}
private void invalidatePolicyCache(final String policyId) {
final EntityId entityId = EntityId.of(PolicyCommand.RESOURCE_TYPE, policyId);
policyEnforcerCache.invalidate(entityId);
}
/**
* 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 ResourceKey resourceKey = ResourceKey.newInstance(ThingCommand.RESOURCE_TYPE, response.getResourcePath());
final AuthorizationContext authorizationContext = response.getDittoHeaders().getAuthorizationContext();
return enforcer.buildJsonView(resourceKey, responseEntity, authorizationContext,
THING_QUERY_COMMAND_RESPONSE_WHITELIST, 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 String thingId,
final String policyId) {
final String 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 String 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.
*/
private static DittoRuntimeException errorForThingCommand(final ThingCommand thingCommand) {
final CommandToExceptionRegistry<ThingCommand, DittoRuntimeException> registry =
thingCommand instanceof ThingModifyCommand
? ThingCommandToModifyExceptionRegistry.getInstance()
: ThingCommandToAccessExceptionRegistry.getInstance();
return registry.exceptionFrom(thingCommand);
}
/**
* Check if an enforcer key points to an access-control-list enforcer.
*
* @param enforcerKeyEntry cache key entry of an enforcer.
* @return whether it is based on an access control list and requires special handling.
*/
private static boolean isAclEnforcer(final Entry<EntityId> enforcerKeyEntry) {
return enforcerKeyEntry.exists() &&
Objects.equals(ThingCommand.RESOURCE_TYPE, enforcerKeyEntry.getValue().getResourceType());
}
/**
* 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 receivedThingCommand the command to authorize.
* @return optionally the authorized command extended by read subjects.
*/
private Optional<CreateThingWithEnforcer> enforceCreateThingBySelf(
final ThingCommand receivedThingCommand, final ActorRef sender) {
final ThingCommand thingCommand = transformModifyThingToCreateThing(receivedThingCommand);
final Optional<CreateThingWithEnforcer> result;
if (thingCommand instanceof CreateThing) {
final CreateThing createThing = (CreateThing) thingCommand;
final Optional<JsonObject> initialPolicyOptional = getInitialPolicyOrCopiedPolicy(createThing);
if (initialPolicyOptional.isPresent()) {
result = enforceCreateThingByOwnInlinedPolicy(createThing, initialPolicyOptional.get(), sender);
} else {
final Optional<AccessControlList> aclOptional =
createThing.getThing().getAccessControlList().filter(acl -> !acl.isEmpty());
if (aclOptional.isPresent()) {
result = enforceCreateThingByOwnAcl(createThing, aclOptional.get(), sender);
} else {
result = enforceCreateThingByAuthorizationContext(createThing);
}
}
} else {
// Other commands cannot be authorized by ACL or policy contained in self.
final DittoRuntimeException error =
ThingNotAccessibleException.newBuilder(thingCommand.getThingId())
.dittoHeaders(thingCommand.getDittoHeaders())
.build();
log(thingCommand).info("Enforcer was not existing for Thing <{}> and no auth info was inlined, " +
"responding with: {}", thingCommand.getThingId(), error);
replyToSender(error, sender);
result = Optional.empty();
}
return result;
}
private Optional<JsonObject> getInitialPolicyOrCopiedPolicy(final CreateThing createThing) {
final DittoHeaders dittoHeaders = createThing.getDittoHeaders();
final Optional<String> policyId = createThing.getPolicyIdOrPlaceholder()
.flatMap(ReferencePlaceholder::fromCharSequence)
.map(referencePlaceholder -> policyIdReferencePlaceholderResolver.resolve(referencePlaceholder,
dittoHeaders))
.map(policyIdCompletionStage -> awaitPolicyIdCompletionStage(policyIdCompletionStage, createThing))
.map(Optional::of)
.orElse(createThing.getPolicyIdOrPlaceholder());
if (policyId.isPresent()) {
final Policy policy = retrievePolicyWithEnforcement(policyId.get(), dittoHeaders);
final JsonObject jsonPolicyWithoutId = policy.toJson(JsonSchemaVersion.V_2).remove("policyId");
return Optional.of(jsonPolicyWithoutId);
}
return createThing.getInitialPolicy();
}
private String awaitPolicyIdCompletionStage(final CompletionStage<String> policyIdCompletionStage,
final CreateThing createThing) {
try {
return policyIdCompletionStage.toCompletableFuture().get(getAskTimeout().toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log(createThing).error(e, "An error occurred when trying to resolve policy id.");
throw GatewayServiceTimeoutException.newBuilder().build();
}
}
private Policy retrievePolicyWithEnforcement(final String policyId, final DittoHeaders dittoHeaders) {
final CompletionStage<Policy> policyCompletionStage =
PatternsCS.ask(conciergeForwarderActor(), RetrievePolicy.of(policyId, dittoHeaders), getAskTimeout())
.thenApply(response -> {
if (response instanceof RetrievePolicyResponse) {
return ((RetrievePolicyResponse) response).getPolicy();
} else if (response instanceof PolicyErrorResponse) {
throw ((PolicyErrorResponse) response).getDittoRuntimeException();
}
throw GatewayInternalErrorException.newBuilder().build();
});
return awaitPolicyCompletionStage(policyCompletionStage, dittoHeaders);
}
private Policy awaitPolicyCompletionStage(final CompletionStage<Policy> policyCompletionStage,
final DittoHeaders dittoHeaders) {
try {
return policyCompletionStage.toCompletableFuture().get(getAskTimeout().toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log(dittoHeaders).error(e, "An error occurred when trying to retrieve policy.");
throw GatewayServiceTimeoutException.newBuilder().build();
}
}
private Optional<CreateThingWithEnforcer> enforceCreateThingByAuthorizationContext(final CreateThing createThing) {
// Command without authorization information is authorized by default.
final Set<String> authorizedSubjects = createThing.getDittoHeaders()
.getAuthorizationContext()
.getFirstAuthorizationSubject()
.map(subject -> Collections.singleton(subject.getId()))
.orElse(Collections.emptySet());
final CreateThing command =
AbstractEnforcement.addReadSubjectsToSignal(createThing, authorizedSubjects);
final Enforcer enforcer = new AuthorizedSubjectsEnforcer(authorizedSubjects);
return Optional.of(new CreateThingWithEnforcer(command, enforcer));
}
private Optional<CreateThingWithEnforcer> enforceCreateThingByOwnInlinedPolicy(final CreateThing createThing,
final JsonObject inlinedPolicy, final ActorRef sender) {
return checkInitialPolicy(createThing, inlinedPolicy, sender).flatMap(initialPolicy -> {
if (PoliciesValidator.newInstance(initialPolicy).isValid()) {
final Enforcer initialEnforcer = PolicyEnforcers.defaultEvaluator(initialPolicy);
return attachEnforcerOrReplyWithError(createThing, initialEnforcer,
ThingCommandEnforcement::authorizeByPolicy, sender);
} else {
final DittoRuntimeException error =
PolicyInvalidException.newBuilder(MIN_REQUIRED_POLICY_PERMISSIONS, createThing.getThingId())
.dittoHeaders(createThing.getDittoHeaders())
.build();
replyToSender(error, sender);
return Optional.empty();
}
});
}
private Optional<Policy> checkInitialPolicy(final CreateThing createThing, final JsonObject inlinedPolicy,
final ActorRef sender) {
try {
// Java doesn't permit conversion of this early return into assignment to final variable.
return Optional.of(PoliciesModelFactory.newPolicy(inlinedPolicy));
} catch (final JsonRuntimeException | DittoJsonException e) {
final String thingId = createThing.getThingId();
final DittoRuntimeException error = PolicyInvalidException.newBuilderForCause(e, thingId)
.dittoHeaders(createThing.getDittoHeaders())
.build();
replyToSender(error, sender);
} catch (final DittoRuntimeException e) {
final DittoHeaders dittoHeaders = createThing.getDittoHeaders();
if (e instanceof PolicyException) {
// user error; no need to log stack trace.
replyToSender(e.setDittoHeaders(dittoHeaders), sender);
} else {
reportError("Error during creation of inline policy from JSON", sender, e, dittoHeaders);
}
}
return Optional.empty();
}
private Optional<CreateThingWithEnforcer> enforceCreateThingByOwnAcl(final CreateThing createThing,
final AccessControlList acl, final ActorRef sender) {
if (AclValidator.newInstance(acl, Thing.MIN_REQUIRED_PERMISSIONS).isValid()) {
final Enforcer initialEnforcer = AclEnforcer.of(acl);
return attachEnforcerOrReplyWithError(createThing, initialEnforcer,
ThingCommandEnforcement::authorizeByAcl, sender);
} else {
final DittoRuntimeException error = AclInvalidException.newBuilder(createThing.getThingId())
.dittoHeaders(createThing.getDittoHeaders())
.build();
replyToSender(error, sender);
return Optional.empty();
}
}
private Optional<CreateThingWithEnforcer> attachEnforcerOrReplyWithError(final CreateThing command,
final Enforcer enforcer,
final BiFunction<Enforcer, ThingCommand<CreateThing>, Optional<CreateThing>> authorization,
final ActorRef sender) {
final Optional<CreateThing> authorizedCommand = authorization.apply(enforcer, command);
if (authorizedCommand.isPresent()) {
return authorizedCommand.map(cmd -> new CreateThingWithEnforcer(cmd, enforcer));
} else {
respondWithError(command, sender, self());
return Optional.empty();
}
}
/**
* 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 ModifyThing modifyThing = (ModifyThing) receivedCommand;
final JsonObject initialPolicy = modifyThing.getInitialPolicy().orElse(null);
return CreateThing.of(modifyThing.getThing(), initialPolicy, 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> Optional<T> authorizeByPolicy(final Enforcer policyEnforcer,
final ThingCommand<T> command) {
final ResourceKey thingResourceKey = PoliciesResourceType.thingResource(command.getResourcePath());
final AuthorizationContext authorizationContext = command.getDittoHeaders().getAuthorizationContext();
final boolean authorized;
if (command instanceof ThingModifyCommand) {
final String permission = Permission.WRITE;
authorized = policyEnforcer.hasUnrestrictedPermissions(thingResourceKey, authorizationContext, permission);
} else {
final String permission = Permission.READ;
authorized = policyEnforcer.hasPartialPermissions(thingResourceKey, authorizationContext, permission);
}
return authorized
? Optional.of(AbstractEnforcement.addReadSubjectsToThingSignal(command, policyEnforcer))
: Optional.empty();
}
/**
* Authorize a thing-command by an ACL enforcer.
*
* @param <T> type of the thing-command.
* @param aclEnforcer the ACL enforcer.
* @param command the command to authorize.
* @return optionally the authorized command extended by read subjects.
*/
static <T extends ThingCommand> Optional<T> authorizeByAcl(final Enforcer aclEnforcer,
final ThingCommand<T> command) {