From 734cba256a85e0bd49e67e6b9c3d09ebcd65e0bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Franti=C5=A1ek=20Bu=C4=8D=C3=ADk?= Date: Fri, 29 May 2020 14:14:03 +0200 Subject: [PATCH] Merged modules and updated dependencies --- openid-connect-server-webapp/pom.xml | 16 +- openid-connect-server/pom.xml | 51 +++- .../data/AbstractPageOperationTemplate.java | 193 ++++++--------- .../org/mitre/data/DefaultPageCriteria.java | 4 +- .../util/WebfingerURLNormalizer.java | 1 - .../mitre/discovery/view/WebfingerView.java | 29 +-- .../discovery/web/DiscoveryEndpoint.java | 108 ++++---- .../mitre/jose/keystore/JWKSetKeyStore.java | 2 - .../assertion/AbstractAssertionValidator.java | 2 +- .../impl/SelfAssertionValidator.java | 2 +- .../WhitelistedIssuerAssertionValidator.java | 7 +- ...aultJWTEncryptionAndDecryptionService.java | 77 +++--- .../JWTSigningAndValidationService.java | 22 +- .../service/impl/ClientKeyCacheService.java | 3 +- ...DefaultJWTSigningAndValidationService.java | 16 +- .../service/impl/JWKSetCacheService.java | 21 +- .../SymmetricKeyJWTValidatorCacheService.java | 9 +- .../AssertionOAuth2RequestFactory.java | 1 - .../impl/DirectCopyRequestFactory.java | 10 +- .../AuthorizationPendingException.java | 16 +- .../exception/DeviceCodeExpiredException.java | 13 +- .../exception/DuplicateClientIdException.java | 8 +- .../oauth2/model/OAuth2AccessTokenEntity.java | 4 - .../impl/BlacklistAwareRedirectResolver.java | 230 ++++++++++++++++-- .../service/impl/DefaultOIDCTokenService.java | 2 +- .../openid/connect/view/UserInfoJWTView.java | 2 +- .../connect/web/UserInfoInterceptor.java | 10 +- .../main/java/org/mitre/uma/model/Claim.java | 7 +- .../TestBlacklistAwareRedirectResolver.java | 4 - ...faultOAuth2ClientDetailsEntityService.java | 78 +++--- ...TestDefaultOAuth2ProviderTokenService.java | 2 - .../impl/TestDefaultApprovedSiteService.java | 1 - .../service/impl/TestDefaultStatsService.java | 11 - .../impl/TestMITREidDataService_1_0.java | 38 +-- .../impl/TestMITREidDataService_1_1.java | 29 --- .../impl/TestMITREidDataService_1_2.java | 29 --- .../impl/TestMITREidDataService_1_3.java | 36 --- pom.xml | 154 ++---------- 38 files changed, 532 insertions(+), 716 deletions(-) diff --git a/openid-connect-server-webapp/pom.xml b/openid-connect-server-webapp/pom.xml index 11881547f..6f1a80e75 100644 --- a/openid-connect-server-webapp/pom.xml +++ b/openid-connect-server-webapp/pom.xml @@ -114,18 +114,6 @@ - - org.slf4j - jcl-over-slf4j - - - org.slf4j - slf4j-log4j12 - - - log4j - log4j - org.hsqldb hsqldb @@ -139,8 +127,8 @@ spring-security-taglibs - javax.servlet - jstl + javax.servlet.jsp.jstl + jstl-api diff --git a/openid-connect-server/pom.xml b/openid-connect-server/pom.xml index 84fe62198..f80421130 100644 --- a/openid-connect-server/pom.xml +++ b/openid-connect-server/pom.xml @@ -40,8 +40,8 @@ - org.mitre - openid-connect-common + org.springframework.security.oauth + spring-security-oauth2 org.springframework @@ -70,13 +70,56 @@ org.eclipse.persistence org.eclipse.persistence.jpa - test - org.apache.commons + commons-io commons-io + + ch.qos.logback + logback-classic + + + com.nimbusds + nimbus-jose-jwt + + + org.bouncycastle + bcprov-jdk15on + + + com.fasterxml.jackson.core + jackson-databind + + + com.google.code.gson + gson + + + com.google.guava + guava + + + javax.servlet + servlet-api + + + org.apache.httpcomponents + httpclient + + + junit + junit + + + org.mockito + mockito-core + + + org.springframework + spring-test + OpenID Connect server libraries for Spring and Spring Security. diff --git a/openid-connect-server/src/main/java/org/mitre/data/AbstractPageOperationTemplate.java b/openid-connect-server/src/main/java/org/mitre/data/AbstractPageOperationTemplate.java index 751c2d2fb..54a35d952 100644 --- a/openid-connect-server/src/main/java/org/mitre/data/AbstractPageOperationTemplate.java +++ b/openid-connect-server/src/main/java/org/mitre/data/AbstractPageOperationTemplate.java @@ -33,135 +33,23 @@ public abstract class AbstractPageOperationTemplate { private static final Logger logger = LoggerFactory.getLogger(AbstractPageOperationTemplate.class); - private static int DEFAULT_MAX_PAGES = 1000; - private static long DEFAULT_MAX_TIME_MILLIS = 600000L; //10 Minutes + private static final int DEFAULT_MAX_PAGES = 1000; + private static final long DEFAULT_MAX_TIME_MILLIS = 600000L; //10 Minutes - /** - * int specifying the maximum number of - * pages which should be fetched before - * execution should terminate - */ private int maxPages; - - /** - * long specifying the maximum execution time - * in milliseconds - */ private long maxTime; - - /** - * boolean specifying whether or not Exceptions - * incurred performing the operation should be - * swallowed during execution default true. - */ private boolean swallowExceptions = true; + private String operationName; - /** - * String that is used for logging in final tallies. - */ - private String operationName = ""; - - - /** - * default constructor which sets the value of - * maxPages and maxTime to DEFAULT_MAX_PAGES and - * DEFAULT_MAX_TIME_MILLIS respectively - */ public AbstractPageOperationTemplate(String operationName){ this(DEFAULT_MAX_PAGES, DEFAULT_MAX_TIME_MILLIS, operationName); } - - /** - * Instantiates a new AbstractPageOperationTemplate with the - * given maxPages and maxTime - * - * @param maxPages the maximum number of pages to fetch. - * @param maxTime the maximum execution time. - */ public AbstractPageOperationTemplate(int maxPages, long maxTime, String operationName){ this.maxPages = maxPages; this.maxTime = maxTime; this.operationName = operationName; } - /** - * Execute the operation on each member of a page of results - * retrieved through the fetch method. the method will execute - * until either the maxPages or maxTime limit is reached or until - * the fetch method returns no more results. Exceptions thrown - * performing the operation on the item will be swallowed if the - * swallowException (default true) field is set true. - */ - public void execute(){ - logger.debug("[" + getOperationName() + "] Starting execution of paged operation. maximum time: " + maxTime + ", maximum pages: " + maxPages); - - long startTime = System.currentTimeMillis(); - long executionTime = 0; - int i = 0; - - int exceptionsSwallowedCount = 0; - int operationsCompleted = 0; - Set exceptionsSwallowedClasses = new HashSet(); - - - while (i< maxPages && executionTime < maxTime){ - Collection page = fetchPage(); - if(page == null || page.size() == 0){ - break; - } - - for (T item : page) { - try { - doOperation(item); - operationsCompleted++; - } catch (Exception e){ - if(swallowExceptions){ - exceptionsSwallowedCount++; - exceptionsSwallowedClasses.add(e.getClass().getName()); - logger.debug("Swallowing exception " + e.getMessage(), e); - } else { - logger.debug("Rethrowing exception " + e.getMessage()); - throw e; - } - } - } - - i++; - executionTime = System.currentTimeMillis() - startTime; - } - - finalReport(operationsCompleted, exceptionsSwallowedCount, exceptionsSwallowedClasses); - } - - /** - * method responsible for fetching - * a page of items. - * - * @return the collection of items - */ - public abstract Collection fetchPage(); - - /** - * method responsible for performing desired - * operation on a fetched page item. - * - * @param item the item - */ - protected abstract void doOperation(T item); - - /** - * Method responsible for final report of progress. - * @return - */ - protected void finalReport(int operationsCompleted, int exceptionsSwallowedCount, Set exceptionsSwallowedClasses) { - if (operationsCompleted > 0 || exceptionsSwallowedCount > 0) { - logger.info("[" + getOperationName() + "] Paged operation run: completed " + operationsCompleted + "; swallowed " + exceptionsSwallowedCount + " exceptions"); - } - for(String className: exceptionsSwallowedClasses) { - logger.warn("[" + getOperationName() + "] Paged operation swallowed at least one exception of type " + className); - } - } - public int getMaxPages() { return maxPages; } @@ -193,4 +81,79 @@ public abstract class AbstractPageOperationTemplate { public void setOperationName(String operationName) { this.operationName = operationName; } + + /** + * Execute the operation on each member of a page of results + * retrieved through the fetch method. the method will execute + * until either the maxPages or maxTime limit is reached or until + * the fetch method returns no more results. Exceptions thrown + * performing the operation on the item will be swallowed if the + * swallowException (default true) field is set true. + */ + public void execute(){ + logger.debug("[{}] Starting execution of paged operation. max time: {}, max pages: {}", getOperationName(), maxTime, maxPages); + + long startTime = System.currentTimeMillis(); + long executionTime = 0; + int i = 0; + + int exceptionsSwallowedCount = 0; + int operationsCompleted = 0; + Set exceptionsSwallowedClasses = new HashSet<>(); + + while (i < maxPages && executionTime < maxTime){ + Collection page = fetchPage(); + if (page == null || page.size() == 0){ + break; + } + + for (T item : page) { + try { + doOperation(item); + operationsCompleted++; + } catch (Exception e){ + if(swallowExceptions){ + exceptionsSwallowedCount++; + exceptionsSwallowedClasses.add(e.getClass().getName()); + logger.debug("Swallowing exception " + e.getMessage(), e); + } else { + logger.debug("Rethrowing exception " + e.getMessage()); + throw e; + } + } + } + + i++; + executionTime = System.currentTimeMillis() - startTime; + } + + finalReport(operationsCompleted, exceptionsSwallowedCount, exceptionsSwallowedClasses); + } + + /** + * Fetch a page of items. + * + * @return the collection of items + */ + public abstract Collection fetchPage(); + + /** + * Perform operation of fetched page of items. + * + * @param item the item + */ + protected abstract void doOperation(T item); + + /** + * Method responsible for final report of progress. + */ + protected void finalReport(int operationsCompleted, int exceptionsSwallowedCount, Set exceptionsSwallowedClasses) { + if (operationsCompleted > 0 || exceptionsSwallowedCount > 0) { + logger.info("[{}] Paged operation run: completed {}; swallowed {} exceptions", + getOperationName(), operationsCompleted, exceptionsSwallowedCount); + } + for(String className: exceptionsSwallowedClasses) { + logger.warn("[{}] Paged operation swallowed at least one exception of type {}", getOperationName(), className); + } + } } diff --git a/openid-connect-server/src/main/java/org/mitre/data/DefaultPageCriteria.java b/openid-connect-server/src/main/java/org/mitre/data/DefaultPageCriteria.java index dd632a55e..050f489ac 100644 --- a/openid-connect-server/src/main/java/org/mitre/data/DefaultPageCriteria.java +++ b/openid-connect-server/src/main/java/org/mitre/data/DefaultPageCriteria.java @@ -26,8 +26,8 @@ public class DefaultPageCriteria implements PageCriteria { private static final int DEFAULT_PAGE_NUMBER = 0; private static final int DEFAULT_PAGE_SIZE = 100; - private int pageNumber; - private int pageSize; + private final int pageNumber; + private final int pageSize; public DefaultPageCriteria(){ this(DEFAULT_PAGE_NUMBER, DEFAULT_PAGE_SIZE); diff --git a/openid-connect-server/src/main/java/org/mitre/discovery/util/WebfingerURLNormalizer.java b/openid-connect-server/src/main/java/org/mitre/discovery/util/WebfingerURLNormalizer.java index 792523981..c004d1134 100644 --- a/openid-connect-server/src/main/java/org/mitre/discovery/util/WebfingerURLNormalizer.java +++ b/openid-connect-server/src/main/java/org/mitre/discovery/util/WebfingerURLNormalizer.java @@ -66,7 +66,6 @@ public class WebfingerURLNormalizer { logger.warn("Can't normalize null or empty URI: " + identifier); return null; } else { - //UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(identifier); UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); Matcher m = pattern.matcher(identifier); diff --git a/openid-connect-server/src/main/java/org/mitre/discovery/view/WebfingerView.java b/openid-connect-server/src/main/java/org/mitre/discovery/view/WebfingerView.java index 493f769d3..527ff4788 100644 --- a/openid-connect-server/src/main/java/org/mitre/discovery/view/WebfingerView.java +++ b/openid-connect-server/src/main/java/org/mitre/discovery/view/WebfingerView.java @@ -48,30 +48,20 @@ import com.google.gson.JsonObject; */ @Component("webfingerView") public class WebfingerView extends AbstractView { - - /** - * Logger for this class - */ private static final Logger logger = LoggerFactory.getLogger(WebfingerView.class); - private Gson gson = new GsonBuilder() + private final Gson gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { - @Override public boolean shouldSkipField(FieldAttributes f) { - return false; } @Override public boolean shouldSkipClass(Class clazz) { // skip the JPA binding wrapper - if (clazz.equals(BeanPropertyBindingResult.class)) { - return true; - } - return false; + return clazz.equals(BeanPropertyBindingResult.class); } - }) .serializeNulls() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") @@ -79,21 +69,17 @@ public class WebfingerView extends AbstractView { @Override protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) { - response.setContentType("application/jrd+json"); - - HttpStatus code = (HttpStatus) model.get(HttpCodeView.CODE); if (code == null) { - code = HttpStatus.OK; // default to 200 + code = HttpStatus.OK; } response.setStatus(code.value()); try { - - String resource = (String)model.get("resource"); - String issuer = (String)model.get("issuer"); + String resource = (String) model.get("resource"); + String issuer = (String) model.get("issuer"); JsonObject obj = new JsonObject(); obj.addProperty("subject", resource); @@ -108,11 +94,8 @@ public class WebfingerView extends AbstractView { Writer out = response.getWriter(); gson.toJson(obj, out); - } catch (IOException e) { - - logger.error("IOException in JsonEntityView.java: ", e); - + logger.error("IOException in WebfingerView.java: ", e); } } diff --git a/openid-connect-server/src/main/java/org/mitre/discovery/web/DiscoveryEndpoint.java b/openid-connect-server/src/main/java/org/mitre/discovery/web/DiscoveryEndpoint.java index 270a7649e..a74633602 100644 --- a/openid-connect-server/src/main/java/org/mitre/discovery/web/DiscoveryEndpoint.java +++ b/openid-connect-server/src/main/java/org/mitre/discovery/web/DiscoveryEndpoint.java @@ -68,88 +68,61 @@ import com.nimbusds.jose.JWSAlgorithm; @Controller public class DiscoveryEndpoint { + private static final Logger logger = LoggerFactory.getLogger(DiscoveryEndpoint.class); + public static final String WELL_KNOWN_URL = ".well-known"; public static final String OPENID_CONFIGURATION_URL = WELL_KNOWN_URL + "/openid-configuration"; public static final String WEBFINGER_URL = WELL_KNOWN_URL + "/webfinger"; + private static final String ISSUER_STRING = "http://openid.net/specs/connect/1.0/issuer"; - /** - * Logger for this class - */ - private static final Logger logger = LoggerFactory.getLogger(DiscoveryEndpoint.class); - - @Autowired - private ConfigurationPropertiesBean config; - - @Autowired - private SystemScopeService scopeService; - - @Autowired - private JWTSigningAndValidationService signService; - - @Autowired - private JWTEncryptionAndDecryptionService encService; - - @Autowired - private UserInfoService userService; - + private final ConfigurationPropertiesBean config; + private final SystemScopeService scopeService; + private final JWTSigningAndValidationService signService; + private final JWTEncryptionAndDecryptionService encService; + private final UserInfoService userService; // used to map JWA algorithms objects to strings - private Function toAlgorithmName = new Function() { - @Override - public String apply(Algorithm alg) { - if (alg == null) { - return null; - } else { - return alg.getName(); - } - } - }; + private final Function toAlgorithmName = alg -> alg == null ? null : alg.getName(); - @RequestMapping(value={"/" + WEBFINGER_URL}, produces = MediaType.APPLICATION_JSON_VALUE) - public String webfinger(@RequestParam("resource") String resource, @RequestParam(value = "rel", required = false) String rel, Model model) { + @Autowired + public DiscoveryEndpoint(UserInfoService userService, ConfigurationPropertiesBean config, + SystemScopeService scopeService, JWTSigningAndValidationService signService, + JWTEncryptionAndDecryptionService encService) { + this.userService = userService; + this.config = config; + this.scopeService = scopeService; + this.signService = signService; + this.encService = encService; + } - if (!Strings.isNullOrEmpty(rel) && !rel.equals("http://openid.net/specs/connect/1.0/issuer")) { - logger.warn("Responding to webfinger request for non-OIDC relation: " + rel); + @RequestMapping(value = '/' + WEBFINGER_URL, produces = MediaType.APPLICATION_JSON_VALUE) + public String webfinger(@RequestParam("resource") String resource, + @RequestParam(value = "rel", required = false) String rel, + Model model) { + if (!Strings.isNullOrEmpty(rel) && !rel.equals(ISSUER_STRING)) { + logger.warn("Responding to webfinger request for non-OIDC relation: {}", rel); } if (!resource.equals(config.getIssuer())) { // it's not the issuer directly, need to check other methods - UriComponents resourceUri = WebfingerURLNormalizer.normalizeResource(resource); if (resourceUri != null && resourceUri.getScheme() != null && resourceUri.getScheme().equals("acct")) { - // acct: URI (email address format) - - // check on email addresses first - UserInfo user = userService.getByEmailAddress(resourceUri.getUserInfo() + "@" + resourceUri.getHost()); - + UserInfo user = extractUser(resourceUri); if (user == null) { - // user wasn't found, see if the local part of the username matches, plus our issuer host - - user = userService.getByUsername(resourceUri.getUserInfo()); // first part is the username - - if (user != null) { - // username matched, check the host component - UriComponents issuerComponents = UriComponentsBuilder.fromHttpUrl(config.getIssuer()).build(); - if (!Strings.nullToEmpty(issuerComponents.getHost()) - .equals(Strings.nullToEmpty(resourceUri.getHost()))) { - logger.info("Host mismatch, expected " + issuerComponents.getHost() + " got " + resourceUri.getHost()); - model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); - return HttpCodeView.VIEWNAME; - } - - } else { - - // if the user's still null, punt and say we didn't find them - - logger.info("User not found: " + resource); - model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); - return HttpCodeView.VIEWNAME; - } - + logger.info("User not found: {}", resource); + model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); + return HttpCodeView.VIEWNAME; } + UriComponents issuerComponents = UriComponentsBuilder.fromHttpUrl(config.getIssuer()).build(); + if (!Strings.nullToEmpty(issuerComponents.getHost()) + .equals(Strings.nullToEmpty(resourceUri.getHost()))) { + logger.info("Host mismatch, expected " + issuerComponents.getHost() + " got " + resourceUri.getHost()); + model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); + return HttpCodeView.VIEWNAME; + } } else { logger.info("Unknown URI format: " + resource); model.addAttribute(HttpCodeView.CODE, HttpStatus.NOT_FOUND); @@ -157,13 +130,20 @@ public class DiscoveryEndpoint { } } - // if we got here, then we're good, return ourselves model.addAttribute("resource", resource); model.addAttribute("issuer", config.getIssuer()); return "webfingerView"; } + private UserInfo extractUser(UriComponents resourceUri) { + UserInfo user = userService.getByEmailAddress(resourceUri.getUserInfo() + "@" + resourceUri.getHost()); + if (user == null) { + user = userService.getByUsername(resourceUri.getUserInfo()); // first part is the username + } + return user; + } + @RequestMapping("/" + OPENID_CONFIGURATION_URL) public String providerConfiguration(Model model) { diff --git a/openid-connect-server/src/main/java/org/mitre/jose/keystore/JWKSetKeyStore.java b/openid-connect-server/src/main/java/org/mitre/jose/keystore/JWKSetKeyStore.java index f635c3e4f..37746f4c1 100644 --- a/openid-connect-server/src/main/java/org/mitre/jose/keystore/JWKSetKeyStore.java +++ b/openid-connect-server/src/main/java/org/mitre/jose/keystore/JWKSetKeyStore.java @@ -91,11 +91,9 @@ public class JWKSetKeyStore { throw new IllegalArgumentException("Key Set resource could not be read: " + location); } catch (ParseException e) { throw new IllegalArgumentException("Key Set resource could not be parsed: " + location); } - } else { throw new IllegalArgumentException("Key Set resource could not be read: " + location); } - } } diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/assertion/AbstractAssertionValidator.java b/openid-connect-server/src/main/java/org/mitre/jwt/assertion/AbstractAssertionValidator.java index 2912cce71..d989b6010 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/assertion/AbstractAssertionValidator.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/assertion/AbstractAssertionValidator.java @@ -10,7 +10,7 @@ import java.text.ParseException; public abstract class AbstractAssertionValidator implements AssertionValidator { - private static Logger logger = LoggerFactory.getLogger(AbstractAssertionValidator.class); + private static final Logger logger = LoggerFactory.getLogger(AbstractAssertionValidator.class); /** * Extract issuer from claims present in JWT assertion. diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/SelfAssertionValidator.java b/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/SelfAssertionValidator.java index 932310895..df028daa0 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/SelfAssertionValidator.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/SelfAssertionValidator.java @@ -37,7 +37,7 @@ import org.springframework.util.StringUtils; @Component("selfAssertionValidator") public class SelfAssertionValidator extends AbstractAssertionValidator implements AssertionValidator { - private static Logger logger = LoggerFactory.getLogger(SelfAssertionValidator.class); + private static final Logger logger = LoggerFactory.getLogger(SelfAssertionValidator.class); private final ConfigurationPropertiesBean config; private final JWTSigningAndValidationService jwtService; diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/WhitelistedIssuerAssertionValidator.java b/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/WhitelistedIssuerAssertionValidator.java index 3cb6c57df..ad8d37c8e 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/WhitelistedIssuerAssertionValidator.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/assertion/impl/WhitelistedIssuerAssertionValidator.java @@ -35,12 +35,9 @@ import java.util.Map; */ public class WhitelistedIssuerAssertionValidator extends AbstractAssertionValidator implements AssertionValidator { - private static Logger logger = LoggerFactory.getLogger(WhitelistedIssuerAssertionValidator.class); + private static final Logger logger = LoggerFactory.getLogger(WhitelistedIssuerAssertionValidator.class); - /** - * Map of issuer -> JWKSetUri - */ - private Map whitelist = new HashMap<>(); + private Map whitelist = new HashMap<>(); //Map of issuer -> JWKSetUri private JWKSetCacheService jwkCache; public Map getWhitelist() { diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/encryption/service/impl/DefaultJWTEncryptionAndDecryptionService.java b/openid-connect-server/src/main/java/org/mitre/jwt/encryption/service/impl/DefaultJWTEncryptionAndDecryptionService.java index 10bc3a9c3..01213faaf 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/encryption/service/impl/DefaultJWTEncryptionAndDecryptionService.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/encryption/service/impl/DefaultJWTEncryptionAndDecryptionService.java @@ -17,8 +17,6 @@ *******************************************************************************/ package org.mitre.jwt.encryption.service.impl; -import java.security.NoSuchAlgorithmException; -import java.security.spec.InvalidKeySpecException; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -27,6 +25,7 @@ import java.util.Set; import javax.annotation.PostConstruct; +import com.nimbusds.jose.KeyLengthException; import org.mitre.jose.keystore.JWKSetKeyStore; import org.mitre.jwt.encryption.service.JWTEncryptionAndDecryptionService; import org.slf4j.Logger; @@ -58,8 +57,8 @@ public class DefaultJWTEncryptionAndDecryptionService implements JWTEncryptionAn private static final Logger logger = LoggerFactory.getLogger(DefaultJWTEncryptionAndDecryptionService.class); - private Map encrypters = new HashMap<>(); - private Map decrypters = new HashMap<>(); + private final Map encrypters = new HashMap<>(); + private final Map decrypters = new HashMap<>(); private String defaultEncryptionKeyId; private String defaultDecryptionKeyId; private JWEAlgorithm defaultAlgorithm; @@ -233,41 +232,53 @@ public class DefaultJWTEncryptionAndDecryptionService implements JWTEncryptionAn JWK jwk = jwkEntry.getValue(); if (jwk instanceof RSAKey) { - RSAEncrypter encrypter = new RSAEncrypter((RSAKey) jwk); - encrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - encrypters.put(id, encrypter); - - if (jwk.isPrivate()) { // we can decrypt! - RSADecrypter decrypter = new RSADecrypter((RSAKey) jwk); - decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - decrypters.put(id, decrypter); - } else { - logger.warn("No private key for key #{}", jwk.getKeyID()); - } + handleRSAKey(id, jwk); } else if (jwk instanceof ECKey) { - ECDHEncrypter encrypter = new ECDHEncrypter((ECKey) jwk); - encrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - encrypters.put(id, encrypter); - - if (jwk.isPrivate()) { // we can decrypt too - ECDHDecrypter decrypter = new ECDHDecrypter((ECKey) jwk); - decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - decrypters.put(id, decrypter); - } else { - logger.warn("No private key for key #{}", jwk.getKeyID()); - } + handleECKey(id, jwk); } else if (jwk instanceof OctetSequenceKey) { - DirectEncrypter encrypter = new DirectEncrypter((OctetSequenceKey) jwk); - encrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - DirectDecrypter decrypter = new DirectDecrypter((OctetSequenceKey) jwk); - decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); - - encrypters.put(id, encrypter); - decrypters.put(id, decrypter); + handleOctetSeqKey(id, jwk); } else { logger.warn("Unknown key type: {}", jwk); } } } + private void handleOctetSeqKey(String id, JWK jwk) throws KeyLengthException { + DirectEncrypter encrypter = new DirectEncrypter((OctetSequenceKey) jwk); + encrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); + DirectDecrypter decrypter = new DirectDecrypter((OctetSequenceKey) jwk); + decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); + + encrypters.put(id, encrypter); + decrypters.put(id, decrypter); + } + + private void handleECKey(String id, JWK jwk) throws JOSEException { + ECDHEncrypter encrypter = new ECDHEncrypter((ECKey) jwk); + encrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); + encrypters.put(id, encrypter); + + if (jwk.isPrivate()) { // we can decrypt too + ECDHDecrypter decrypter = new ECDHDecrypter((ECKey) jwk); + decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); + decrypters.put(id, decrypter); + } else { + logger.warn("No private key for key #{}", jwk.getKeyID()); + } + } + + private void handleRSAKey(String id, JWK jwk) throws JOSEException { + RSAEncrypter encrypter = new RSAEncrypter((RSAKey) jwk); + encrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); + encrypters.put(id, encrypter); + + if (jwk.isPrivate()) { // we can decrypt! + RSADecrypter decrypter = new RSADecrypter((RSAKey) jwk); + decrypter.getJCAContext().setProvider(BouncyCastleProviderSingleton.getInstance()); + decrypters.put(id, decrypter); + } else { + logger.warn("No private key for key #{}", jwk.getKeyID()); + } + } + } diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/JWTSigningAndValidationService.java b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/JWTSigningAndValidationService.java index 61772d02d..582e2c39a 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/JWTSigningAndValidationService.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/JWTSigningAndValidationService.java @@ -27,17 +27,17 @@ import com.nimbusds.jwt.SignedJWT; public interface JWTSigningAndValidationService { - /** - * Get all public keys for this service, mapped by their Key ID - */ Map getAllPublicKeys(); + JWSAlgorithm getDefaultSigningAlgorithm(); + + Collection getAllSigningAlgsSupported(); + /** * Checks the signature of the given JWT against all configured signers, * returns true if at least one of the signers validates it. * - * @param jwtString - * the string representation of the JWT as sent on the wire + * @param jwtString the string representation of the JWT as sent on the wire * @return true if the signature is valid, false if not * @throws NoSuchAlgorithmException */ @@ -53,18 +53,6 @@ public interface JWTSigningAndValidationService { */ void signJwt(SignedJWT jwt); - /** - * Get the default signing algorithm for use when nothing else has been specified. - * @return - */ - JWSAlgorithm getDefaultSigningAlgorithm(); - - /** - * Get the list of all signing algorithms supported by this service. - * @return - */ - Collection getAllSigningAlgsSupported(); - /** * Sign a jwt using the selected algorithm. The algorithm is selected using the String parameter values specified * in the JWT spec, section 6. I.E., "HS256" means HMAC with SHA-256 and corresponds to our HmacSigner class. diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/ClientKeyCacheService.java b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/ClientKeyCacheService.java index 1c6558dbd..5f6866ff6 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/ClientKeyCacheService.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/ClientKeyCacheService.java @@ -17,7 +17,6 @@ package org.mitre.jwt.signer.service.impl; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutionException; @@ -99,7 +98,7 @@ public class ClientKeyCacheService { return null; } } else if (symmetric.contains(alg)) { - return symmetricCache.getSymmetricValidtor(client); + return symmetricCache.getSymmetricValidator(client); } else { return null; } diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJWTSigningAndValidationService.java b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJWTSigningAndValidationService.java index 41ef3a891..34a97ff30 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJWTSigningAndValidationService.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJWTSigningAndValidationService.java @@ -18,6 +18,7 @@ package org.mitre.jwt.signer.service.impl; import com.nimbusds.jose.JOSEException; + import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSProvider; import com.nimbusds.jose.JWSSigner; @@ -50,8 +51,9 @@ public class DefaultJWTSigningAndValidationService implements JWTSigningAndValid private static final Logger logger = LoggerFactory.getLogger(DefaultJWTSigningAndValidationService.class); - private Map signers = new HashMap<>(); - private Map verifiers = new HashMap<>(); + private final Map signers = new HashMap<>(); + private final Map verifiers = new HashMap<>(); + private String defaultSignerKeyId; private JWSAlgorithm defaultAlgorithm; private Map keys = new HashMap<>(); @@ -113,9 +115,6 @@ public class DefaultJWTSigningAndValidationService implements JWTSigningAndValid } } - /** - * Sign a jwt in place using the configured default signer. - */ @Override public void signJwt(SignedJWT jwt) { if (getDefaultSignerKeyId() == null) { @@ -143,8 +142,7 @@ public class DefaultJWTSigningAndValidationService implements JWTSigningAndValid } if (signer == null) { - //If we can't find an algorithm that matches, we can't sign - logger.error("No matching algirthm found for alg=" + alg); + logger.error("No matching algorithm found for alg={}", alg); } else { try { jwt.sign(signer); @@ -158,9 +156,7 @@ public class DefaultJWTSigningAndValidationService implements JWTSigningAndValid public boolean validateSignature(SignedJWT jwt) { for (JWSVerifier verifier : verifiers.values()) { try { - if (jwt.verify(verifier)) { - return true; - } + return jwt.verify(verifier); } catch (JOSEException e) { logger.error("Failed to validate signature with {} error message: {}", verifier, e.getMessage()); } diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/JWKSetCacheService.java b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/JWKSetCacheService.java index 5a88d82d4..227550c96 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/JWKSetCacheService.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/JWKSetCacheService.java @@ -54,8 +54,8 @@ public class JWKSetCacheService { private static final Logger logger = LoggerFactory.getLogger(JWKSetCacheService.class); - private LoadingCache validators; - private LoadingCache encrypters; + private final LoadingCache validators; + private final LoadingCache encrypters; public JWKSetCacheService() { this.validators = CacheBuilder.newBuilder() @@ -68,16 +68,11 @@ public class JWKSetCacheService { .build(new JWKSetEncryptorFetcher(HttpClientBuilder.create().useSystemProperties().build())); } - /** - * @param jwksUri - * @return - * @throws ExecutionException - */ public JWTSigningAndValidationService getValidator(String jwksUri) { try { return validators.get(jwksUri); } catch (UncheckedExecutionException | ExecutionException e) { - logger.warn("Couldn't load JWK Set from " + jwksUri + ": " + e.getMessage()); + logger.warn("Couldn't load JWK Set from {}: {}", jwksUri, e.getMessage()); return null; } } @@ -86,13 +81,13 @@ public class JWKSetCacheService { try { return encrypters.get(jwksUri); } catch (UncheckedExecutionException | ExecutionException e) { - logger.warn("Couldn't load JWK Set from " + jwksUri + ": " + e.getMessage()); + logger.warn("Couldn't load JWK Set from {}: {}", jwksUri, e.getMessage()); return null; } } private static class JWKSetVerifierFetcher extends CacheLoader { - private RestTemplate restTemplate; + private final RestTemplate restTemplate; JWKSetVerifierFetcher(HttpClient httpClient) { HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); @@ -103,15 +98,13 @@ public class JWKSetCacheService { public JWTSigningAndValidationService load(String key) throws Exception { String jsonString = restTemplate.getForObject(key, String.class); JWKSet jwkSet = JWKSet.parse(jsonString); - JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); - return new DefaultJWTSigningAndValidationService(keyStore); } } private static class JWKSetEncryptorFetcher extends CacheLoader { - private RestTemplate restTemplate; + private final RestTemplate restTemplate; public JWKSetEncryptorFetcher(HttpClient httpClient) { HttpComponentsClientHttpRequestFactory httpFactory = new HttpComponentsClientHttpRequestFactory(httpClient); @@ -123,9 +116,7 @@ public class JWKSetCacheService { try { String jsonString = restTemplate.getForObject(key, String.class); JWKSet jwkSet = JWKSet.parse(jsonString); - JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); - return new DefaultJWTEncryptionAndDecryptionService(keyStore); } catch (JsonParseException | RestClientException e) { throw new IllegalArgumentException("Unable to load JWK Set"); diff --git a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/SymmetricKeyJWTValidatorCacheService.java b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/SymmetricKeyJWTValidatorCacheService.java index 597b2939a..3a40559c5 100644 --- a/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/SymmetricKeyJWTValidatorCacheService.java +++ b/openid-connect-server/src/main/java/org/mitre/jwt/signer/service/impl/SymmetricKeyJWTValidatorCacheService.java @@ -45,7 +45,7 @@ public class SymmetricKeyJWTValidatorCacheService { private static final Logger logger = LoggerFactory.getLogger(SymmetricKeyJWTValidatorCacheService.class); - private LoadingCache validators; + private final LoadingCache validators; public SymmetricKeyJWTValidatorCacheService() { validators = CacheBuilder.newBuilder() @@ -54,13 +54,11 @@ public class SymmetricKeyJWTValidatorCacheService { .build(new SymmetricValidatorBuilder()); } - public JWTSigningAndValidationService getSymmetricValidtor(ClientDetailsEntity client) { + public JWTSigningAndValidationService getSymmetricValidator(ClientDetailsEntity client) { if (client == null) { logger.error("Couldn't create symmetric validator for null client"); return null; - } - - if (StringUtils.isEmpty(client.getClientSecret())) { + } else if (StringUtils.isEmpty(client.getClientSecret())) { logger.error("Couldn't create symmetric validator for client {} without a client secret", client.getClientId()); return null; } @@ -76,7 +74,6 @@ public class SymmetricKeyJWTValidatorCacheService { public static class SymmetricValidatorBuilder extends CacheLoader { @Override public JWTSigningAndValidationService load(String key) { - String id = "SYMMETRIC-KEY"; JWK jwk = new OctetSequenceKey.Builder(Base64URL.encode(key)) .keyUse(KeyUse.SIGNATURE) diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/AssertionOAuth2RequestFactory.java b/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/AssertionOAuth2RequestFactory.java index e8c9465ff..729d8a30d 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/AssertionOAuth2RequestFactory.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/AssertionOAuth2RequestFactory.java @@ -26,7 +26,6 @@ import com.nimbusds.jwt.JWT; * Take in an assertion and token request and generate an OAuth2Request from it, including scopes and other important components * * @author jricher - * */ public interface AssertionOAuth2RequestFactory { diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/impl/DirectCopyRequestFactory.java b/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/impl/DirectCopyRequestFactory.java index 1b508dac4..31a7bbd4e 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/impl/DirectCopyRequestFactory.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/assertion/impl/DirectCopyRequestFactory.java @@ -36,27 +36,23 @@ import com.nimbusds.jwt.JWTClaimsSet; * - aud, array of audience IDs * * @author jricher - * */ public class DirectCopyRequestFactory implements AssertionOAuth2RequestFactory { - /* (non-Javadoc) - * @see org.mitre.oauth2.assertion.AssertionOAuth2RequestFactory#createOAuth2Request(org.springframework.security.oauth2.provider.ClientDetails, org.springframework.security.oauth2.provider.TokenRequest, com.nimbusds.jwt.JWT) - */ @Override public OAuth2Request createOAuth2Request(ClientDetails client, TokenRequest tokenRequest, JWT assertion) { - try { JWTClaimsSet claims = assertion.getJWTClaimsSet(); Set scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope")); Set resources = Sets.newHashSet(claims.getAudience()); - return new OAuth2Request(tokenRequest.getRequestParameters(), client.getClientId(), client.getAuthorities(), true, scope, resources, null, null, null); + return new OAuth2Request(tokenRequest.getRequestParameters(), client.getClientId(), + client.getAuthorities(), true, scope, resources, null, + null, null); } catch (ParseException e) { return null; } - } } diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/exception/AuthorizationPendingException.java b/openid-connect-server/src/main/java/org/mitre/oauth2/exception/AuthorizationPendingException.java index c98f95cfc..20ba04b8a 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/exception/AuthorizationPendingException.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/exception/AuthorizationPendingException.java @@ -20,30 +20,18 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; /** * @author jricher - * */ public class AuthorizationPendingException extends OAuth2Exception { - /** - * @param msg - */ + private static final long serialVersionUID = -7078098692596870940L; + public AuthorizationPendingException(String msg) { super(msg); } - /** - * - */ - private static final long serialVersionUID = -7078098692596870940L; - - /* (non-Javadoc) - * @see org.springframework.security.oauth2.common.exceptions.OAuth2Exception#getOAuth2ErrorCode() - */ @Override public String getOAuth2ErrorCode() { return "authorization_pending"; } - - } diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DeviceCodeExpiredException.java b/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DeviceCodeExpiredException.java index 3194531f8..006760ace 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DeviceCodeExpiredException.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DeviceCodeExpiredException.java @@ -24,21 +24,12 @@ import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; */ public class DeviceCodeExpiredException extends OAuth2Exception { - /** - * @param msg - */ + private static final long serialVersionUID = -7078098692596870940L; + public DeviceCodeExpiredException(String msg) { super(msg); } - /** - * - */ - private static final long serialVersionUID = -7078098692596870940L; - - /* (non-Javadoc) - * @see org.springframework.security.oauth2.common.exceptions.OAuth2Exception#getOAuth2ErrorCode() - */ @Override public String getOAuth2ErrorCode() { return "expired_token"; diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DuplicateClientIdException.java b/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DuplicateClientIdException.java index 52e90477e..8e01c86bc 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DuplicateClientIdException.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/exception/DuplicateClientIdException.java @@ -19,14 +19,10 @@ package org.mitre.oauth2.exception; public class DuplicateClientIdException extends RuntimeException { + private static final long serialVersionUID = 1L; + public DuplicateClientIdException(String clientId) { super("Duplicate client id: " + clientId); } - /** - * - */ - private static final long serialVersionUID = 1L; - - } diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java b/openid-connect-server/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java index 8d5847c56..e702910db 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java @@ -50,8 +50,6 @@ import org.mitre.oauth2.model.convert.JWTStringConverter; import org.mitre.openid.connect.model.ApprovedSite; import org.mitre.uma.model.Permission; import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.common.OAuth2AccessTokenJackson1Deserializer; -import org.springframework.security.oauth2.common.OAuth2AccessTokenJackson1Serializer; import org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Deserializer; import org.springframework.security.oauth2.common.OAuth2AccessTokenJackson2Serializer; import org.springframework.security.oauth2.common.OAuth2RefreshToken; @@ -74,8 +72,6 @@ import com.nimbusds.jwt.JWT; @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, query = "select a from OAuth2AccessTokenEntity a join a.permissions p where p.resourceSet.id = :" + OAuth2AccessTokenEntity.PARAM_RESOURCE_SET_ID), @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_NAME, query = "select r from OAuth2AccessTokenEntity r where r.authenticationHolder.userAuth.name = :" + OAuth2AccessTokenEntity.PARAM_NAME) }) -@org.codehaus.jackson.map.annotate.JsonSerialize(using = OAuth2AccessTokenJackson1Serializer.class) -@org.codehaus.jackson.map.annotate.JsonDeserialize(using = OAuth2AccessTokenJackson1Deserializer.class) @com.fasterxml.jackson.databind.annotation.JsonSerialize(using = OAuth2AccessTokenJackson2Serializer.class) @com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = OAuth2AccessTokenJackson2Deserializer.class) public class OAuth2AccessTokenEntity implements OAuth2AccessToken { diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/BlacklistAwareRedirectResolver.java b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/BlacklistAwareRedirectResolver.java index fc45ed20b..f47581694 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/BlacklistAwareRedirectResolver.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/BlacklistAwareRedirectResolver.java @@ -21,13 +21,28 @@ package org.mitre.oauth2.service.impl; import org.mitre.openid.connect.config.ConfigurationPropertiesBean; import org.mitre.openid.connect.service.BlacklistedSiteService; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.oauth2.common.exceptions.InvalidGrantException; import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; +import org.springframework.security.oauth2.common.exceptions.RedirectMismatchException; import org.springframework.security.oauth2.provider.ClientDetails; import org.springframework.security.oauth2.provider.endpoint.DefaultRedirectResolver; +import org.springframework.security.oauth2.provider.endpoint.RedirectResolver; import org.springframework.stereotype.Component; import com.google.common.base.Strings; +import org.springframework.util.Assert; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; /** * @@ -38,7 +53,7 @@ import com.google.common.base.Strings; * */ @Component("blacklistAwareRedirectResolver") -public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver { +public class BlacklistAwareRedirectResolver implements RedirectResolver { @Autowired private BlacklistedSiteService blacklistService; @@ -46,37 +61,36 @@ public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver { @Autowired private ConfigurationPropertiesBean config; + private Collection redirectGrantTypes = Arrays.asList("implicit", "authorization_code"); + private boolean matchSubdomains = false; + private boolean matchPorts = true; private boolean strictMatch = true; - /* (non-Javadoc) - * @see org.springframework.security.oauth2.provider.endpoint.RedirectResolver#resolveRedirect(java.lang.String, org.springframework.security.oauth2.provider.ClientDetails) + /** + * Flag to indicate that requested URIs will match if they are a subdomain of the registered value. + * + * @param matchSubdomains the flag value to set (default true) */ - @Override - public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { - String redirect = super.resolveRedirect(requestedRedirect, client); - if (blacklistService.isBlacklisted(redirect)) { - // don't let it go through - throw new InvalidRequestException("The supplied redirect_uri is not allowed on this server."); - } else { - // not blacklisted, passed the parent test, we're fine - return redirect; - } + public void setMatchSubdomains(boolean matchSubdomains) { + this.matchSubdomains = matchSubdomains; } - /* (non-Javadoc) - * @see org.springframework.security.oauth2.provider.endpoint.DefaultRedirectResolver#redirectMatches(java.lang.String, java.lang.String) + /** + * Flag that enables/disables port matching between the requested redirect URI and the registered redirect URI(s). + * + * @param matchPorts true to enable port matching, false to disable (defaults to true) */ - @Override - protected boolean redirectMatches(String requestedRedirect, String redirectUri) { - - if (isStrictMatch()) { - // we're doing a strict string match for all clients - return Strings.nullToEmpty(requestedRedirect).equals(redirectUri); - } else { - // otherwise do the prefix-match from the library - return super.redirectMatches(requestedRedirect, redirectUri); - } + public void setMatchPorts(boolean matchPorts) { + this.matchPorts = matchPorts; + } + /** + * Grant types that are permitted to have a redirect uri. + * + * @param redirectGrantTypes the redirect grant types to set + */ + public void setRedirectGrantTypes(Collection redirectGrantTypes) { + this.redirectGrantTypes = new HashSet(redirectGrantTypes); } /** @@ -100,6 +114,172 @@ public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver { this.strictMatch = strictMatch; } + /* (non-Javadoc) + * @see org.springframework.security.oauth2.provider.endpoint.RedirectResolver#resolveRedirect(java.lang.String, org.springframework.security.oauth2.provider.ClientDetails) + */ + @Override + public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { + Set authorizedGrantTypes = client.getAuthorizedGrantTypes(); + if (authorizedGrantTypes.isEmpty()) { + throw new InvalidGrantException("A client must have at least one authorized grant type."); + } + if (!containsRedirectGrantType(authorizedGrantTypes)) { + throw new InvalidGrantException( + "A redirect_uri can only be used by implicit or authorization_code grant types."); + } + Set registeredRedirectUris = client.getRegisteredRedirectUri(); + if (registeredRedirectUris == null || registeredRedirectUris.isEmpty()) { + throw new InvalidRequestException("At least one redirect_uri must be registered with the client."); + } + + String redirect = obtainMatchingRedirect(registeredRedirectUris, requestedRedirect); + + if (blacklistService.isBlacklisted(redirect)) { + // don't let it go through + throw new InvalidRequestException("The supplied redirect_uri is not allowed on this server."); + } else { + // not blacklisted, passed the parent test, we're fine + return redirect; + } + } + + /** + * Whether the requested redirect URI "matches" the specified redirect URI. For a URL, this implementation tests if + * the user requested redirect starts with the registered redirect, so it would have the same host and root path if + * it is an HTTP URL. The port, userinfo, query params also matched. Request redirect uri path can include + * additional parameters which are ignored for the match + *

+ * For other (non-URL) cases, such as for some implicit clients, the redirect_uri must be an exact match. + * + * @param requestedRedirect The requested redirect URI. + * @param redirectUri The registered redirect URI. + * @return Whether the requested redirect URI "matches" the specified redirect URI. + */ + protected boolean redirectMatches(String requestedRedirect, String redirectUri) { + UriComponents requestedRedirectUri = UriComponentsBuilder.fromUriString(requestedRedirect).build(); + UriComponents registeredRedirectUri = UriComponentsBuilder.fromUriString(redirectUri).build(); + + boolean schemeMatch = isEqual(registeredRedirectUri.getScheme(), requestedRedirectUri.getScheme()); + boolean userInfoMatch = isEqual(registeredRedirectUri.getUserInfo(), requestedRedirectUri.getUserInfo()); + boolean hostMatch = hostMatches(registeredRedirectUri.getHost(), requestedRedirectUri.getHost()); + boolean portMatch = !matchPorts || registeredRedirectUri.getPort() == requestedRedirectUri.getPort(); + boolean pathMatch = true; + boolean queryParamMatch = true; + if (strictMatch) { + pathMatch = isEqual(registeredRedirectUri.getPath(), + StringUtils.cleanPath(requestedRedirectUri.getPath())); + queryParamMatch = matchQueryParams(registeredRedirectUri.getQueryParams(), + requestedRedirectUri.getQueryParams()); + } + + return schemeMatch && userInfoMatch && hostMatch && portMatch && pathMatch && queryParamMatch; + } + + /** + * @param grantTypes some grant types + * @return true if the supplied grant types includes one or more of the redirect types + */ + private boolean containsRedirectGrantType(Set grantTypes) { + for (String type : grantTypes) { + if (redirectGrantTypes.contains(type)) { + return true; + } + } + return false; + } + + /** + * Attempt to match one of the registered URIs to the that of the requested one. + * + * @param redirectUris the set of the registered URIs to try and find a match. This cannot be null or empty. + * @param requestedRedirect the URI used as part of the request + * @return redirect uri + * @throws RedirectMismatchException if no match was found + */ + private String obtainMatchingRedirect(Set redirectUris, String requestedRedirect) { + Assert.notEmpty(redirectUris, "Redirect URIs cannot be empty"); + + if (redirectUris.size() == 1 && requestedRedirect == null) { + return redirectUris.iterator().next(); + } + + for (String redirectUri : redirectUris) { + if (requestedRedirect != null && redirectMatches(requestedRedirect, redirectUri)) { + // Initialize with the registered redirect-uri + UriComponentsBuilder redirectUriBuilder = UriComponentsBuilder.fromUriString(redirectUri); + UriComponents requestedRedirectUri = UriComponentsBuilder.fromUriString(requestedRedirect).build(); + + if (this.matchSubdomains) { + redirectUriBuilder.host(requestedRedirectUri.getHost()); + } + if (!this.matchPorts) { + redirectUriBuilder.port(requestedRedirectUri.getPort()); + } + if (!this.strictMatch) { + redirectUriBuilder.path(requestedRedirectUri.getPath()); + } + redirectUriBuilder.replaceQuery(requestedRedirectUri.getQuery()); // retain additional params (if any) + redirectUriBuilder.fragment(null); + return redirectUriBuilder.build().toUriString(); + } + } + + throw new RedirectMismatchException("Invalid redirect: " + requestedRedirect + + " does not match one of the registered values."); + } + + /** + * Compares two strings but treats empty string or null equal + * + * @param str1 + * @param str2 + * @return true if strings are equal, false otherwise + */ + private boolean isEqual(String str1, String str2) { + if (StringUtils.isEmpty(str1)) { + return StringUtils.isEmpty(str2); + } else { + return str1.equals(str2); + } + } + + /** + * Check if host matches the registered value. + * + * @param registered the registered host. Can be null. + * @param requested the requested host. Can be null. + * @return true if they match + */ + protected boolean hostMatches(String registered, String requested) { + if (matchSubdomains) { + return isEqual(registered, requested) || (requested != null && requested.endsWith("." + registered)); + } + return isEqual(registered, requested); + } + + /** + * Checks whether the registered redirect uri query params key and values contains match the requested set + * + * The requested redirect uri query params are allowed to contain additional params which will be retained + * + * @param registeredRedirectUriQueryParams + * @param requestedRedirectUriQueryParams + * @return whether the params match + */ + private boolean matchQueryParams(MultiValueMap registeredRedirectUriQueryParams, + MultiValueMap requestedRedirectUriQueryParams) + { + for (String key : registeredRedirectUriQueryParams.keySet()) { + List registeredRedirectUriQueryParamsValues = registeredRedirectUriQueryParams.get(key); + List requestedRedirectUriQueryParamsValues = requestedRedirectUriQueryParams.get(key); + + if (!registeredRedirectUriQueryParamsValues.equals(requestedRedirectUriQueryParamsValues)) { + return false; + } + } + + return true; + } } diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/DefaultOIDCTokenService.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/DefaultOIDCTokenService.java index 00863745a..2b6fb1ec7 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/DefaultOIDCTokenService.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/DefaultOIDCTokenService.java @@ -188,7 +188,7 @@ public class DefaultOIDCTokenService implements OIDCTokenService { null, null); idToken = new SignedJWT(header, idClaims.build()); - JWTSigningAndValidationService signer = symmetricCacheService.getSymmetricValidtor(client); + JWTSigningAndValidationService signer = symmetricCacheService.getSymmetricValidator(client); // sign it with the client's secret signer.signJwt((SignedJWT) idToken); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoJWTView.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoJWTView.java index e452b352b..1ce83dff0 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoJWTView.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoJWTView.java @@ -142,7 +142,7 @@ public class UserInfoJWTView extends UserInfoView { || signingAlg.equals(JWSAlgorithm.HS512)) { // sign it with the client's secret - JWTSigningAndValidationService signer = symmetricCacheService.getSymmetricValidtor(client); + JWTSigningAndValidationService signer = symmetricCacheService.getSymmetricValidator(client); signer.signJwt(signed); } else { diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java index eff165d06..e58a1cda2 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java @@ -20,11 +20,6 @@ */ package org.mitre.openid.connect.web; -import java.lang.reflect.Type; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.mitre.openid.connect.model.OIDCAuthenticationToken; import org.mitre.openid.connect.model.UserInfo; import org.mitre.openid.connect.service.UserInfoService; @@ -38,11 +33,12 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + /** * Injects the UserInfo object for the current user into the current model's context, if both exist. Allows JSPs and the like to call "userInfo.name" and other fields. * diff --git a/openid-connect-server/src/main/java/org/mitre/uma/model/Claim.java b/openid-connect-server/src/main/java/org/mitre/uma/model/Claim.java index d6d30b64d..aaa88eb56 100644 --- a/openid-connect-server/src/main/java/org/mitre/uma/model/Claim.java +++ b/openid-connect-server/src/main/java/org/mitre/uma/model/Claim.java @@ -16,6 +16,9 @@ package org.mitre.uma.model; +import com.google.gson.JsonElement; +import org.mitre.oauth2.model.convert.JsonElementStringConverter; + import java.util.Set; import javax.persistence.Basic; @@ -31,10 +34,6 @@ import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.Table; -import org.mitre.oauth2.model.convert.JsonElementStringConverter; - -import com.google.gson.JsonElement; - /** * @author jricher */ diff --git a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java index 3698ec9e0..ae0b525a7 100644 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java @@ -74,8 +74,6 @@ public class TestBlacklistAwareRedirectResolver { when(client.getAuthorizedGrantTypes()).thenReturn(ImmutableSet.of("authorization_code")); when(client.getRegisteredRedirectUri()).thenReturn(ImmutableSet.of(goodUri, blacklistedUri)); - - when(config.isHeartMode()).thenReturn(false); } @Test @@ -141,8 +139,6 @@ public class TestBlacklistAwareRedirectResolver { @Test public void testHeartMode() { - when(config.isHeartMode()).thenReturn(true); - // this is not an exact match boolean res1 = resolver.redirectMatches(pathUri, goodUri); diff --git a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ClientDetailsEntityService.java b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ClientDetailsEntityService.java index 6ec31ca80..23f5993c8 100644 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ClientDetailsEntityService.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ClientDetailsEntityService.java @@ -17,15 +17,11 @@ *******************************************************************************/ package org.mitre.oauth2.service.impl; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; - +import com.google.common.collect.Sets; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mitre.oauth2.model.ClientDetailsEntity; -import org.mitre.oauth2.model.ClientDetailsEntity.AuthMethod; import org.mitre.oauth2.model.SystemScope; import org.mitre.oauth2.repository.OAuth2ClientRepository; import org.mitre.oauth2.repository.OAuth2TokenRepository; @@ -40,22 +36,23 @@ import org.mitre.uma.model.ResourceSet; import org.mitre.uma.service.ResourceSetService; import org.mockito.AdditionalAnswers; import org.mockito.InjectMocks; -import org.mockito.Matchers; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.security.oauth2.common.exceptions.InvalidClientException; -import com.google.common.collect.Sets; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; - -import static org.junit.Assert.assertThat; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.fail; /** @@ -99,7 +96,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { public void prepare() { Mockito.reset(clientRepository, tokenRepository, approvedSiteService, whitelistedSiteService, blacklistedSiteService, scopeService, statsService); - Mockito.when(clientRepository.saveClient(Matchers.any(ClientDetailsEntity.class))).thenAnswer(new Answer() { + Mockito.when(clientRepository.saveClient(ArgumentMatchers.any(ClientDetailsEntity.class))).thenAnswer(new Answer() { @Override public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); @@ -107,15 +104,10 @@ public class TestDefaultOAuth2ClientDetailsEntityService { } }); - Mockito.when(clientRepository.updateClient(Matchers.anyLong(), Matchers.any(ClientDetailsEntity.class))).thenAnswer(new Answer() { - @Override - public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return (ClientDetailsEntity) args[1]; - } - }); + Mockito.when(clientRepository.updateClient(ArgumentMatchers.nullable(Long.class), ArgumentMatchers.any(ClientDetailsEntity.class))) + .then(a -> a.getArgument(1)); - Mockito.when(scopeService.fromStrings(Matchers.anySet())).thenAnswer(new Answer>() { + Mockito.when(scopeService.fromStrings(ArgumentMatchers.anySet())).thenAnswer(new Answer>() { @Override public Set answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); @@ -128,7 +120,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { } }); - Mockito.when(scopeService.toStrings(Matchers.anySet())).thenAnswer(new Answer>() { + Mockito.when(scopeService.toStrings(ArgumentMatchers.anySet())).thenAnswer(new Answer>() { @Override public Set answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); @@ -142,7 +134,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { }); // we're not testing reserved scopes here, just pass through when it's called - Mockito.when(scopeService.removeReservedScopes(Matchers.anySet())).then(AdditionalAnswers.returnsFirstArg()); + Mockito.when(scopeService.removeReservedScopes(ArgumentMatchers.anySet())).then(AdditionalAnswers.returnsFirstArg()); Mockito.when(config.isHeartMode()).thenReturn(false); @@ -187,7 +179,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { service.saveNewClient(client); - Mockito.verify(client).setClientId(Matchers.anyString()); + Mockito.verify(client).setClientId(ArgumentMatchers.anyString()); } /** @@ -217,7 +209,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { client = service.saveNewClient(client); - Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); + Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(ArgumentMatchers.anySet()); assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); } @@ -343,7 +335,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { client = service.updateClient(oldClient, client); - Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); + Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(ArgumentMatchers.anySet()); assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(true))); } @@ -359,7 +351,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { client = service.updateClient(oldClient, client); - Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); + Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(ArgumentMatchers.anySet()); assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); } @@ -375,7 +367,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("client_credentials"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); @@ -396,7 +388,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("client_credentials"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.NONE); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.NONE); client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); @@ -417,7 +409,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("implicit"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setJwksUri("https://foo.bar/jwks"); @@ -434,7 +426,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("authorization_code"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.SECRET_POST); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_POST); client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); @@ -453,7 +445,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("implicit"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); @@ -472,7 +464,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("client_credentials"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.SECRET_BASIC); client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); @@ -491,7 +483,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("authorization_code"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); service.saveNewClient(client); @@ -506,7 +498,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("implicit"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.NONE); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.NONE); service.saveNewClient(client); @@ -521,7 +513,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("client_credentials"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); @@ -538,7 +530,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("authorization_code"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); @@ -557,7 +549,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("authorization_code"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); @@ -578,7 +570,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("refresh_token"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); @@ -600,7 +592,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("refresh_token"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); @@ -620,7 +612,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { grantTypes.add("refresh_token"); client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(ClientDetailsEntity.AuthMethod.PRIVATE_KEY); client.setRedirectUris(Sets.newHashSet("http://localhost/", "https://foo.bar", "foo://bar")); diff --git a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ProviderTokenService.java b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ProviderTokenService.java index afdb9dd6b..a409d15af 100644 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ProviderTokenService.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ProviderTokenService.java @@ -191,8 +191,6 @@ public class TestDefaultOAuth2ProviderTokenService { // we're not testing restricted or reserved scopes here, just pass through when(scopeService.removeReservedScopes(anySet())).then(returnsFirstArg()); - when(scopeService.removeRestrictedAndReservedScopes(anySet())).then(returnsFirstArg()); - when(tokenEnhancer.enhance(any(OAuth2AccessTokenEntity.class), any(OAuth2Authentication.class))) .thenAnswer(new Answer(){ @Override diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java index 8524145f0..149694449 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java @@ -123,7 +123,6 @@ public class TestDefaultApprovedSiteService { String otherId = "a different id"; client.setClientId(otherId); service.clearApprovedSitesForClient(client); - Mockito.when(repository.getByClientId(otherId)).thenReturn(new HashSet()); Mockito.verify(repository, never()).remove(any(ApprovedSite.class)); } diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java index b5c1ae6b3..db4a78a9c 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java @@ -63,11 +63,6 @@ public class TestDefaultStatsService { private ApprovedSite ap5 = Mockito.mock(ApprovedSite.class); private ApprovedSite ap6 = Mockito.mock(ApprovedSite.class); - private ClientDetailsEntity client1 = Mockito.mock(ClientDetailsEntity.class); - private ClientDetailsEntity client2 = Mockito.mock(ClientDetailsEntity.class); - private ClientDetailsEntity client3 = Mockito.mock(ClientDetailsEntity.class); - private ClientDetailsEntity client4 = Mockito.mock(ClientDetailsEntity.class); - @Mock private ApprovedSiteService approvedSiteService; @@ -102,12 +97,6 @@ public class TestDefaultStatsService { Mockito.when(ap6.getClientId()).thenReturn(clientId4); Mockito.when(approvedSiteService.getAll()).thenReturn(Sets.newHashSet(ap1, ap2, ap3, ap4)); - - Mockito.when(client1.getId()).thenReturn(1L); - Mockito.when(client2.getId()).thenReturn(2L); - Mockito.when(client3.getId()).thenReturn(3L); - Mockito.when(client4.getId()).thenReturn(4L); - Mockito.when(approvedSiteService.getByClientId(clientId1)).thenReturn(Sets.newHashSet(ap1, ap2)); Mockito.when(approvedSiteService.getByClientId(clientId2)).thenReturn(Sets.newHashSet(ap3)); Mockito.when(approvedSiteService.getByClientId(clientId3)).thenReturn(Sets.newHashSet(ap4)); diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_0.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_0.java index 6d5e7ec7c..a17e775b9 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_0.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_0.java @@ -61,7 +61,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.datetime.DateFormatter; @@ -150,7 +150,6 @@ public class TestMITREidDataService_1_0 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -165,7 +164,6 @@ public class TestMITREidDataService_1_0 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -229,7 +227,6 @@ public class TestMITREidDataService_1_0 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -267,7 +264,6 @@ public class TestMITREidDataService_1_0 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -285,10 +281,8 @@ public class TestMITREidDataService_1_0 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -359,7 +353,6 @@ public class TestMITREidDataService_1_0 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -554,13 +547,6 @@ public class TestMITREidDataService_1_0 { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); dataService.importData(reader); verify(wlSiteRepository, times(3)).save(capturedWhitelistedSites.capture()); @@ -580,8 +566,6 @@ public class TestMITREidDataService_1_0 { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); - ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); site1.setClientId("foo"); @@ -589,7 +573,6 @@ public class TestMITREidDataService_1_0 { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH); @@ -648,25 +631,13 @@ public class TestMITREidDataService_1_0 { return fakeDb.get(_id); } }); - when(wlSiteRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 244L; - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); - return _site; - } - }); when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { Long id = 221L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); - return _token; + return mock(OAuth2AccessTokenEntity.class); } }); - when(tokenRepository.getAccessTokensForApprovedSite(site1)).thenReturn(Lists.newArrayList(mockToken1)); dataService.importData(reader); //2 for sites, 1 for updating access token ref on #1 @@ -835,7 +806,6 @@ public class TestMITREidDataService_1_0 { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -858,7 +828,6 @@ public class TestMITREidDataService_1_0 { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -929,7 +898,6 @@ public class TestMITREidDataService_1_0 { public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { String _clientId = (String) invocation.getArguments()[0]; ClientDetailsEntity _client = mock(ClientDetailsEntity.class); - when(_client.getClientId()).thenReturn(_clientId); return _client; } }); @@ -967,4 +935,4 @@ public class TestMITREidDataService_1_0 { dataService.exportData(writer); } -} \ No newline at end of file +} diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_1.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_1.java index d7ab851fd..f98ea784f 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_1.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_1.java @@ -152,7 +152,6 @@ public class TestMITREidDataService_1_1 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -168,7 +167,6 @@ public class TestMITREidDataService_1_1 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -232,7 +230,6 @@ public class TestMITREidDataService_1_1 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -271,7 +268,6 @@ public class TestMITREidDataService_1_1 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -289,10 +285,8 @@ public class TestMITREidDataService_1_1 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -363,7 +357,6 @@ public class TestMITREidDataService_1_1 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -557,13 +550,6 @@ public class TestMITREidDataService_1_1 { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); dataService.importData(reader); verify(wlSiteRepository, times(3)).save(capturedWhitelistedSites.capture()); @@ -583,7 +569,6 @@ public class TestMITREidDataService_1_1 { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -592,7 +577,6 @@ public class TestMITREidDataService_1_1 { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH); @@ -651,21 +635,11 @@ public class TestMITREidDataService_1_1 { return fakeDb.get(_id); } }); - when(wlSiteRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 432L; - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); - return _site; - } - }); when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { Long id = 245L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); return _token; } }); @@ -837,7 +811,6 @@ public class TestMITREidDataService_1_1 { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -860,7 +833,6 @@ public class TestMITREidDataService_1_1 { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -931,7 +903,6 @@ public class TestMITREidDataService_1_1 { public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { String _clientId = (String) invocation.getArguments()[0]; ClientDetailsEntity _client = mock(ClientDetailsEntity.class); - when(_client.getClientId()).thenReturn(_clientId); return _client; } }); diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_2.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_2.java index 594900ae2..2f72a9ea2 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_2.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_2.java @@ -154,7 +154,6 @@ public class TestMITREidDataService_1_2 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -170,7 +169,6 @@ public class TestMITREidDataService_1_2 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -234,7 +232,6 @@ public class TestMITREidDataService_1_2 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -273,7 +270,6 @@ public class TestMITREidDataService_1_2 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -291,10 +287,8 @@ public class TestMITREidDataService_1_2 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -365,7 +359,6 @@ public class TestMITREidDataService_1_2 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -559,13 +552,6 @@ public class TestMITREidDataService_1_2 { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); dataService.importData(reader); verify(wlSiteRepository, times(3)).save(capturedWhitelistedSites.capture()); @@ -585,7 +571,6 @@ public class TestMITREidDataService_1_2 { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -594,7 +579,6 @@ public class TestMITREidDataService_1_2 { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH); @@ -653,21 +637,11 @@ public class TestMITREidDataService_1_2 { return fakeDb.get(_id); } }); - when(wlSiteRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 432L; - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); - return _site; - } - }); when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { Long id = 245L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); return _token; } }); @@ -839,7 +813,6 @@ public class TestMITREidDataService_1_2 { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -862,7 +835,6 @@ public class TestMITREidDataService_1_2 { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -933,7 +905,6 @@ public class TestMITREidDataService_1_2 { public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { String _clientId = (String) invocation.getArguments()[0]; ClientDetailsEntity _client = mock(ClientDetailsEntity.class); - when(_client.getClientId()).thenReturn(_clientId); return _client; } }); diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java index 29a04d932..73c9bc466 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java @@ -280,8 +280,6 @@ public class TestMITREidDataService_1_3 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); - OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); token1.setClient(mockedClient1); @@ -296,8 +294,6 @@ public class TestMITREidDataService_1_3 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); - OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); token2.setClient(mockedClient2); @@ -360,7 +356,6 @@ public class TestMITREidDataService_1_3 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -530,8 +525,6 @@ public class TestMITREidDataService_1_3 { when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); - OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); token1.setClient(mockedClient1); @@ -548,11 +541,7 @@ public class TestMITREidDataService_1_3 { when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); - OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); - OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); token2.setClient(mockedClient2); @@ -622,7 +611,6 @@ public class TestMITREidDataService_1_3 { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -1109,13 +1097,6 @@ public class TestMITREidDataService_1_3 { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); dataService.importData(reader); verify(wlSiteRepository, times(3)).save(capturedWhitelistedSites.capture()); @@ -1135,7 +1116,6 @@ public class TestMITREidDataService_1_3 { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -1144,7 +1124,6 @@ public class TestMITREidDataService_1_3 { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH); @@ -1250,7 +1229,6 @@ public class TestMITREidDataService_1_3 { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+0000", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -1259,7 +1237,6 @@ public class TestMITREidDataService_1_3 { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+0000", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+0000", Locale.ENGLISH); @@ -1318,21 +1295,11 @@ public class TestMITREidDataService_1_3 { return fakeDb.get(_id); } }); - when(wlSiteRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 432L; - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); - return _site; - } - }); when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { Long id = 245L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); return _token; } }); @@ -1721,7 +1688,6 @@ public class TestMITREidDataService_1_3 { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -1744,7 +1710,6 @@ public class TestMITREidDataService_1_3 { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -1815,7 +1780,6 @@ public class TestMITREidDataService_1_3 { public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { String _clientId = (String) invocation.getArguments()[0]; ClientDetailsEntity _client = mock(ClientDetailsEntity.class); - when(_client.getClientId()).thenReturn(_clientId); return _client; } }); diff --git a/pom.xml b/pom.xml index 74337f5a1..630d1a214 100644 --- a/pom.xml +++ b/pom.xml @@ -358,23 +358,24 @@ 2.4.1.RELEASE 2.11.0 1.2 - 4.0.1 + 2.5 2.2 8.0.20 2.4.0 2.7.7 2.2.1 - 2.12.0 + 3.4.5 + 1.2.3 1.7.30 2.13.3 - 5.6.2 + 4.13 4.2 - 1.10.19 + 3.2.4 29.0-jre 2.8.6 4.5.12 8.17.1 - 1.65.01 + 1.65 2.7 1.9.0 @@ -402,6 +403,12 @@ spring-security-oauth2 ${spring-security-oauth2.version} + + org.springframework + spring-test + ${spring.version} + test + com.fasterxml.jackson.core @@ -416,14 +423,14 @@ javax.servlet.jsp.jstl - jstl + jstl-api ${jstl.version} javax.servlet - javax.servlet-api + servlet-api ${servlet-api.version} - provided + compile javax.servlet.jsp @@ -448,11 +455,6 @@ org.eclipse.persistence.jpa ${eclipse-persistence.version} - - org.eclipse.persistence - javax.persistence - ${javax-persistence.version} - com.zaxxer HikariCP @@ -460,68 +462,21 @@ - org.slf4j - slf4j-api - ${org.slf4j-version} - - - org.slf4j - slf4j-jdk14 - test - ${org.slf4j-version} - - - org.slf4j - jcl-over-slf4j - ${org.slf4j-version} - - - org.slf4j - slf4j-log4j12 - ${org.slf4j-version} - runtime - - - org.apache.logging.log4j - log4j-core - ${log4j-core.version} - - - javax.mail - mail - - - javax.jms - jms - - - com.sun.jdmk - jmxtools - - - com.sun.jmx - jmxri - - - runtime + ch.qos.logback + logback-classic + ${logback.version} - org.junit.jupiter - junit-jupiter-api - ${junit-jupiter-api.version} - test - - - org.easymock - easymock - ${easymock.version} + junit + junit + ${junit.version} test org.mockito - mockito-all - ${mockito-all.version} + mockito-core + ${mockito.version} test @@ -530,18 +485,6 @@ openid-connect-server ${project.version} - - org.mitre - openid-connect-server-webapp - ${project.version} - war - - - org.mitre - openid-connect-server-webapp - ${project.version} - warpath - com.google.guava @@ -557,12 +500,6 @@ org.apache.httpcomponents httpclient ${httpclient.version} - - - commons-logging - commons-logging - - com.nimbusds @@ -580,54 +517,11 @@ ${eclipse-persistence.version} - org.apache.commons + commons-io commons-io ${commons-io.version} - - ro.isdc.wro4j - wro4j-extensions - ${wro4j-extensions.version} - - - - - junit - junit - - - org.easymock - easymock - - - org.springframework - spring-test - - - commons-logging - commons-logging - - - - - org.mockito - mockito-all - - - org.slf4j - slf4j-jdk14 - - - javax.servlet - servlet-api - - - javax.servlet.jsp - jsp-api - - -