001package ca.cdr.api.model.json;
002
003/*-
004 * #%L
005 * Smile CDR - CDR
006 * %%
007 * Copyright (C) 2016 - 2026 Smile CDR, Inc.
008 * %%
009 * All rights reserved.
010 * #L%
011 */
012
013import ca.cdr.api.model.enm.OAuth2AuthorizedGrantTypeEnum;
014import ca.cdr.api.model.enm.PermissionEnum;
015import ca.cdr.api.security.ScopeValidation;
016import com.fasterxml.jackson.annotation.JsonProperty;
017import io.swagger.v3.oas.annotations.media.Schema;
018import jakarta.annotation.Nonnull;
019import jakarta.validation.constraints.NotBlank;
020import jakarta.validation.constraints.Pattern;
021import org.apache.commons.lang3.Validate;
022import org.springframework.security.core.GrantedAuthority;
023import org.springframework.security.oauth2.provider.ClientDetails;
024
025import java.util.ArrayList;
026import java.util.Collection;
027import java.util.Collections;
028import java.util.Date;
029import java.util.HashMap;
030import java.util.Iterator;
031import java.util.List;
032import java.util.Map;
033import java.util.Optional;
034import java.util.Set;
035import java.util.TreeSet;
036import java.util.stream.Collectors;
037
038import static org.apache.commons.lang3.StringUtils.defaultString;
039import static org.apache.commons.lang3.StringUtils.isNotBlank;
040import static org.apache.commons.lang3.StringUtils.join;
041
042public class OAuth2WritableClientDetailsJson implements ClientDetails, IHasAuthorities, IModelJson {
043
044        public static final String CLIENTID_PATTERN = "[^ ]+";
045        public static final String CLIENT_ID = "clientId";
046        public static final String CLIENT_NAME = "clientName";
047        public static final String ENABLED = "enabled";
048        public static final String PID = "pid";
049        private static final long serialVersionUID = 1L;
050
051        public static final String CLIENT_SECRET_JOINED_DELIMITER = " ";
052
053        @Schema(accessMode = Schema.AccessMode.READ_ONLY, description = "The internal ID for this client.")
054        @JsonProperty(PID)
055        private Long myPid;
056
057        @JsonProperty("accessTokenValiditySeconds")
058        @Schema(description = "The number of seconds that an access token should be valid once it has been created.")
059        private Integer myAccessTokenValiditySeconds;
060
061        @JsonProperty("allowedGrantTypes")
062        @Schema(
063                        description =
064                                        "The grant types that this client is permitted to perform. See [Authorization Flows](/docs/smart/smart_on_fhir_authorization_flows.html) for a description of the possible flows.")
065        private TreeSet<OAuth2AuthorizedGrantTypeEnum> myAllowedGrantTypes;
066
067        @JsonProperty("autoApproveScopes")
068        @Schema(
069                        description =
070                                        "Scopes listed here will be automatically approved if requested by the client during the initial authorization request, without requiring the user to explicitly accept them.")
071        private TreeSet<String> myAutoApproveScopes;
072
073        @JsonProperty("autoGrantScopes")
074        @Schema(
075                        description =
076                                        "Scopes listed here will be automatically granted during every successful authorization by this client. These scopes do not have to be explicitly requested by the client during the initial authorization request.")
077        private TreeSet<String> myAutoGrantScopes;
078
079        @NotBlank
080        @JsonProperty(CLIENT_ID)
081        @Schema(description = "The Client ID (corresponds to the `iss` field in many OAuth2 exchanges).")
082        @Pattern(regexp = CLIENTID_PATTERN, message = "module_validation.invalid_client_id")
083        private String myClientId;
084
085        @JsonProperty(CLIENT_NAME)
086        @Schema(description = "A human friendly description/name for the client.")
087        private String myClientName;
088
089        @JsonProperty("clientSecrets")
090        @Schema(description = "Optionally contains client secrets to be used by the client in some grant types.")
091        private List<OAuth2ClientSecretJson> myClientSecrets;
092
093        @JsonProperty("fixedScope")
094        @Schema(
095                        description =
096                                        "Is this client fixed scope? When authorizing a fixed scope client, the list of scopes requested in the initial authorization request will be ignored, and the complete list of scopes in the Scope property will be assumed. If these scopes are not listed as Auto-Approve, the user will still be required to approve them.")
097        private boolean myFixedScope;
098
099        @JsonProperty("refreshTokenValiditySeconds")
100        @Schema(description = "The number of seconds that a refresh token will be valid for.")
101        private Integer myRefreshTokenValiditySeconds;
102
103        @JsonProperty("registeredRedirectUris")
104        @Schema(description = "The allowable redirect URIs that may be requested.")
105        private TreeSet<String> myRegisteredRedirectUris;
106
107        @JsonProperty("scopes")
108        @Schema(description = "A list of OAuth2 scopes that the client is allowed to request user approval for.")
109        private TreeSet<String> myScope;
110
111        @JsonProperty("secretRequired")
112        @Schema(
113                        description = "Authentication Required. When true, every token request from this client must include a"
114                                        + " valid client secret, or a client assertion signed with a key from the client's JWKS or"
115                                        + " JWKS URL. When false, token requests without client credentials are accepted.")
116        private boolean mySecretRequired;
117
118        @JsonProperty("secretClientCanChange")
119        @Schema(description = "Can the client change their own secret?")
120        private boolean mySecretClientCanChange;
121
122        @JsonProperty(ENABLED)
123        @Schema(description = "Is the client enabled?")
124        private boolean myEnabled;
125
126        @JsonProperty("canIntrospectOwnTokens")
127        @Schema(description = "Can this client perform token introspection on tokens that it issued?")
128        private boolean myCanIntrospectOwnTokens;
129
130        @JsonProperty("canIntrospectAnyTokens")
131        @Schema(
132                        description =
133                                        "Can this client perform token introspecton on any tokens issued by the security module it is registered against?")
134        private boolean myCanIntrospectAnyTokens;
135
136        @JsonProperty("alwaysRequireApproval")
137        @Schema(
138                        description =
139                                        "Should the user approval page be displayed even if the client has not requested any scopes that require user approval?")
140        private boolean myAlwaysRequireApproval;
141
142        @JsonProperty("canReissueTokens")
143        @Schema(
144                        description =
145                                        "Can the OAuth2 server reissue tokens that have been previously issued for this client, if the token request is the same (e.g. for the same user, requesting the same scopes, etc.) and the token is not close to expiry?")
146        private boolean myCanReissueTokens;
147
148        @JsonProperty("permissions")
149        @Schema(
150                        description =
151                                        "Any permission that should be granted directly to the client when it authenticates using the [Client Credentials Grant](/docs/smart/smart_on_fhir_authorization_flows.html#client-credentials-flow).")
152        private List<GrantedAuthorityJson> myPermissions;
153
154        @JsonProperty("rememberApprovedScopes")
155        @Schema(
156                        description =
157                                        "When a user performs an OAuth2 authentication/authorization flow for this client, should their approved scopes be remembered the next time they authenticate?")
158        private boolean myRememberApprovedScopes;
159
160        @JsonProperty("attestationAccepted")
161        @Schema(description = "Has the client developer attested to the policy?")
162        private boolean myAttestationAccepted;
163
164        @JsonProperty("publicJwks")
165        @Schema(
166                        description =
167                                        "The public JWKS Keystore for this client. Used when the client authenticated using a bearer token.")
168        private String myPublicJwks;
169
170        @JsonProperty("jwksUrl")
171        @Schema(
172                        description =
173                                        "A public endpoint location of the JWK Set. If present, this will be used before any public JWKS on the client directly.")
174        private String myJwksUrl;
175
176        @JsonProperty("archivedAt")
177        @Schema(description = "The time at which this client was archived, if it has been.")
178        private Date myArchivedAt;
179
180        @JsonProperty("createdByAppSphere")
181        private boolean myCreatedByAppSphere;
182
183        /**
184         * Constructor
185         */
186        public OAuth2WritableClientDetailsJson() {
187                super();
188        }
189
190        public OAuth2WritableClientDetailsJson(OAuth2WritableClientDetailsJson theClientDetailsJson) {
191                myPid = theClientDetailsJson.myPid;
192                myAccessTokenValiditySeconds = theClientDetailsJson.myAccessTokenValiditySeconds;
193                myAllowedGrantTypes = nullSafeClone(theClientDetailsJson.myAllowedGrantTypes);
194                myAutoApproveScopes = nullSafeClone(theClientDetailsJson.myAutoApproveScopes);
195                myAutoGrantScopes = nullSafeClone(theClientDetailsJson.myAutoGrantScopes);
196                myClientId = theClientDetailsJson.myClientId;
197                myClientName = theClientDetailsJson.myClientName;
198                myClientSecrets = nullSafeClone(theClientDetailsJson.myClientSecrets);
199                myFixedScope = theClientDetailsJson.myFixedScope;
200                myRefreshTokenValiditySeconds = theClientDetailsJson.myRefreshTokenValiditySeconds;
201                myRegisteredRedirectUris = nullSafeClone(theClientDetailsJson.myRegisteredRedirectUris);
202                myScope = nullSafeClone(theClientDetailsJson.myScope);
203                mySecretRequired = theClientDetailsJson.mySecretRequired;
204                mySecretClientCanChange = theClientDetailsJson.mySecretClientCanChange;
205                myEnabled = theClientDetailsJson.myEnabled;
206                myCanIntrospectOwnTokens = theClientDetailsJson.myCanIntrospectOwnTokens;
207                myCanIntrospectAnyTokens = theClientDetailsJson.myCanIntrospectAnyTokens;
208                myAlwaysRequireApproval = theClientDetailsJson.myAlwaysRequireApproval;
209                myCanReissueTokens = theClientDetailsJson.myCanReissueTokens;
210                myPermissions = nullSafeClone(theClientDetailsJson.myPermissions);
211                myRememberApprovedScopes = theClientDetailsJson.myRememberApprovedScopes;
212                myAttestationAccepted = theClientDetailsJson.myAttestationAccepted;
213                myPublicJwks = theClientDetailsJson.myPublicJwks;
214                myJwksUrl = theClientDetailsJson.myJwksUrl;
215                myArchivedAt = theClientDetailsJson.myArchivedAt;
216                myCreatedByAppSphere = theClientDetailsJson.myCreatedByAppSphere;
217        }
218
219        public String getJwksUrl() {
220                return myJwksUrl;
221        }
222
223        public void setJwksUrl(String theJwksUrl) {
224                myJwksUrl = theJwksUrl;
225        }
226
227        public String getPublicJwks() {
228                return myPublicJwks;
229        }
230
231        public void setPublicJwks(String thePublicJwks) {
232                myPublicJwks = thePublicJwks;
233        }
234
235        @Override
236        public List<GrantedAuthorityJson> getPermissions() {
237                if (myPermissions == null) {
238                        myPermissions = new ArrayList<>();
239                }
240                return myPermissions;
241        }
242
243        public void setPermissions(List<GrantedAuthorityJson> thePermissions) {
244                myPermissions = thePermissions;
245        }
246
247        public void addAllowedGrantType(String theName) {
248                addAllowedGrantType(OAuth2AuthorizedGrantTypeEnum.valueOf(theName));
249        }
250
251        public void addAllowedGrantType(@Nonnull OAuth2AuthorizedGrantTypeEnum theGrantType) {
252                getAllowedGrantTypes().add(theGrantType);
253        }
254
255        public void addAutoApproveScopeIfNotBlank(String theScope) {
256                if (isNotBlank(theScope)) {
257                        getAutoApproveScopes().add(theScope.trim());
258                }
259        }
260
261        public void addRedirectUrlIfNotBlank(String theRedirectUrl) {
262                if (isNotBlank(theRedirectUrl)) {
263                        getRegisteredRedirectUri().add(theRedirectUrl.trim());
264                }
265        }
266
267        public OAuth2WritableClientDetailsJson addScopeIfNotBlank(String theScope) {
268                if (isNotBlank(theScope)) {
269                        getScope().add(theScope.trim());
270                }
271                return this;
272        }
273
274        @Override
275        public Integer getAccessTokenValiditySeconds() {
276                return myAccessTokenValiditySeconds;
277        }
278
279        public void setAccessTokenValiditySeconds(Integer theAccessTokenValiditySeconds) {
280                myAccessTokenValiditySeconds = theAccessTokenValiditySeconds;
281        }
282
283        @Override
284        public Map<String, Object> getAdditionalInformation() {
285                return new HashMap<>();
286        }
287
288        public TreeSet<OAuth2AuthorizedGrantTypeEnum> getAllowedGrantTypes() {
289                if (myAllowedGrantTypes == null) {
290                        myAllowedGrantTypes = new TreeSet<>();
291                }
292                return myAllowedGrantTypes;
293        }
294
295        public void setAllowedGrantTypes(TreeSet<OAuth2AuthorizedGrantTypeEnum> theAllowedGrantTypes) {
296                myAllowedGrantTypes = theAllowedGrantTypes;
297        }
298
299        /**
300         * This method is a part of the Spring Security framework, and returns
301         * an <b>unmodifiable</b> copy of the client authorities. Use
302         * {@link #getPermissions()} if you want to modify the actual
303         * values.
304         */
305        @Override
306        public Collection<GrantedAuthority> getAuthorities() {
307                ArrayList<GrantedAuthorityJson> retVal = new ArrayList<>();
308                retVal.addAll(getPermissions());
309                return Collections.unmodifiableList(retVal);
310        }
311
312        @Override
313        public Set<String> getAuthorizedGrantTypes() {
314                TreeSet<String> retVal =
315                                getAllowedGrantTypes().stream().map(t -> t.getCode()).collect(Collectors.toCollection(TreeSet::new));
316                return Collections.unmodifiableSet(retVal);
317        }
318
319        public boolean hasAutoApproveScopes() {
320                return myAutoApproveScopes != null && !myAutoApproveScopes.isEmpty();
321        }
322
323        public boolean hasAutoGrantScopes() {
324                return myAutoGrantScopes != null && !myAutoGrantScopes.isEmpty();
325        }
326
327        @Nonnull
328        public TreeSet<String> getAutoApproveScopes() {
329                if (myAutoApproveScopes == null) {
330                        myAutoApproveScopes = new TreeSet<>();
331                }
332                return myAutoApproveScopes;
333        }
334
335        public void setAutoApproveScopes(TreeSet<String> theAutoApproveScopes) {
336                myAutoApproveScopes = theAutoApproveScopes;
337        }
338
339        @Nonnull
340        public TreeSet<String> getAutoGrantScopes() {
341                if (myAutoGrantScopes == null) {
342                        myAutoGrantScopes = new TreeSet<>();
343                }
344                return myAutoGrantScopes;
345        }
346
347        public void setAutoGrantScopes(TreeSet<String> theAutoGrantScopes) {
348                myAutoGrantScopes = theAutoGrantScopes;
349        }
350
351        public String getAutoApproveScopesSpaceSeparated() {
352                return defaultString(join(getAutoApproveScopes(), ' '));
353        }
354
355        public String getAutoGrantScopesSpaceSeparated() {
356                return defaultString(join(getAutoGrantScopes(), ' '));
357        }
358
359        @Override
360        public String getClientId() {
361                return myClientId;
362        }
363
364        public OAuth2WritableClientDetailsJson setClientId(String theClientId) {
365                myClientId = theClientId;
366                return this;
367        }
368
369        public String getClientName() {
370                return myClientName;
371        }
372
373        public void setClientName(String theClientName) {
374                myClientName = theClientName;
375        }
376
377        @Override
378        public String getClientSecret() {
379                // NB: If you ever decide to cache the return value of this method, note that
380                // we sometimes mask the secrets after generating the JSON entity (e.g. if the
381                // client def is going to be returned to a user)
382                return getClientSecrets().stream()
383                                .filter(t -> t.getExpiration() == null || t.getExpiration().getTime() >= System.currentTimeMillis())
384                                .filter(t -> t.getActivation() == null || t.getActivation().getTime() <= System.currentTimeMillis())
385                                .map(t -> t.getSecret())
386                                .collect(Collectors.joining(CLIENT_SECRET_JOINED_DELIMITER));
387        }
388
389        public List<OAuth2ClientSecretJson> getClientSecrets() {
390                if (myClientSecrets == null) {
391                        myClientSecrets = new ArrayList<>();
392                }
393                return myClientSecrets;
394        }
395
396        public void setClientSecrets(List<OAuth2ClientSecretJson> theClientSecrets) {
397                myClientSecrets = theClientSecrets;
398        }
399
400        public Long getPid() {
401                return myPid;
402        }
403
404        public OAuth2WritableClientDetailsJson setPid(Long myPid) {
405                this.myPid = myPid;
406                return this;
407        }
408
409        @Override
410        public Integer getRefreshTokenValiditySeconds() {
411                return myRefreshTokenValiditySeconds;
412        }
413
414        public void setRefreshTokenValiditySeconds(Integer theRefreshTokenValiditySeconds) {
415                myRefreshTokenValiditySeconds = theRefreshTokenValiditySeconds;
416        }
417
418        @Nonnull
419        @Override
420        public TreeSet<String> getRegisteredRedirectUri() {
421                if (myRegisteredRedirectUris == null) {
422                        myRegisteredRedirectUris = new TreeSet<>();
423                }
424                return myRegisteredRedirectUris;
425        }
426
427        public TreeSet<String> getRegisteredRedirectUris() {
428                return getRegisteredRedirectUri();
429        }
430
431        public void setRegisteredRedirectUris(TreeSet<String> theRegisteredRedirectUris) {
432                myRegisteredRedirectUris = theRegisteredRedirectUris;
433        }
434
435        public void setRegisteredRedirectUris(Iterable<String> theRegisteredRedirectUri) {
436                myRegisteredRedirectUris = new TreeSet<>();
437                if (theRegisteredRedirectUri != null) {
438                        theRegisteredRedirectUri.forEach(t -> myRegisteredRedirectUris.add(t));
439                }
440        }
441
442        public String getRegisteredRedirectUriOnePerLine() {
443                return defaultString(join(getRegisteredRedirectUri(), '\n'));
444        }
445
446        @Override
447        public Set<String> getResourceIds() {
448                return Collections.emptySet();
449        }
450
451        public boolean hasScope() {
452                return myScope != null && !myScope.isEmpty();
453        }
454
455        @Nonnull
456        @Override
457        public Set<String> getScope() {
458                if (myScope == null) {
459                        myScope = new TreeSet<>();
460                }
461                return new ScopeSetWrapper(myScope);
462        }
463
464        public void setScope(TreeSet<String> theScope) {
465                myScope = theScope;
466        }
467
468        public Set<String> getScopes() {
469                return getScope();
470        }
471
472        public void setScopes(TreeSet<String> theScope) {
473                setScope(theScope);
474        }
475
476        public String getScopeSpaceSeparated() {
477                return defaultString(join(getScope(), ' '));
478        }
479
480        public boolean isAlwaysRequireApproval() {
481                return myAlwaysRequireApproval;
482        }
483
484        public void setAlwaysRequireApproval(boolean theAlwaysRequireApproval) {
485                myAlwaysRequireApproval = theAlwaysRequireApproval;
486        }
487
488        @Override
489        public boolean isAutoApprove(String theScope) {
490                boolean retVal = getAutoApproveScopes().contains(theScope);
491                if (!retVal) {
492                        retVal = ScopeValidation.isScopeAllowedDirectlyOrIndirectly(getAutoApproveScopes(), theScope);
493                }
494                return retVal;
495        }
496
497        public boolean isCanIntrospectAnyTokens() {
498                return myCanIntrospectAnyTokens;
499        }
500
501        public void setCanIntrospectAnyTokens(boolean theCanIntrospectAnyTokens) {
502                myCanIntrospectAnyTokens = theCanIntrospectAnyTokens;
503        }
504
505        public boolean isCanIntrospectOwnTokens() {
506                return myCanIntrospectOwnTokens;
507        }
508
509        public void setCanIntrospectOwnTokens(boolean theCanIntrospectOwnTokens) {
510                myCanIntrospectOwnTokens = theCanIntrospectOwnTokens;
511        }
512
513        public boolean isFixedScope() {
514                return myFixedScope;
515        }
516
517        public void setFixedScope(boolean theFixedScope) {
518                myFixedScope = theFixedScope;
519        }
520
521        @Override
522        public boolean isScoped() {
523                return myFixedScope;
524        }
525
526        @Override
527        public boolean isSecretRequired() {
528                return mySecretRequired;
529        }
530
531        public void setSecretRequired(boolean theSecretRequired) {
532                mySecretRequired = theSecretRequired;
533        }
534
535        public boolean isSecretClientCanChange() {
536                return mySecretClientCanChange;
537        }
538
539        public void setSecretClientCanChange(boolean theSecretClientCanChange) {
540                mySecretClientCanChange = theSecretClientCanChange;
541        }
542
543        public boolean isEnabled() {
544                return myEnabled;
545        }
546
547        public void setEnabled(boolean theEnabled) {
548                myEnabled = theEnabled;
549        }
550
551        public Optional<OAuth2ClientSecretJson> getClientSecret(Long thePid) {
552                Validate.notNull(thePid, "thePid must not be null");
553                return getClientSecrets().stream()
554                                .filter(t -> thePid.equals(t.getPid()))
555                                .findFirst();
556        }
557
558        public OAuth2WritableClientDetailsJson addClientSecret(OAuth2ClientSecretJson theSecret) {
559                Validate.notNull(theSecret, "theSecret must not be null");
560                getClientSecrets().add(theSecret);
561                return this;
562        }
563
564        public OAuth2ClientSecretJson addClientSecret(String theSecret) {
565                Validate.notBlank(theSecret, "theSecret must not be null or blank");
566                OAuth2ClientSecretJson secret = addClientSecret();
567                secret.setSecret(theSecret);
568                return secret;
569        }
570
571        public OAuth2ClientSecretJson addClientSecret() {
572                OAuth2ClientSecretJson secret = new OAuth2ClientSecretJson();
573                addClientSecret(secret);
574                return secret;
575        }
576
577        public OAuth2ClientSecretJson addClientSecret(String theSecret, Date theExpiration) {
578                return addClientSecret(theSecret).setExpiration(theExpiration);
579        }
580
581        public boolean isCanReissueTokens() {
582                return myCanReissueTokens;
583        }
584
585        public void setCanReissueTokens(boolean theCanReissueTokens) {
586                myCanReissueTokens = theCanReissueTokens;
587        }
588
589        public void addAutoGrantScopeIfNotBlank(String theScope) {
590                if (isNotBlank(theScope)) {
591                        getAutoGrantScopes().add(theScope.trim());
592                }
593        }
594
595        public void addPermission(GrantedAuthorityJson thePermission) {
596                Validate.notNull(thePermission);
597                getPermissions().add(thePermission);
598        }
599
600        public void addPermission(PermissionEnum thePermission, String theArgument) {
601                Validate.notNull(thePermission);
602                addPermission(new GrantedAuthorityJson(thePermission, theArgument));
603        }
604
605        public void addPermission(PermissionEnum thePermission) {
606                Validate.notNull(thePermission);
607                addPermission(new GrantedAuthorityJson(thePermission));
608        }
609
610        public void removePermission(PermissionEnum thePermission, String theArgument) {
611                Validate.notNull(thePermission);
612                removePermission(new GrantedAuthorityJson(thePermission, theArgument));
613        }
614
615        public void removePermission(GrantedAuthorityJson thePermission) {
616                Validate.notNull(thePermission);
617                getPermissions().remove(thePermission);
618        }
619
620        public boolean isRememberApprovedScopes() {
621                return myRememberApprovedScopes;
622        }
623
624        public void setRememberApprovedScopes(boolean theRememberApprovedScopes) {
625                myRememberApprovedScopes = theRememberApprovedScopes;
626        }
627
628        public boolean isAttestationAccepted() {
629                return myAttestationAccepted;
630        }
631
632        public void setAttestationAccepted(boolean theAttestationAccepted) {
633                myAttestationAccepted = theAttestationAccepted;
634        }
635
636        public Date getArchivedAt() {
637                return myArchivedAt;
638        }
639
640        public void setArchivedAt(Date theArchivedAt) {
641                myArchivedAt = theArchivedAt;
642        }
643
644        public boolean isCreatedByAppSphere() {
645                return myCreatedByAppSphere;
646        }
647
648        public void setCreatedByAppSphere(boolean theCreatedByAppSphere) {
649                myCreatedByAppSphere = theCreatedByAppSphere;
650        }
651
652        private static <T> TreeSet<T> nullSafeClone(TreeSet<T> theTreeSet) {
653                return theTreeSet != null ? new TreeSet<>(theTreeSet) : null;
654        }
655
656        private static <T> List<T> nullSafeClone(List<T> theList) {
657                return theList != null ? new ArrayList<>(theList) : null;
658        }
659
660        /**
661         * This class provides a wrapper around the client scopes property
662         * (see {@link #getScope()}) but modifies the behaviour of the
663         * {@link #contains(Object)} method. Effectively, any tests for whether
664         * the {@link Set#contains(Object)} method contains a given scope will test
665         * the scopes, but will also account for {@link #getAutoGrantScopes()} and
666         * equivalent but narrower scopes (e.g. we allow <code>patient/Observation.read</code>
667         * if the client is allowed <code>patient/*.read</code>).
668         * <p>
669         * We use this clunky wrapper approach because Spring Security added a test in
670         * {@link org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager}
671         * that we can't modify.
672         * </p>
673         */
674        private class ScopeSetWrapper implements Set<String> {
675                private final TreeSet<String> myWrap;
676
677                public ScopeSetWrapper(TreeSet<String> theWrap) {
678                        myWrap = theWrap;
679                }
680
681                @Override
682                public int size() {
683                        return myWrap.size();
684                }
685
686                @Override
687                public boolean isEmpty() {
688                        return myWrap.isEmpty();
689                }
690
691                /**
692                 * See class documentation for a description of what this method is about
693                 */
694                @Override
695                public boolean contains(Object theScope) {
696                        if (!(theScope instanceof String scopeStr)) {
697                                return false;
698                        } else if (ScopeValidation.isScopeAllowedDirectlyOrIndirectly(myWrap, scopeStr)) {
699                                return true;
700                        } else {
701                                return ScopeValidation.isScopeAllowedDirectlyOrIndirectly(getAutoGrantScopes(), scopeStr);
702                        }
703                }
704
705                @Nonnull
706                @Override
707                public Iterator<String> iterator() {
708                        return myWrap.iterator();
709                }
710
711                @Nonnull
712                @Override
713                public Object[] toArray() {
714                        return myWrap.toArray();
715                }
716
717                @Nonnull
718                @Override
719                public <T> T[] toArray(@Nonnull T[] a) {
720                        return myWrap.toArray(a);
721                }
722
723                @Override
724                public boolean add(String theScope) {
725                        return myWrap.add(theScope);
726                }
727
728                @Override
729                public boolean remove(Object o) {
730                        return myWrap.remove(o);
731                }
732
733                @Override
734                public boolean containsAll(@Nonnull Collection<?> c) {
735                        return myWrap.containsAll(c);
736                }
737
738                @Override
739                public boolean addAll(@Nonnull Collection<? extends String> c) {
740                        return myWrap.addAll(c);
741                }
742
743                @Override
744                public boolean retainAll(@Nonnull Collection<?> c) {
745                        return myWrap.retainAll(c);
746                }
747
748                @Override
749                public boolean removeAll(@Nonnull Collection<?> c) {
750                        return myWrap.removeAll(c);
751                }
752
753                @Override
754                public void clear() {
755                        myWrap.clear();
756                }
757        }
758}