-
Notifications
You must be signed in to change notification settings - Fork 157
/
AuthzPolicyEnforcementPersistenceInterceptor.java
1113 lines (999 loc) · 58.8 KB
/
AuthzPolicyEnforcementPersistenceInterceptor.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
/*
* (C) Copyright IBM Corp. 2019, 2022
*
* SPDX-License-Identifier: Apache-2.0
*/
package com.ibm.fhir.smart;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.ws.rs.core.Response;
import com.ibm.fhir.config.FHIRConfigHelper;
import com.ibm.fhir.config.FHIRRequestContext;
import com.ibm.fhir.model.resource.Bundle;
import com.ibm.fhir.model.resource.Parameters;
import com.ibm.fhir.model.resource.Parameters.Parameter;
import com.ibm.fhir.model.resource.Provenance;
import com.ibm.fhir.model.resource.Resource;
import com.ibm.fhir.model.resource.SearchParameter;
import com.ibm.fhir.model.type.Canonical;
import com.ibm.fhir.model.type.Reference;
import com.ibm.fhir.model.type.code.CompartmentType;
import com.ibm.fhir.model.type.code.HTTPVerb;
import com.ibm.fhir.model.type.code.IssueType;
import com.ibm.fhir.model.type.code.ResourceType;
import com.ibm.fhir.model.util.FHIRUtil;
import com.ibm.fhir.model.util.ModelSupport;
import com.ibm.fhir.path.FHIRPathNode;
import com.ibm.fhir.path.evaluator.FHIRPathEvaluator;
import com.ibm.fhir.path.evaluator.FHIRPathEvaluator.EvaluationContext;
import com.ibm.fhir.persistence.FHIRPersistence;
import com.ibm.fhir.persistence.SingleResourceResult;
import com.ibm.fhir.persistence.context.FHIRPersistenceContext;
import com.ibm.fhir.persistence.context.FHIRPersistenceContextFactory;
import com.ibm.fhir.persistence.context.FHIRPersistenceEvent;
import com.ibm.fhir.persistence.exception.FHIRPersistenceException;
import com.ibm.fhir.persistence.exception.FHIRPersistenceResourceDeletedException;
import com.ibm.fhir.persistence.exception.FHIRPersistenceResourceNotFoundException;
import com.ibm.fhir.search.compartment.CompartmentHelper;
import com.ibm.fhir.search.context.FHIRSearchContext;
import com.ibm.fhir.search.exception.FHIRSearchException;
import com.ibm.fhir.search.parameters.QueryParameter;
import com.ibm.fhir.search.util.ReferenceUtil;
import com.ibm.fhir.search.util.ReferenceValue;
import com.ibm.fhir.search.util.SearchHelper;
import com.ibm.fhir.server.spi.interceptor.FHIRPersistenceInterceptor;
import com.ibm.fhir.server.spi.interceptor.FHIRPersistenceInterceptorException;
import com.ibm.fhir.server.spi.operation.FHIROperationContext;
import com.ibm.fhir.smart.JWT.Claim;
import com.ibm.fhir.smart.JWT.DecodedJWT;
import com.ibm.fhir.smart.Scope.ContextType;
import com.ibm.fhir.smart.Scope.Permission;
import jakarta.json.Json;
import jakarta.json.JsonObject;
import jakarta.json.JsonReader;
import jakarta.json.JsonReaderFactory;
import jakarta.json.JsonValue;
/**
* A persistence interceptor that enforces authorization policy based on a JWT access token with SMART-on-FHIR scopes.
*
* <p><a href="http://hl7.org/fhir/smart-app-launch/1.0.0/scopes-and-launch-context/index.html">SMART App Launch: Scopes and Launch Context</a>
* defines the following pattern for the OAuth 2.0 scopes expected in the JWT:
* <pre>
* ( 'patient' | 'user' ) '/' ( fhir-resource | '*' ) '.' ( 'read' | 'write' | '*' )`
* </pre>
*
* <p><a href="http://www.hl7.org/fhir/smart-app-launch/backend-services.html">SMART Backend Services</a>
* extends that to include an additional context type for 'system'.
*
* <p>This interceptor supports both flavors.
* <p>Before and after each interaction, as appropriate, the Authorization header
* is checked for a scope that permits the requested interaction. If the scope that permits the interaction is of
* context type 'patient' then the interceptor looks for a {@code patient_id} claim in the access token.
* <ol>
* <li> For search interactions targeting resource types that can be in a patient compartment, the search is automatically
* scoped to the Patient compartment(s) of the id(s) in the patient_id claim.
* <li> For any interaction that returns resources, if the resource type can be in a patient compartment then the interceptor
* ensures that it is in the compartment of the the id(s) passed in the patient_id claim.
* </ol>
*/
public class AuthzPolicyEnforcementPersistenceInterceptor implements FHIRPersistenceInterceptor {
private static final Logger log = Logger.getLogger(AuthzPolicyEnforcementPersistenceInterceptor.class.getName());
private static final String DAVINCI_DRUG_FORMULARY_COVERAGE_PLAN =
"http://hl7.org/fhir/us/davinci-drug-formulary/StructureDefinition/usdf-CoveragePlan";
private static final String BEARER_TOKEN_PREFIX = "Bearer";
private static final String PATIENT = "Patient";
private static final String RESOURCE = "Resource";
private static final String REQUEST_NOT_PERMITTED = "Requested interaction is not permitted by any of the passed scopes.";
private static final JsonReaderFactory JSON_READER_FACTORY = Json.createReaderFactory(null);
private final CompartmentHelper compartmentHelper = new CompartmentHelper();
private final SearchHelper searchHelper = new SearchHelper();
@Override
public void beforeInvoke(FHIROperationContext context) throws FHIRPersistenceInterceptorException {
Permission neededPermission;
Set<String> resourceTypes;
if ("import".equals(context.getOperationCode())) {
neededPermission = Permission.WRITE;
resourceTypes = computeImportResourceTypes(context);
} else if ("export".equals(context.getOperationCode())) {
neededPermission = Permission.READ;
resourceTypes = computeExportResourceTypes(context);
} else {
return;
}
if (resourceTypes.isEmpty()) {
throw new IllegalStateException("The set of resource types was unexpectedly empty");
}
DecodedJWT jwt = JWT.decode(getAccessToken());
List<Scope> systemScopesFromToken = getScopesFromToken(jwt).get(ContextType.SYSTEM);
for (String resourceType : resourceTypes) {
checkSystemScopes(resourceType, neededPermission, systemScopesFromToken, jwt);
}
}
@Override
public void afterInvoke(FHIROperationContext context) throws FHIRPersistenceInterceptorException {
Permission neededPermission = Permission.READ;
Set<String> resourceTypes = new HashSet<>();
if (!"bulkdata-status".equals(context.getOperationCode())) {
return;
}
Parameters parameters = (Parameters) context.getProperty(FHIROperationContext.PROPNAME_REQUEST_PARAMETERS);
// bulkdata-status has a special JSON response that is not a Parameters object
Response response = (Response) context.getProperty(FHIROperationContext.PROPNAME_RESPONSE);
if (response.hasEntity()) {
Object entity = response.getEntity();
if (entity instanceof String) {
JsonReader responseReader = JSON_READER_FACTORY.createReader(new StringReader((String)entity));
JsonObject responseObj = responseReader.readObject();
String request = responseObj.getJsonString("request").getString();
if (request.contains("$export")) {
for (JsonValue output : responseObj.getJsonArray("output")) {
resourceTypes.add(output.asJsonObject().getString("type"));
}
} else if (request.contains("$import")) {
// nothing much to check for bulk-import status; the only output is a set of OperationOutcome
} else {
String jobId = parameters.getParameter().stream()
.filter(p -> "job".equals(p.getName().getValue()))
.map(p -> p.getValue().as(ModelSupport.FHIR_STRING).getValue())
.findFirst()
.get();
throw new IllegalStateException("Bulk data request for job '" + jobId + "' is neither '$import' nor '$export'!");
}
} else {
throw new IllegalStateException("Encountered unexpected response entity of type " + entity.getClass().getName());
}
}
DecodedJWT jwt = JWT.decode(getAccessToken());
List<Scope> systemScopesFromToken = getScopesFromToken(jwt).get(ContextType.SYSTEM);
for (String resourceType : resourceTypes) {
checkSystemScopes(resourceType, neededPermission, systemScopesFromToken, jwt);
}
}
private Set<String> computeImportResourceTypes(FHIROperationContext context) {
Parameters parameters = (Parameters) context.getProperty(FHIROperationContext.PROPNAME_REQUEST_PARAMETERS);
Set<String> types = parameters.getParameter().stream()
.filter(p -> "input".equals(p.getName().getValue()))
.map(p -> p.getPart())
.flatMap(part -> part.stream()
.filter(pp -> "type".equals(pp.getName().getValue()))
.map(pp -> pp.getValue().as(ModelSupport.FHIR_STRING).getValue()))
.collect(Collectors.toSet());
return Collections.unmodifiableSet(types);
}
private Set<String> computeExportResourceTypes(FHIROperationContext context) {
Set<String> supportedResourceTypes = FHIRConfigHelper.getSupportedResourceTypes();
Set<String> resourceTypes = new HashSet<>();
Parameters parameters = (Parameters) context.getProperty(FHIROperationContext.PROPNAME_REQUEST_PARAMETERS);
Optional<Parameter> typesParam = parameters.getParameter().stream().filter(p -> "_type".equals(p.getName().getValue())).findFirst();
switch (context.getType()) {
case INSTANCE: // Group/:id/$export
case RESOURCE_TYPE: // Patient/$export
// Either way, the set of resourceTypes to export are those from the Patient compartment
try {
Set<String> compartmentResourceMembers = compartmentHelper.getCompartmentResourceTypes(PATIENT);
if (typesParam.isPresent() && typesParam.get().getValue() != null) {
String typesString = typesParam.get().getValue().as(ModelSupport.FHIR_STRING).getValue();
for (String requestedType : Arrays.asList(typesString.split(","))) {
if (!supportedResourceTypes.contains(requestedType)) {
throw new IllegalStateException("Requested resource is not configured");
}
if (!compartmentResourceMembers.contains(requestedType)) {
throw new IllegalStateException("Requested resource is outside of the Patient Compartment");
}
resourceTypes.add(requestedType);
}
} else {
resourceTypes = compartmentResourceMembers;
}
} catch (FHIRSearchException e) {
throw new IllegalStateException("Unexpected error while computing the resource types for the export", e);
}
break;
case SYSTEM:
if (typesParam.isPresent() && typesParam.get().getValue() != null) {
String typesString = typesParam.get().getValue().as(ModelSupport.FHIR_STRING).getValue();
resourceTypes = Set.of(typesString.split(","));
for (String resourceType : resourceTypes) {
if (!supportedResourceTypes.contains(resourceType)) {
throw new IllegalStateException("Requested resource is not configured");
}
}
} else {
// "Resource" is used as a placeholder for the set of all resource types; equivalent to "*" in SMART
resourceTypes = supportedResourceTypes;
}
break;
default:
log.warning("Unexpected export of type " + context.getType());
break;
}
return resourceTypes;
}
@Override
public void beforeRead(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
String resourceType = event.getFhirResourceType();
DecodedJWT jwt = JWT.decode(getAccessToken());
if (PATIENT.equals(resourceType)) {
enforceDirectPatientAccess(resourceType, event.getFhirResourceId(), jwt);
} else {
ContextType approvedContext = checkScopes(resourceType, Permission.READ, getScopesFromToken(jwt));
if (approvedContext == ContextType.PATIENT) {
assertPatientIdClaimIsValued(jwt);
}
}
}
private void assertPatientIdClaimIsValued(DecodedJWT jwt) throws FHIRPersistenceInterceptorException {
if (jwt.getClaim("patient_id").isNull()) {
String msg = "Access token is missing 'patient_id' claim";
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
}
@Override
public void beforeVread(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
String resourceType = event.getFhirResourceType();
DecodedJWT jwt = JWT.decode(getAccessToken());
if (PATIENT.equals(resourceType)) {
enforceDirectPatientAccess(resourceType, event.getFhirResourceId(), jwt);
} else {
ContextType approvedContext = checkScopes(resourceType, Permission.READ, getScopesFromToken(jwt));
if (approvedContext == ContextType.PATIENT) {
assertPatientIdClaimIsValued(jwt);
}
}
}
@Override
public void beforeHistory(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
String resourceType = event.getFhirResourceType();
DecodedJWT jwt = JWT.decode(getAccessToken());
if (event.getFhirResourceId() == null) {
// System/type-level history
enforceSystemLevelAccess(resourceType, event.getSystemHistoryContextImpl().getResourceTypes(), jwt);
} else if (PATIENT.equals(resourceType)) {
// For a Patient resource instance, check scopes for direct patient access
enforceDirectPatientAccess(resourceType, event.getFhirResourceId(), jwt);
} else {
ContextType approvedContext = checkScopes(resourceType, Permission.READ, getScopesFromToken(jwt));
if (approvedContext == ContextType.PATIENT) {
assertPatientIdClaimIsValued(jwt);
}
}
}
private void enforceDirectPatientAccess(String resourceType, String resourceId, DecodedJWT jwt) throws FHIRPersistenceInterceptorException {
Map<ContextType, List<Scope>> groupedScopes = getScopesFromToken(jwt);
if (isApprovedByScopes(resourceType, Permission.READ, groupedScopes.get(ContextType.USER)) ||
isApprovedByScopes(resourceType, Permission.READ, groupedScopes.get(ContextType.SYSTEM))) {
return;
}
// If a patient/ scope is the only approving scope, then check the patient context
if (isApprovedByScopes(resourceType, Permission.READ, groupedScopes.get(ContextType.PATIENT))) {
Set<String> patientIdFromToken = getPatientIdFromToken(jwt);
if (!patientIdFromToken.contains(resourceId)) {
String msg = "Interaction with 'Patient/" + resourceId +
"' is not permitted under patient context '" + patientIdFromToken + "'.";
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
} else {
// no approving scopes
String msg = "Read permission for '" + resourceType +
"' is not granted by any of the provided scopes: " + groupedScopes.values();
if (log.isLoggable(Level.FINE)) {
log.fine(msg);
}
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
}
private void enforceSystemLevelAccess(String resourceType, List<String> types, DecodedJWT jwt) throws FHIRPersistenceInterceptorException {
Map<ContextType, List<Scope>> groupedScopes = getScopesFromToken(jwt);
boolean hasTypeParam = types != null && !types.isEmpty();
// Check for user or system access to the resource types
// If types specified, then check each of those, otherwise check the single type (which will be 'Resource')
if (!hasTypeParam && RESOURCE.equals(resourceType)) {
if (!isApprovedByScopes(resourceType, Permission.READ, groupedScopes.get(ContextType.USER)) &&
!isApprovedByScopes(resourceType, Permission.READ, groupedScopes.get(ContextType.SYSTEM))) {
String msg = "Whole-system interactions require a user or system scope with a wildcard resource type: "
+ "('user'|'system') '/' '*' '.' ('read'|'*')";
if (log.isLoggable(Level.FINE)) {
log.fine(msg);
}
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
} else {
List<String> typesToCheck = hasTypeParam ? types : Arrays.asList(resourceType);
for (String type : typesToCheck) {
if (!isApprovedByScopes(type, Permission.READ, groupedScopes.get(ContextType.USER)) &&
!isApprovedByScopes(type, Permission.READ, groupedScopes.get(ContextType.SYSTEM))) {
if (isApprovedByScopes(type, Permission.READ, groupedScopes.get(ContextType.PATIENT))) {
boolean isPatientCompartmentResource = false;
try {
isPatientCompartmentResource = compartmentHelper.getCompartmentResourceTypes(PATIENT).contains(type);
} catch (Exception e) {
String msg = "Unexpected exception while enforcing system level access";
throw new FHIRPersistenceInterceptorException(msg, e)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.EXCEPTION));
}
if (isPatientCompartmentResource) {
String msg = "'patient' scoped access tokens are not supported for system-level interactions against " +
"patient compartment resource types like " + type;
if (log.isLoggable(Level.FINE)) {
log.fine(msg);
}
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
} else {
// allow it and move on to the next type to check
continue;
}
}
String msg = "Read permission for system-level interaction with type '" + type +
"' is not granted by any of the provided scopes: " + groupedScopes.values();
if (log.isLoggable(Level.FINE)) {
log.fine(msg);
}
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
}
}
}
/**
* This method ensures the search is either for a resource type that is not a member of the
* patient compartment, or is a valid patient-compartment resource search that is scoped
* to the patient context from the access token.
*/
@Override
public void beforeSearch(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
String resourceType = event.getFhirResourceType();
DecodedJWT jwt = JWT.decode(getAccessToken());
FHIRSearchContext searchContext = event.getSearchContextImpl();
if (RESOURCE.equals(resourceType)) {
// System-level search
enforceSystemLevelAccess(resourceType, searchContext.getSearchResourceTypes(), jwt);
return;
}
ContextType approvedContext = checkScopes(event.getFhirResourceType(), Permission.READ, getScopesFromToken(jwt));
if (approvedContext == ContextType.SYSTEM || approvedContext == ContextType.USER) {
return;
}
// if the interaction is granted by PATIENT (and not SYSTEM or USER)
// then scope the search to the compartment(s) of the in-context patient(s)
assertPatientIdClaimIsValued(jwt);
Set<String> patientIdFromToken = getPatientIdFromToken(jwt);
// Determine if compartment search
String compartment = null;
String compartmentId = null;
for (QueryParameter queryParameter : searchContext.getSearchParameters()) {
if (queryParameter.isInclusionCriteria()) {
// Value will contain a reference to compartment
String[] tokens = queryParameter.getValues().get(0).getValueString().split("/");
compartment = tokens[0];
compartmentId = tokens[1];
break;
}
}
if (compartment != null) {
// Compartment search - validate patient access
switch(compartment) {
case "Patient":
if (!patientIdFromToken.contains(compartmentId)) {
String msg = "Interaction with 'Patient/" + compartmentId + "' is not permitted for patient context " + patientIdFromToken;
throw new FHIRPersistenceInterceptorException(msg).withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
break;
case "Encounter":
Resource r = executeRead(event.getPersistenceImpl(), ModelSupport.getResourceType(compartment), compartmentId);
if (!isInCompartment(compartment, compartmentId, r, CompartmentType.PATIENT, patientIdFromToken)) {
String msg = "Interaction with 'Encounter/" + compartmentId + "' is not permitted for patient context " + patientIdFromToken;
throw new FHIRPersistenceInterceptorException(msg).withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
break;
case "Device":
case "Practitioner":
case "RelatedPerson":
String msg = "Compartment search for compartment type '" + compartment + "' is not permitted.";
throw new FHIRPersistenceInterceptorException(msg).withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
default:
// If the operator has extended the server with custom compartment definitions, they will need to protect those separately
}
if (log.isLoggable(Level.FINE)) {
log.fine("Performing compartment search for compartment '" + compartment + "/" + compartmentId + "'.");
}
} else {
// Not compartment search - validate and convert to Patient compartment search if the resource type can be in the Patient compartment
try {
if (compartmentHelper.getCompartmentResourceTypes(PATIENT).contains(event.getFhirResourceType())) {
// Special case for the List resource because we want to enable searches for Formulary Coverage Plan lists
if ("List".equals(event.getFhirResourceType())) {
// In this case, we will rely on the afterSearch logic to prevent unauthorized access to patient-scoped Lists
return;
}
// Build the Patient compartment inclusion criteria search parameter
QueryParameter inclusionCriteria = searchHelper.buildInclusionCriteria(PATIENT, patientIdFromToken, event.getFhirResourceType());
// Add the inclusion criteria parameter to the front of the search parameter list
searchContext.getSearchParameters().add(0, inclusionCriteria);
}
} catch (Exception e) {
String msg = "Unexpected exception converting to Patient compartment search: " + e.getMessage();
throw new FHIRPersistenceInterceptorException(msg).withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.EXCEPTION));
}
}
}
@Override
public void beforeCreate(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
DecodedJWT jwt = JWT.decode(getAccessToken());
enforce(event.getFhirResource(), getPatientIdFromToken(jwt), Permission.WRITE, getScopesFromToken(jwt));
}
@Override
public void beforeDelete(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
DecodedJWT jwt = JWT.decode(getAccessToken());
enforce(event.getPrevFhirResource(), getPatientIdFromToken(jwt), Permission.WRITE, getScopesFromToken(jwt));
}
@Override
public void beforeUpdate(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
DecodedJWT jwt = JWT.decode(getAccessToken());
Set<String> patientIdFromToken = getPatientIdFromToken(jwt);
Map<ContextType, List<Scope>> scopesFromToken = getScopesFromToken(jwt);
// First, check READ permission on the existing resource to ensure we don't write over something that
// the user doesn't have access to
enforce(event.getPrevFhirResource(), patientIdFromToken, Permission.READ, scopesFromToken);
enforce(event.getFhirResource(), patientIdFromToken, Permission.WRITE, scopesFromToken);
}
@Override
public void afterRead(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
Resource resource = event.getFhirResource();
if (resource != null) {
DecodedJWT jwt = JWT.decode(getAccessToken());
Set<String> patientIdFromToken = getPatientIdFromToken(jwt);
Map<ContextType, List<Scope>> scopesFromToken = getScopesFromToken(jwt);
enforceDirectProvenanceAccess(event, resource, patientIdFromToken, scopesFromToken);
enforce(resource, patientIdFromToken, Permission.READ, scopesFromToken);
}
}
@Override
public void afterVread(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
Resource resource = event.getFhirResource();
if (resource != null) {
DecodedJWT jwt = JWT.decode(getAccessToken());
Set<String> patientIdFromToken = getPatientIdFromToken(jwt);
Map<ContextType, List<Scope>> scopesFromToken = getScopesFromToken(jwt);
enforceDirectProvenanceAccess(event, resource, patientIdFromToken, scopesFromToken);
enforce(resource, patientIdFromToken, Permission.READ, scopesFromToken);
}
}
@Override
public void afterHistory(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
DecodedJWT jwt = JWT.decode(getAccessToken());
Set<String> patientIdFromToken = getPatientIdFromToken(jwt);
Map<ContextType, List<Scope>> scopesFromToken = getScopesFromToken(jwt);
if (event.getFhirResource() instanceof Bundle) {
for (Bundle.Entry entry : ((Bundle) event.getFhirResource()).getEntry()) {
String resourceType = getResourceType(entry);
String resourceId = getResourceId(entry);
Resource resource = entry.getResource();
enforceDirectProvenanceAccess(event, resource, patientIdFromToken, scopesFromToken);
if (resourceType != null && resourceId != null) {
if (resource == null && entry.getRequest() != null && entry.getRequest().getMethod().getValueAsEnum() == HTTPVerb.Value.DELETE) {
// explicitly allow DELETE entries
// this is safe because beforeHistory prohibits system and type-level history request for patient-compartment resource types
// that are only covered by 'patient' scoped access tokens (and not 'user' or 'system' scopes)
continue;
}
enforce(resourceType, resourceId, resource, patientIdFromToken, Permission.READ, scopesFromToken);
} else {
throw new FHIRPersistenceInterceptorException("Unable to enforce authorization for history interaction "
+ "due to failure to compute the resource type and id for one or more response Bundle entries.");
}
}
} else {
throw new IllegalStateException("Expected event resource of type Bundle but found " +
event.getFhirResource().getClass().getSimpleName());
}
}
private void enforceDirectProvenanceAccess(FHIRPersistenceEvent event, Resource resource, Set<String> patientIdFromToken, Map<ContextType, List<Scope>> scopesFromToken)
throws FHIRPersistenceInterceptorException {
if (resource instanceof Provenance) {
ContextType approvedContext = checkScopes("Provenance", Permission.READ, scopesFromToken);
// if the approving context is of type 'patient' then the Provenance should only be returned if the patient has access
// to the target of the Provenance
if (approvedContext == ContextType.PATIENT) {
if (!isAllowed(((Provenance) resource).getTarget(), event.getPersistenceImpl(), patientIdFromToken, Permission.READ, scopesFromToken)) {
String msg = Permission.READ + " permission to 'Provenance/" + resource.getId() +
"' with context id(s): " + patientIdFromToken +
" requires access to one or more of its target resources.";
if (log.isLoggable(Level.FINE)) {
log.fine(msg);
}
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
}
}
}
/**
* Determine whether authorization to one or more referenced resources is granted by the end user in the form of scope strings.
*
* @param references a list of resource references; this method will dereference only relative literal references
* @param persistence the FHIRPersistence implementation to use for dereferencing the literal references
* @param contextIds an identifier for the current context (e.g. patient or user) as determined by the scope strings
* @param requiredPermission
* @param grantedScopes the SMART scopes associated with the request, indexed by ContextType
* @throws IllegalStateException if the baseUrl cannot be computed from the request context
* @throws FHIRPersistenceInterceptorException if the interaction is not permitted
*/
private boolean isAllowed(List<Reference> references, FHIRPersistence persistence, Set<String> contextIds, Permission requiredPermission, Map<ContextType, List<Scope>> grantedScopes) {
boolean allow = false;
String baseUrl;
try {
baseUrl = ReferenceUtil.getServiceBaseUrl();
} catch (FHIRSearchException e) {
throw new IllegalStateException("Unexpected error while computing the service baseUrl");
}
for (Reference ref : references) {
ReferenceValue referenceValue = ReferenceUtil.createReferenceValueFrom(ref, baseUrl);
if (ReferenceValue.ReferenceType.LITERAL_RELATIVE == referenceValue.getType()) {
Class<? extends Resource> resourceType = ModelSupport.getResourceType(referenceValue.getTargetResourceType());
try {
SingleResourceResult<? extends Resource> result = executeRead(persistence, referenceValue, resourceType);
if (result.isSuccess() && isInCompartment(result.getResourceTypeName(), result.getLogicalId(), result.getResource(), CompartmentType.PATIENT, contextIds)) {
allow = true;
break;
}
if (!result.isSuccess() && log.isLoggable(Level.FINE)) {
log.fine("Skipping target " + referenceValue.getTargetResourceType() + "/" + referenceValue.getType() +
"' during enforcement due to a read failure: " + result.getOutcome());
}
} catch (FHIRPersistenceException e) {
if (log.isLoggable(Level.FINE)){
log.log(Level.FINE, "Skipping target '" + referenceValue.getTargetResourceType() + "/" + referenceValue.getType() +
"' during enforcement due to an error while reading.", e);
}
}
} else if (log.isLoggable(Level.FINE)){
log.fine("Skipping target '" + referenceValue.getValue() + "' of type '" + referenceValue.getType() +
"' during enforcement of Provenance access.");
}
}
return allow;
}
private SingleResourceResult<? extends Resource> executeRead(FHIRPersistence persistence, ReferenceValue referenceValue,
Class<? extends Resource> resourceType) throws FHIRPersistenceException {
FHIRPersistenceContext freshContext = FHIRPersistenceContextFactory.createPersistenceContext(null);
return referenceValue.getVersion() == null ?
persistence.read(freshContext, resourceType, referenceValue.getValue()) :
persistence.vread(freshContext, resourceType, referenceValue.getValue(), referenceValue.getVersion().toString());
}
private Resource executeRead(FHIRPersistence persistence, Class<? extends Resource> resourceType, String resourceId)
throws FHIRPersistenceInterceptorException {
try {
FHIRPersistenceContext freshContext = FHIRPersistenceContextFactory.createPersistenceContext(null);
SingleResourceResult<? extends Resource> result = persistence.read(freshContext, resourceType, resourceId);
if (!result.isSuccess()) {
String msg = "Unexpected error while reading resource " + resourceType.getSimpleName() + "/" + resourceId;
throw new FHIRPersistenceInterceptorException(msg).withIssue(result.getOutcome().getIssue());
}
return result.getResource();
} catch (FHIRPersistenceInterceptorException e) {
throw e;
} catch (FHIRPersistenceResourceNotFoundException | FHIRPersistenceResourceDeletedException e) {
String msg = "The resource '" + resourceType.getSimpleName() + "/" + resourceId + "' does not exist.";
throw new FHIRPersistenceInterceptorException(msg).withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
} catch (FHIRPersistenceException e) {
String msg = "Unexpected error while reading resource " + resourceType.getSimpleName() + "/" + resourceId;
log.log(Level.WARNING, msg, e);
throw new FHIRPersistenceInterceptorException(msg);
}
}
@Override
public void afterSearch(FHIRPersistenceEvent event) throws FHIRPersistenceInterceptorException {
DecodedJWT jwt = JWT.decode(getAccessToken());
Set<String> patientIdFromToken = getPatientIdFromToken(jwt);
Map<ContextType, List<Scope>> scopesFromToken = getScopesFromToken(jwt);
if (event.getFhirResource() instanceof Bundle) {
for (Bundle.Entry entry : ((Bundle) event.getFhirResource()).getEntry()) {
String resourceType = getResourceType(entry);
String resourceId = getResourceId(entry);
if (resourceType != null && resourceId != null) {
enforce(resourceType, resourceId, entry.getResource(), patientIdFromToken, Permission.READ, scopesFromToken);
} else {
throw new FHIRPersistenceInterceptorException("Unable to enforce authorization for search interaction "
+ "due to failure to compute the resource type and id for one or more response Bundle entries.");
}
}
} else {
throw new IllegalStateException("Expected event resource of type Bundle but found " +
event.getFhirResource().getClass().getSimpleName());
}
}
/**
* Check whether the permissions required for the current interaction are granted by the passed scopes.
*
* @param resourceType the resource type used in the endpoint of the request (or "Resource" for whole-system interactions)
* @param requiredPermission the permission required for the requested interaction
* @param grantedScopes the SMART scopes associated with the request, indexed by ContextType
* @return
* The ContextType of the scope that permits the requested interaction; 'system/' before 'user/' before 'patient/' scopes
* @throws FHIRPersistenceInterceptorException if the interaction is not permitted
*/
private ContextType checkScopes(String resourceType, Permission requiredPermission, Map<ContextType, List<Scope>> grantedScopes) throws FHIRPersistenceInterceptorException {
// The order is important
for (ContextType context : List.of(ContextType.SYSTEM, ContextType.USER, ContextType.PATIENT)) {
if (isApprovedByScopes(resourceType, requiredPermission, grantedScopes.get(context))) {
return context;
}
}
String msg = requiredPermission.value() + " permission for '" + resourceType +
"' is not granted by any of the provided scopes: " + grantedScopes.values();
if (log.isLoggable(Level.FINE)) {
log.fine(msg);
}
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
/**
* Check whether the permissions required for the current interaction are granted by the passed *system* scopes.
*
* @see #checkScopes(String, Permission, List)
*/
private void checkSystemScopes(String resourceType, Permission requiredPermission, List<Scope> systemScopes, DecodedJWT jwt) throws FHIRPersistenceInterceptorException {
if (!isApprovedByScopes(resourceType, requiredPermission, systemScopes)) {
String msg = requiredPermission.value() + " permission for '" + resourceType
+ "' not granted by any of the provided scopes that begin with 'system/':" + getScopesFromToken(jwt);
if (log.isLoggable(Level.FINE)) {
log.fine(msg);
}
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
}
private boolean isApprovedByScopes(String resourceType, Permission requiredPermission, List<Scope> grantedScopes) {
if (grantedScopes == null) {
return false;
}
for (Scope scope : grantedScopes) {
// "Resource" is used for "*" which applies to all resource types
if (scope.getResourceType() == ResourceType.Value.RESOURCE || scope.getResourceType().value().equals(resourceType)) {
if (hasPermission(scope.getPermission(), requiredPermission)) {
if (log.isLoggable(Level.FINE)) {
log.fine(requiredPermission.value() + " permission for '" + resourceType +
"' is granted via scope " + scope);
}
return true;
}
}
}
return false;
}
/**
* @param grantedPermission
* @param requiredPermission
* @return true if the grantedPermission includes the requiredPermission; otherwise false
*/
private boolean hasPermission(Permission grantedPermission, Permission requiredPermission) {
if (grantedPermission == Permission.ALL) {
return true;
} else {
return grantedPermission == requiredPermission;
}
}
/**
* Enforce the authorizations granted by the end user in the form of scope strings.
*
* @param resource the resource to check
* @param contextIds an identifier for the current context (e.g. patient or user) as determined by the scope strings
* @param requiredPermission the permission required for the requested interaction
* @param grantedScopes the SMART scopes associated with the request, indexed by ContextType
* @throws FHIRPersistenceInterceptorException if the interaction is not permitted
*/
private void enforce(Resource resource, Set<String> contextIds, Permission requiredPermission, Map<ContextType, List<Scope>> grantedScopes)
throws FHIRPersistenceInterceptorException {
Objects.requireNonNull(resource, "resource");
enforce(resource.getClass().getSimpleName(), resource.getId(), resource, contextIds, requiredPermission, grantedScopes);
}
/**
* Enforce the authorizations granted by the end user in the form of scope strings.
*
* @param resourceType the resource type
* @param resourceId the resource ID
* @param resource the resource to check, or null if resource was not retrieved
* @param contextIds an identifier for the current context (e.g. patient or user) as determined by the scope strings
* @param requiredPermission the permission required for the requested interaction
* @param grantedScopes the SMART scopes associated with the request, indexed by ContextType
* @throws FHIRPersistenceInterceptorException if the interaction is not permitted
*/
private void enforce(String resourceType, String resourceId, Resource resource, Set<String> contextIds, Permission requiredPermission, Map<ContextType, List<Scope>> grantedScopes)
throws FHIRPersistenceInterceptorException {
if (!isAllowed(resourceType, resourceId, resource, contextIds, requiredPermission, grantedScopes)) {
if (log.isLoggable(Level.FINE)) {
log.fine(requiredPermission.value() + " permission for '" + resourceType + "/" + resourceId +
"' is not granted by any of the provided scopes: " + grantedScopes.values() +
" with context id(s): " + contextIds);
}
throw new FHIRPersistenceInterceptorException(REQUEST_NOT_PERMITTED)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(REQUEST_NOT_PERMITTED, IssueType.FORBIDDEN));
}
}
/**
* Determine whether authorization to a given resource is granted by the end user in the form of scope strings.
*
* @param resourceType the resource type
* @param resourceId the resource ID
* @param resource the resource to check, or null if resource not retrieved
* @param contextIds an identifier for the current context (e.g. patient or user) as determined by the scope strings
* @param requiredPermission the permission required for the requested interaction
* @param grantedScopes the SMART scopes associated with the request, indexed by ContextType
* @throws FHIRPersistenceInterceptorException if the interaction is not permitted
*/
private boolean isAllowed(String resourceType, String resourceId, Resource resource, Set<String> contextIds, Permission requiredPermission, Map<ContextType, List<Scope>> grantedScopes)
throws FHIRPersistenceInterceptorException {
Objects.requireNonNull(resourceType, "resourceType");
Objects.requireNonNull(resourceId, "resourceId");
Objects.requireNonNull(contextIds, "contextIds");
// For `system` and `user` scopes, we grant access to all resources of the requested type.
// Implementers that use these scopes are encouraged to layer on their own permissions model beyond this.
for (ContextType context : List.of(ContextType.SYSTEM, ContextType.USER)) {
if (!grantedScopes.containsKey(context)) {
continue;
}
// look for any scope that approves the current interaction
Optional<Scope> approvingScope = grantedScopes.get(context).stream()
.filter(s -> s.getResourceType() == ResourceType.Value.RESOURCE || s.getResourceType().value().equals(resourceType))
.filter(s -> hasPermission(s.getPermission(), requiredPermission))
.findAny();
if (approvingScope.isPresent()) {
if (log.isLoggable(Level.FINE)) {
log.fine(requiredPermission.value() + " permission for '" + resourceType + "/" + resourceId +
"' is granted via scope " + approvingScope.get());
}
return true;
}
}
// For `patient` scopes, except for a couple special cases, we prevent access to resources that can be in a patient
// compartment unless those resources exist in one or more compartment of the patient ids passed via 'contextIds'
if (grantedScopes.containsKey(ContextType.PATIENT)) {
if (contextIds.isEmpty()) {
String msg = "Access token is missing 'patient_id' claim";
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
// look for any scope that approves the current interaction
Optional<Scope> approvingScope = grantedScopes.get(ContextType.PATIENT).stream()
.filter(s -> s.getResourceType() == ResourceType.Value.RESOURCE || s.getResourceType().value().equals(resourceType))
.filter(s -> hasPermission(s.getPermission(), requiredPermission))
.findAny();
if (approvingScope.isPresent()) {
if ("Provenance".equals(resourceType)) {
// Addressed for issue #1881, Provenance is a special-case: a Patient-compartment resource type that
// we want to allow access to if and only if the patient has access to one or more resources that it targets.
// In the case of search, Provenance resources can be in the response bundle for two reasons:
// 1. direct search
// 2. _revinclude from a different resource type
// For case 1, the search is already scoped to the patient compartment and therefore only approved resources should be included
// For case 2, only Provenance resources which target to another resource in the response bundle will be included and therefore we
// can base the access decision on those resources rather than the Provenance
// In the case of read/vread/history, access to Provenance will be handled elsewhere;
// not by its Patient compartment membership but by the membership of the resources which it targets
if (log.isLoggable(Level.FINE)) {
log.fine(requiredPermission.value() + " permission for 'Provenance/" + resource.getId() +
"' is granted via scope " + approvingScope.get());
}
return true;
} else if (resource instanceof com.ibm.fhir.model.resource.List) {
// List is another special-case: a Patient-compartment resource type that
// we may want to grant access to when it is not scoped to any particular patient (e.g. for
// <a href="http://hl7.org/fhir/us/davinci-drug-formulary/StructureDefinition-usdf-CoveragePlan.html">Drug Formulary</a>).
// TODO: consider double-checking that the Patient compartment inclusion criteria for List have no
// patient references. The inclusion criteria are "subject" and "source".
if (resource.getMeta() != null &&
resource.getMeta().getProfile().contains(Canonical.of(DAVINCI_DRUG_FORMULARY_COVERAGE_PLAN))) {
if (log.isLoggable(Level.FINE)) {
log.fine(requiredPermission.value() + " permission for 'List/" + resource.getId() +
"' is granted via scope " + approvingScope.get());
}
return true;
}
}
// Else, see if the target resource belongs to the Patient compartment of the in-context patient
return isInCompartment(resourceType, resourceId, resource, CompartmentType.PATIENT, contextIds);
}
}
return false;
}
/**
* Internal helper for checking compartment membership.
*
* @param resourceType
* @param resourceId
* @param resource possibly null
* @param compartmentType
* @param contextIds
* @return true if the resource is in one of the compartment defined by the compartmentType and the contextIds
* or if the resource type is not applicable for the given compartmentType
* @throws FHIRPersistenceInterceptorException if the membership could not be checked
*/
private boolean isInCompartment(String resourceType, String resourceId, Resource resource, CompartmentType compartmentType, Set<String> contextIds)
throws FHIRPersistenceInterceptorException {
String compartment = compartmentType.getValue();
try {
if (!compartmentHelper.getCompartmentResourceTypes(compartment).contains(resourceType)) {
// If the resource type is not applicable for the patient compartment, allow it
// TODO: this may be overly broad...how do we appropriately scope user access to non-Patient resources?
return true;
}
if (resource == null) {
// Two reasons we might not have a resource:
// 1. if this is a history response and there exists one or more DELETE entries in the response
// 2. if this is a history/search operation with an HTTP Prefer header with 'return=minimal'
// Case 1 is handled in afterHistory before this method would be called (where we can better determine the type of the entry)
// For case 2, if we've made it this far then the resourceType can possibly exist in a patient compartment but we have no way to check which one
String msg = "Unable to determine compartment membership for one or more resources of type '" + resourceType + "'"
+ " due to the resource content being absent in the response";
throw new FHIRPersistenceInterceptorException(msg)
.withIssue(FHIRUtil.buildOperationOutcomeIssue(msg, IssueType.FORBIDDEN));
}
// If the target resource type matches the compartment type, allow it if the id is one of the passed contextIds
if (compartment.equals(resourceType) && contextIds.contains(resourceId)) {
if (log.isLoggable(Level.FINE)) {
log.fine("Bypassing compartment check for the compartment identity resource " + resourceType + "/" + resource.getId());
}
return true;
}
Set<String> inclusionCriteria = compartmentHelper.getCompartmentResourceTypeInclusionCriteria(compartment, resourceType);
EvaluationContext resourceContext = new FHIRPathEvaluator.EvaluationContext(resource);
for (String searchParmCode : inclusionCriteria) {
try {
SearchParameter inclusionParm = searchHelper.getSearchParameter(resourceType, searchParmCode);
if (inclusionParm != null & inclusionParm.getExpression() != null) {
String expression = inclusionParm.getExpression().getValue();
Collection<FHIRPathNode> nodes = FHIRPathEvaluator.evaluator().evaluate(resourceContext, expression);
for (FHIRPathNode node : nodes) {
String patientRefVal = getPatientRefVal(node);
if (patientRefVal != null && contextIds.contains(patientRefVal)) {
if (log.isLoggable(Level.FINE)) {
log.fine(resourceType + "/" + resource.getId() +
"' is in " + compartment + " compartment '" + patientRefVal + "'");
}
return true;
}
}
}
} catch (Exception e) {
log.log(Level.WARNING, "Unexpected exception while processing inclusionCriteria '" + searchParmCode +
"' in the " + compartment + " compartment for resource type " + resourceType, e);
}
}
} catch (FHIRSearchException e) {
log.log(Level.WARNING, "Unexpected exception while enforcing authorization policy in the " + compartment + " compartment"
+ " for resource type " + resourceType, e);
}
return false;
}
/**
* @param node
* @return the id to the Patient resource referenced by this node (assuming it is a Reference with a valid
* reference value); otherwise null
* @throws FHIRSearchException
*/
private String getPatientRefVal(FHIRPathNode node) throws FHIRSearchException {
if (!node.isElementNode() || !node.asElementNode().element().is(Reference.class)) {
throw new IllegalStateException("Patient compartment inclusionCriteria expression has returned a non-Reference");
}
Reference reference = node.asElementNode().element().as(Reference.class);
ReferenceValue refValue = ReferenceUtil.createReferenceValueFrom(reference, ReferenceUtil.getServiceBaseUrl());
if (refValue.getType() == com.ibm.fhir.search.util.ReferenceValue.ReferenceType.LITERAL_RELATIVE &&
PATIENT.equals(refValue.getTargetResourceType())) {
return refValue.getValue();