/
ThingCommandEnforcement.java
1290 lines (1150 loc) · 65 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.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.HashMap;
import java.util.List;
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.Supplier;
import javax.annotation.Nullable;
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.entity.id.EntityId;
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.namespaces.NamespaceBlockedException;
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.PolicyId;
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.model.things.ThingConstants;
import org.eclipse.ditto.model.things.ThingId;
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.ConciergeMessagingConstants;
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.akka.LogUtil;
import org.eclipse.ditto.services.utils.akka.controlflow.AbstractGraphActor;
import org.eclipse.ditto.services.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.services.utils.akka.logging.ThreadSafeDittoLogger;
import org.eclipse.ditto.services.utils.cache.Cache;
import org.eclipse.ditto.services.utils.cache.EntityIdWithResourceType;
import org.eclipse.ditto.services.utils.cache.InvalidateCacheEntry;
import org.eclipse.ditto.services.utils.cache.entry.Entry;
import org.eclipse.ditto.services.utils.cacheloaders.IdentityCache;
import org.eclipse.ditto.services.utils.cluster.DistPubSubAccess;
import org.eclipse.ditto.signals.commands.base.CommandToExceptionRegistry;
import org.eclipse.ditto.signals.commands.base.exceptions.GatewayInternalErrorException;
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.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.pattern.AskTimeoutException;
import akka.pattern.Patterns;
/**
* Authorize {@code ThingCommand}.
*/
public final class ThingCommandEnforcement extends AbstractEnforcement<ThingCommand> {
private static final ThreadSafeDittoLogger LOGGER =
DittoLoggerFactory.getThreadSafeLogger(ThingCommandEnforcement.class);
/**
* 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 List<SubjectIssuer> subjectIssuersForPolicyMigration;
private final ActorRef thingsShardRegion;
private final ActorRef policiesShardRegion;
private final EnforcerRetriever thingEnforcerRetriever;
private final EnforcerRetriever policyEnforcerRetriever;
private final Cache<EntityIdWithResourceType, Entry<EntityIdWithResourceType>> thingIdCache;
private final Cache<EntityIdWithResourceType, Entry<Enforcer>> policyEnforcerCache;
private final PreEnforcer preEnforcer;
private final Cache<EntityIdWithResourceType, Entry<Enforcer>> aclEnforcerCache;
private final PolicyIdReferencePlaceholderResolver policyIdReferencePlaceholderResolver;
private ThingCommandEnforcement(final Contextual<ThingCommand> data,
final ActorRef thingsShardRegion,
final ActorRef policiesShardRegion,
final Cache<EntityIdWithResourceType, Entry<EntityIdWithResourceType>> thingIdCache,
final Cache<EntityIdWithResourceType, Entry<Enforcer>> policyEnforcerCache,
final Cache<EntityIdWithResourceType, Entry<Enforcer>> aclEnforcerCache,
final PreEnforcer preEnforcer,
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);
this.preEnforcer = preEnforcer;
thingEnforcerRetriever =
PolicyOrAclEnforcerRetrieverFactory.create(thingIdCache, policyEnforcerCache, aclEnforcerCache);
policyEnforcerRetriever = new EnforcerRetriever(IdentityCache.INSTANCE, policyEnforcerCache);
policyIdReferencePlaceholderResolver =
PolicyIdReferencePlaceholderResolver.of(conciergeForwarder(), getAskTimeout());
}
@Override
public CompletionStage<Contextual<WithDittoHeaders>> enforce() {
final ThingCommand signal = signal();
LogUtil.enhanceLogWithCorrelationIdOrRandom(signal);
return thingEnforcerRetriever.retrieve(entityId(), (enforcerKeyEntry, enforcerEntry) -> {
try {
return doEnforce(enforcerKeyEntry, enforcerEntry).exceptionally(this::handleExceptionally);
} catch (final RuntimeException e) {
return CompletableFuture.completedFuture(handleExceptionally(e));
}
});
}
private CompletionStage<Contextual<WithDittoHeaders>> doEnforce(
final Entry<EntityIdWithResourceType> enforcerKeyEntry, final Entry<Enforcer> enforcerEntry) {
if (!enforcerEntry.exists()) {
return enforceThingCommandByNonexistentEnforcer(enforcerKeyEntry);
} else {
final Contextual<WithDittoHeaders> enforcementResult;
if (isAclEnforcer(enforcerKeyEntry)) {
enforcementResult = enforceThingCommandByAclEnforcer(enforcerEntry.getValueOrThrow());
} else {
final EntityId policyId = enforcerKeyEntry.getValueOrThrow().getId();
enforcementResult = enforceThingCommandByPolicyEnforcer(signal(),
PolicyId.of(policyId),
enforcerEntry.getValueOrThrow());
}
return CompletableFuture.completedFuture(enforcementResult);
}
}
/**
* 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<EntityIdWithResourceType> enforcerKeyEntry) {
if (enforcerKeyEntry.exists()) {
// Thing exists but its policy is deleted.
final ThingId thingId = signal().getThingEntityId();
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 DittoRuntimeException 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;
});
}
}
/**
* Authorize a thing command by ACL enforcer with special handling for the field "/acl".
*
* @param enforcer the ACL enforcer.
* @return the contextual including message and receiver
*/
private Contextual<WithDittoHeaders> enforceThingCommandByAclEnforcer(final Enforcer enforcer) {
final ThingCommand<?> thingCommand = signal();
final ThingCommand commandWithReadSubjects = authorizeByAclOrThrow(enforcer, thingCommand);
final Contextual<WithDittoHeaders> result;
if (commandWithReadSubjects instanceof RetrieveThing &&
shouldRetrievePolicyWithThing(commandWithReadSubjects)) {
final RetrieveThing retrieveThing = (RetrieveThing) commandWithReadSubjects;
result = retrieveThingAclAndMigrateToPolicy(retrieveThing, enforcer);
} else {
result = forwardToThingsShardRegion(commandWithReadSubjects);
}
return result;
}
private Contextual<WithDittoHeaders> retrieveThingAclAndMigrateToPolicy(final RetrieveThing retrieveThing,
final Enforcer enforcer) {
final JsonFieldSelectorBuilder jsonFieldSelectorBuilder =
JsonFactory.newFieldSelectorBuilder().addFieldDefinition(Thing.JsonFields.ACL);
retrieveThing.getSelectedFields().ifPresent(jsonFieldSelectorBuilder::addPointers);
final DittoHeaders dittoHeaders = DittoHeaders.newBuilder(retrieveThing.getDittoHeaders())
.schemaVersion(JsonSchemaVersion.V_1)
.build();
final RetrieveThing retrieveThingV1 = RetrieveThing.getBuilder(retrieveThing.getThingEntityId(), dittoHeaders)
.withSelectedFields(jsonFieldSelectorBuilder.build())
.build();
final Supplier<CompletionStage<RetrieveThingResponse>> askFuture = () ->
Patterns.ask(thingsShardRegion, retrieveThingV1, getAskTimeout())
.handle((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(),
PolicyId.of(retrieveThing.getThingEntityId()),
subjectIssuersForPolicyMigration);
return reportAggregatedThingAndPolicy(retrieveThing,
retrieveThingResponse.setDittoHeaders(retrieveThing.getDittoHeaders()),
policy, enforcer);
} else {
return retrieveThingResponse.setDittoHeaders(retrieveThing.getDittoHeaders());
}
} else if (isAskTimeoutException(response, error)) {
throw reportThingUnavailable();
} else {
throw reportUnexpectedErrorOrResponse("retrieving thing for ACL migration", response,
error);
}
});
return withMessageToReceiverViaAskFuture(retrieveThingV1, sender(), askFuture);
}
/**
* Authorize a thing command by policy enforcer with view restriction for query commands.
*
* @param policyId 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;
if (thingQueryCommand instanceof RetrieveThing &&
shouldRetrievePolicyWithThing(thingQueryCommand)) {
final RetrieveThing retrieveThing = (RetrieveThing) thingQueryCommand;
result = withMessageToReceiverViaAskFuture(retrieveThing, sender(),
() -> retrieveThingAndPolicy(retrieveThing, policyId, enforcer));
} else {
result = withMessageToReceiverViaAskFuture(thingQueryCommand, sender(),
() -> askThingsShardRegionAndBuildJsonView(thingQueryCommand, enforcer));
}
} else {
result = forwardToThingsShardRegion(commandWithReadSubjects);
}
return result;
}
/**
* 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.
* @return always {@code true}.
*/
private CompletionStage<WithDittoHeaders> askThingsShardRegionAndBuildJsonView(
final ThingQueryCommand commandWithReadSubjects, final Enforcer enforcer) {
return Patterns.ask(thingsShardRegion, commandWithReadSubjects, getAskTimeout())
.handle((response, error) -> {
if (response instanceof ThingQueryCommandResponse) {
return reportJsonViewForThingQuery((ThingQueryCommandResponse) response, enforcer);
} else if (response instanceof DittoRuntimeException) {
return (DittoRuntimeException) response;
} else if (isAskTimeoutException(response, error)) {
final AskTimeoutException askTimeoutException = error instanceof AskTimeoutException
? (AskTimeoutException) error
: (AskTimeoutException) response;
return reportTimeoutForThingQuery(commandWithReadSubjects, askTimeoutException);
} else if (error != null) {
return reportUnexpectedError("before building JsonView", error);
} else {
return reportUnknownResponse("before building JsonView", response);
}
});
}
/**
* 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.
* @return always {@code true}.
*/
private CompletionStage<WithDittoHeaders> retrieveThingAndPolicy(final RetrieveThing retrieveThing,
final PolicyId policyId, final Enforcer enforcer) {
final DittoHeaders dittoHeadersWithoutPreconditionHeaders = retrieveThing.getDittoHeaders()
.toBuilder()
.removePreconditionHeaders()
.build();
final Optional<RetrievePolicy> retrievePolicyOptional = PolicyCommandEnforcement.authorizePolicyCommand(
RetrievePolicy.of(policyId, dittoHeadersWithoutPreconditionHeaders), enforcer);
if (retrievePolicyOptional.isPresent()) {
return retrieveThingBeforePolicy(retrieveThing)
.thenCompose(retrieveThingResponse -> {
if (retrieveThingResponse instanceof RetrieveThingResponse) {
final RetrievePolicy 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 askThingsShardRegionAndBuildJsonView(retrieveThing, enforcer);
}
}
/**
* 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<WithDittoHeaders> retrieveThingBeforePolicy(final RetrieveThing command) {
return Patterns.ask(thingsShardRegion, command, getAskTimeout())
.handle((response, error) -> {
if (response instanceof WithDittoHeaders) {
return (WithDittoHeaders) response;
} else if (isAskTimeoutException(response, error)) {
return reportThingUnavailable();
} else {
return reportUnexpectedErrorOrResponse("retrieving thing before inlined policy", response,
error);
}
});
}
private ThingUnavailableException reportThingUnavailable() {
return ThingUnavailableException.newBuilder(signal().getThingEntityId()).dittoHeaders(dittoHeaders()).build();
}
/**
* 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 -> Patterns.ask(policiesShardRegion, msg, getAskTimeout()))
.handle((response, error) -> {
LOGGER.debug("Response of policiesShardRegion: <{}>", response);
if (response instanceof RetrievePolicyResponse) {
return Optional.of((RetrievePolicyResponse) response);
} else if (error != null) {
LOGGER.withCorrelationId(getCorrelationIdOrNull(error, retrieveThing))
.error("Retrieving inlined policy after RetrieveThing", error);
} else {
LOGGER.withCorrelationId(getCorrelationIdOrNull(response, retrieveThing))
.info("No authorized response when retrieving inlined policy <{}> for thing <{}>: {}",
retrievePolicy.getEntityId(), retrieveThing.getThingEntityId(), response);
}
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 DittoHeaders 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 askTimeoutException the timeout exception.
*/
private ThingUnavailableException reportTimeoutForThingQuery(final ThingQueryCommand command,
final AskTimeoutException askTimeoutException) {
LOGGER.withCorrelationId(dittoHeaders()).error("Timeout before building JsonView", askTimeoutException);
return ThingUnavailableException.newBuilder(command.getThingEntityId())
.dittoHeaders(command.getDittoHeaders())
.build();
}
/**
* Mixin-private: report thing query response with view on entity restricted by enforcer.
*
* @param thingQueryCommandResponse response of query.
* @param enforcer the enforcer.
*/
private ThingQueryCommandResponse reportJsonViewForThingQuery(
final ThingQueryCommandResponse<?> thingQueryCommandResponse, final Enforcer enforcer) {
try {
return buildJsonViewForThingQueryCommandResponse(thingQueryCommandResponse, enforcer);
} catch (final RuntimeException e) {
throw reportError("Error after building JsonView", e);
}
}
/**
* 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.
*
* @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.getThingEntityId());
}
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 EntityIdWithResourceType entityId = EntityIdWithResourceType.of(ThingCommand.RESOURCE_TYPE, thingId);
thingIdCache.invalidate(entityId);
aclEnforcerCache.invalidate(entityId);
pubSubMediator().tell(DistPubSubAccess.sendToAll(
ConciergeMessagingConstants.ENFORCER_ACTOR_PATH,
InvalidateCacheEntry.of(entityId),
true),
self());
}
private void invalidatePolicyCache(final PolicyId policyId) {
final EntityIdWithResourceType entityId = EntityIdWithResourceType.of(PolicyCommand.RESOURCE_TYPE, policyId);
policyEnforcerCache.invalidate(entityId);
pubSubMediator().tell(DistPubSubAccess.sendToAll(
ConciergeMessagingConstants.ENFORCER_ACTOR_PATH,
InvalidateCacheEntry.of(entityId),
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 ResourceKey resourceKey = ResourceKey.newInstance(ThingConstants.ENTITY_TYPE, response.getResourcePath());
final AuthorizationContext 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 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.
*/
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();
if (initialPolicyOptional.isPresent()) {
return enforceCreateThingByOwnInlinedPolicyOrThrow(createThing,
initialPolicyOptional.get());
} else {
final Thing thing = createThing.getThing();
return thing.getAccessControlList()
.filter(acl -> !acl.isEmpty())
.map(aclEntries -> enforceCreateThingByOwnAclOrThrow(createThing, aclEntries))
.orElseGet(() -> enforceCreateThingByAuthorizationContext(createThing));
}
});
} else {
// Other commands cannot be authorized by ACL or policy contained in self.
final DittoRuntimeException error = ThingNotAccessibleException.newBuilder(thingCommand.getThingEntityId())
.dittoHeaders(thingCommand.getDittoHeaders())
.build();
LOGGER.withCorrelationId(dittoHeaders())
.info("Enforcer was not existing for Thing <{}> and no auth info was inlined, responding with: {}",
thingCommand.getThingEntityId(), error);
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);
return policyIdReferencePlaceholderResolver.resolve(referencePlaceholder, dittoHeaders());
})
.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 Map<String, String> enhancedMap = new HashMap<>(dittoHeaders());
enhancedMap.put(AbstractGraphActor.DITTO_INTERNAL_SPECIAL_ENFORCEMENT_LANE, "true");
final DittoHeaders adjustedHeaders = DittoHeaders.of(enhancedMap);
return Patterns.ask(conciergeForwarder(), RetrievePolicy.of(policyId, adjustedHeaders), getAskTimeout())
.thenApply(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(dittoHeaders())
.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 DittoHeaders dittoHeaders = createThing.getDittoHeaders();
final AuthorizationContext 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 Policy initialPolicy = getInitialPolicy(createThing, inlinedPolicy);
final PoliciesValidator policiesValidator = PoliciesValidator.newInstance(initialPolicy);
if (policiesValidator.isValid()) {
final Enforcer initialEnforcer = PolicyEnforcers.defaultEvaluator(initialPolicy);
return attachEnforcerOrThrow(createThing, initialEnforcer,
ThingCommandEnforcement::authorizeByPolicyOrThrow);
} else {
throw PolicyInvalidException.newBuilder(MIN_REQUIRED_POLICY_PERMISSIONS, createThing.getThingEntityId())
.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 ThingId thingId = createThing.getThingEntityId();
throw PolicyInvalidException.newBuilderForCause(e, thingId)
.dittoHeaders(createThing.getDittoHeaders())
.build();
} catch (final DittoRuntimeException e) {
final DittoHeaders 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 enforceCreateThingByOwnAclOrThrow(final CreateThing command,
final AccessControlList acl) {
final AclValidator aclValidator = AclValidator.newInstance(acl, Thing.MIN_REQUIRED_PERMISSIONS);
if (aclValidator.isValid()) {
final Enforcer initialEnforcer = AclEnforcer.of(acl);
return attachEnforcerOrThrow(command, initialEnforcer, ThingCommandEnforcement::authorizeByAclOrThrow);
} else {
throw AclInvalidException.newBuilder(command.getThingEntityId())
.dittoHeaders(command.getDittoHeaders())
.build();
}
}
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 ModifyThing modifyThing = (ModifyThing) receivedCommand;
final JsonObject initialPolicy = modifyThing.getInitialPolicy().orElse(null);
final String policyIdOrPlaceholder = modifyThing.getPolicyIdOrPlaceholder().orElse(null);
final Thing newThing = modifyThing.getThing().toBuilder()
.setId(modifyThing.getThingEntityId())
.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 authorizeByPolicyOrThrow(final Enforcer policyEnforcer,
final ThingCommand<T> command) {
final ResourceKey thingResourceKey = PoliciesResourceType.thingResource(command.getResourcePath());
final DittoHeaders dittoHeaders = command.getDittoHeaders();
final AuthorizationContext authorizationContext = dittoHeaders.getAuthorizationContext();
final boolean authorized;
if (command instanceof ThingModifyCommand) {
authorized = policyEnforcer.hasUnrestrictedPermissions(thingResourceKey, authorizationContext,
Permission.WRITE);
} else {
authorized = policyEnforcer.hasPartialPermissions(thingResourceKey, authorizationContext, Permission.READ);
}
if (authorized) {
return AbstractEnforcement.addEffectedReadSubjectsToThingSignal(command, policyEnforcer);
} else {
throw errorForThingCommand(command);
}
}
/**
* Authorizes 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 the authorized command extended by read subjects.
*/
static <T extends ThingCommand<T>> T authorizeByAclOrThrow(final Enforcer aclEnforcer,
final ThingCommand<T> command) {
final ResourceKey thingResourceKey = PoliciesResourceType.thingResource(command.getResourcePath());
final AuthorizationContext authorizationContext = command.getDittoHeaders().getAuthorizationContext();
final Permissions permissions = command instanceof ThingModifyCommand
? computeAclPermissions((ThingModifyCommand<?>) command)
: Permissions.newInstance(Permission.READ);
if (aclEnforcer.hasUnrestrictedPermissions(thingResourceKey, authorizationContext, permissions)) {
return AbstractEnforcement.addEffectedReadSubjectsToThingSignal(command, aclEnforcer);
} else {
throw errorForThingCommand(command);
}
}
/**
* Compute ACL permissions relevant for a {@code ThingModifyCommand}. The field "/acl" is handled specially with the
* "ADMINISTRATE" permission.
*
* @param command the command.
* @return permissions needed to execute the command.
*/
private static Permissions computeAclPermissions(final ThingModifyCommand<?> command) {
return command.changesAuthorization()
? Permissions.newInstance(Permission.WRITE, ADMINISTRATE.name())
: Permissions.newInstance(Permission.WRITE);
}
/**
* Check if inlined policy should be retrieved together with the thing.
*
* @param command the thing query command.
* @return whether it is necessary to retrieve the thing's policy.
*/
private static boolean shouldRetrievePolicyWithThing(final ThingCommand command) {
final RetrieveThing retrieveThing = (RetrieveThing) command;
final boolean isNotV1 = JsonSchemaVersion.V_1 != command.getImplementedSchemaVersion();
return isNotV1 && retrieveThing.getSelectedFields()
.filter(selector -> selector.getPointers()
.stream()
.anyMatch(jsonPointer -> jsonPointer.getRoot()
.filter(jsonKey -> Policy.INLINED_FIELD_NAME.equals(jsonKey.toString()))
.isPresent()))
.isPresent();
}
private CompletionStage<Contextual<WithDittoHeaders>> handleInitialCreateThing(
final CreateThing createThing, final Enforcer enforcer) {
final CompletionStage<Contextual<WithDittoHeaders>> result;
if (shouldCreatePolicyForCreateThing(createThing)) {
checkForErrorsInCreateThingWithPolicy(createThing);
result = createThingWithInitialPolicy(createThing, enforcer).thenApply(this::forwardToThingsShardRegion);
} else if (createThing.getThing().getPolicyEntityId().isPresent()) {
final PolicyId policyId = createThing.getThing()
.getPolicyEntityId()
.orElseThrow(IllegalStateException::new);
checkForErrorsInCreateThingWithPolicy(createThing);
result = enforceCreateThingForNonexistentThingWithPolicyId(createThing, policyId);
} else {
// nothing to do with policy, simply forward the command
result = CompletableFuture.completedFuture(forwardToThingsShardRegion(createThing));
}
return result;
}
private static boolean shouldCreatePolicyForCreateThing(final CreateThing createThing) {
final JsonSchemaVersion commandVersion =
createThing.getDittoHeaders().getSchemaVersion().orElse(JsonSchemaVersion.LATEST);
return createThing.getInitialPolicy().isPresent() ||
JsonSchemaVersion.V_1 != commandVersion && createThing.getThing().getPolicyEntityId().isEmpty();
}
private static void checkForErrorsInCreateThingWithPolicy(final CreateThing command) {
checkAclAbsenceInCreateThing(command);
validatePolicyIdForCreateThing(command);
}
private static void checkAclAbsenceInCreateThing(final CreateThing createThing) {
final Thing thing = createThing.getThing();
final Optional<AccessControlList> accessControlListOptional = thing.getAccessControlList();
if (accessControlListOptional.isPresent()) {
throw AclNotAllowedException.newBuilder(createThing.getThingEntityId())
.dittoHeaders(createThing.getDittoHeaders())
.build();
}
}
private static void validatePolicyIdForCreateThing(final CreateThing createThing) {
final Thing thing = createThing.getThing();
final Optional<String> policyIdOpt = thing.getPolicyEntityId().map(String::valueOf);
final Optional<String> policyIdInPolicyOpt = createThing.getInitialPolicy()
.flatMap(jsonObject -> jsonObject.getValue(Thing.JsonFields.POLICY_ID));
final boolean isValid;
if (policyIdOpt.isPresent()) {
isValid = policyIdInPolicyOpt.isEmpty() || policyIdInPolicyOpt.equals(policyIdOpt);