From 685960358c1b60ce9e238f1a4b56667c4c922392 Mon Sep 17 00:00:00 2001 From: Justin Richer Date: Tue, 17 Feb 2015 11:08:46 -0500 Subject: [PATCH] formatting cleanup --- .../OAuth2AccessTokenImpl.java | 30 +- .../client/OIDCAuthenticationFilter.java | 46 +- .../connect/client/UserInfoFetcher.java | 20 +- ...egistrationClientConfigurationService.java | 10 +- .../TestOAuth2AccessTokenImpl.java | 38 +- .../impl/TestPlainAuthRequestUrlBuilder.java | 6 +- ...DefaultJwtSigningAndValidationService.java | 4 +- .../model/AuthenticationHolderEntity.java | 2 +- .../oauth2/model/ClientDetailsEntity.java | 4 +- .../AuthenticationHolderRepository.java | 2 +- .../service/IntrospectionResultAssembler.java | 36 +- .../service/OAuth2TokenEntityService.java | 2 +- .../impl/DefaultClientUserDetailsService.java | 14 +- .../ClientDetailsEntityJsonProcessor.java | 4 +- .../ConfigurationBeanLocaleResolver.java | 2 +- .../config/ConfigurationPropertiesBean.java | 10 +- .../connect/config/ServerConfiguration.java | 16 +- .../openid/connect/model/DefaultUserInfo.java | 4 + .../connect/service/MITREidDataService.java | 30 +- .../connect/web/UserInfoInterceptor.java | 4 +- .../java/org/mitre/jose/JOSEEmbedTest.java | 20 +- .../org/mitre/jose/TestJWKSetKeyStore.java | 164 +- ...aultJwtEncryptionAndDecryptionService.java | 105 +- .../ConfigurationPropertiesBeanTest.java | 18 +- .../discovery/web/DiscoveryEndpoint.java | 2 +- .../JpaAuthenticationHolderRepository.java | 10 +- .../impl/BlacklistAwareRedirectResolver.java | 2 +- .../DefaultIntrospectionResultAssembler.java | 86 +- ...faultOAuth2ClientDetailsEntityService.java | 5 +- .../DefaultOAuth2ProviderTokenService.java | 16 +- .../oauth2/web/IntrospectionEndpoint.java | 63 +- .../web/OAuthConfirmationController.java | 8 +- .../java/org/mitre/oauth2/web/TokenAPI.java | 26 +- .../connect/ConnectOAuth2RequestFactory.java | 6 +- .../JwtBearerAuthenticationProvider.java | 10 +- .../exception/ValidationException.java | 2 +- .../filter/AuthorizationRequestFilter.java | 6 +- .../impl/JpaUserInfoRepository.java | 2 - .../service/impl/DefaultOIDCTokenService.java | 34 +- .../service/impl/MITREidDataService_1_0.java | 1520 ++++++------ .../service/impl/MITREidDataService_1_1.java | 1520 ++++++------ .../service/impl/MITREidDataService_1_2.java | 2146 ++++++++--------- .../service/impl/MITREidDataService_1_X.java | 186 +- .../token/TofuUserApprovalHandler.java | 2 +- .../mitre/openid/connect/util/DateUtil.java | 49 +- .../view/ClientEntityViewForUsers.java | 2 +- .../view/ClientInformationResponseView.java | 2 +- .../openid/connect/view/HttpCodeView.java | 2 +- .../connect/view/JsonApprovedSiteView.java | 2 +- .../openid/connect/view/JsonEntityView.java | 2 +- .../openid/connect/view/JsonErrorView.java | 2 +- .../openid/connect/view/UserInfoJwtView.java | 4 +- .../openid/connect/view/UserInfoView.java | 2 +- .../mitre/openid/connect/web/ClientAPI.java | 50 +- .../ClientDynamicRegistrationEndpoint.java | 74 +- .../org/mitre/openid/connect/web/DataAPI.java | 52 +- ...ProtectedResourceRegistrationEndpoint.java | 23 +- .../openid/connect/web/UserInfoEndpoint.java | 8 +- .../TestDefaultIntrospectionAuthorizer.java | 6 +- ...stDefaultIntrospectionResultAssembler.java | 339 +-- ...faultOAuth2ClientDetailsEntityService.java | 26 +- ...TestDefaultOAuth2ProviderTokenService.java | 44 +- .../impl/TestMITREidDataService_1_0.java | 1216 +++++----- .../impl/TestMITREidDataService_1_1.java | 1254 +++++----- .../impl/TestMITREidDataService_1_2.java | 1860 +++++++------- .../connect/util/TestIdTokenHashUtils.java | 17 +- 66 files changed, 5651 insertions(+), 5628 deletions(-) diff --git a/openid-connect-client/src/main/java/org/mitre/oauth2/introspectingfilter/OAuth2AccessTokenImpl.java b/openid-connect-client/src/main/java/org/mitre/oauth2/introspectingfilter/OAuth2AccessTokenImpl.java index a156023bf..8141794ca 100644 --- a/openid-connect-client/src/main/java/org/mitre/oauth2/introspectingfilter/OAuth2AccessTokenImpl.java +++ b/openid-connect-client/src/main/java/org/mitre/oauth2/introspectingfilter/OAuth2AccessTokenImpl.java @@ -32,21 +32,21 @@ import com.google.gson.JsonObject; public class OAuth2AccessTokenImpl implements OAuth2AccessToken { - private JsonObject token; + private JsonObject introspectionResponse; private String tokenString; private Set scopes = new HashSet(); private Date expireDate; - public OAuth2AccessTokenImpl(JsonObject token, String tokenString) { - this.token = token; + public OAuth2AccessTokenImpl(JsonObject introspectionResponse, String tokenString) { + this.setIntrospectionResponse(introspectionResponse); this.tokenString = tokenString; - if (token.get("scope") != null) { - scopes = Sets.newHashSet(Splitter.on(" ").split(token.get("scope").getAsString())); + if (introspectionResponse.get("scope") != null) { + scopes = Sets.newHashSet(Splitter.on(" ").split(introspectionResponse.get("scope").getAsString())); } - if (token.get("exp") != null) { - expireDate = new Date(token.get("exp").getAsLong() * 1000L); + if (introspectionResponse.get("exp") != null) { + expireDate = new Date(introspectionResponse.get("exp").getAsLong() * 1000L); } } @@ -97,4 +97,20 @@ public class OAuth2AccessTokenImpl implements OAuth2AccessToken { return tokenString; } + + /** + * @return the token + */ + public JsonObject getIntrospectionResponse() { + return introspectionResponse; + } + + + /** + * @param token the token to set + */ + public void setIntrospectionResponse(JsonObject token) { + this.introspectionResponse = token; + } + } diff --git a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/OIDCAuthenticationFilter.java b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/OIDCAuthenticationFilter.java index 1164a949f..806c85742 100644 --- a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/OIDCAuthenticationFilter.java +++ b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/OIDCAuthenticationFilter.java @@ -311,16 +311,16 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi } // Handle Token Endpoint interaction - + HttpClient httpClient = HttpClientBuilder.create() .useSystemProperties() .setDefaultRequestConfig( RequestConfig.custom() - .setSocketTimeout(httpSocketTimeout) - .build() + .setSocketTimeout(httpSocketTimeout) + .build() ) - .build(); - + .build(); + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate; @@ -363,7 +363,7 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi // needs to be wired in to the bean signer = authenticationSignerService; - + if (alg == null) { alg = authenticationSignerService.getDefaultSigningAlgorithm(); } @@ -475,39 +475,39 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi JwtSigningAndValidationService jwtValidator = null; Algorithm tokenAlg = idToken.getHeader().getAlgorithm(); - + Algorithm clientAlg = clientConfig.getIdTokenSignedResponseAlg(); - + if (clientAlg != null) { if (!clientAlg.equals(tokenAlg)) { throw new AuthenticationServiceException("Token algorithm " + tokenAlg + " does not match expected algorithm " + clientAlg); } } - + if (idToken instanceof PlainJWT) { - + if (clientAlg == null) { throw new AuthenticationServiceException("Unsigned ID tokens can only be used if explicitly configured in client."); } - - if (tokenAlg != null && !tokenAlg.equals(JWSAlgorithm.NONE)) { + + if (tokenAlg != null && !tokenAlg.equals(Algorithm.NONE)) { throw new AuthenticationServiceException("Unsigned token received, expected signature with " + tokenAlg); } } else if (idToken instanceof SignedJWT) { - + SignedJWT signedIdToken = (SignedJWT)idToken; - + if (tokenAlg.equals(JWSAlgorithm.HS256) - || tokenAlg.equals(JWSAlgorithm.HS384) - || tokenAlg.equals(JWSAlgorithm.HS512)) { - + || tokenAlg.equals(JWSAlgorithm.HS384) + || tokenAlg.equals(JWSAlgorithm.HS512)) { + // generate one based on client secret jwtValidator = symmetricCacheService.getSymmetricValidtor(clientConfig.getClient()); } else { // otherwise load from the server's public key jwtValidator = validationServices.getValidator(serverConfig.getJwksUri()); } - + if (jwtValidator != null) { if(!jwtValidator.validateSignature(signedIdToken)) { throw new AuthenticationServiceException("Signature validation failed"); @@ -564,20 +564,20 @@ public class OIDCAuthenticationFilter extends AbstractAuthenticationProcessingFi // compare the nonce to our stored claim String nonce = idClaims.getStringClaim("nonce"); - + if (serverConfig.isNonceEnabled()) { if (Strings.isNullOrEmpty(nonce)) { - + logger.error("ID token did not contain a nonce claim."); - + throw new AuthenticationServiceException("ID token did not contain a nonce claim."); } - + String storedNonce = getStoredNonce(session); if (!nonce.equals(storedNonce)) { logger.error("Possible replay attack detected! The comparison of the nonce in the returned " + "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + "."); - + throw new AuthenticationServiceException( "Possible replay attack detected! The comparison of the nonce in the returned " + "ID Token to the session " + NONCE_SESSION_VARIABLE + " failed. Expected " + storedNonce + " got " + nonce + "."); diff --git a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/UserInfoFetcher.java b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/UserInfoFetcher.java index 6992e1993..4d33d1eda 100644 --- a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/UserInfoFetcher.java +++ b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/UserInfoFetcher.java @@ -64,19 +64,19 @@ public class UserInfoFetcher { } try { - + // if we got this far, try to actually get the userinfo HttpClient httpClient = HttpClientBuilder.create() .useSystemProperties() .build(); - + HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); - + String userInfoString = null; - + if (serverConfiguration.getUserInfoTokenMethod() == null || serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.HEADER)) { RestTemplate restTemplate = new RestTemplate(factory) { - + @Override protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException { ClientHttpRequest httpRequest = super.createRequest(url, method); @@ -84,19 +84,19 @@ public class UserInfoFetcher { return httpRequest; } }; - + userInfoString = restTemplate.getForObject(serverConfiguration.getUserInfoUri(), String.class); - + } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.FORM)) { MultiValueMap form = new LinkedMultiValueMap(); form.add("access_token", token.getAccessTokenValue()); - + RestTemplate restTemplate = new RestTemplate(factory); userInfoString = restTemplate.postForObject(serverConfiguration.getUserInfoUri(), form, String.class); } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.QUERY)) { URIBuilder builder = new URIBuilder(serverConfiguration.getUserInfoUri()); builder.setParameter("access_token", token.getAccessTokenValue()); - + RestTemplate restTemplate = new RestTemplate(factory); userInfoString = restTemplate.getForObject(builder.toString(), String.class); } @@ -105,7 +105,7 @@ public class UserInfoFetcher { if (!Strings.isNullOrEmpty(userInfoString)) { JsonObject userInfoJson = new JsonParser().parse(userInfoString).getAsJsonObject(); - + UserInfo userInfo = DefaultUserInfo.fromJson(userInfoJson); return userInfo; diff --git a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/service/impl/DynamicRegistrationClientConfigurationService.java b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/service/impl/DynamicRegistrationClientConfigurationService.java index 575704944..360ff7290 100644 --- a/openid-connect-client/src/main/java/org/mitre/openid/connect/client/service/impl/DynamicRegistrationClientConfigurationService.java +++ b/openid-connect-client/src/main/java/org/mitre/openid/connect/client/service/impl/DynamicRegistrationClientConfigurationService.java @@ -203,19 +203,19 @@ public class DynamicRegistrationClientConfigurationService implements ClientConf } else { if (knownClient.getClientId() == null) { - + // load this client's information from the server HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, knownClient.getRegistrationAccessToken())); headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON)); - + HttpEntity entity = new HttpEntity(headers); - + String registered = restTemplate.exchange(knownClient.getRegistrationClientUri(), HttpMethod.GET, entity, String.class).getBody(); // TODO: handle HTTP errors - + RegisteredClient client = ClientDetailsEntityJsonProcessor.parseRegistered(registered); - + return client; } else { // it's got a client ID from the store, don't bother trying to load it diff --git a/openid-connect-client/src/test/java/org/mitre/oauth2/introspectingfilter/TestOAuth2AccessTokenImpl.java b/openid-connect-client/src/test/java/org/mitre/oauth2/introspectingfilter/TestOAuth2AccessTokenImpl.java index 55086fade..df3f00c65 100644 --- a/openid-connect-client/src/test/java/org/mitre/oauth2/introspectingfilter/TestOAuth2AccessTokenImpl.java +++ b/openid-connect-client/src/test/java/org/mitre/oauth2/introspectingfilter/TestOAuth2AccessTokenImpl.java @@ -32,73 +32,73 @@ import com.google.gson.JsonObject; public class TestOAuth2AccessTokenImpl { private static String tokenString = "thisisatokenstring"; - + private static Set scopes = ImmutableSet.of("bar", "foo"); private static String scopeString = "foo bar"; - + private static Date exp = new Date(123 * 1000L); private static Long expVal = 123L; - + @Test public void testFullToken() { - - + + JsonObject tokenObj = new JsonObject(); tokenObj.addProperty("active", true); tokenObj.addProperty("scope", scopeString); tokenObj.addProperty("exp", expVal); tokenObj.addProperty("sub", "subject"); tokenObj.addProperty("client_id", "123-456-789"); - + OAuth2AccessTokenImpl tok = new OAuth2AccessTokenImpl(tokenObj, tokenString); - + assertThat(tok.getScope(), is(equalTo(scopes))); assertThat(tok.getExpiration(), is(equalTo(exp))); } @Test public void testNullExp() { - - + + JsonObject tokenObj = new JsonObject(); tokenObj.addProperty("active", true); tokenObj.addProperty("scope", scopeString); tokenObj.addProperty("sub", "subject"); tokenObj.addProperty("client_id", "123-456-789"); - + OAuth2AccessTokenImpl tok = new OAuth2AccessTokenImpl(tokenObj, tokenString); - + assertThat(tok.getScope(), is(equalTo(scopes))); assertThat(tok.getExpiration(), is(equalTo(null))); } @Test public void testNullScopes() { - - + + JsonObject tokenObj = new JsonObject(); tokenObj.addProperty("active", true); tokenObj.addProperty("exp", expVal); tokenObj.addProperty("sub", "subject"); tokenObj.addProperty("client_id", "123-456-789"); - + OAuth2AccessTokenImpl tok = new OAuth2AccessTokenImpl(tokenObj, tokenString); - + assertThat(tok.getScope(), is(equalTo(Collections.EMPTY_SET))); assertThat(tok.getExpiration(), is(equalTo(exp))); } @Test public void testNullScopesNullExp() { - - + + JsonObject tokenObj = new JsonObject(); tokenObj.addProperty("active", true); tokenObj.addProperty("sub", "subject"); tokenObj.addProperty("client_id", "123-456-789"); - + OAuth2AccessTokenImpl tok = new OAuth2AccessTokenImpl(tokenObj, tokenString); - + assertThat(tok.getScope(), is(equalTo(Collections.EMPTY_SET))); assertThat(tok.getExpiration(), is(equalTo(null))); } diff --git a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestPlainAuthRequestUrlBuilder.java b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestPlainAuthRequestUrlBuilder.java index 66e4871b3..2e9664594 100644 --- a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestPlainAuthRequestUrlBuilder.java +++ b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestPlainAuthRequestUrlBuilder.java @@ -82,11 +82,11 @@ public class TestPlainAuthRequestUrlBuilder { urlBuilder.buildAuthRequestUrl(serverConfig, clientConfig, "example.com", "", "", options); } - + @Test public void buildAuthRequestUrl_withNoNonce() { Mockito.when(serverConfig.isNonceEnabled()).thenReturn(false); - + String expectedUrl = "https://server.example.com/authorize?" + "response_type=code" + "&client_id=s6BhdRkqt3" + @@ -100,7 +100,7 @@ public class TestPlainAuthRequestUrlBuilder { String actualUrl = urlBuilder.buildAuthRequestUrl(serverConfig, clientConfig, "https://client.example.org/", null, "af0ifjsldkj", options); assertThat(actualUrl, equalTo(expectedUrl)); - + } } diff --git a/openid-connect-common/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java b/openid-connect-common/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java index 7e6617f11..5a40f5781 100644 --- a/openid-connect-common/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java +++ b/openid-connect-common/src/main/java/org/mitre/jwt/signer/service/impl/DefaultJwtSigningAndValidationService.java @@ -115,7 +115,7 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid */ @Override public String getDefaultSignerKeyId() { - return defaultSignerKeyId; + return defaultSignerKeyId; } /** @@ -188,7 +188,7 @@ public class DefaultJwtSigningAndValidationService implements JwtSigningAndValid logger.warn("Unknown key type: " + jwk); } } - + if (defaultSignerKeyId == null && keys.size() == 1) { // if there's only one key, it's the default setDefaultSignerKeyId(keys.keySet().iterator().next()); diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/model/AuthenticationHolderEntity.java b/openid-connect-common/src/main/java/org/mitre/oauth2/model/AuthenticationHolderEntity.java index a46b91dea..4a76339e0 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/model/AuthenticationHolderEntity.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/model/AuthenticationHolderEntity.java @@ -33,7 +33,7 @@ import org.springframework.security.oauth2.provider.OAuth2Authentication; @Entity @Table(name = "authentication_holder") @NamedQueries ({ - @NamedQuery(name = "AuthenticationHolderEntity.getAll", query = "select a from AuthenticationHolderEntity a"), + @NamedQuery(name = "AuthenticationHolderEntity.getAll", query = "select a from AuthenticationHolderEntity a"), @NamedQuery(name = "AuthenticationHolderEntity.getByAuthentication", query = "select a from AuthenticationHolderEntity a where a.authentication = :authentication"), @NamedQuery(name = "AuthenticationHolderEntity.getUnusedAuthenticationHolders", query = "select a from AuthenticationHolderEntity a where a.id not in (select t.authenticationHolder.id from OAuth2AccessTokenEntity t) and a.id not in (select r.authenticationHolder.id from OAuth2RefreshTokenEntity r)") }) diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientDetailsEntity.java b/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientDetailsEntity.java index 8fb51580b..329e0b800 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientDetailsEntity.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientDetailsEntity.java @@ -353,8 +353,8 @@ public class ClientDetailsEntity implements ClientDetails { public boolean isSecretRequired() { if (getTokenEndpointAuthMethod() != null && (getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) || - getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) || - getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) { + getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) || + getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) { return true; } else { return false; diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/repository/AuthenticationHolderRepository.java b/openid-connect-common/src/main/java/org/mitre/oauth2/repository/AuthenticationHolderRepository.java index 0efadf244..73848837d 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/repository/AuthenticationHolderRepository.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/repository/AuthenticationHolderRepository.java @@ -22,7 +22,7 @@ import org.mitre.oauth2.model.AuthenticationHolderEntity; import org.springframework.security.oauth2.provider.OAuth2Authentication; public interface AuthenticationHolderRepository { - public List getAll(); + public List getAll(); public AuthenticationHolderEntity getById(Long id); diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/service/IntrospectionResultAssembler.java b/openid-connect-common/src/main/java/org/mitre/oauth2/service/IntrospectionResultAssembler.java index 7a027b886..0415c537c 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/service/IntrospectionResultAssembler.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/service/IntrospectionResultAssembler.java @@ -16,33 +16,33 @@ *******************************************************************************/ package org.mitre.oauth2.service; +import java.util.Map; + import org.mitre.oauth2.model.OAuth2AccessTokenEntity; import org.mitre.oauth2.model.OAuth2RefreshTokenEntity; import org.mitre.openid.connect.model.UserInfo; -import java.util.Map; - /** * Strategy interface for assembling a token introspection result. */ public interface IntrospectionResultAssembler { - /** - * Assemble a token introspection result from the given access token and user info. - * - * @param accessToken the access token - * @param userInfo the user info - * @return the token introspection result - */ - Map assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo); + /** + * Assemble a token introspection result from the given access token and user info. + * + * @param accessToken the access token + * @param userInfo the user info + * @return the token introspection result + */ + Map assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo); - /** - * Assemble a token introspection result from the given refresh token and user info. - * - * @param refreshToken the refresh token - * @param userInfo the user info - * @return the token introspection result - */ - Map assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo); + /** + * Assemble a token introspection result from the given refresh token and user info. + * + * @param refreshToken the refresh token + * @param userInfo the user info + * @return the token introspection result + */ + Map assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo); } diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/service/OAuth2TokenEntityService.java b/openid-connect-common/src/main/java/org/mitre/oauth2/service/OAuth2TokenEntityService.java index 295d22202..ed7f3a105 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/service/OAuth2TokenEntityService.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/service/OAuth2TokenEntityService.java @@ -63,6 +63,6 @@ public interface OAuth2TokenEntityService extends AuthorizationServerTokenServic public Set getAllAccessTokensForUser(String name); public Set getAllRefreshTokensForUser(String name); - + public OAuth2AccessTokenEntity getRegistrationAccessTokenForClient(ClientDetailsEntity client); } diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/service/impl/DefaultClientUserDetailsService.java b/openid-connect-common/src/main/java/org/mitre/oauth2/service/impl/DefaultClientUserDetailsService.java index b8694a412..808a6d3bb 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/service/impl/DefaultClientUserDetailsService.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/service/impl/DefaultClientUserDetailsService.java @@ -45,7 +45,7 @@ import com.google.common.base.Strings; public class DefaultClientUserDetailsService implements UserDetailsService { private static GrantedAuthority ROLE_CLIENT = new SimpleGrantedAuthority("ROLE_CLIENT"); - + @Autowired private ClientDetailsEntityService clientDetailsService; @@ -57,17 +57,17 @@ public class DefaultClientUserDetailsService implements UserDetailsService { if (client != null) { String password = Strings.nullToEmpty(client.getClientSecret()); - - if (client.getTokenEndpointAuthMethod() != null && + + if (client.getTokenEndpointAuthMethod() != null && (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT))) { - - // Issue a random password each time to prevent password auth from being used (or skipped) + + // Issue a random password each time to prevent password auth from being used (or skipped) // for private key or shared key clients, see #715 - + password = new BigInteger(512, new SecureRandom()).toString(16); } - + boolean enabled = true; boolean accountNonExpired = true; boolean credentialsNonExpired = true; diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/ClientDetailsEntityJsonProcessor.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/ClientDetailsEntityJsonProcessor.java index 1d5e6a93d..a488cb941 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/ClientDetailsEntityJsonProcessor.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/ClientDetailsEntityJsonProcessor.java @@ -60,7 +60,7 @@ public class ClientDetailsEntityJsonProcessor { JsonElement jsonEl = parser.parse(jsonString); return parse(jsonEl); } - + public static ClientDetailsEntity parse(JsonElement jsonEl) { if (jsonEl.isJsonObject()) { @@ -155,7 +155,7 @@ public class ClientDetailsEntityJsonProcessor { JsonElement jsonEl = parser.parse(jsonString); return parseRegistered(jsonEl); } - + public static RegisteredClient parseRegistered(JsonElement jsonEl) { if (jsonEl.isJsonObject()) { diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationBeanLocaleResolver.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationBeanLocaleResolver.java index 7ce8390e8..316a37849 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationBeanLocaleResolver.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationBeanLocaleResolver.java @@ -40,7 +40,7 @@ import org.springframework.web.servlet.i18n.AbstractLocaleContextResolver; */ @Component("localeResolver") public class ConfigurationBeanLocaleResolver extends AbstractLocaleContextResolver { - + @Autowired private ConfigurationPropertiesBean config; diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationPropertiesBean.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationPropertiesBean.java index 3963c2aa5..f225c9465 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationPropertiesBean.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ConfigurationPropertiesBean.java @@ -44,11 +44,11 @@ public class ConfigurationPropertiesBean { private String topbarTitle; private String logoImageUrl; - + private Long regTokenLifeTime; - + private boolean forceHttps = false; - + private Locale locale = Locale.getDefault(); public ConfigurationPropertiesBean() { @@ -57,7 +57,7 @@ public class ConfigurationPropertiesBean { /** * Endpoints protected by TLS must have https scheme in the URI. - * @throws HttpsUrlRequiredException + * @throws HttpsUrlRequiredException */ @PostConstruct public void checkForHttps() { @@ -127,7 +127,7 @@ public class ConfigurationPropertiesBean { public void setRegTokenLifeTime(Long regTokenLifeTime) { this.regTokenLifeTime = regTokenLifeTime; } - + public boolean isForceHttps() { return forceHttps; } diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ServerConfiguration.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ServerConfiguration.java index 40b8d9ad7..75bd8ff25 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ServerConfiguration.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/config/ServerConfiguration.java @@ -205,23 +205,23 @@ public class ServerConfiguration { private Boolean requireRequestUriRegistration; private String opPolicyUri; private String opTosUri; - + // // extensions to the discoverable methods // - + // how do we send the access token to the userinfo endpoint? - private UserInfoTokenMethod userInfoTokenMethod; - + private UserInfoTokenMethod userInfoTokenMethod; + public enum UserInfoTokenMethod { HEADER, FORM, QUERY; } - + // do we create and send a nonce value? private boolean nonceEnabled = true; - + /** * @return the authorizationEndpointUri */ @@ -666,7 +666,7 @@ public class ServerConfiguration { public void setOpTosUri(String opTosUri) { this.opTosUri = opTosUri; } - + public String getRevocationEndpointUri() { return revocationEndpointUri; } @@ -681,7 +681,7 @@ public class ServerConfiguration { this.userInfoTokenMethod = userInfoTokenMethod; } - + /** * @return the nonceEnabled */ diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java index d29570881..1c9505903 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/model/DefaultUserInfo.java @@ -37,6 +37,10 @@ import com.google.gson.JsonObject; }) public class DefaultUserInfo implements UserInfo { + /** + * + */ + private static final long serialVersionUID = 6078310513185681918L; private Long id; private String sub; private String preferredUsername; diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/service/MITREidDataService.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/service/MITREidDataService.java index 5ae0306ff..706795012 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/service/MITREidDataService.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/service/MITREidDataService.java @@ -31,32 +31,32 @@ public interface MITREidDataService { * Data member for 1.X configurations */ public static final String MITREID_CONNECT_1_0 = "mitreid-connect-1.0"; - public static final String MITREID_CONNECT_1_1 = "mitreid-connect-1.1"; - public static final String MITREID_CONNECT_1_2 = "mitreid-connect-1.2"; + public static final String MITREID_CONNECT_1_1 = "mitreid-connect-1.1"; + public static final String MITREID_CONNECT_1_2 = "mitreid-connect-1.2"; - // member names - public static final String REFRESHTOKENS = "refreshTokens"; - public static final String ACCESSTOKENS = "accessTokens"; - public static final String WHITELISTEDSITES = "whitelistedSites"; - public static final String BLACKLISTEDSITES = "blacklistedSites"; - public static final String AUTHENTICATIONHOLDERS = "authenticationHolders"; - public static final String GRANTS = "grants"; - public static final String CLIENTS = "clients"; - public static final String SYSTEMSCOPES = "systemScopes"; + // member names + public static final String REFRESHTOKENS = "refreshTokens"; + public static final String ACCESSTOKENS = "accessTokens"; + public static final String WHITELISTEDSITES = "whitelistedSites"; + public static final String BLACKLISTEDSITES = "blacklistedSites"; + public static final String AUTHENTICATIONHOLDERS = "authenticationHolders"; + public static final String GRANTS = "grants"; + public static final String CLIENTS = "clients"; + public static final String SYSTEMSCOPES = "systemScopes"; - /** + /** * Write out the current server state to the given JSON writer as a JSON object * * @param writer - * @throws IOException + * @throws IOException */ - void exportData(JsonWriter writer) throws IOException; + void exportData(JsonWriter writer) throws IOException; /** * Read in the current server state from the given JSON reader as a JSON object * * @param reader */ - void importData(JsonReader reader) throws IOException; + void importData(JsonReader reader) throws IOException; } \ No newline at end of file diff --git a/openid-connect-common/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java b/openid-connect-common/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java index b70ef4dca..eecb934b8 100644 --- a/openid-connect-common/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java +++ b/openid-connect-common/src/main/java/org/mitre/openid/connect/web/UserInfoInterceptor.java @@ -87,11 +87,11 @@ public class UserInfoInterceptor extends HandlerInterceptorAdapter { modelAndView.addObject("userInfoJson", oidc.getUserInfo().toJson()); } else { modelAndView.addObject("userInfo", null); - modelAndView.addObject("userInfoJson", "null"); + modelAndView.addObject("userInfoJson", "null"); } } else { // don't bother checking if we don't have a principal or a userInfoService to work with - if (p != null && p.getName() != null && userInfoService != null) { + if (p != null && p.getName() != null && userInfoService != null) { // try to look up a user based on the principal's name UserInfo user = userInfoService.getByUsername(p.getName()); diff --git a/openid-connect-common/src/test/java/org/mitre/jose/JOSEEmbedTest.java b/openid-connect-common/src/test/java/org/mitre/jose/JOSEEmbedTest.java index 4b0ca15a6..c9a9e9183 100644 --- a/openid-connect-common/src/test/java/org/mitre/jose/JOSEEmbedTest.java +++ b/openid-connect-common/src/test/java/org/mitre/jose/JOSEEmbedTest.java @@ -43,10 +43,10 @@ public class JOSEEmbedTest { assertEquals(JWSAlgorithm.HS256, a.getAlgorithm()); assertEquals("HS256", a.getAlgorithmName()); - + a.setAlgorithm(JWSAlgorithm.HS384); assertEquals(JWSAlgorithm.HS384, a.getAlgorithm()); - + JWSAlgorithmEmbed null_a = new JWSAlgorithmEmbed(null); assertEquals(null, null_a.getAlgorithm()); assertEquals(null, null_a.getAlgorithmName()); @@ -58,8 +58,8 @@ public class JOSEEmbedTest { assertEquals(JWSAlgorithm.RS256, a.getAlgorithm()); assertEquals("RS256", a.getAlgorithmName()); - - JWSAlgorithmEmbed null_a = JWSAlgorithmEmbed.getForAlgorithmName(""); + + JWSAlgorithmEmbed null_a = JWSAlgorithmEmbed.getForAlgorithmName(""); assertEquals(null, null_a); } @@ -69,10 +69,10 @@ public class JOSEEmbedTest { assertEquals(JWEAlgorithm.A128KW, a.getAlgorithm()); assertEquals("A128KW", a.getAlgorithmName()); - + a.setAlgorithm(JWEAlgorithm.A256KW); assertEquals(JWEAlgorithm.A256KW, a.getAlgorithm()); - + JWEAlgorithmEmbed null_a = new JWEAlgorithmEmbed(null); assertEquals(null, null_a.getAlgorithm()); assertEquals(null, null_a.getAlgorithmName()); @@ -84,7 +84,7 @@ public class JOSEEmbedTest { assertEquals(JWEAlgorithm.RSA1_5, a.getAlgorithm()); assertEquals("RSA1_5", a.getAlgorithmName()); - + JWEAlgorithmEmbed null_a = JWEAlgorithmEmbed.getForAlgorithmName(""); assertEquals(null, null_a); } @@ -95,10 +95,10 @@ public class JOSEEmbedTest { assertEquals(EncryptionMethod.A128CBC_HS256, a.getAlgorithm()); assertEquals("A128CBC-HS256", a.getAlgorithmName()); - + a.setAlgorithm(EncryptionMethod.A256GCM); assertEquals(EncryptionMethod.A256GCM, a.getAlgorithm()); - + JWEEncryptionMethodEmbed null_a = new JWEEncryptionMethodEmbed(null); assertEquals(null, null_a.getAlgorithm()); assertEquals(null, null_a.getAlgorithmName()); @@ -110,7 +110,7 @@ public class JOSEEmbedTest { assertEquals(EncryptionMethod.A256GCM, a.getAlgorithm()); assertEquals("A256GCM", a.getAlgorithmName()); - + JWEEncryptionMethodEmbed null_a = JWEEncryptionMethodEmbed.getForAlgorithmName(""); assertEquals(null, null_a); } diff --git a/openid-connect-common/src/test/java/org/mitre/jose/TestJWKSetKeyStore.java b/openid-connect-common/src/test/java/org/mitre/jose/TestJWKSetKeyStore.java index 7bde9a6e6..13efb5c6b 100644 --- a/openid-connect-common/src/test/java/org/mitre/jose/TestJWKSetKeyStore.java +++ b/openid-connect-common/src/test/java/org/mitre/jose/TestJWKSetKeyStore.java @@ -45,65 +45,65 @@ import com.nimbusds.jose.util.Base64URL; * */ -public class TestJWKSetKeyStore { +public class TestJWKSetKeyStore { private String RSAkid = "rsa_1"; private JWK RSAjwk = new RSAKey( new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" + - "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + - "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + - "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + - "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + - "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n + "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + + "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + + "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + + "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + + "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n new Base64URL("AQAB"), // e new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" + - "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + - "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + - "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + - "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + - "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d - KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null); + "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + + "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + + "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + + "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + + "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d + KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null); private String RSAkid_rsa2 = "rsa_2"; private JWK RSAjwk_rsa2 = new RSAKey( new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" + - "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + - "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + - "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + - "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + - "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n + "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + + "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + + "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + + "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + + "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n new Base64URL("AQAB"), // e new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" + - "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + - "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + - "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + - "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + - "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d - KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_rsa2, null, null, null); - + "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + + "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + + "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + + "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + + "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d + KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_rsa2, null, null, null); + + + List keys_list = new LinkedList(); + private JWKSet jwkSet; + private String ks_file = "ks.txt"; + private String ks_file_badJWK = "ks_badJWK.txt"; - List keys_list = new LinkedList(); - private JWKSet jwkSet; - private String ks_file = "ks.txt"; - private String ks_file_badJWK = "ks_badJWK.txt"; - @Before public void prepare() throws IOException { - + keys_list.add(RSAjwk); keys_list.add(RSAjwk_rsa2); jwkSet = new JWKSet(keys_list); jwkSet.getKeys(); - - byte jwtbyte[] = jwkSet.toString().getBytes(); + + byte jwtbyte[] = jwkSet.toString().getBytes(); FileOutputStream out = new FileOutputStream(ks_file); out.write(jwtbyte); out.close(); } - - @After - public void cleanup() throws IOException { - + + @After + public void cleanup() throws IOException { + File f1 = new File(ks_file); if (f1.exists()) { f1.delete(); @@ -112,21 +112,21 @@ public class TestJWKSetKeyStore { if (f2.exists()) { f2.delete(); } - } - + } + /* Constructors with no valid Resource setup */ @Test public void ksConstructorTest() { JWKSetKeyStore ks = new JWKSetKeyStore(jwkSet); assertEquals(ks.getJwkSet(), jwkSet); - + JWKSetKeyStore ks_empty= new JWKSetKeyStore(); - assertEquals(ks_empty.getJwkSet(), null); - + assertEquals(ks_empty.getJwkSet(), null); + boolean thrown = false; try { - JWKSetKeyStore ks_null = new JWKSetKeyStore(null); + new JWKSetKeyStore(null); } catch (IllegalArgumentException e) { thrown = true; } @@ -136,74 +136,74 @@ public class TestJWKSetKeyStore { /* Misformatted JWK */ @Test(expected=IllegalArgumentException.class) public void ksBadJWKinput() throws IOException { - - byte jwtbyte[] = RSAjwk.toString().getBytes(); + + byte jwtbyte[] = RSAjwk.toString().getBytes(); FileOutputStream out = new FileOutputStream(ks_file_badJWK); out.write(jwtbyte); out.close(); - + JWKSetKeyStore ks_badJWK = new JWKSetKeyStore(); Resource loc = new FileSystemResource(ks_file_badJWK); assertTrue(loc.exists()); - + ks_badJWK.setLocation(loc); assertEquals(loc.getFilename(), ks_file_badJWK); - + ks_badJWK = new JWKSetKeyStore(null); } - + /* Empty constructor with valid Resource */ @Test public void ksEmptyConstructorkLoc() { JWKSetKeyStore ks = new JWKSetKeyStore(); - + File file = new File(ks_file); - + /* First, test with file without "read" permission */ - boolean set = false; + boolean set = false; - if (file.exists()) { - set = file.setReadable(false); - } - - // skip this part of the test on systems that don't allow the settable function, like Windows - if (set) { - - Resource loc_noread = new FileSystemResource(file); - assertTrue(loc_noread.exists()); - // assertTrue(!loc_noread.isReadable()); - - boolean thrown = false; - try { - ks.setLocation(loc_noread); - } catch (IllegalArgumentException e) { - thrown = true; - } - assertTrue(thrown); - - /* Now, make cache file readable */ - - if (file.exists()) { - file.setReadable(true); - } + if (file.exists()) { + set = file.setReadable(false); + } - } - - Resource loc = new FileSystemResource(file); + // skip this part of the test on systems that don't allow the settable function, like Windows + if (set) { + + Resource loc_noread = new FileSystemResource(file); + assertTrue(loc_noread.exists()); + // assertTrue(!loc_noread.isReadable()); + + boolean thrown = false; + try { + ks.setLocation(loc_noread); + } catch (IllegalArgumentException e) { + thrown = true; + } + assertTrue(thrown); + + /* Now, make cache file readable */ + + if (file.exists()) { + file.setReadable(true); + } + + } + + Resource loc = new FileSystemResource(file); assertTrue(loc.exists()); assertTrue(loc.isReadable()); ks.setLocation(loc); - - assertEquals(loc.getFilename(),ks.getLocation().getFilename()); + + assertEquals(loc.getFilename(),ks.getLocation().getFilename()); } - + @Test public void ksSetJwkSet() throws IllegalArgumentException { - + JWKSetKeyStore ks = new JWKSetKeyStore(); boolean thrown = false; try { diff --git a/openid-connect-common/src/test/java/org/mitre/jwt/encryption/service/impl/TestDefaultJwtEncryptionAndDecryptionService.java b/openid-connect-common/src/test/java/org/mitre/jwt/encryption/service/impl/TestDefaultJwtEncryptionAndDecryptionService.java index dcde79870..bdab59645 100644 --- a/openid-connect-common/src/test/java/org/mitre/jwt/encryption/service/impl/TestDefaultJwtEncryptionAndDecryptionService.java +++ b/openid-connect-common/src/test/java/org/mitre/jwt/encryption/service/impl/TestDefaultJwtEncryptionAndDecryptionService.java @@ -78,44 +78,45 @@ public class TestDefaultJwtEncryptionAndDecryptionService { "XFBoMYUZodetZdvTiFvSkQ"; private String RSAkid = "rsa321"; - private JWK RSAjwk = new RSAKey(new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" + - "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + - "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + - "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + - "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + - "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n + private JWK RSAjwk = new RSAKey( + new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" + + "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + + "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + + "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + + "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + + "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n new Base64URL("AQAB"), // e new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" + - "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + - "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + - "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + - "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + - "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d - KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null); + "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + + "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + + "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + + "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + + "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d + KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA_OAEP, RSAkid, null, null, null); private String RSAkid_2 = "rsa3210"; private JWK RSAjwk_2 = new RSAKey( new Base64URL("oahUIoWw0K0usKNuOR6H4wkf4oBUXHTxRvgb48E-BVvxkeDNjbC4he8rUW" + - "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + - "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + - "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + - "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + - "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n + "cJoZmds2h7M70imEVhRU5djINXtqllXI4DFqcI1DgjT9LewND8MW2Krf3S" + + "psk_ZkoFnilakGygTwpZ3uesH-PFABNIUYpOiN15dsQRkgr0vEhxN92i2a" + + "sbOenSZeyaxziK72UwxrrKoExv6kc5twXTq4h-QChLOln0_mtUZwfsRaMS" + + "tPs6mS6XrgxnxbWhojf663tuEQueGC-FCMfra36C9knDFGzKsNa7LZK2dj" + + "YgyD3JR_MB_4NUJW_TqOQtwHYbxevoJArm-L5StowjzGy-_bq6Gw"), // n new Base64URL("AQAB"), // e new Base64URL("kLdtIj6GbDks_ApCSTYQtelcNttlKiOyPzMrXHeI-yk1F7-kpDxY4-WY5N" + - "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + - "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + - "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + - "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + - "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d - KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_2, null, null, null); + "WV5KntaEeXS1j82E375xxhWMHXyvjYecPT9fpwR_M9gV8n9Hrh2anTpTD9" + + "3Dt62ypW3yDsJzBnTnrYu1iwWRgBKrEYY46qAZIrA2xAwnm2X7uGR1hghk" + + "qDp0Vqj3kbSCz1XyfCs6_LehBwtxHIyh8Ripy40p24moOAbgxVw3rxT_vl" + + "t3UVe4WO3JkJOzlpUf-KTVI2Ptgm-dARxTEtE-id-4OJr0h-K-VFs3VSnd" + + "VTIznSxfyrj8ILL6MG_Uv8YAu7VILSB3lOW085-4qE3DzgrTjgyQ"), // d + KeyUse.ENCRYPTION, null, JWEAlgorithm.RSA1_5, RSAkid_2, null, null, null); private String AESkid = "aes123"; private JWK AESjwk = new OctetSequenceKey( new Base64URL("GawgguFyGrWKav7AX4VKUg"), KeyUse.ENCRYPTION, null, JWEAlgorithm.A128KW, AESkid, null, null, null); - - + + private Map keys = new ImmutableMap.Builder() .put(RSAkid, RSAjwk) .build(); @@ -131,7 +132,7 @@ public class TestDefaultJwtEncryptionAndDecryptionService { .put(RSAkid_2, RSAjwk_2) .put(AESkid, AESjwk) .build(); - + private List keys_list = new LinkedList(); @@ -139,8 +140,8 @@ public class TestDefaultJwtEncryptionAndDecryptionService { private DefaultJwtEncryptionAndDecryptionService service_2; private DefaultJwtEncryptionAndDecryptionService service_3; private DefaultJwtEncryptionAndDecryptionService service_4; - private DefaultJwtEncryptionAndDecryptionService service_ks; - + private DefaultJwtEncryptionAndDecryptionService service_ks; + @Before public void prepare() throws NoSuchAlgorithmException, InvalidKeySpecException, JOSEException { @@ -152,21 +153,21 @@ public class TestDefaultJwtEncryptionAndDecryptionService { claimsSet.setIssuer(issuer); claimsSet.setSubject(subject); - + // Key Store - + keys_list.add(RSAjwk); keys_list.add(AESjwk); JWKSet jwkSet = new JWKSet(keys_list); JWKSetKeyStore keyStore = new JWKSetKeyStore(jwkSet); - + service_ks = new DefaultJwtEncryptionAndDecryptionService(keyStore); } @Test public void decrypt_RSA() throws ParseException { - + service.setDefaultDecryptionKeyId(RSAkid); service.setDefaultEncryptionKeyId(RSAkid); @@ -210,7 +211,7 @@ public class TestDefaultJwtEncryptionAndDecryptionService { // The same as encryptThenDecrypt_RSA() but relies on the key from the map @Test - public void encryptThenDecrypt_nullID() throws ParseException { + public void encryptThenDecrypt_nullID() throws ParseException { service.setDefaultDecryptionKeyId(null); service.setDefaultEncryptionKeyId(null); @@ -250,7 +251,7 @@ public class TestDefaultJwtEncryptionAndDecryptionService { assertEquals(null, service_2.getDefaultEncryptionKeyId()); } - + @Test(expected=IllegalStateException.class) public void decrypt_nullID() throws ParseException { @@ -286,25 +287,25 @@ public class TestDefaultJwtEncryptionAndDecryptionService { @Test - public void getAllPubKeys() throws ParseException { + public void getAllPubKeys() throws ParseException { Map keys2check = service_2.getAllPublicKeys(); assertEquals( - JSONObjectUtils.getString(RSAjwk.toPublicJWK().toJSONObject(), "e"), - JSONObjectUtils.getString(keys2check.get(RSAkid).toJSONObject(), "e") - ); + JSONObjectUtils.getString(RSAjwk.toPublicJWK().toJSONObject(), "e"), + JSONObjectUtils.getString(keys2check.get(RSAkid).toJSONObject(), "e") + ); assertEquals( - JSONObjectUtils.getString(RSAjwk_2.toPublicJWK().toJSONObject(), "e"), - JSONObjectUtils.getString(keys2check.get(RSAkid_2).toJSONObject(), "e") - ); + JSONObjectUtils.getString(RSAjwk_2.toPublicJWK().toJSONObject(), "e"), + JSONObjectUtils.getString(keys2check.get(RSAkid_2).toJSONObject(), "e") + ); assertTrue(service_3.getAllPublicKeys().isEmpty()); } - - + + @Test - public void getAllCryptoAlgsSupported() throws ParseException { - + public void getAllCryptoAlgsSupported() throws ParseException { + assertTrue(service_4.getAllEncryptionAlgsSupported().contains(JWEAlgorithm.RSA_OAEP)); assertTrue(service_4.getAllEncryptionAlgsSupported().contains(JWEAlgorithm.RSA1_5)); assertTrue(service_4.getAllEncryptionAlgsSupported().contains(JWEAlgorithm.DIR)); @@ -323,24 +324,24 @@ public class TestDefaultJwtEncryptionAndDecryptionService { assertTrue(service_ks.getAllEncryptionEncsSupported().contains(EncryptionMethod.A192CBC_HS384)); assertTrue(service_ks.getAllEncryptionEncsSupported().contains(EncryptionMethod.A192GCM)); assertTrue(service_ks.getAllEncryptionEncsSupported().contains(EncryptionMethod.A256GCM)); - assertTrue(service_ks.getAllEncryptionEncsSupported().contains(EncryptionMethod.A256CBC_HS512)); + assertTrue(service_ks.getAllEncryptionEncsSupported().contains(EncryptionMethod.A256CBC_HS512)); } - - + + @Test public void getDefaultCryptoKeyId() throws ParseException { - + // Test set/getDefaultEn/DecryptionKeyId assertEquals(null, service_4.getDefaultEncryptionKeyId()); - assertEquals(null, service_4.getDefaultDecryptionKeyId()); + assertEquals(null, service_4.getDefaultDecryptionKeyId()); service_4.setDefaultEncryptionKeyId(RSAkid); service_4.setDefaultDecryptionKeyId(AESkid); assertEquals(RSAkid, service_4.getDefaultEncryptionKeyId()); assertEquals(AESkid, service_4.getDefaultDecryptionKeyId()); - + assertEquals(null, service_ks.getDefaultEncryptionKeyId()); - assertEquals(null, service_ks.getDefaultDecryptionKeyId()); + assertEquals(null, service_ks.getDefaultDecryptionKeyId()); service_ks.setDefaultEncryptionKeyId(RSAkid); service_ks.setDefaultDecryptionKeyId(AESkid); assertEquals( RSAkid, service_ks.getDefaultEncryptionKeyId()) ; diff --git a/openid-connect-common/src/test/java/org/mitre/openid/connect/config/ConfigurationPropertiesBeanTest.java b/openid-connect-common/src/test/java/org/mitre/openid/connect/config/ConfigurationPropertiesBeanTest.java index 2a54eec8d..d5cf815ff 100644 --- a/openid-connect-common/src/test/java/org/mitre/openid/connect/config/ConfigurationPropertiesBeanTest.java +++ b/openid-connect-common/src/test/java/org/mitre/openid/connect/config/ConfigurationPropertiesBeanTest.java @@ -30,7 +30,7 @@ import org.springframework.beans.factory.BeanCreationException; * */ public class ConfigurationPropertiesBeanTest { - + /** * Test getters and setters for configuration object. */ @@ -58,12 +58,12 @@ public class ConfigurationPropertiesBeanTest { @Test public void testCheckForHttpsIssuerHttpDefaultFlag() { ConfigurationPropertiesBean bean = new ConfigurationPropertiesBean(); - + // issuer is http // leave as default, which is unset/false try { bean.setIssuer("http://localhost:8080/openid-connect-server/"); - bean.checkForHttps(); + bean.checkForHttps(); } catch (BeanCreationException e) { fail("Unexpected BeanCreationException for http issuer with default forceHttps, message:" + e.getMessage()); } @@ -86,7 +86,7 @@ public class ConfigurationPropertiesBeanTest { @Test(expected = BeanCreationException.class) public void testCheckForHttpsIssuerHttpTrueFlag() { ConfigurationPropertiesBean bean = new ConfigurationPropertiesBean(); - // issuer is http + // issuer is http // set to true bean.setIssuer("http://localhost:8080/openid-connect-server/"); bean.setForceHttps(true); @@ -100,12 +100,12 @@ public class ConfigurationPropertiesBeanTest { // leave as default, which is unset/false try { bean.setIssuer("https://localhost:8080/openid-connect-server/"); - bean.checkForHttps(); + bean.checkForHttps(); } catch (BeanCreationException e) { fail("Unexpected BeanCreationException for https issuer with default forceHttps, message:" + e.getMessage()); } } - + @Test public void testCheckForHttpsIssuerHttpsFalseFlag() { ConfigurationPropertiesBean bean = new ConfigurationPropertiesBean(); @@ -119,11 +119,11 @@ public class ConfigurationPropertiesBeanTest { fail("Unexpected BeanCreationException for https issuer with forceHttps=false, message:" + e.getMessage()); } } - + @Test public void testCheckForHttpsIssuerHttpsTrueFlag() { ConfigurationPropertiesBean bean = new ConfigurationPropertiesBean(); - // issuer is https + // issuer is https // set to true try { bean.setIssuer("https://localhost:8080/openid-connect-server/"); @@ -132,7 +132,7 @@ public class ConfigurationPropertiesBeanTest { } catch (BeanCreationException e) { fail("Unexpected BeanCreationException for https issuer with forceHttps=true, message:" + e.getMessage()); } - + } } 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 7ee597339..fbbf492fb 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 @@ -263,7 +263,7 @@ public class DiscoveryEndpoint { Collection serverSigningAlgs = signService.getAllSigningAlgsSupported(); Collection clientSymmetricSigningAlgs = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512); Collection clientSymmetricAndAsymmetricSigningAlgs = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512, JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512); - Collection clientSymmetricAndAsymmetricSigningAlgsWithNone = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512, JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512, JWSAlgorithm.NONE); + Collection clientSymmetricAndAsymmetricSigningAlgsWithNone = Lists.newArrayList(JWSAlgorithm.HS256, JWSAlgorithm.HS384, JWSAlgorithm.HS512, JWSAlgorithm.RS256, JWSAlgorithm.RS384, JWSAlgorithm.RS512, Algorithm.NONE); Map m = new HashMap(); m.put("issuer", config.getIssuer()); diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaAuthenticationHolderRepository.java b/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaAuthenticationHolderRepository.java index 7eb841642..ba7acdcf7 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaAuthenticationHolderRepository.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaAuthenticationHolderRepository.java @@ -37,13 +37,13 @@ public class JpaAuthenticationHolderRepository implements AuthenticationHolderRe @PersistenceContext private EntityManager manager; - - @Override - public List getAll() { + + @Override + public List getAll() { TypedQuery query = manager.createNamedQuery("AuthenticationHolderEntity.getAll", AuthenticationHolderEntity.class); return query.getResultList(); - } - + } + @Override public AuthenticationHolderEntity getById(Long id) { return manager.find(AuthenticationHolderEntity.class, id); 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 d5993165d..3a276c37d 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 @@ -36,7 +36,7 @@ public class BlacklistAwareRedirectResolver extends DefaultRedirectResolver { @Autowired private BlacklistedSiteService blacklistService; - + /* (non-Javadoc) * @see org.springframework.security.oauth2.provider.endpoint.RedirectResolver#resolveRedirect(java.lang.String, org.springframework.security.oauth2.provider.ClientDetails) */ diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultIntrospectionResultAssembler.java b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultIntrospectionResultAssembler.java index e7bb6f702..a24518cf2 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultIntrospectionResultAssembler.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultIntrospectionResultAssembler.java @@ -42,77 +42,77 @@ import com.google.common.base.Joiner; public class DefaultIntrospectionResultAssembler implements IntrospectionResultAssembler { private static Logger log = LoggerFactory.getLogger(DefaultIntrospectionResultAssembler.class); - + private static DateFormatter dateFormat = new DateFormatter(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")); - - @Override - public Map assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo) { - Map result = newLinkedHashMap(); - OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication(); + @Override + public Map assembleFrom(OAuth2AccessTokenEntity accessToken, UserInfo userInfo) { - result.put("active", true); + Map result = newLinkedHashMap(); + OAuth2Authentication authentication = accessToken.getAuthenticationHolder().getAuthentication(); - result.put("scope", Joiner.on(" ").join(accessToken.getScope())); + result.put("active", true); - if (accessToken.getExpiration() != null) { - try { + result.put("scope", Joiner.on(" ").join(accessToken.getScope())); + + if (accessToken.getExpiration() != null) { + try { result.put("expires_at", dateFormat.valueToString(accessToken.getExpiration())); result.put("exp", accessToken.getExpiration().getTime() / 1000L); } catch (ParseException e) { log.error("Parse exception in token introspection", e); } - } + } - if (userInfo != null) { - // if we have a UserInfo, use that for the subject - result.put("sub", userInfo.getSub()); - } else { - // otherwise, use the authentication's username - result.put("sub", authentication.getName()); - } + if (userInfo != null) { + // if we have a UserInfo, use that for the subject + result.put("sub", userInfo.getSub()); + } else { + // otherwise, use the authentication's username + result.put("sub", authentication.getName()); + } - result.put("user_id", authentication.getName()); + result.put("user_id", authentication.getName()); - result.put("client_id", authentication.getOAuth2Request().getClientId()); + result.put("client_id", authentication.getOAuth2Request().getClientId()); - result.put("token_type", accessToken.getTokenType()); + result.put("token_type", accessToken.getTokenType()); - return result; - } + return result; + } - @Override - public Map assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo) { + @Override + public Map assembleFrom(OAuth2RefreshTokenEntity refreshToken, UserInfo userInfo) { - Map result = newLinkedHashMap(); - OAuth2Authentication authentication = refreshToken.getAuthenticationHolder().getAuthentication(); + Map result = newLinkedHashMap(); + OAuth2Authentication authentication = refreshToken.getAuthenticationHolder().getAuthentication(); - result.put("active", true); + result.put("active", true); - result.put("scope", Joiner.on(" ").join(authentication.getOAuth2Request().getScope())); + result.put("scope", Joiner.on(" ").join(authentication.getOAuth2Request().getScope())); - if (refreshToken.getExpiration() != null) { - try { + if (refreshToken.getExpiration() != null) { + try { result.put("expires_at", dateFormat.valueToString(refreshToken.getExpiration())); result.put("exp", refreshToken.getExpiration().getTime() / 1000L); } catch (ParseException e) { log.error("Parse exception in token introspection", e); } - } + } - if (userInfo != null) { - // if we have a UserInfo, use that for the subject - result.put("sub", userInfo.getSub()); - } else { - // otherwise, use the authentication's username - result.put("sub", authentication.getName()); - } + if (userInfo != null) { + // if we have a UserInfo, use that for the subject + result.put("sub", userInfo.getSub()); + } else { + // otherwise, use the authentication's username + result.put("sub", authentication.getName()); + } - result.put("user_id", authentication.getName()); + result.put("user_id", authentication.getName()); - result.put("client_id", authentication.getOAuth2Request().getClientId()); + result.put("client_id", authentication.getOAuth2Request().getClientId()); - return result; - } + return result; + } } diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ClientDetailsEntityService.java b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ClientDetailsEntityService.java index 5df2e5b18..cb208ba45 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ClientDetailsEntityService.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ClientDetailsEntityService.java @@ -52,7 +52,6 @@ import com.google.common.base.Strings; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; -import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.gson.JsonElement; import com.google.gson.JsonParser; @@ -149,7 +148,7 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt } private void ensureRefreshTokenConsistency(ClientDetailsEntity client) { - if (client.getAuthorizedGrantTypes().contains("refresh_token") + if (client.getAuthorizedGrantTypes().contains("refresh_token") || client.getScope().contains(SystemScopeService.OFFLINE_ACCESS)) { client.getScope().add(SystemScopeService.OFFLINE_ACCESS); client.getAuthorizedGrantTypes().add("refresh_token"); @@ -239,7 +238,7 @@ public class DefaultOAuth2ClientDetailsEntityService implements ClientDetailsEnt // if the client is flagged to allow for refresh tokens, make sure it's got the right scope ensureRefreshTokenConsistency(newClient); - + // check the sector URI checkSectorIdentifierUri(newClient); diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ProviderTokenService.java b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ProviderTokenService.java index 8c0dee5df..92e91dedf 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ProviderTokenService.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/service/impl/DefaultOAuth2ProviderTokenService.java @@ -194,7 +194,7 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi token.setRefreshToken(savedRefreshToken); } - + OAuth2AccessTokenEntity enhancedToken = (OAuth2AccessTokenEntity) tokenEnhancer.enhance(token, authentication); OAuth2AccessTokenEntity savedToken = tokenRepository.saveAccessToken(enhancedToken); @@ -235,14 +235,14 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi ClientDetailsEntity client = refreshToken.getClient(); AuthenticationHolderEntity authHolder = refreshToken.getAuthenticationHolder(); - + // make sure that the client requesting the token is the one who owns the refresh token ClientDetailsEntity requestingClient = clientDetailsService.loadClientByClientId(authRequest.getClientId()); if (!client.getClientId().equals(requestingClient.getClientId())) { tokenRepository.removeRefreshToken(refreshToken); throw new InvalidClientException("Client does not own the presented refresh token"); } - + //Make sure this client allows access token refreshing if (!client.isAllowRefresh()) { throw new InvalidClientException("Client does not allow refreshing access token!"); @@ -483,18 +483,18 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi @Override public OAuth2AccessTokenEntity getRegistrationAccessTokenForClient(ClientDetailsEntity client) { List allTokens = getAccessTokensForClient(client); - + for (OAuth2AccessTokenEntity token : allTokens) { - if ((token.getScope().contains(SystemScopeService.REGISTRATION_TOKEN_SCOPE) || token.getScope().contains(SystemScopeService.RESOURCE_TOKEN_SCOPE)) + if ((token.getScope().contains(SystemScopeService.REGISTRATION_TOKEN_SCOPE) || token.getScope().contains(SystemScopeService.RESOURCE_TOKEN_SCOPE)) && token.getScope().size() == 1) { // if it only has the registration scope, then it's a registration token return token; } } - + return null; } - - + + } diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/web/IntrospectionEndpoint.java b/openid-connect-server/src/main/java/org/mitre/oauth2/web/IntrospectionEndpoint.java index 15cf0a816..e8f79cf98 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/web/IntrospectionEndpoint.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/web/IntrospectionEndpoint.java @@ -16,8 +16,10 @@ *******************************************************************************/ package org.mitre.oauth2.web; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableMap; +import java.security.Principal; +import java.util.Map; +import java.util.Set; + import org.mitre.oauth2.model.ClientDetailsEntity; import org.mitre.oauth2.model.OAuth2AccessTokenEntity; import org.mitre.oauth2.model.OAuth2RefreshTokenEntity; @@ -40,9 +42,8 @@ import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import java.security.Principal; -import java.util.Map; -import java.util.Set; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableMap; @Controller public class IntrospectionEndpoint { @@ -56,8 +57,8 @@ public class IntrospectionEndpoint { @Autowired private IntrospectionAuthorizer introspectionAuthorizer; - @Autowired - private IntrospectionResultAssembler introspectionResultAssembler; + @Autowired + private IntrospectionResultAssembler introspectionResultAssembler; @Autowired private UserInfoService userInfoService; @@ -86,8 +87,8 @@ public class IntrospectionEndpoint { return JsonEntityView.VIEWNAME; } - OAuth2AccessTokenEntity accessToken = null; - OAuth2RefreshTokenEntity refreshToken = null; + OAuth2AccessTokenEntity accessToken = null; + OAuth2RefreshTokenEntity refreshToken = null; ClientDetailsEntity tokenClient; Set scopes; UserInfo user; @@ -100,7 +101,7 @@ public class IntrospectionEndpoint { tokenClient = accessToken.getClient(); scopes = accessToken.getScope(); - user = userInfoService.getByUsernameAndClientId(accessToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId()); + user = userInfoService.getByUsernameAndClientId(accessToken.getAuthenticationHolder().getAuthentication().getName(), tokenClient.getClientId()); } catch (InvalidTokenException e) { logger.info("Verify failed; Invalid access token. Checking refresh token."); @@ -122,28 +123,28 @@ public class IntrospectionEndpoint { } } - // clientID is the principal name in the authentication - String clientId = p.getName(); - ClientDetailsEntity authClient = clientService.loadClientByClientId(clientId); + // clientID is the principal name in the authentication + String clientId = p.getName(); + ClientDetailsEntity authClient = clientService.loadClientByClientId(clientId); - if (authClient.isAllowIntrospection()) { - if (introspectionAuthorizer.isIntrospectionPermitted(authClient, tokenClient, scopes)) { - // if it's a valid token, we'll print out information on it - Map entity = accessToken != null - ? introspectionResultAssembler.assembleFrom(accessToken, user) - : introspectionResultAssembler.assembleFrom(refreshToken, user); - model.addAttribute("entity", entity); - return JsonEntityView.VIEWNAME; - } else { - logger.error("Verify failed; client configuration or scope don't permit token introspection"); - model.addAttribute("code", HttpStatus.FORBIDDEN); - return HttpCodeView.VIEWNAME; - } - } else { - logger.error("Verify failed; client " + clientId + " is not allowed to call introspection endpoint"); - model.addAttribute("code", HttpStatus.FORBIDDEN); - return HttpCodeView.VIEWNAME; - } + if (authClient.isAllowIntrospection()) { + if (introspectionAuthorizer.isIntrospectionPermitted(authClient, tokenClient, scopes)) { + // if it's a valid token, we'll print out information on it + Map entity = accessToken != null + ? introspectionResultAssembler.assembleFrom(accessToken, user) + : introspectionResultAssembler.assembleFrom(refreshToken, user); + model.addAttribute("entity", entity); + return JsonEntityView.VIEWNAME; + } else { + logger.error("Verify failed; client configuration or scope don't permit token introspection"); + model.addAttribute("code", HttpStatus.FORBIDDEN); + return HttpCodeView.VIEWNAME; + } + } else { + logger.error("Verify failed; client " + clientId + " is not allowed to call introspection endpoint"); + model.addAttribute("code", HttpStatus.FORBIDDEN); + return HttpCodeView.VIEWNAME; + } } diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/web/OAuthConfirmationController.java b/openid-connect-server/src/main/java/org/mitre/oauth2/web/OAuthConfirmationController.java index 3f84e0c0d..cb8ee020b 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/web/OAuthConfirmationController.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/web/OAuthConfirmationController.java @@ -102,7 +102,7 @@ public class OAuthConfirmationController { model.put("code", HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } - + if (prompts.contains("consent")) { model.put("consent", true); } @@ -160,10 +160,10 @@ public class OAuthConfirmationController { Map> claimsForScopes = new HashMap>(); if (user != null) { JsonObject userJson = user.toJson(); - + for (SystemScope systemScope : sortedScopes) { Map claimValues = new HashMap(); - + Set claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue()); for (String claim : claims) { if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) { @@ -171,7 +171,7 @@ public class OAuthConfirmationController { claimValues.put(claim, userJson.get(claim).getAsString()); } } - + claimsForScopes.put(systemScope.getValue(), claimValues); } } diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/web/TokenAPI.java b/openid-connect-server/src/main/java/org/mitre/oauth2/web/TokenAPI.java index e25a131d1..c768ce837 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/web/TokenAPI.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/web/TokenAPI.java @@ -52,10 +52,10 @@ public class TokenAPI { @Autowired private OAuth2TokenEntityService tokenService; - + @Autowired private ClientDetailsEntityService clientService; - + @Autowired private OIDCTokenService oidcTokenService; @@ -115,9 +115,9 @@ public class TokenAPI { @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/client/{clientId}", method = RequestMethod.GET, produces = "application/json") public String getAccessTokensByClientId(@PathVariable("clientId") String clientId, ModelMap m, Principal p) { - + ClientDetailsEntity client = clientService.loadClientByClientId(clientId); - + if (client != null) { List tokens = tokenService.getAccessTokensForClient(client); m.put("entity", tokens); @@ -128,15 +128,15 @@ public class TokenAPI { m.put("errorMessage", "The requested client with id " + clientId + " could not be found."); return JsonErrorView.VIEWNAME; } - + } @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/registration/{clientId}", method = RequestMethod.GET, produces = "application/json") public String getRegistrationTokenByClientId(@PathVariable("clientId") String clientId, ModelMap m, Principal p) { - + ClientDetailsEntity client = clientService.loadClientByClientId(clientId); - + if (client != null) { OAuth2AccessTokenEntity token = tokenService.getRegistrationAccessTokenForClient(client); if (token != null) { @@ -153,18 +153,18 @@ public class TokenAPI { m.put("errorMessage", "The requested client with id " + clientId + " could not be found."); return JsonErrorView.VIEWNAME; } - + } - + @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(value = "/registration/{clientId}", method = RequestMethod.PUT, produces = "application/json") public String rotateRegistrationTokenByClientId(@PathVariable("clientId") String clientId, ModelMap m, Principal p) { ClientDetailsEntity client = clientService.loadClientByClientId(clientId); - + if (client != null) { OAuth2AccessTokenEntity token = oidcTokenService.rotateRegistrationAccessTokenForClient(client); token = tokenService.saveAccessToken(token); - + if (token != null) { m.put("entity", token); return TokenApiView.VIEWNAME; @@ -179,9 +179,9 @@ public class TokenAPI { m.put("errorMessage", "The requested client with id " + clientId + " could not be found."); return JsonErrorView.VIEWNAME; } - + } - + @RequestMapping(value = "/refresh", method = RequestMethod.GET, produces = "application/json") public String getAllRefreshTokens(ModelMap m, Principal p) { diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/ConnectOAuth2RequestFactory.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/ConnectOAuth2RequestFactory.java index 840c79922..50e45de78 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/ConnectOAuth2RequestFactory.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/ConnectOAuth2RequestFactory.java @@ -120,12 +120,12 @@ public class ConnectOAuth2RequestFactory extends DefaultOAuth2RequestFactory { if (inputParams.containsKey("login_hint")) { request.getExtensions().put("login_hint", inputParams.get("login_hint")); } - + if (inputParams.containsKey("request")) { request.getExtensions().put("request", inputParams.get("request")); processRequestObject(inputParams.get("request"), request); } - + if (request.getClientId() != null) { try { ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); @@ -352,7 +352,7 @@ public class ConnectOAuth2RequestFactory extends DefaultOAuth2RequestFactory { // we save the string because the object might not be a Java Serializable, and we can parse it easily enough anyway request.getExtensions().put("claims", claimRequest.toString()); } - + String loginHint = claims.getStringClaim("login_hint"); if (loginHint != null) { if (!loginHint.equals(request.getExtensions().get("login_hint"))) { diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/assertion/JwtBearerAuthenticationProvider.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/assertion/JwtBearerAuthenticationProvider.java index 607eca8d8..36625b885 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/assertion/JwtBearerAuthenticationProvider.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/assertion/JwtBearerAuthenticationProvider.java @@ -57,7 +57,7 @@ public class JwtBearerAuthenticationProvider implements AuthenticationProvider { private static final Logger logger = LoggerFactory.getLogger(JwtBearerAuthenticationProvider.class); private static final GrantedAuthority ROLE_CLIENT = new SimpleGrantedAuthority("ROLE_CLIENT"); - + // map of verifiers, load keys for clients @Autowired private JWKSetCacheService validators; @@ -107,10 +107,10 @@ public class JwtBearerAuthenticationProvider implements AuthenticationProvider { client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST)) { - + // this client doesn't support this type of authentication throw new AuthenticationServiceException("Client does not support this authentication method."); - + } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.PRIVATE_KEY) && (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384) @@ -188,11 +188,11 @@ public class JwtBearerAuthenticationProvider implements AuthenticationProvider { } // IFF we managed to get all the way down here, the token is valid - + // add in the ROLE_CLIENT authority Set authorities = new HashSet<>(client.getAuthorities()); authorities.add(ROLE_CLIENT); - + return new JwtBearerAssertionAuthenticationToken(client.getClientId(), jwt, authorities); } catch (InvalidClientException e) { diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/exception/ValidationException.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/exception/ValidationException.java index 47c9ac757..5088464ce 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/exception/ValidationException.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/exception/ValidationException.java @@ -54,7 +54,7 @@ public class ValidationException extends Exception { public void setStatus(HttpStatus status) { this.status = status; } - + @Override public String toString() { return "ValidationException [error=" + error + ", errorDescription=" diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/filter/AuthorizationRequestFilter.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/filter/AuthorizationRequestFilter.java index 4548b9bc4..1409810de 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/filter/AuthorizationRequestFilter.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/filter/AuthorizationRequestFilter.java @@ -97,15 +97,15 @@ public class AuthorizationRequestFilter extends GenericFilterBean { // no need to worry about this here, it would be caught elsewhere } - + // save the login hint to the session if (authRequest.getExtensions().get("login_hint") != null) { session.setAttribute("login_hint", authRequest.getExtensions().get("login_hint")); } else { session.removeAttribute("login_hint"); } - - + + if (authRequest.getExtensions().get("prompt") != null) { // we have a "prompt" parameter String prompt = (String)authRequest.getExtensions().get("prompt"); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaUserInfoRepository.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaUserInfoRepository.java index 979c36fae..fe2ee87c1 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaUserInfoRepository.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaUserInfoRepository.java @@ -19,8 +19,6 @@ package org.mitre.openid.connect.repository.impl; import static org.mitre.util.jpa.JpaUtil.getSingleResult; import static org.mitre.util.jpa.JpaUtil.saveOrUpdate; -import java.util.Collection; - import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; 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 4870082fd..12a96c52a 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 @@ -84,7 +84,7 @@ public class DefaultOIDCTokenService implements OIDCTokenService { @Autowired private SymmetricCacheService symmetricCacheService; - + @Autowired private OAuth2TokenEntityService tokenService; @@ -156,17 +156,17 @@ public class DefaultOIDCTokenService implements OIDCTokenService { } } else { - + JWT idToken; - - if (signingAlg.equals(JWSAlgorithm.NONE)) { + + if (signingAlg.equals(Algorithm.NONE)) { // unsigned ID token idToken = new PlainJWT(idClaims); } else { // signed ID token - + if (signingAlg.equals(JWSAlgorithm.HS256) || signingAlg.equals(JWSAlgorithm.HS384) || signingAlg.equals(JWSAlgorithm.HS512)) { @@ -174,19 +174,19 @@ public class DefaultOIDCTokenService implements OIDCTokenService { idToken = new SignedJWT(new JWSHeader(signingAlg), idClaims); JwtSigningAndValidationService signer = symmetricCacheService.getSymmetricValidtor(client); - + // sign it with the client's secret signer.signJwt((SignedJWT) idToken); } else { idClaims.setCustomClaim("kid", jwtService.getDefaultSignerKeyId()); - + idToken = new SignedJWT(new JWSHeader(signingAlg), idClaims); - + // sign it with the server's key jwtService.signJwt((SignedJWT) idToken); } } - + idTokenEntity.setJwt(idToken); } @@ -212,9 +212,9 @@ public class DefaultOIDCTokenService implements OIDCTokenService { public OAuth2AccessTokenEntity createRegistrationAccessToken(ClientDetailsEntity client) { return createAssociatedToken(client, Sets.newHashSet(SystemScopeService.REGISTRATION_TOKEN_SCOPE)); - + } - + /** * @param client * @return @@ -223,7 +223,7 @@ public class DefaultOIDCTokenService implements OIDCTokenService { public OAuth2AccessTokenEntity createResourceAccessToken(ClientDetailsEntity client) { return createAssociatedToken(client, Sets.newHashSet(SystemScopeService.RESOURCE_TOKEN_SCOPE)); - + } @Override @@ -237,19 +237,19 @@ public class DefaultOIDCTokenService implements OIDCTokenService { } else { return null; } - + } - + private OAuth2AccessTokenEntity createAssociatedToken(ClientDetailsEntity client, Set scope) { - + // revoke any previous tokens that might exist, just to be sure OAuth2AccessTokenEntity oldToken = tokenService.getRegistrationAccessTokenForClient(client); if (oldToken != null) { tokenService.revokeAccessToken(oldToken); } - + // create a new token - + Map authorizationParameters = Maps.newHashMap(); OAuth2Request clientAuth = new OAuth2Request(authorizationParameters, client.getClientId(), Sets.newHashSet(new SimpleGrantedAuthority("ROLE_CLIENT")), true, diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_0.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_0.java index cb5ebfbe5..373c1153a 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_0.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_0.java @@ -16,10 +16,6 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; -import com.google.common.collect.Sets; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.text.ParseException; import java.util.Collection; @@ -29,6 +25,7 @@ import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; + import org.mitre.jose.JWEAlgorithmEmbed; import org.mitre.jose.JWEEncryptionMethodEmbed; import org.mitre.jose.JWSAlgorithmEmbed; @@ -60,7 +57,12 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; import org.springframework.stereotype.Service; -/** + +import com.google.common.collect.Sets; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +/** * * Data service to import MITREid 1.0 configuration. * @@ -70,773 +72,773 @@ import org.springframework.stereotype.Service; @Service public class MITREidDataService_1_0 extends MITREidDataService_1_X { - private final static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_0.class); - @Autowired - private OAuth2ClientRepository clientRepository; - @Autowired - private ApprovedSiteRepository approvedSiteRepository; - @Autowired - private WhitelistedSiteRepository wlSiteRepository; - @Autowired - private BlacklistedSiteRepository blSiteRepository; - @Autowired - private AuthenticationHolderRepository authHolderRepository; - @Autowired - private OAuth2TokenRepository tokenRepository; - @Autowired - private SystemScopeRepository sysScopeRepository; - /* (non-Javadoc) - * @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter) - */ + private final static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_0.class); + @Autowired + private OAuth2ClientRepository clientRepository; + @Autowired + private ApprovedSiteRepository approvedSiteRepository; + @Autowired + private WhitelistedSiteRepository wlSiteRepository; + @Autowired + private BlacklistedSiteRepository blSiteRepository; + @Autowired + private AuthenticationHolderRepository authHolderRepository; + @Autowired + private OAuth2TokenRepository tokenRepository; + @Autowired + private SystemScopeRepository sysScopeRepository; + /* (non-Javadoc) + * @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter) + */ - @Override - public void exportData(JsonWriter writer) throws IOException { - throw new UnsupportedOperationException("Can not export 1.0 format from this version."); - } + @Override + public void exportData(JsonWriter writer) throws IOException { + throw new UnsupportedOperationException("Can not export 1.0 format from this version."); + } - /* (non-Javadoc) - * @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader) - */ - @Override - public void importData(JsonReader reader) throws IOException { + /* (non-Javadoc) + * @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader) + */ + @Override + public void importData(JsonReader reader) throws IOException { - logger.info("Reading configuration for 1.0"); + logger.info("Reading configuration for 1.0"); - // this *HAS* to start as an object - reader.beginObject(); + // this *HAS* to start as an object + reader.beginObject(); - while (reader.hasNext()) { - JsonToken tok = reader.peek(); - switch (tok) { - case NAME: - String name = reader.nextName(); - // find out which member it is - if (name.equals(CLIENTS)) { - readClients(reader); - } else if (name.equals(GRANTS)) { - readGrants(reader); - } else if (name.equals(WHITELISTEDSITES)) { - readWhitelistedSites(reader); - } else if (name.equals(BLACKLISTEDSITES)) { - readBlacklistedSites(reader); - } else if (name.equals(AUTHENTICATIONHOLDERS)) { - readAuthenticationHolders(reader); - } else if (name.equals(ACCESSTOKENS)) { - readAccessTokens(reader); - } else if (name.equals(REFRESHTOKENS)) { - readRefreshTokens(reader); - } else if (name.equals(SYSTEMSCOPES)) { - readSystemScopes(reader); - } else { - // unknown token, skip it - reader.skipValue(); - } - break; - case END_OBJECT: - // the object ended, we're done here - reader.endObject(); - continue; - } - } - fixObjectReferences(); - } - private Map refreshTokenToClientRefs = new HashMap(); - private Map refreshTokenToAuthHolderRefs = new HashMap(); - private Map refreshTokenOldToNewIdMap = new HashMap(); + while (reader.hasNext()) { + JsonToken tok = reader.peek(); + switch (tok) { + case NAME: + String name = reader.nextName(); + // find out which member it is + if (name.equals(CLIENTS)) { + readClients(reader); + } else if (name.equals(GRANTS)) { + readGrants(reader); + } else if (name.equals(WHITELISTEDSITES)) { + readWhitelistedSites(reader); + } else if (name.equals(BLACKLISTEDSITES)) { + readBlacklistedSites(reader); + } else if (name.equals(AUTHENTICATIONHOLDERS)) { + readAuthenticationHolders(reader); + } else if (name.equals(ACCESSTOKENS)) { + readAccessTokens(reader); + } else if (name.equals(REFRESHTOKENS)) { + readRefreshTokens(reader); + } else if (name.equals(SYSTEMSCOPES)) { + readSystemScopes(reader); + } else { + // unknown token, skip it + reader.skipValue(); + } + break; + case END_OBJECT: + // the object ended, we're done here + reader.endObject(); + continue; + } + } + fixObjectReferences(); + } + private Map refreshTokenToClientRefs = new HashMap(); + private Map refreshTokenToAuthHolderRefs = new HashMap(); + private Map refreshTokenOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - /** - * @param reader - * @throws IOException - */ - private void readRefreshTokens(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity(); - reader.beginObject(); - Long currentId = null; - String clientId = null; - Long authHolderId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("expiration")) { - Date date = DateUtil.utcToDate(reader.nextString()); - token.setExpiration(date); - } else if (name.equals("value")) { - String value = reader.nextString(); - try { - token.setValue(value); - } catch (ParseException ex) { - logger.error("Unable to set refresh token value to {}", value, ex); - } - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("authenticationHolderId")) { - authHolderId = reader.nextLong(); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = tokenRepository.saveRefreshToken(token).getId(); - refreshTokenToClientRefs.put(currentId, clientId); - refreshTokenToAuthHolderRefs.put(currentId, authHolderId); - refreshTokenOldToNewIdMap.put(currentId, newId); - logger.debug("Read refresh token {}", currentId); - } - reader.endArray(); - logger.info("Done reading refresh tokens"); - } - private Map accessTokenToClientRefs = new HashMap(); - private Map accessTokenToAuthHolderRefs = new HashMap(); - private Map accessTokenToRefreshTokenRefs = new HashMap(); - private Map accessTokenToIdTokenRefs = new HashMap(); - private Map accessTokenOldToNewIdMap = new HashMap(); + /** + * @param reader + * @throws IOException + */ + /** + * @param reader + * @throws IOException + */ + private void readRefreshTokens(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity(); + reader.beginObject(); + Long currentId = null; + String clientId = null; + Long authHolderId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("expiration")) { + Date date = DateUtil.utcToDate(reader.nextString()); + token.setExpiration(date); + } else if (name.equals("value")) { + String value = reader.nextString(); + try { + token.setValue(value); + } catch (ParseException ex) { + logger.error("Unable to set refresh token value to {}", value, ex); + } + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("authenticationHolderId")) { + authHolderId = reader.nextLong(); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = tokenRepository.saveRefreshToken(token).getId(); + refreshTokenToClientRefs.put(currentId, clientId); + refreshTokenToAuthHolderRefs.put(currentId, authHolderId); + refreshTokenOldToNewIdMap.put(currentId, newId); + logger.debug("Read refresh token {}", currentId); + } + reader.endArray(); + logger.info("Done reading refresh tokens"); + } + private Map accessTokenToClientRefs = new HashMap(); + private Map accessTokenToAuthHolderRefs = new HashMap(); + private Map accessTokenToRefreshTokenRefs = new HashMap(); + private Map accessTokenToIdTokenRefs = new HashMap(); + private Map accessTokenOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - /** - * @param reader - * @throws IOException - */ - private void readAccessTokens(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity(); - reader.beginObject(); - Long currentId = null; - String clientId = null; - Long authHolderId = null; - Long refreshTokenId = null; - Long idTokenId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("expiration")) { - Date date = DateUtil.utcToDate(reader.nextString()); - token.setExpiration(date); - } else if (name.equals("value")) { - String value = reader.nextString(); - try { - token.setValue(value); - } catch (ParseException ex) { - logger.error("Unable to set refresh token value to {}", value, ex); - } - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("authenticationHolderId")) { - authHolderId = reader.nextLong(); - } else if (name.equals("refreshTokenId")) { - refreshTokenId = reader.nextLong(); - } else if (name.equals("idTokenId")) { - idTokenId = reader.nextLong(); - } else if (name.equals("scope")) { - Set scope = readSet(reader); - token.setScope(scope); - } else if (name.equals("type")) { - token.setTokenType(reader.nextString()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = tokenRepository.saveAccessToken(token).getId(); - accessTokenToClientRefs.put(currentId, clientId); - accessTokenToAuthHolderRefs.put(currentId, authHolderId); - if (refreshTokenId != null) { - accessTokenToRefreshTokenRefs.put(currentId, refreshTokenId); - } - if (idTokenId != null) { - accessTokenToIdTokenRefs.put(currentId, idTokenId); - } - accessTokenOldToNewIdMap.put(currentId, newId); - logger.debug("Read access token {}", currentId); - } - reader.endArray(); - logger.info("Done reading access tokens"); - } - private Map authHolderOldToNewIdMap = new HashMap(); + /** + * @param reader + * @throws IOException + */ + /** + * @param reader + * @throws IOException + */ + private void readAccessTokens(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity(); + reader.beginObject(); + Long currentId = null; + String clientId = null; + Long authHolderId = null; + Long refreshTokenId = null; + Long idTokenId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("expiration")) { + Date date = DateUtil.utcToDate(reader.nextString()); + token.setExpiration(date); + } else if (name.equals("value")) { + String value = reader.nextString(); + try { + token.setValue(value); + } catch (ParseException ex) { + logger.error("Unable to set refresh token value to {}", value, ex); + } + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("authenticationHolderId")) { + authHolderId = reader.nextLong(); + } else if (name.equals("refreshTokenId")) { + refreshTokenId = reader.nextLong(); + } else if (name.equals("idTokenId")) { + idTokenId = reader.nextLong(); + } else if (name.equals("scope")) { + Set scope = readSet(reader); + token.setScope(scope); + } else if (name.equals("type")) { + token.setTokenType(reader.nextString()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = tokenRepository.saveAccessToken(token).getId(); + accessTokenToClientRefs.put(currentId, clientId); + accessTokenToAuthHolderRefs.put(currentId, authHolderId); + if (refreshTokenId != null) { + accessTokenToRefreshTokenRefs.put(currentId, refreshTokenId); + } + if (idTokenId != null) { + accessTokenToIdTokenRefs.put(currentId, idTokenId); + } + accessTokenOldToNewIdMap.put(currentId, newId); + logger.debug("Read access token {}", currentId); + } + reader.endArray(); + logger.info("Done reading access tokens"); + } + private Map authHolderOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - private void readAuthenticationHolders(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - AuthenticationHolderEntity ahe = new AuthenticationHolderEntity(); - reader.beginObject(); - Long currentId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("ownerId")) { - //not needed - reader.skipValue(); - } else if (name.equals("authentication")) { - OAuth2Request clientAuthorization = null; - Authentication userAuthentication = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String subName = reader.nextName(); - if (subName.equals("clientAuthorization")) { - clientAuthorization = readAuthorizationRequest(reader); - } else if (subName.equals("userAuthentication")) { - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else { - String authString = reader.nextString(); - userAuthentication = base64UrlDecodeObject(authString, Authentication.class); - } - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - OAuth2Authentication auth = new OAuth2Authentication(clientAuthorization, userAuthentication); - ahe.setAuthentication(auth); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = authHolderRepository.save(ahe).getId(); - authHolderOldToNewIdMap.put(currentId, newId); - logger.debug("Read authentication holder {}", currentId); - } - reader.endArray(); - logger.info("Done reading authentication holders"); - } + /** + * @param reader + * @throws IOException + */ + private void readAuthenticationHolders(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + AuthenticationHolderEntity ahe = new AuthenticationHolderEntity(); + reader.beginObject(); + Long currentId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("ownerId")) { + //not needed + reader.skipValue(); + } else if (name.equals("authentication")) { + OAuth2Request clientAuthorization = null; + Authentication userAuthentication = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String subName = reader.nextName(); + if (subName.equals("clientAuthorization")) { + clientAuthorization = readAuthorizationRequest(reader); + } else if (subName.equals("userAuthentication")) { + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else { + String authString = reader.nextString(); + userAuthentication = base64UrlDecodeObject(authString, Authentication.class); + } + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + OAuth2Authentication auth = new OAuth2Authentication(clientAuthorization, userAuthentication); + ahe.setAuthentication(auth); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = authHolderRepository.save(ahe).getId(); + authHolderOldToNewIdMap.put(currentId, newId); + logger.debug("Read authentication holder {}", currentId); + } + reader.endArray(); + logger.info("Done reading authentication holders"); + } - //used by readAuthenticationHolders - private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException { - Set scope = new LinkedHashSet(); - Set resourceIds = new HashSet(); - boolean approved = false; - Collection authorities = new HashSet(); - Map authorizationParameters = new HashMap(); - Set responseTypes = new HashSet(); - String redirectUri = null; - String clientId = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("authorizationParameters")) { - authorizationParameters = readMap(reader); - } else if (name.equals("approvalParameters")) { - reader.skipValue(); - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("scope")) { - scope = readSet(reader); - } else if (name.equals("resourceIds")) { - resourceIds = readSet(reader); - } else if (name.equals("authorities")) { - Set authorityStrs = readSet(reader); - authorities = new HashSet(); - for (String s : authorityStrs) { - GrantedAuthority ga = new SimpleGrantedAuthority(s); - authorities.add(ga); - } - } else if (name.equals("approved")) { - approved = reader.nextBoolean(); - } else if (name.equals("denied")) { - if (approved == false) { - approved = !reader.nextBoolean(); - } - } else if (name.equals("redirectUri")) { - redirectUri = reader.nextString(); - } else if (name.equals("responseTypes")) { - responseTypes = readSet(reader); - } else { - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - return new OAuth2Request(authorizationParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, null); - } - Map grantOldToNewIdMap = new HashMap(); - Map grantToWhitelistedSiteRefs = new HashMap(); - Map> grantToAccessTokensRefs = new HashMap>(); + //used by readAuthenticationHolders + private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException { + Set scope = new LinkedHashSet(); + Set resourceIds = new HashSet(); + boolean approved = false; + Collection authorities = new HashSet(); + Map authorizationParameters = new HashMap(); + Set responseTypes = new HashSet(); + String redirectUri = null; + String clientId = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("authorizationParameters")) { + authorizationParameters = readMap(reader); + } else if (name.equals("approvalParameters")) { + reader.skipValue(); + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("scope")) { + scope = readSet(reader); + } else if (name.equals("resourceIds")) { + resourceIds = readSet(reader); + } else if (name.equals("authorities")) { + Set authorityStrs = readSet(reader); + authorities = new HashSet(); + for (String s : authorityStrs) { + GrantedAuthority ga = new SimpleGrantedAuthority(s); + authorities.add(ga); + } + } else if (name.equals("approved")) { + approved = reader.nextBoolean(); + } else if (name.equals("denied")) { + if (approved == false) { + approved = !reader.nextBoolean(); + } + } else if (name.equals("redirectUri")) { + redirectUri = reader.nextString(); + } else if (name.equals("responseTypes")) { + responseTypes = readSet(reader); + } else { + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + return new OAuth2Request(authorizationParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, null); + } + Map grantOldToNewIdMap = new HashMap(); + Map grantToWhitelistedSiteRefs = new HashMap(); + Map> grantToAccessTokensRefs = new HashMap>(); - /** - * @param reader - * @throws IOException - */ - private void readGrants(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - ApprovedSite site = new ApprovedSite(); - Long currentId = null; - Long whitelistedSiteId = null; - Set tokenIds = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("accessDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setAccessDate(date); - } else if (name.equals("clientId")) { - site.setClientId(reader.nextString()); - } else if (name.equals("creationDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setCreationDate(date); - } else if (name.equals("timeoutDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setTimeoutDate(date); - } else if (name.equals("userId")) { - site.setUserId(reader.nextString()); - } else if (name.equals("allowedScopes")) { - Set allowedScopes = readSet(reader); - site.setAllowedScopes(allowedScopes); - } else if (name.equals("whitelistedSiteId")) { - whitelistedSiteId = reader.nextLong(); - } else if (name.equals("approvedAccessTokens")) { - tokenIds = readSet(reader); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = approvedSiteRepository.save(site).getId(); - grantOldToNewIdMap.put(currentId, newId); - if (whitelistedSiteId != null) { - grantToWhitelistedSiteRefs.put(currentId, whitelistedSiteId); - } - if (tokenIds != null) { - grantToAccessTokensRefs.put(currentId, tokenIds); - } - logger.debug("Read grant {}", currentId); - } - reader.endArray(); - logger.info("Done reading grants"); - } - Map whitelistedSiteOldToNewIdMap = new HashMap(); + /** + * @param reader + * @throws IOException + */ + private void readGrants(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + ApprovedSite site = new ApprovedSite(); + Long currentId = null; + Long whitelistedSiteId = null; + Set tokenIds = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("accessDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setAccessDate(date); + } else if (name.equals("clientId")) { + site.setClientId(reader.nextString()); + } else if (name.equals("creationDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setCreationDate(date); + } else if (name.equals("timeoutDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setTimeoutDate(date); + } else if (name.equals("userId")) { + site.setUserId(reader.nextString()); + } else if (name.equals("allowedScopes")) { + Set allowedScopes = readSet(reader); + site.setAllowedScopes(allowedScopes); + } else if (name.equals("whitelistedSiteId")) { + whitelistedSiteId = reader.nextLong(); + } else if (name.equals("approvedAccessTokens")) { + tokenIds = readSet(reader); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = approvedSiteRepository.save(site).getId(); + grantOldToNewIdMap.put(currentId, newId); + if (whitelistedSiteId != null) { + grantToWhitelistedSiteRefs.put(currentId, whitelistedSiteId); + } + if (tokenIds != null) { + grantToAccessTokensRefs.put(currentId, tokenIds); + } + logger.debug("Read grant {}", currentId); + } + reader.endArray(); + logger.info("Done reading grants"); + } + Map whitelistedSiteOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - private void readWhitelistedSites(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - WhitelistedSite wlSite = new WhitelistedSite(); - Long currentId = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("clientId")) { - wlSite.setClientId(reader.nextString()); - } else if (name.equals("creatorUserId")) { - wlSite.setCreatorUserId(reader.nextString()); - } else if (name.equals("allowedScopes")) { - Set allowedScopes = readSet(reader); - wlSite.setAllowedScopes(allowedScopes); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = wlSiteRepository.save(wlSite).getId(); - whitelistedSiteOldToNewIdMap.put(currentId, newId); - } - reader.endArray(); - logger.info("Done reading whitelisted sites"); - } + /** + * @param reader + * @throws IOException + */ + private void readWhitelistedSites(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + WhitelistedSite wlSite = new WhitelistedSite(); + Long currentId = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("clientId")) { + wlSite.setClientId(reader.nextString()); + } else if (name.equals("creatorUserId")) { + wlSite.setCreatorUserId(reader.nextString()); + } else if (name.equals("allowedScopes")) { + Set allowedScopes = readSet(reader); + wlSite.setAllowedScopes(allowedScopes); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = wlSiteRepository.save(wlSite).getId(); + whitelistedSiteOldToNewIdMap.put(currentId, newId); + } + reader.endArray(); + logger.info("Done reading whitelisted sites"); + } - /** - * @param reader - * @throws IOException - */ - private void readBlacklistedSites(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - BlacklistedSite blSite = new BlacklistedSite(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (name.equals("id")) { - reader.skipValue(); - } else if (name.equals("uri")) { - blSite.setUri(reader.nextString()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - blSiteRepository.save(blSite); - } - reader.endArray(); - logger.info("Done reading blacklisted sites"); - } + /** + * @param reader + * @throws IOException + */ + private void readBlacklistedSites(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + BlacklistedSite blSite = new BlacklistedSite(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (name.equals("id")) { + reader.skipValue(); + } else if (name.equals("uri")) { + blSite.setUri(reader.nextString()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + blSiteRepository.save(blSite); + } + reader.endArray(); + logger.info("Done reading blacklisted sites"); + } - /** - * @param reader - * @throws IOException - */ - private void readClients(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - ClientDetailsEntity client = new ClientDetailsEntity(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("clientId")) { - client.setClientId(reader.nextString()); - } else if (name.equals("resourceIds")) { - Set resourceIds = readSet(reader); - client.setResourceIds(resourceIds); - } else if (name.equals("secret")) { - client.setClientSecret(reader.nextString()); - } else if (name.equals("scope")) { - Set scope = readSet(reader); - client.setScope(scope); - } else if (name.equals("authorities")) { - Set authorityStrs = readSet(reader); - Set authorities = new HashSet(); - for (String s : authorityStrs) { - GrantedAuthority ga = new SimpleGrantedAuthority(s); - authorities.add(ga); - } - client.setAuthorities(authorities); - } else if (name.equals("accessTokenValiditySeconds")) { - client.setAccessTokenValiditySeconds(reader.nextInt()); - } else if (name.equals("refreshTokenValiditySeconds")) { - client.setRefreshTokenValiditySeconds(reader.nextInt()); - } else if (name.equals("redirectUris")) { - Set redirectUris = readSet(reader); - client.setRedirectUris(redirectUris); - } else if (name.equals("name")) { - client.setClientName(reader.nextString()); - } else if (name.equals("uri")) { - client.setClientUri(reader.nextString()); - } else if (name.equals("logoUri")) { - client.setLogoUri(reader.nextString()); - } else if (name.equals("contacts")) { - Set contacts = readSet(reader); - client.setContacts(contacts); - } else if (name.equals("tosUri")) { - client.setTosUri(reader.nextString()); - } else if (name.equals("tokenEndpointAuthMethod")) { - AuthMethod am = AuthMethod.getByValue(reader.nextString()); - client.setTokenEndpointAuthMethod(am); - } else if (name.equals("grantTypes")) { - Set grantTypes = readSet(reader); - client.setGrantTypes(grantTypes); - } else if (name.equals("responseTypes")) { - Set responseTypes = readSet(reader); - client.setResponseTypes(responseTypes); - } else if (name.equals("policyUri")) { - client.setPolicyUri(reader.nextString()); - } else if (name.equals("applicationType")) { - AppType appType = AppType.getByValue(reader.nextString()); - client.setApplicationType(appType); - } else if (name.equals("sectorIdentifierUri")) { - client.setSectorIdentifierUri(reader.nextString()); - } else if (name.equals("subjectType")) { - SubjectType st = SubjectType.getByValue(reader.nextString()); - client.setSubjectType(st); - } else if (name.equals("requestObjectSigningAlg")) { - JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setRequestObjectSigningAlgEmbed(alg); - } else if (name.equals("userInfoEncryptedResponseAlg")) { - JWEAlgorithmEmbed alg = JWEAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoEncryptedResponseAlgEmbed(alg); - } else if (name.equals("userInfoEncryptedResponseEnc")) { - JWEEncryptionMethodEmbed alg = JWEEncryptionMethodEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoEncryptedResponseEncEmbed(alg); - } else if (name.equals("userInfoSignedResponseAlg")) { - JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoSignedResponseAlgEmbed(alg); - } else if (name.equals("defaultMaxAge")) { - client.setDefaultMaxAge(reader.nextInt()); - } else if (name.equals("requireAuthTime")) { - client.setRequireAuthTime(reader.nextBoolean()); - } else if (name.equals("defaultACRValues")) { - Set defaultACRvalues = readSet(reader); - client.setDefaultACRvalues(defaultACRvalues); - } else if (name.equals("initiateLoginUri")) { - client.setInitiateLoginUri(reader.nextString()); - } else if (name.equals("postLogoutRedirectUri")) { - HashSet postLogoutUris = Sets.newHashSet(reader.nextString()); - client.setPostLogoutRedirectUris(postLogoutUris); - } else if (name.equals("requestUris")) { - Set requestUris = readSet(reader); - client.setRequestUris(requestUris); - } else if (name.equals("description")) { - client.setClientDescription(reader.nextString()); - } else if (name.equals("allowIntrospection")) { - client.setAllowIntrospection(reader.nextBoolean()); - } else if (name.equals("reuseRefreshToken")) { - client.setReuseRefreshToken(reader.nextBoolean()); - } else if (name.equals("dynamicallyRegistered")) { - client.setDynamicallyRegistered(reader.nextBoolean()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - clientRepository.saveClient(client); - } - reader.endArray(); - logger.info("Done reading clients"); - } + /** + * @param reader + * @throws IOException + */ + private void readClients(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + ClientDetailsEntity client = new ClientDetailsEntity(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("clientId")) { + client.setClientId(reader.nextString()); + } else if (name.equals("resourceIds")) { + Set resourceIds = readSet(reader); + client.setResourceIds(resourceIds); + } else if (name.equals("secret")) { + client.setClientSecret(reader.nextString()); + } else if (name.equals("scope")) { + Set scope = readSet(reader); + client.setScope(scope); + } else if (name.equals("authorities")) { + Set authorityStrs = readSet(reader); + Set authorities = new HashSet(); + for (String s : authorityStrs) { + GrantedAuthority ga = new SimpleGrantedAuthority(s); + authorities.add(ga); + } + client.setAuthorities(authorities); + } else if (name.equals("accessTokenValiditySeconds")) { + client.setAccessTokenValiditySeconds(reader.nextInt()); + } else if (name.equals("refreshTokenValiditySeconds")) { + client.setRefreshTokenValiditySeconds(reader.nextInt()); + } else if (name.equals("redirectUris")) { + Set redirectUris = readSet(reader); + client.setRedirectUris(redirectUris); + } else if (name.equals("name")) { + client.setClientName(reader.nextString()); + } else if (name.equals("uri")) { + client.setClientUri(reader.nextString()); + } else if (name.equals("logoUri")) { + client.setLogoUri(reader.nextString()); + } else if (name.equals("contacts")) { + Set contacts = readSet(reader); + client.setContacts(contacts); + } else if (name.equals("tosUri")) { + client.setTosUri(reader.nextString()); + } else if (name.equals("tokenEndpointAuthMethod")) { + AuthMethod am = AuthMethod.getByValue(reader.nextString()); + client.setTokenEndpointAuthMethod(am); + } else if (name.equals("grantTypes")) { + Set grantTypes = readSet(reader); + client.setGrantTypes(grantTypes); + } else if (name.equals("responseTypes")) { + Set responseTypes = readSet(reader); + client.setResponseTypes(responseTypes); + } else if (name.equals("policyUri")) { + client.setPolicyUri(reader.nextString()); + } else if (name.equals("applicationType")) { + AppType appType = AppType.getByValue(reader.nextString()); + client.setApplicationType(appType); + } else if (name.equals("sectorIdentifierUri")) { + client.setSectorIdentifierUri(reader.nextString()); + } else if (name.equals("subjectType")) { + SubjectType st = SubjectType.getByValue(reader.nextString()); + client.setSubjectType(st); + } else if (name.equals("requestObjectSigningAlg")) { + JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setRequestObjectSigningAlgEmbed(alg); + } else if (name.equals("userInfoEncryptedResponseAlg")) { + JWEAlgorithmEmbed alg = JWEAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoEncryptedResponseAlgEmbed(alg); + } else if (name.equals("userInfoEncryptedResponseEnc")) { + JWEEncryptionMethodEmbed alg = JWEEncryptionMethodEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoEncryptedResponseEncEmbed(alg); + } else if (name.equals("userInfoSignedResponseAlg")) { + JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoSignedResponseAlgEmbed(alg); + } else if (name.equals("defaultMaxAge")) { + client.setDefaultMaxAge(reader.nextInt()); + } else if (name.equals("requireAuthTime")) { + client.setRequireAuthTime(reader.nextBoolean()); + } else if (name.equals("defaultACRValues")) { + Set defaultACRvalues = readSet(reader); + client.setDefaultACRvalues(defaultACRvalues); + } else if (name.equals("initiateLoginUri")) { + client.setInitiateLoginUri(reader.nextString()); + } else if (name.equals("postLogoutRedirectUri")) { + HashSet postLogoutUris = Sets.newHashSet(reader.nextString()); + client.setPostLogoutRedirectUris(postLogoutUris); + } else if (name.equals("requestUris")) { + Set requestUris = readSet(reader); + client.setRequestUris(requestUris); + } else if (name.equals("description")) { + client.setClientDescription(reader.nextString()); + } else if (name.equals("allowIntrospection")) { + client.setAllowIntrospection(reader.nextBoolean()); + } else if (name.equals("reuseRefreshToken")) { + client.setReuseRefreshToken(reader.nextBoolean()); + } else if (name.equals("dynamicallyRegistered")) { + client.setDynamicallyRegistered(reader.nextBoolean()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + clientRepository.saveClient(client); + } + reader.endArray(); + logger.info("Done reading clients"); + } - /** - * Read the list of system scopes from the reader and insert them into the - * scope repository. - * - * @param reader - * @throws IOException - */ - private void readSystemScopes(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - SystemScope scope = new SystemScope(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("value")) { - scope.setValue(reader.nextString()); - } else if (name.equals("description")) { - scope.setDescription(reader.nextString()); - } else if (name.equals("allowDynReg")) { - scope.setAllowDynReg(reader.nextBoolean()); - } else if (name.equals("defaultScope")) { - scope.setDefaultScope(reader.nextBoolean()); - } else if (name.equals("icon")) { - scope.setIcon(reader.nextString()); - } else { - logger.debug("found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - sysScopeRepository.save(scope); - } - reader.endArray(); - logger.info("Done reading system scopes"); - } + /** + * Read the list of system scopes from the reader and insert them into the + * scope repository. + * + * @param reader + * @throws IOException + */ + private void readSystemScopes(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + SystemScope scope = new SystemScope(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("value")) { + scope.setValue(reader.nextString()); + } else if (name.equals("description")) { + scope.setDescription(reader.nextString()); + } else if (name.equals("allowDynReg")) { + scope.setAllowDynReg(reader.nextBoolean()); + } else if (name.equals("defaultScope")) { + scope.setDefaultScope(reader.nextBoolean()); + } else if (name.equals("icon")) { + scope.setIcon(reader.nextString()); + } else { + logger.debug("found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + sysScopeRepository.save(scope); + } + reader.endArray(); + logger.info("Done reading system scopes"); + } - private void fixObjectReferences() { - for (Long oldRefreshTokenId : refreshTokenToClientRefs.keySet()) { - String clientRef = refreshTokenToClientRefs.get(oldRefreshTokenId); - ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - refreshToken.setClient(client); - tokenRepository.saveRefreshToken(refreshToken); - } - refreshTokenToClientRefs.clear(); - for (Long oldRefreshTokenId : refreshTokenToAuthHolderRefs.keySet()) { - Long oldAuthHolderId = refreshTokenToAuthHolderRefs.get(oldRefreshTokenId); - Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); - AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - refreshToken.setAuthenticationHolder(authHolder); - tokenRepository.saveRefreshToken(refreshToken); - } - refreshTokenToAuthHolderRefs.clear(); - for (Long oldAccessTokenId : accessTokenToClientRefs.keySet()) { - String clientRef = accessTokenToClientRefs.get(oldAccessTokenId); - ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setClient(client); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToClientRefs.clear(); - for (Long oldAccessTokenId : accessTokenToAuthHolderRefs.keySet()) { - Long oldAuthHolderId = accessTokenToAuthHolderRefs.get(oldAccessTokenId); - Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); - AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setAuthenticationHolder(authHolder); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToAuthHolderRefs.clear(); - for (Long oldAccessTokenId : accessTokenToRefreshTokenRefs.keySet()) { - Long oldRefreshTokenId = accessTokenToRefreshTokenRefs.get(oldAccessTokenId); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setRefreshToken(refreshToken); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToRefreshTokenRefs.clear(); - refreshTokenOldToNewIdMap.clear(); - for (Long oldAccessTokenId : accessTokenToIdTokenRefs.keySet()) { - Long oldIdTokenId = accessTokenToIdTokenRefs.get(oldAccessTokenId); - Long newIdTokenId = accessTokenOldToNewIdMap.get(oldIdTokenId); - OAuth2AccessTokenEntity idToken = tokenRepository.getAccessTokenById(newIdTokenId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setIdToken(idToken); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToIdTokenRefs.clear(); - for (Long oldGrantId : grantToWhitelistedSiteRefs.keySet()) { - Long oldWhitelistedSiteId = grantToWhitelistedSiteRefs.get(oldGrantId); - Long newWhitelistedSiteId = whitelistedSiteOldToNewIdMap.get(oldWhitelistedSiteId); - WhitelistedSite wlSite = wlSiteRepository.getById(newWhitelistedSiteId); - Long newGrantId = grantOldToNewIdMap.get(oldGrantId); - ApprovedSite approvedSite = approvedSiteRepository.getById(newGrantId); - approvedSite.setWhitelistedSite(wlSite); - approvedSiteRepository.save(approvedSite); - } - grantToWhitelistedSiteRefs.clear(); - whitelistedSiteOldToNewIdMap.clear(); - for (Long oldGrantId : grantToAccessTokensRefs.keySet()) { - Set oldAccessTokenIds = grantToAccessTokensRefs.get(oldGrantId); - Set tokens = new HashSet(); - for(Long oldTokenId : oldAccessTokenIds) { - Long newTokenId = accessTokenOldToNewIdMap.get(oldTokenId); - tokens.add(tokenRepository.getAccessTokenById(newTokenId)); - } - Long newGrantId = grantOldToNewIdMap.get(oldGrantId); - ApprovedSite site = approvedSiteRepository.getById(newGrantId); - site.setApprovedAccessTokens(tokens); - approvedSiteRepository.save(site); - } - accessTokenOldToNewIdMap.clear(); - grantOldToNewIdMap.clear(); - } + private void fixObjectReferences() { + for (Long oldRefreshTokenId : refreshTokenToClientRefs.keySet()) { + String clientRef = refreshTokenToClientRefs.get(oldRefreshTokenId); + ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + refreshToken.setClient(client); + tokenRepository.saveRefreshToken(refreshToken); + } + refreshTokenToClientRefs.clear(); + for (Long oldRefreshTokenId : refreshTokenToAuthHolderRefs.keySet()) { + Long oldAuthHolderId = refreshTokenToAuthHolderRefs.get(oldRefreshTokenId); + Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); + AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + refreshToken.setAuthenticationHolder(authHolder); + tokenRepository.saveRefreshToken(refreshToken); + } + refreshTokenToAuthHolderRefs.clear(); + for (Long oldAccessTokenId : accessTokenToClientRefs.keySet()) { + String clientRef = accessTokenToClientRefs.get(oldAccessTokenId); + ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setClient(client); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToClientRefs.clear(); + for (Long oldAccessTokenId : accessTokenToAuthHolderRefs.keySet()) { + Long oldAuthHolderId = accessTokenToAuthHolderRefs.get(oldAccessTokenId); + Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); + AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setAuthenticationHolder(authHolder); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToAuthHolderRefs.clear(); + for (Long oldAccessTokenId : accessTokenToRefreshTokenRefs.keySet()) { + Long oldRefreshTokenId = accessTokenToRefreshTokenRefs.get(oldAccessTokenId); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setRefreshToken(refreshToken); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToRefreshTokenRefs.clear(); + refreshTokenOldToNewIdMap.clear(); + for (Long oldAccessTokenId : accessTokenToIdTokenRefs.keySet()) { + Long oldIdTokenId = accessTokenToIdTokenRefs.get(oldAccessTokenId); + Long newIdTokenId = accessTokenOldToNewIdMap.get(oldIdTokenId); + OAuth2AccessTokenEntity idToken = tokenRepository.getAccessTokenById(newIdTokenId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setIdToken(idToken); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToIdTokenRefs.clear(); + for (Long oldGrantId : grantToWhitelistedSiteRefs.keySet()) { + Long oldWhitelistedSiteId = grantToWhitelistedSiteRefs.get(oldGrantId); + Long newWhitelistedSiteId = whitelistedSiteOldToNewIdMap.get(oldWhitelistedSiteId); + WhitelistedSite wlSite = wlSiteRepository.getById(newWhitelistedSiteId); + Long newGrantId = grantOldToNewIdMap.get(oldGrantId); + ApprovedSite approvedSite = approvedSiteRepository.getById(newGrantId); + approvedSite.setWhitelistedSite(wlSite); + approvedSiteRepository.save(approvedSite); + } + grantToWhitelistedSiteRefs.clear(); + whitelistedSiteOldToNewIdMap.clear(); + for (Long oldGrantId : grantToAccessTokensRefs.keySet()) { + Set oldAccessTokenIds = grantToAccessTokensRefs.get(oldGrantId); + Set tokens = new HashSet(); + for(Long oldTokenId : oldAccessTokenIds) { + Long newTokenId = accessTokenOldToNewIdMap.get(oldTokenId); + tokens.add(tokenRepository.getAccessTokenById(newTokenId)); + } + Long newGrantId = grantOldToNewIdMap.get(oldGrantId); + ApprovedSite site = approvedSiteRepository.getById(newGrantId); + site.setApprovedAccessTokens(tokens); + approvedSiteRepository.save(site); + } + accessTokenOldToNewIdMap.clear(); + grantOldToNewIdMap.clear(); + } } diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_1.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_1.java index 1445b0f96..a60d9fb94 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_1.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_1.java @@ -75,779 +75,779 @@ import com.google.gson.stream.JsonWriter; @Service public class MITREidDataService_1_1 extends MITREidDataService_1_X { - private final static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_1.class); - @Autowired - private OAuth2ClientRepository clientRepository; - @Autowired - private ApprovedSiteRepository approvedSiteRepository; - @Autowired - private WhitelistedSiteRepository wlSiteRepository; - @Autowired - private BlacklistedSiteRepository blSiteRepository; - @Autowired - private AuthenticationHolderRepository authHolderRepository; - @Autowired - private OAuth2TokenRepository tokenRepository; - @Autowired - private SystemScopeRepository sysScopeRepository; + private final static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_1.class); + @Autowired + private OAuth2ClientRepository clientRepository; + @Autowired + private ApprovedSiteRepository approvedSiteRepository; + @Autowired + private WhitelistedSiteRepository wlSiteRepository; + @Autowired + private BlacklistedSiteRepository blSiteRepository; + @Autowired + private AuthenticationHolderRepository authHolderRepository; + @Autowired + private OAuth2TokenRepository tokenRepository; + @Autowired + private SystemScopeRepository sysScopeRepository; - /* (non-Javadoc) - * @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter) - */ - @Override - public void exportData(JsonWriter writer) throws IOException { - throw new UnsupportedOperationException("Can not export 1.1 format from this version."); - } + /* (non-Javadoc) + * @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter) + */ + @Override + public void exportData(JsonWriter writer) throws IOException { + throw new UnsupportedOperationException("Can not export 1.1 format from this version."); + } - /* (non-Javadoc) - * @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader) - */ - @Override - public void importData(JsonReader reader) throws IOException { + /* (non-Javadoc) + * @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader) + */ + @Override + public void importData(JsonReader reader) throws IOException { - logger.info("Reading configuration for 1.0"); + logger.info("Reading configuration for 1.0"); - // this *HAS* to start as an object - reader.beginObject(); + // this *HAS* to start as an object + reader.beginObject(); - while (reader.hasNext()) { - JsonToken tok = reader.peek(); - switch (tok) { - case NAME: - String name = reader.nextName(); - // find out which member it is - if (name.equals(CLIENTS)) { - readClients(reader); - } else if (name.equals(GRANTS)) { - readGrants(reader); - } else if (name.equals(WHITELISTEDSITES)) { - readWhitelistedSites(reader); - } else if (name.equals(BLACKLISTEDSITES)) { - readBlacklistedSites(reader); - } else if (name.equals(AUTHENTICATIONHOLDERS)) { - readAuthenticationHolders(reader); - } else if (name.equals(ACCESSTOKENS)) { - readAccessTokens(reader); - } else if (name.equals(REFRESHTOKENS)) { - readRefreshTokens(reader); - } else if (name.equals(SYSTEMSCOPES)) { - readSystemScopes(reader); - } else { - // unknown token, skip it - reader.skipValue(); - } - break; - case END_OBJECT: - // the object ended, we're done here - reader.endObject(); - continue; - } - } - fixObjectReferences(); - } - private Map refreshTokenToClientRefs = new HashMap(); - private Map refreshTokenToAuthHolderRefs = new HashMap(); - private Map refreshTokenOldToNewIdMap = new HashMap(); + while (reader.hasNext()) { + JsonToken tok = reader.peek(); + switch (tok) { + case NAME: + String name = reader.nextName(); + // find out which member it is + if (name.equals(CLIENTS)) { + readClients(reader); + } else if (name.equals(GRANTS)) { + readGrants(reader); + } else if (name.equals(WHITELISTEDSITES)) { + readWhitelistedSites(reader); + } else if (name.equals(BLACKLISTEDSITES)) { + readBlacklistedSites(reader); + } else if (name.equals(AUTHENTICATIONHOLDERS)) { + readAuthenticationHolders(reader); + } else if (name.equals(ACCESSTOKENS)) { + readAccessTokens(reader); + } else if (name.equals(REFRESHTOKENS)) { + readRefreshTokens(reader); + } else if (name.equals(SYSTEMSCOPES)) { + readSystemScopes(reader); + } else { + // unknown token, skip it + reader.skipValue(); + } + break; + case END_OBJECT: + // the object ended, we're done here + reader.endObject(); + continue; + } + } + fixObjectReferences(); + } + private Map refreshTokenToClientRefs = new HashMap(); + private Map refreshTokenToAuthHolderRefs = new HashMap(); + private Map refreshTokenOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - /** - * @param reader - * @throws IOException - */ - private void readRefreshTokens(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity(); - reader.beginObject(); - Long currentId = null; - String clientId = null; - Long authHolderId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("expiration")) { - Date date = DateUtil.utcToDate(reader.nextString()); - token.setExpiration(date); - } else if (name.equals("value")) { - String value = reader.nextString(); - try { - token.setValue(value); - } catch (ParseException ex) { - logger.error("Unable to set refresh token value to {}", value, ex); - } - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("authenticationHolderId")) { - authHolderId = reader.nextLong(); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = tokenRepository.saveRefreshToken(token).getId(); - refreshTokenToClientRefs.put(currentId, clientId); - refreshTokenToAuthHolderRefs.put(currentId, authHolderId); - refreshTokenOldToNewIdMap.put(currentId, newId); - logger.debug("Read refresh token {}", currentId); - } - reader.endArray(); - logger.info("Done reading refresh tokens"); - } - private Map accessTokenToClientRefs = new HashMap(); - private Map accessTokenToAuthHolderRefs = new HashMap(); - private Map accessTokenToRefreshTokenRefs = new HashMap(); - private Map accessTokenToIdTokenRefs = new HashMap(); - private Map accessTokenOldToNewIdMap = new HashMap(); + /** + * @param reader + * @throws IOException + */ + /** + * @param reader + * @throws IOException + */ + private void readRefreshTokens(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity(); + reader.beginObject(); + Long currentId = null; + String clientId = null; + Long authHolderId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("expiration")) { + Date date = DateUtil.utcToDate(reader.nextString()); + token.setExpiration(date); + } else if (name.equals("value")) { + String value = reader.nextString(); + try { + token.setValue(value); + } catch (ParseException ex) { + logger.error("Unable to set refresh token value to {}", value, ex); + } + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("authenticationHolderId")) { + authHolderId = reader.nextLong(); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = tokenRepository.saveRefreshToken(token).getId(); + refreshTokenToClientRefs.put(currentId, clientId); + refreshTokenToAuthHolderRefs.put(currentId, authHolderId); + refreshTokenOldToNewIdMap.put(currentId, newId); + logger.debug("Read refresh token {}", currentId); + } + reader.endArray(); + logger.info("Done reading refresh tokens"); + } + private Map accessTokenToClientRefs = new HashMap(); + private Map accessTokenToAuthHolderRefs = new HashMap(); + private Map accessTokenToRefreshTokenRefs = new HashMap(); + private Map accessTokenToIdTokenRefs = new HashMap(); + private Map accessTokenOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - /** - * @param reader - * @throws IOException - */ - private void readAccessTokens(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity(); - reader.beginObject(); - Long currentId = null; - String clientId = null; - Long authHolderId = null; - Long refreshTokenId = null; - Long idTokenId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("expiration")) { - Date date = DateUtil.utcToDate(reader.nextString()); - token.setExpiration(date); - } else if (name.equals("value")) { - String value = reader.nextString(); - try { - token.setValue(value); - } catch (ParseException ex) { - logger.error("Unable to set refresh token value to {}", value, ex); - } - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("authenticationHolderId")) { - authHolderId = reader.nextLong(); - } else if (name.equals("refreshTokenId")) { - refreshTokenId = reader.nextLong(); - } else if (name.equals("idTokenId")) { - idTokenId = reader.nextLong(); - } else if (name.equals("scope")) { - Set scope = readSet(reader); - token.setScope(scope); - } else if (name.equals("type")) { - token.setTokenType(reader.nextString()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = tokenRepository.saveAccessToken(token).getId(); - accessTokenToClientRefs.put(currentId, clientId); - accessTokenToAuthHolderRefs.put(currentId, authHolderId); - if (refreshTokenId != null) { - accessTokenToRefreshTokenRefs.put(currentId, refreshTokenId); - } - if (idTokenId != null) { - accessTokenToIdTokenRefs.put(currentId, idTokenId); - } - accessTokenOldToNewIdMap.put(currentId, newId); - logger.debug("Read access token {}", currentId); - } - reader.endArray(); - logger.info("Done reading access tokens"); - } - private Map authHolderOldToNewIdMap = new HashMap(); + /** + * @param reader + * @throws IOException + */ + /** + * @param reader + * @throws IOException + */ + private void readAccessTokens(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity(); + reader.beginObject(); + Long currentId = null; + String clientId = null; + Long authHolderId = null; + Long refreshTokenId = null; + Long idTokenId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("expiration")) { + Date date = DateUtil.utcToDate(reader.nextString()); + token.setExpiration(date); + } else if (name.equals("value")) { + String value = reader.nextString(); + try { + token.setValue(value); + } catch (ParseException ex) { + logger.error("Unable to set refresh token value to {}", value, ex); + } + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("authenticationHolderId")) { + authHolderId = reader.nextLong(); + } else if (name.equals("refreshTokenId")) { + refreshTokenId = reader.nextLong(); + } else if (name.equals("idTokenId")) { + idTokenId = reader.nextLong(); + } else if (name.equals("scope")) { + Set scope = readSet(reader); + token.setScope(scope); + } else if (name.equals("type")) { + token.setTokenType(reader.nextString()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = tokenRepository.saveAccessToken(token).getId(); + accessTokenToClientRefs.put(currentId, clientId); + accessTokenToAuthHolderRefs.put(currentId, authHolderId); + if (refreshTokenId != null) { + accessTokenToRefreshTokenRefs.put(currentId, refreshTokenId); + } + if (idTokenId != null) { + accessTokenToIdTokenRefs.put(currentId, idTokenId); + } + accessTokenOldToNewIdMap.put(currentId, newId); + logger.debug("Read access token {}", currentId); + } + reader.endArray(); + logger.info("Done reading access tokens"); + } + private Map authHolderOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - private void readAuthenticationHolders(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - AuthenticationHolderEntity ahe = new AuthenticationHolderEntity(); - reader.beginObject(); - Long currentId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("ownerId")) { - //not needed - reader.skipValue(); - } else if (name.equals("authentication")) { - OAuth2Request clientAuthorization = null; - Authentication userAuthentication = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String subName = reader.nextName(); - if (subName.equals("clientAuthorization")) { - clientAuthorization = readAuthorizationRequest(reader); - } else if (subName.equals("userAuthentication")) { - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else { - String authString = reader.nextString(); - userAuthentication = base64UrlDecodeObject(authString, Authentication.class); - } - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - OAuth2Authentication auth = new OAuth2Authentication(clientAuthorization, userAuthentication); - ahe.setAuthentication(auth); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = authHolderRepository.save(ahe).getId(); - authHolderOldToNewIdMap.put(currentId, newId); - logger.debug("Read authentication holder {}", currentId); - } - reader.endArray(); - logger.info("Done reading authentication holders"); - } + /** + * @param reader + * @throws IOException + */ + private void readAuthenticationHolders(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + AuthenticationHolderEntity ahe = new AuthenticationHolderEntity(); + reader.beginObject(); + Long currentId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("ownerId")) { + //not needed + reader.skipValue(); + } else if (name.equals("authentication")) { + OAuth2Request clientAuthorization = null; + Authentication userAuthentication = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String subName = reader.nextName(); + if (subName.equals("clientAuthorization")) { + clientAuthorization = readAuthorizationRequest(reader); + } else if (subName.equals("userAuthentication")) { + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else { + String authString = reader.nextString(); + userAuthentication = base64UrlDecodeObject(authString, Authentication.class); + } + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + OAuth2Authentication auth = new OAuth2Authentication(clientAuthorization, userAuthentication); + ahe.setAuthentication(auth); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = authHolderRepository.save(ahe).getId(); + authHolderOldToNewIdMap.put(currentId, newId); + logger.debug("Read authentication holder {}", currentId); + } + reader.endArray(); + logger.info("Done reading authentication holders"); + } - //used by readAuthenticationHolders - private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException { - Set scope = new LinkedHashSet(); - Set resourceIds = new HashSet(); - boolean approved = false; - Collection authorities = new HashSet(); - Map requestParameters = new HashMap(); - Set responseTypes = new HashSet(); - Map extensions = new HashMap(); - String redirectUri = null; - String clientId = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("requestParameters")) { - requestParameters = readMap(reader); - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("scope")) { - scope = readSet(reader); - } else if (name.equals("resourceIds")) { - resourceIds = readSet(reader); - } else if (name.equals("authorities")) { - Set authorityStrs = readSet(reader); - authorities = new HashSet(); - for (String s : authorityStrs) { - GrantedAuthority ga = new SimpleGrantedAuthority(s); - authorities.add(ga); - } - } else if (name.equals("approved")) { - approved = reader.nextBoolean(); - } else if (name.equals("denied")) { - if (approved == false) { - approved = !reader.nextBoolean(); - } - } else if (name.equals("redirectUri")) { - redirectUri = reader.nextString(); - } else if (name.equals("responseTypes")) { - responseTypes = readSet(reader); - } else if (name.equals("extensions")) { - Map extEnc = readMap(reader); - for (Entry entry : extEnc.entrySet()) { - Serializable decoded = base64UrlDecodeObject(entry.getValue(), Serializable.class); - if (decoded != null) { - extensions.put(entry.getKey(), decoded); - } - } - } else { - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - return new OAuth2Request(requestParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, extensions); - } - Map grantOldToNewIdMap = new HashMap(); - Map grantToWhitelistedSiteRefs = new HashMap(); - Map> grantToAccessTokensRefs = new HashMap>(); - /** - * @param reader - * @throws IOException - */ - private void readGrants(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - ApprovedSite site = new ApprovedSite(); - Long currentId = null; - Long whitelistedSiteId = null; - Set tokenIds = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("accessDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setAccessDate(date); - } else if (name.equals("clientId")) { - site.setClientId(reader.nextString()); - } else if (name.equals("creationDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setCreationDate(date); - } else if (name.equals("timeoutDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setTimeoutDate(date); - } else if (name.equals("userId")) { - site.setUserId(reader.nextString()); - } else if (name.equals("allowedScopes")) { - Set allowedScopes = readSet(reader); - site.setAllowedScopes(allowedScopes); - } else if (name.equals("whitelistedSiteId")) { - whitelistedSiteId = reader.nextLong(); - } else if (name.equals("approvedAccessTokens")) { - tokenIds = readSet(reader); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = approvedSiteRepository.save(site).getId(); - grantOldToNewIdMap.put(currentId, newId); - if (whitelistedSiteId != null) { - grantToWhitelistedSiteRefs.put(currentId, whitelistedSiteId); - } - if (tokenIds != null) { - grantToAccessTokensRefs.put(currentId, tokenIds); - } - logger.debug("Read grant {}", currentId); - } - reader.endArray(); - logger.info("Done reading grants"); - } - Map whitelistedSiteOldToNewIdMap = new HashMap(); + //used by readAuthenticationHolders + private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException { + Set scope = new LinkedHashSet(); + Set resourceIds = new HashSet(); + boolean approved = false; + Collection authorities = new HashSet(); + Map requestParameters = new HashMap(); + Set responseTypes = new HashSet(); + Map extensions = new HashMap(); + String redirectUri = null; + String clientId = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("requestParameters")) { + requestParameters = readMap(reader); + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("scope")) { + scope = readSet(reader); + } else if (name.equals("resourceIds")) { + resourceIds = readSet(reader); + } else if (name.equals("authorities")) { + Set authorityStrs = readSet(reader); + authorities = new HashSet(); + for (String s : authorityStrs) { + GrantedAuthority ga = new SimpleGrantedAuthority(s); + authorities.add(ga); + } + } else if (name.equals("approved")) { + approved = reader.nextBoolean(); + } else if (name.equals("denied")) { + if (approved == false) { + approved = !reader.nextBoolean(); + } + } else if (name.equals("redirectUri")) { + redirectUri = reader.nextString(); + } else if (name.equals("responseTypes")) { + responseTypes = readSet(reader); + } else if (name.equals("extensions")) { + Map extEnc = readMap(reader); + for (Entry entry : extEnc.entrySet()) { + Serializable decoded = base64UrlDecodeObject(entry.getValue(), Serializable.class); + if (decoded != null) { + extensions.put(entry.getKey(), decoded); + } + } + } else { + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + return new OAuth2Request(requestParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, extensions); + } + Map grantOldToNewIdMap = new HashMap(); + Map grantToWhitelistedSiteRefs = new HashMap(); + Map> grantToAccessTokensRefs = new HashMap>(); + /** + * @param reader + * @throws IOException + */ + private void readGrants(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + ApprovedSite site = new ApprovedSite(); + Long currentId = null; + Long whitelistedSiteId = null; + Set tokenIds = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("accessDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setAccessDate(date); + } else if (name.equals("clientId")) { + site.setClientId(reader.nextString()); + } else if (name.equals("creationDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setCreationDate(date); + } else if (name.equals("timeoutDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setTimeoutDate(date); + } else if (name.equals("userId")) { + site.setUserId(reader.nextString()); + } else if (name.equals("allowedScopes")) { + Set allowedScopes = readSet(reader); + site.setAllowedScopes(allowedScopes); + } else if (name.equals("whitelistedSiteId")) { + whitelistedSiteId = reader.nextLong(); + } else if (name.equals("approvedAccessTokens")) { + tokenIds = readSet(reader); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = approvedSiteRepository.save(site).getId(); + grantOldToNewIdMap.put(currentId, newId); + if (whitelistedSiteId != null) { + grantToWhitelistedSiteRefs.put(currentId, whitelistedSiteId); + } + if (tokenIds != null) { + grantToAccessTokensRefs.put(currentId, tokenIds); + } + logger.debug("Read grant {}", currentId); + } + reader.endArray(); + logger.info("Done reading grants"); + } + Map whitelistedSiteOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - private void readWhitelistedSites(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - WhitelistedSite wlSite = new WhitelistedSite(); - Long currentId = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("clientId")) { - wlSite.setClientId(reader.nextString()); - } else if (name.equals("creatorUserId")) { - wlSite.setCreatorUserId(reader.nextString()); - } else if (name.equals("allowedScopes")) { - Set allowedScopes = readSet(reader); - wlSite.setAllowedScopes(allowedScopes); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = wlSiteRepository.save(wlSite).getId(); - whitelistedSiteOldToNewIdMap.put(currentId, newId); - } - reader.endArray(); - logger.info("Done reading whitelisted sites"); - } + /** + * @param reader + * @throws IOException + */ + private void readWhitelistedSites(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + WhitelistedSite wlSite = new WhitelistedSite(); + Long currentId = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("clientId")) { + wlSite.setClientId(reader.nextString()); + } else if (name.equals("creatorUserId")) { + wlSite.setCreatorUserId(reader.nextString()); + } else if (name.equals("allowedScopes")) { + Set allowedScopes = readSet(reader); + wlSite.setAllowedScopes(allowedScopes); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = wlSiteRepository.save(wlSite).getId(); + whitelistedSiteOldToNewIdMap.put(currentId, newId); + } + reader.endArray(); + logger.info("Done reading whitelisted sites"); + } - /** - * @param reader - * @throws IOException - */ - private void readBlacklistedSites(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - BlacklistedSite blSite = new BlacklistedSite(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (name.equals("id")) { - reader.skipValue(); - } else if (name.equals("uri")) { - blSite.setUri(reader.nextString()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - blSiteRepository.save(blSite); - } - reader.endArray(); - logger.info("Done reading blacklisted sites"); - } + /** + * @param reader + * @throws IOException + */ + private void readBlacklistedSites(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + BlacklistedSite blSite = new BlacklistedSite(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (name.equals("id")) { + reader.skipValue(); + } else if (name.equals("uri")) { + blSite.setUri(reader.nextString()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + blSiteRepository.save(blSite); + } + reader.endArray(); + logger.info("Done reading blacklisted sites"); + } - /** - * @param reader - * @throws IOException - */ - private void readClients(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - ClientDetailsEntity client = new ClientDetailsEntity(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("clientId")) { - client.setClientId(reader.nextString()); - } else if (name.equals("resourceIds")) { - Set resourceIds = readSet(reader); - client.setResourceIds(resourceIds); - } else if (name.equals("secret")) { - client.setClientSecret(reader.nextString()); - } else if (name.equals("scope")) { - Set scope = readSet(reader); - client.setScope(scope); - } else if (name.equals("authorities")) { - Set authorityStrs = readSet(reader); - Set authorities = new HashSet(); - for (String s : authorityStrs) { - GrantedAuthority ga = new SimpleGrantedAuthority(s); - authorities.add(ga); - } - client.setAuthorities(authorities); - } else if (name.equals("accessTokenValiditySeconds")) { - client.setAccessTokenValiditySeconds(reader.nextInt()); - } else if (name.equals("refreshTokenValiditySeconds")) { - client.setRefreshTokenValiditySeconds(reader.nextInt()); - } else if (name.equals("redirectUris")) { - Set redirectUris = readSet(reader); - client.setRedirectUris(redirectUris); - } else if (name.equals("name")) { - client.setClientName(reader.nextString()); - } else if (name.equals("uri")) { - client.setClientUri(reader.nextString()); - } else if (name.equals("logoUri")) { - client.setLogoUri(reader.nextString()); - } else if (name.equals("contacts")) { - Set contacts = readSet(reader); - client.setContacts(contacts); - } else if (name.equals("tosUri")) { - client.setTosUri(reader.nextString()); - } else if (name.equals("tokenEndpointAuthMethod")) { - AuthMethod am = AuthMethod.getByValue(reader.nextString()); - client.setTokenEndpointAuthMethod(am); - } else if (name.equals("grantTypes")) { - Set grantTypes = readSet(reader); - client.setGrantTypes(grantTypes); - } else if (name.equals("responseTypes")) { - Set responseTypes = readSet(reader); - client.setResponseTypes(responseTypes); - } else if (name.equals("policyUri")) { - client.setPolicyUri(reader.nextString()); - } else if (name.equals("applicationType")) { - AppType appType = AppType.getByValue(reader.nextString()); - client.setApplicationType(appType); - } else if (name.equals("sectorIdentifierUri")) { - client.setSectorIdentifierUri(reader.nextString()); - } else if (name.equals("subjectType")) { - SubjectType st = SubjectType.getByValue(reader.nextString()); - client.setSubjectType(st); - } else if (name.equals("requestObjectSigningAlg")) { - JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setRequestObjectSigningAlgEmbed(alg); - } else if (name.equals("userInfoEncryptedResponseAlg")) { - JWEAlgorithmEmbed alg = JWEAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoEncryptedResponseAlgEmbed(alg); - } else if (name.equals("userInfoEncryptedResponseEnc")) { - JWEEncryptionMethodEmbed alg = JWEEncryptionMethodEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoEncryptedResponseEncEmbed(alg); - } else if (name.equals("userInfoSignedResponseAlg")) { - JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoSignedResponseAlgEmbed(alg); - } else if (name.equals("defaultMaxAge")) { - client.setDefaultMaxAge(reader.nextInt()); - } else if (name.equals("requireAuthTime")) { - client.setRequireAuthTime(reader.nextBoolean()); - } else if (name.equals("defaultACRValues")) { - Set defaultACRvalues = readSet(reader); - client.setDefaultACRvalues(defaultACRvalues); - } else if (name.equals("initiateLoginUri")) { - client.setInitiateLoginUri(reader.nextString()); - } else if (name.equals("postLogoutRedirectUri")) { - HashSet postLogoutUris = Sets.newHashSet(reader.nextString()); - client.setPostLogoutRedirectUris(postLogoutUris); - } else if (name.equals("requestUris")) { - Set requestUris = readSet(reader); - client.setRequestUris(requestUris); - } else if (name.equals("description")) { - client.setClientDescription(reader.nextString()); - } else if (name.equals("allowIntrospection")) { - client.setAllowIntrospection(reader.nextBoolean()); - } else if (name.equals("reuseRefreshToken")) { - client.setReuseRefreshToken(reader.nextBoolean()); - } else if (name.equals("dynamicallyRegistered")) { - client.setDynamicallyRegistered(reader.nextBoolean()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - clientRepository.saveClient(client); - } - reader.endArray(); - logger.info("Done reading clients"); - } + /** + * @param reader + * @throws IOException + */ + private void readClients(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + ClientDetailsEntity client = new ClientDetailsEntity(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("clientId")) { + client.setClientId(reader.nextString()); + } else if (name.equals("resourceIds")) { + Set resourceIds = readSet(reader); + client.setResourceIds(resourceIds); + } else if (name.equals("secret")) { + client.setClientSecret(reader.nextString()); + } else if (name.equals("scope")) { + Set scope = readSet(reader); + client.setScope(scope); + } else if (name.equals("authorities")) { + Set authorityStrs = readSet(reader); + Set authorities = new HashSet(); + for (String s : authorityStrs) { + GrantedAuthority ga = new SimpleGrantedAuthority(s); + authorities.add(ga); + } + client.setAuthorities(authorities); + } else if (name.equals("accessTokenValiditySeconds")) { + client.setAccessTokenValiditySeconds(reader.nextInt()); + } else if (name.equals("refreshTokenValiditySeconds")) { + client.setRefreshTokenValiditySeconds(reader.nextInt()); + } else if (name.equals("redirectUris")) { + Set redirectUris = readSet(reader); + client.setRedirectUris(redirectUris); + } else if (name.equals("name")) { + client.setClientName(reader.nextString()); + } else if (name.equals("uri")) { + client.setClientUri(reader.nextString()); + } else if (name.equals("logoUri")) { + client.setLogoUri(reader.nextString()); + } else if (name.equals("contacts")) { + Set contacts = readSet(reader); + client.setContacts(contacts); + } else if (name.equals("tosUri")) { + client.setTosUri(reader.nextString()); + } else if (name.equals("tokenEndpointAuthMethod")) { + AuthMethod am = AuthMethod.getByValue(reader.nextString()); + client.setTokenEndpointAuthMethod(am); + } else if (name.equals("grantTypes")) { + Set grantTypes = readSet(reader); + client.setGrantTypes(grantTypes); + } else if (name.equals("responseTypes")) { + Set responseTypes = readSet(reader); + client.setResponseTypes(responseTypes); + } else if (name.equals("policyUri")) { + client.setPolicyUri(reader.nextString()); + } else if (name.equals("applicationType")) { + AppType appType = AppType.getByValue(reader.nextString()); + client.setApplicationType(appType); + } else if (name.equals("sectorIdentifierUri")) { + client.setSectorIdentifierUri(reader.nextString()); + } else if (name.equals("subjectType")) { + SubjectType st = SubjectType.getByValue(reader.nextString()); + client.setSubjectType(st); + } else if (name.equals("requestObjectSigningAlg")) { + JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setRequestObjectSigningAlgEmbed(alg); + } else if (name.equals("userInfoEncryptedResponseAlg")) { + JWEAlgorithmEmbed alg = JWEAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoEncryptedResponseAlgEmbed(alg); + } else if (name.equals("userInfoEncryptedResponseEnc")) { + JWEEncryptionMethodEmbed alg = JWEEncryptionMethodEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoEncryptedResponseEncEmbed(alg); + } else if (name.equals("userInfoSignedResponseAlg")) { + JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoSignedResponseAlgEmbed(alg); + } else if (name.equals("defaultMaxAge")) { + client.setDefaultMaxAge(reader.nextInt()); + } else if (name.equals("requireAuthTime")) { + client.setRequireAuthTime(reader.nextBoolean()); + } else if (name.equals("defaultACRValues")) { + Set defaultACRvalues = readSet(reader); + client.setDefaultACRvalues(defaultACRvalues); + } else if (name.equals("initiateLoginUri")) { + client.setInitiateLoginUri(reader.nextString()); + } else if (name.equals("postLogoutRedirectUri")) { + HashSet postLogoutUris = Sets.newHashSet(reader.nextString()); + client.setPostLogoutRedirectUris(postLogoutUris); + } else if (name.equals("requestUris")) { + Set requestUris = readSet(reader); + client.setRequestUris(requestUris); + } else if (name.equals("description")) { + client.setClientDescription(reader.nextString()); + } else if (name.equals("allowIntrospection")) { + client.setAllowIntrospection(reader.nextBoolean()); + } else if (name.equals("reuseRefreshToken")) { + client.setReuseRefreshToken(reader.nextBoolean()); + } else if (name.equals("dynamicallyRegistered")) { + client.setDynamicallyRegistered(reader.nextBoolean()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + clientRepository.saveClient(client); + } + reader.endArray(); + logger.info("Done reading clients"); + } - /** - * Read the list of system scopes from the reader and insert them into the - * scope repository. - * - * @param reader - * @throws IOException - */ - private void readSystemScopes(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - SystemScope scope = new SystemScope(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("value")) { - scope.setValue(reader.nextString()); - } else if (name.equals("description")) { - scope.setDescription(reader.nextString()); - } else if (name.equals("allowDynReg")) { - scope.setAllowDynReg(reader.nextBoolean()); - } else if (name.equals("defaultScope")) { - scope.setDefaultScope(reader.nextBoolean()); - } else if (name.equals("icon")) { - scope.setIcon(reader.nextString()); - } else { - logger.debug("found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - sysScopeRepository.save(scope); - } - reader.endArray(); - logger.info("Done reading system scopes"); - } + /** + * Read the list of system scopes from the reader and insert them into the + * scope repository. + * + * @param reader + * @throws IOException + */ + private void readSystemScopes(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + SystemScope scope = new SystemScope(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("value")) { + scope.setValue(reader.nextString()); + } else if (name.equals("description")) { + scope.setDescription(reader.nextString()); + } else if (name.equals("allowDynReg")) { + scope.setAllowDynReg(reader.nextBoolean()); + } else if (name.equals("defaultScope")) { + scope.setDefaultScope(reader.nextBoolean()); + } else if (name.equals("icon")) { + scope.setIcon(reader.nextString()); + } else { + logger.debug("found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + sysScopeRepository.save(scope); + } + reader.endArray(); + logger.info("Done reading system scopes"); + } - private void fixObjectReferences() { - for (Long oldRefreshTokenId : refreshTokenToClientRefs.keySet()) { - String clientRef = refreshTokenToClientRefs.get(oldRefreshTokenId); - ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - refreshToken.setClient(client); - tokenRepository.saveRefreshToken(refreshToken); - } - refreshTokenToClientRefs.clear(); - for (Long oldRefreshTokenId : refreshTokenToAuthHolderRefs.keySet()) { - Long oldAuthHolderId = refreshTokenToAuthHolderRefs.get(oldRefreshTokenId); - Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); - AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - refreshToken.setAuthenticationHolder(authHolder); - tokenRepository.saveRefreshToken(refreshToken); - } - refreshTokenToAuthHolderRefs.clear(); - for (Long oldAccessTokenId : accessTokenToClientRefs.keySet()) { - String clientRef = accessTokenToClientRefs.get(oldAccessTokenId); - ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setClient(client); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToClientRefs.clear(); - for (Long oldAccessTokenId : accessTokenToAuthHolderRefs.keySet()) { - Long oldAuthHolderId = accessTokenToAuthHolderRefs.get(oldAccessTokenId); - Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); - AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setAuthenticationHolder(authHolder); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToAuthHolderRefs.clear(); - for (Long oldAccessTokenId : accessTokenToRefreshTokenRefs.keySet()) { - Long oldRefreshTokenId = accessTokenToRefreshTokenRefs.get(oldAccessTokenId); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setRefreshToken(refreshToken); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToRefreshTokenRefs.clear(); - refreshTokenOldToNewIdMap.clear(); - for (Long oldAccessTokenId : accessTokenToIdTokenRefs.keySet()) { - Long oldIdTokenId = accessTokenToIdTokenRefs.get(oldAccessTokenId); - Long newIdTokenId = accessTokenOldToNewIdMap.get(oldIdTokenId); - OAuth2AccessTokenEntity idToken = tokenRepository.getAccessTokenById(newIdTokenId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setIdToken(idToken); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToIdTokenRefs.clear(); - for (Long oldGrantId : grantToWhitelistedSiteRefs.keySet()) { - Long oldWhitelistedSiteId = grantToWhitelistedSiteRefs.get(oldGrantId); - Long newWhitelistedSiteId = whitelistedSiteOldToNewIdMap.get(oldWhitelistedSiteId); - WhitelistedSite wlSite = wlSiteRepository.getById(newWhitelistedSiteId); - Long newGrantId = grantOldToNewIdMap.get(oldGrantId); - ApprovedSite approvedSite = approvedSiteRepository.getById(newGrantId); - approvedSite.setWhitelistedSite(wlSite); - approvedSiteRepository.save(approvedSite); - } - grantToWhitelistedSiteRefs.clear(); - for (Long oldGrantId : grantToAccessTokensRefs.keySet()) { - Set oldAccessTokenIds = grantToAccessTokensRefs.get(oldGrantId); - Set tokens = new HashSet(); - for(Long oldTokenId : oldAccessTokenIds) { - Long newTokenId = accessTokenOldToNewIdMap.get(oldTokenId); - tokens.add(tokenRepository.getAccessTokenById(newTokenId)); - } - Long newGrantId = grantOldToNewIdMap.get(oldGrantId); - ApprovedSite site = approvedSiteRepository.getById(newGrantId); - site.setApprovedAccessTokens(tokens); - approvedSiteRepository.save(site); - } - accessTokenOldToNewIdMap.clear(); - grantOldToNewIdMap.clear(); - } + private void fixObjectReferences() { + for (Long oldRefreshTokenId : refreshTokenToClientRefs.keySet()) { + String clientRef = refreshTokenToClientRefs.get(oldRefreshTokenId); + ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + refreshToken.setClient(client); + tokenRepository.saveRefreshToken(refreshToken); + } + refreshTokenToClientRefs.clear(); + for (Long oldRefreshTokenId : refreshTokenToAuthHolderRefs.keySet()) { + Long oldAuthHolderId = refreshTokenToAuthHolderRefs.get(oldRefreshTokenId); + Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); + AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + refreshToken.setAuthenticationHolder(authHolder); + tokenRepository.saveRefreshToken(refreshToken); + } + refreshTokenToAuthHolderRefs.clear(); + for (Long oldAccessTokenId : accessTokenToClientRefs.keySet()) { + String clientRef = accessTokenToClientRefs.get(oldAccessTokenId); + ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setClient(client); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToClientRefs.clear(); + for (Long oldAccessTokenId : accessTokenToAuthHolderRefs.keySet()) { + Long oldAuthHolderId = accessTokenToAuthHolderRefs.get(oldAccessTokenId); + Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); + AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setAuthenticationHolder(authHolder); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToAuthHolderRefs.clear(); + for (Long oldAccessTokenId : accessTokenToRefreshTokenRefs.keySet()) { + Long oldRefreshTokenId = accessTokenToRefreshTokenRefs.get(oldAccessTokenId); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setRefreshToken(refreshToken); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToRefreshTokenRefs.clear(); + refreshTokenOldToNewIdMap.clear(); + for (Long oldAccessTokenId : accessTokenToIdTokenRefs.keySet()) { + Long oldIdTokenId = accessTokenToIdTokenRefs.get(oldAccessTokenId); + Long newIdTokenId = accessTokenOldToNewIdMap.get(oldIdTokenId); + OAuth2AccessTokenEntity idToken = tokenRepository.getAccessTokenById(newIdTokenId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setIdToken(idToken); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToIdTokenRefs.clear(); + for (Long oldGrantId : grantToWhitelistedSiteRefs.keySet()) { + Long oldWhitelistedSiteId = grantToWhitelistedSiteRefs.get(oldGrantId); + Long newWhitelistedSiteId = whitelistedSiteOldToNewIdMap.get(oldWhitelistedSiteId); + WhitelistedSite wlSite = wlSiteRepository.getById(newWhitelistedSiteId); + Long newGrantId = grantOldToNewIdMap.get(oldGrantId); + ApprovedSite approvedSite = approvedSiteRepository.getById(newGrantId); + approvedSite.setWhitelistedSite(wlSite); + approvedSiteRepository.save(approvedSite); + } + grantToWhitelistedSiteRefs.clear(); + for (Long oldGrantId : grantToAccessTokensRefs.keySet()) { + Set oldAccessTokenIds = grantToAccessTokensRefs.get(oldGrantId); + Set tokens = new HashSet(); + for(Long oldTokenId : oldAccessTokenIds) { + Long newTokenId = accessTokenOldToNewIdMap.get(oldTokenId); + tokens.add(tokenRepository.getAccessTokenById(newTokenId)); + } + Long newGrantId = grantOldToNewIdMap.get(oldGrantId); + ApprovedSite site = approvedSiteRepository.getById(newGrantId); + site.setApprovedAccessTokens(tokens); + approvedSiteRepository.save(site); + } + accessTokenOldToNewIdMap.clear(); + grantOldToNewIdMap.clear(); + } } diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_2.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_2.java index 02217a37c..4d4231838 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_2.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_2.java @@ -75,1115 +75,1115 @@ import com.google.gson.stream.JsonWriter; @Service public class MITREidDataService_1_2 extends MITREidDataService_1_X { - private final static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_2.class); - @Autowired - private OAuth2ClientRepository clientRepository; - @Autowired - private ApprovedSiteRepository approvedSiteRepository; - @Autowired - private WhitelistedSiteRepository wlSiteRepository; - @Autowired - private BlacklistedSiteRepository blSiteRepository; - @Autowired - private AuthenticationHolderRepository authHolderRepository; - @Autowired - private OAuth2TokenRepository tokenRepository; - @Autowired - private SystemScopeRepository sysScopeRepository; + private final static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_2.class); + @Autowired + private OAuth2ClientRepository clientRepository; + @Autowired + private ApprovedSiteRepository approvedSiteRepository; + @Autowired + private WhitelistedSiteRepository wlSiteRepository; + @Autowired + private BlacklistedSiteRepository blSiteRepository; + @Autowired + private AuthenticationHolderRepository authHolderRepository; + @Autowired + private OAuth2TokenRepository tokenRepository; + @Autowired + private SystemScopeRepository sysScopeRepository; - /* (non-Javadoc) - * @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter) - */ - @Override - public void exportData(JsonWriter writer) throws IOException { + /* (non-Javadoc) + * @see org.mitre.openid.connect.service.MITREidDataService#export(com.google.gson.stream.JsonWriter) + */ + @Override + public void exportData(JsonWriter writer) throws IOException { - // version tag at the root - writer.name(MITREID_CONNECT_1_2); + // version tag at the root + writer.name(MITREID_CONNECT_1_2); - writer.beginObject(); + writer.beginObject(); - // clients list - writer.name(CLIENTS); - writer.beginArray(); - writeClients(writer); - writer.endArray(); + // clients list + writer.name(CLIENTS); + writer.beginArray(); + writeClients(writer); + writer.endArray(); - writer.name(GRANTS); - writer.beginArray(); - writeGrants(writer); - writer.endArray(); + writer.name(GRANTS); + writer.beginArray(); + writeGrants(writer); + writer.endArray(); - writer.name(WHITELISTEDSITES); - writer.beginArray(); - writeWhitelistedSites(writer); - writer.endArray(); + writer.name(WHITELISTEDSITES); + writer.beginArray(); + writeWhitelistedSites(writer); + writer.endArray(); - writer.name(BLACKLISTEDSITES); - writer.beginArray(); - writeBlacklistedSites(writer); - writer.endArray(); + writer.name(BLACKLISTEDSITES); + writer.beginArray(); + writeBlacklistedSites(writer); + writer.endArray(); - writer.name(AUTHENTICATIONHOLDERS); - writer.beginArray(); - writeAuthenticationHolders(writer); - writer.endArray(); + writer.name(AUTHENTICATIONHOLDERS); + writer.beginArray(); + writeAuthenticationHolders(writer); + writer.endArray(); - writer.name(ACCESSTOKENS); - writer.beginArray(); - writeAccessTokens(writer); - writer.endArray(); + writer.name(ACCESSTOKENS); + writer.beginArray(); + writeAccessTokens(writer); + writer.endArray(); - writer.name(REFRESHTOKENS); - writer.beginArray(); - writeRefreshTokens(writer); - writer.endArray(); + writer.name(REFRESHTOKENS); + writer.beginArray(); + writeRefreshTokens(writer); + writer.endArray(); - writer.name(SYSTEMSCOPES); - writer.beginArray(); - writeSystemScopes(writer); - writer.endArray(); + writer.name(SYSTEMSCOPES); + writer.beginArray(); + writeSystemScopes(writer); + writer.endArray(); - writer.endObject(); // end mitreid-connect-1.1 - } + writer.endObject(); // end mitreid-connect-1.1 + } - /** - * @param writer - */ - private void writeRefreshTokens(JsonWriter writer) throws IOException { - for (OAuth2RefreshTokenEntity token : tokenRepository.getAllRefreshTokens()) { - writer.beginObject(); - writer.name("id").value(token.getId()); - writer.name("expiration").value(DateUtil.toUTCString(token.getExpiration())); - writer.name("clientId") - .value((token.getClient() != null) ? token.getClient().getClientId() : null); - writer.name("authenticationHolderId") - .value((token.getAuthenticationHolder() != null) ? token.getAuthenticationHolder().getId() : null); - writer.name("value").value(token.getValue()); - writer.endObject(); - logger.debug("Wrote refresh token {}", token.getId()); - } - logger.info("Done writing refresh tokens"); - } + /** + * @param writer + */ + private void writeRefreshTokens(JsonWriter writer) throws IOException { + for (OAuth2RefreshTokenEntity token : tokenRepository.getAllRefreshTokens()) { + writer.beginObject(); + writer.name("id").value(token.getId()); + writer.name("expiration").value(DateUtil.toUTCString(token.getExpiration())); + writer.name("clientId") + .value((token.getClient() != null) ? token.getClient().getClientId() : null); + writer.name("authenticationHolderId") + .value((token.getAuthenticationHolder() != null) ? token.getAuthenticationHolder().getId() : null); + writer.name("value").value(token.getValue()); + writer.endObject(); + logger.debug("Wrote refresh token {}", token.getId()); + } + logger.info("Done writing refresh tokens"); + } - /** - * @param writer - */ - private void writeAccessTokens(JsonWriter writer) throws IOException { - for (OAuth2AccessTokenEntity token : tokenRepository.getAllAccessTokens()) { - writer.beginObject(); - writer.name("id").value(token.getId()); - writer.name("expiration").value(DateUtil.toUTCString(token.getExpiration())); - writer.name("clientId") - .value((token.getClient() != null) ? token.getClient().getClientId() : null); - writer.name("authenticationHolderId") - .value((token.getAuthenticationHolder() != null) ? token.getAuthenticationHolder().getId() : null); - writer.name("refreshTokenId") - .value((token.getRefreshToken() != null) ? token.getRefreshToken().getId() : null); - writer.name("idTokenId") - .value((token.getIdToken() != null) ? token.getIdToken().getId() : null); - writer.name("scope"); - writer.beginArray(); - for (String s : token.getScope()) { - writer.value(s); - } - writer.endArray(); - writer.name("type").value(token.getTokenType()); - writer.name("value").value(token.getValue()); - writer.endObject(); - logger.debug("Wrote access token {}", token.getId()); - } - logger.info("Done writing access tokens"); - } + /** + * @param writer + */ + private void writeAccessTokens(JsonWriter writer) throws IOException { + for (OAuth2AccessTokenEntity token : tokenRepository.getAllAccessTokens()) { + writer.beginObject(); + writer.name("id").value(token.getId()); + writer.name("expiration").value(DateUtil.toUTCString(token.getExpiration())); + writer.name("clientId") + .value((token.getClient() != null) ? token.getClient().getClientId() : null); + writer.name("authenticationHolderId") + .value((token.getAuthenticationHolder() != null) ? token.getAuthenticationHolder().getId() : null); + writer.name("refreshTokenId") + .value((token.getRefreshToken() != null) ? token.getRefreshToken().getId() : null); + writer.name("idTokenId") + .value((token.getIdToken() != null) ? token.getIdToken().getId() : null); + writer.name("scope"); + writer.beginArray(); + for (String s : token.getScope()) { + writer.value(s); + } + writer.endArray(); + writer.name("type").value(token.getTokenType()); + writer.name("value").value(token.getValue()); + writer.endObject(); + logger.debug("Wrote access token {}", token.getId()); + } + logger.info("Done writing access tokens"); + } - /** - * @param writer - */ - private void writeAuthenticationHolders(JsonWriter writer) throws IOException { - for (AuthenticationHolderEntity holder : authHolderRepository.getAll()) { - writer.beginObject(); - writer.name("id").value(holder.getId()); - writer.name("authentication"); - writer.beginObject(); - writer.name("authorizationRequest"); - OAuth2Authentication oa2Auth = holder.getAuthentication(); - writeAuthorizationRequest(oa2Auth.getOAuth2Request(), writer); - String userAuthentication = base64UrlEncodeObject(oa2Auth.getUserAuthentication()); - writer.name("userAuthentication").value(userAuthentication); - writer.endObject(); - writer.endObject(); - logger.debug("Wrote authentication holder {}", holder.getId()); - } - logger.info("Done writing authentication holders"); - } + /** + * @param writer + */ + private void writeAuthenticationHolders(JsonWriter writer) throws IOException { + for (AuthenticationHolderEntity holder : authHolderRepository.getAll()) { + writer.beginObject(); + writer.name("id").value(holder.getId()); + writer.name("authentication"); + writer.beginObject(); + writer.name("authorizationRequest"); + OAuth2Authentication oa2Auth = holder.getAuthentication(); + writeAuthorizationRequest(oa2Auth.getOAuth2Request(), writer); + String userAuthentication = base64UrlEncodeObject(oa2Auth.getUserAuthentication()); + writer.name("userAuthentication").value(userAuthentication); + writer.endObject(); + writer.endObject(); + logger.debug("Wrote authentication holder {}", holder.getId()); + } + logger.info("Done writing authentication holders"); + } - //used by writeAuthenticationHolders - private void writeAuthorizationRequest(OAuth2Request authReq, JsonWriter writer) throws IOException { - writer.beginObject(); - writer.name("requestParameters"); - writer.beginObject(); - for (Entry entry : authReq.getRequestParameters().entrySet()) { - writer.name(entry.getKey()).value(entry.getValue()); - } - writer.endObject(); - writer.name("clientId").value(authReq.getClientId()); - Set scope = authReq.getScope(); - writer.name("scope"); - writer.beginArray(); - for (String s : scope) { - writer.value(s); - } - writer.endArray(); - writer.name("resourceIds"); - writer.beginArray(); - if (authReq.getResourceIds() != null) { - for (String s : authReq.getResourceIds()) { - writer.value(s); - } - } - writer.endArray(); - writer.name("authorities"); - writer.beginArray(); - for (GrantedAuthority authority : authReq.getAuthorities()) { - writer.value(authority.getAuthority()); - } - writer.endArray(); - writer.name("approved").value(authReq.isApproved()); - writer.name("redirectUri").value(authReq.getRedirectUri()); - writer.name("responseTypes"); - writer.beginArray(); - for (String s : authReq.getResponseTypes()) { - writer.value(s); - } - writer.endArray(); - writer.name("extensions"); - writer.beginObject(); - for (Entry entry : authReq.getExtensions().entrySet()) { - writer.name(entry.getKey()).value(base64UrlEncodeObject(entry.getValue())); - } - writer.endObject(); - writer.endObject(); - } + //used by writeAuthenticationHolders + private void writeAuthorizationRequest(OAuth2Request authReq, JsonWriter writer) throws IOException { + writer.beginObject(); + writer.name("requestParameters"); + writer.beginObject(); + for (Entry entry : authReq.getRequestParameters().entrySet()) { + writer.name(entry.getKey()).value(entry.getValue()); + } + writer.endObject(); + writer.name("clientId").value(authReq.getClientId()); + Set scope = authReq.getScope(); + writer.name("scope"); + writer.beginArray(); + for (String s : scope) { + writer.value(s); + } + writer.endArray(); + writer.name("resourceIds"); + writer.beginArray(); + if (authReq.getResourceIds() != null) { + for (String s : authReq.getResourceIds()) { + writer.value(s); + } + } + writer.endArray(); + writer.name("authorities"); + writer.beginArray(); + for (GrantedAuthority authority : authReq.getAuthorities()) { + writer.value(authority.getAuthority()); + } + writer.endArray(); + writer.name("approved").value(authReq.isApproved()); + writer.name("redirectUri").value(authReq.getRedirectUri()); + writer.name("responseTypes"); + writer.beginArray(); + for (String s : authReq.getResponseTypes()) { + writer.value(s); + } + writer.endArray(); + writer.name("extensions"); + writer.beginObject(); + for (Entry entry : authReq.getExtensions().entrySet()) { + writer.name(entry.getKey()).value(base64UrlEncodeObject(entry.getValue())); + } + writer.endObject(); + writer.endObject(); + } - /** - * @param writer - */ - private void writeGrants(JsonWriter writer) throws IOException { - for (ApprovedSite site : approvedSiteRepository.getAll()) { - writer.beginObject(); - writer.name("id").value(site.getId()); - writer.name("accessDate").value(DateUtil.toUTCString(site.getAccessDate())); - writer.name("clientId").value(site.getClientId()); - writer.name("creationDate").value(DateUtil.toUTCString(site.getCreationDate())); - writer.name("timeoutDate").value(DateUtil.toUTCString(site.getTimeoutDate())); - writer.name("userId").value(site.getUserId()); - writer.name("allowedScopes"); - writeNullSafeArray(writer, site.getAllowedScopes()); - writer.name("whitelistedSiteId").value(site.getIsWhitelisted() ? site.getWhitelistedSite().getId() : null); - Set tokens = site.getApprovedAccessTokens(); - writer.name("approvedAccessTokens"); - writer.beginArray(); - for (OAuth2AccessTokenEntity token : tokens) { - writer.value(token.getId()); - } - writer.endArray(); - writer.endObject(); - logger.debug("Wrote grant {}", site.getId()); - } - logger.info("Done writing grants"); - } + /** + * @param writer + */ + private void writeGrants(JsonWriter writer) throws IOException { + for (ApprovedSite site : approvedSiteRepository.getAll()) { + writer.beginObject(); + writer.name("id").value(site.getId()); + writer.name("accessDate").value(DateUtil.toUTCString(site.getAccessDate())); + writer.name("clientId").value(site.getClientId()); + writer.name("creationDate").value(DateUtil.toUTCString(site.getCreationDate())); + writer.name("timeoutDate").value(DateUtil.toUTCString(site.getTimeoutDate())); + writer.name("userId").value(site.getUserId()); + writer.name("allowedScopes"); + writeNullSafeArray(writer, site.getAllowedScopes()); + writer.name("whitelistedSiteId").value(site.getIsWhitelisted() ? site.getWhitelistedSite().getId() : null); + Set tokens = site.getApprovedAccessTokens(); + writer.name("approvedAccessTokens"); + writer.beginArray(); + for (OAuth2AccessTokenEntity token : tokens) { + writer.value(token.getId()); + } + writer.endArray(); + writer.endObject(); + logger.debug("Wrote grant {}", site.getId()); + } + logger.info("Done writing grants"); + } - /** - * @param writer - */ - private void writeWhitelistedSites(JsonWriter writer) throws IOException { - for (WhitelistedSite wlSite : wlSiteRepository.getAll()) { - writer.beginObject(); - writer.name("id").value(wlSite.getId()); - writer.name("clientId").value(wlSite.getClientId()); - writer.name("creatorUserId").value(wlSite.getCreatorUserId()); - writer.name("allowedScopes"); - writeNullSafeArray(writer, wlSite.getAllowedScopes()); - writer.endObject(); - logger.debug("Wrote whitelisted site {}", wlSite.getId()); - } - logger.info("Done writing whitelisted sites"); - } + /** + * @param writer + */ + private void writeWhitelistedSites(JsonWriter writer) throws IOException { + for (WhitelistedSite wlSite : wlSiteRepository.getAll()) { + writer.beginObject(); + writer.name("id").value(wlSite.getId()); + writer.name("clientId").value(wlSite.getClientId()); + writer.name("creatorUserId").value(wlSite.getCreatorUserId()); + writer.name("allowedScopes"); + writeNullSafeArray(writer, wlSite.getAllowedScopes()); + writer.endObject(); + logger.debug("Wrote whitelisted site {}", wlSite.getId()); + } + logger.info("Done writing whitelisted sites"); + } - /** - * @param writer - */ - private void writeBlacklistedSites(JsonWriter writer) throws IOException { - for (BlacklistedSite blSite : blSiteRepository.getAll()) { - writer.beginObject(); - writer.name("id").value(blSite.getId()); - writer.name("uri").value(blSite.getUri()); - writer.endObject(); - logger.debug("Wrote blacklisted site {}", blSite.getId()); - } - logger.info("Done writing blacklisted sites"); - } + /** + * @param writer + */ + private void writeBlacklistedSites(JsonWriter writer) throws IOException { + for (BlacklistedSite blSite : blSiteRepository.getAll()) { + writer.beginObject(); + writer.name("id").value(blSite.getId()); + writer.name("uri").value(blSite.getUri()); + writer.endObject(); + logger.debug("Wrote blacklisted site {}", blSite.getId()); + } + logger.info("Done writing blacklisted sites"); + } - /** - * @param writer - */ - private void writeClients(JsonWriter writer) { - for (ClientDetailsEntity client : clientRepository.getAllClients()) { - try { - writer.beginObject(); - writer.name("clientId").value(client.getClientId()); - writer.name("resourceIds"); - writeNullSafeArray(writer, client.getResourceIds()); + /** + * @param writer + */ + private void writeClients(JsonWriter writer) { + for (ClientDetailsEntity client : clientRepository.getAllClients()) { + try { + writer.beginObject(); + writer.name("clientId").value(client.getClientId()); + writer.name("resourceIds"); + writeNullSafeArray(writer, client.getResourceIds()); - writer.name("secret").value(client.getClientSecret()); + writer.name("secret").value(client.getClientSecret()); - writer.name("scope"); - writeNullSafeArray(writer, client.getScope()); + writer.name("scope"); + writeNullSafeArray(writer, client.getScope()); - writer.name("authorities"); - writer.beginArray(); - for (GrantedAuthority authority : client.getAuthorities()) { - writer.value(authority.getAuthority()); - } - writer.endArray(); - writer.name("accessTokenValiditySeconds").value(client.getAccessTokenValiditySeconds()); - writer.name("refreshTokenValiditySeconds").value(client.getRefreshTokenValiditySeconds()); - writer.name("redirectUris"); - writeNullSafeArray(writer, client.getRedirectUris()); - writer.name("name").value(client.getClientName()); - writer.name("uri").value(client.getClientUri()); - writer.name("logoUri").value(client.getLogoUri()); - writer.name("contacts"); - writeNullSafeArray(writer, client.getContacts()); - writer.name("tosUri").value(client.getTosUri()); - writer.name("tokenEndpointAuthMethod") - .value((client.getTokenEndpointAuthMethod() != null) ? client.getTokenEndpointAuthMethod().getValue() : null); - writer.name("grantTypes"); - writer.beginArray(); - for (String s : client.getGrantTypes()) { - writer.value(s); - } - writer.endArray(); - writer.name("responseTypes"); - writer.beginArray(); - for (String s : client.getResponseTypes()) { - writer.value(s); - } - writer.endArray(); - writer.name("policyUri").value(client.getPolicyUri()); - writer.name("jwksUri").value(client.getJwksUri()); - writer.name("applicationType") - .value((client.getApplicationType() != null) ? client.getApplicationType().getValue() : null); - writer.name("sectorIdentifierUri").value(client.getSectorIdentifierUri()); - writer.name("subjectType") - .value((client.getSubjectType() != null) ? client.getSubjectType().getValue() : null); - writer.name("requestObjectSigningAlg") - .value((client.getRequestObjectSigningAlgEmbed() != null) ? client.getRequestObjectSigningAlgEmbed().getAlgorithmName() : null); - writer.name("userInfoEncryptedResponseAlg") - .value((client.getUserInfoEncryptedResponseAlgEmbed() != null) ? client.getUserInfoEncryptedResponseAlgEmbed().getAlgorithmName() : null); - writer.name("userInfoEncryptedResponseEnc") - .value((client.getUserInfoEncryptedResponseEncEmbed() != null) ? client.getUserInfoEncryptedResponseEncEmbed().getAlgorithmName() : null); - writer.name("userInfoSignedResponseAlg") - .value((client.getUserInfoSignedResponseAlgEmbed() != null) ? client.getUserInfoSignedResponseAlgEmbed().getAlgorithmName() : null); - writer.name("defaultMaxAge").value(client.getDefaultMaxAge()); - Boolean requireAuthTime = null; - try { - requireAuthTime = client.getRequireAuthTime(); - } catch (NullPointerException e) { - } - if (requireAuthTime != null) { - writer.name("requireAuthTime").value(requireAuthTime); - } - writer.name("defaultACRValues"); - writeNullSafeArray(writer, client.getDefaultACRvalues()); - writer.name("intitateLoginUri").value(client.getInitiateLoginUri()); - writer.name("postLogoutRedirectUri"); - writeNullSafeArray(writer, client.getPostLogoutRedirectUris()); - writer.name("requestUris"); - writeNullSafeArray(writer, client.getRequestUris()); - writer.name("description").value(client.getClientDescription()); - writer.name("allowIntrospection").value(client.isAllowIntrospection()); - writer.name("reuseRefreshToken").value(client.isReuseRefreshToken()); - writer.name("dynamicallyRegistered").value(client.isDynamicallyRegistered()); - writer.endObject(); - logger.debug("Wrote client {}", client.getId()); - } catch (IOException ex) { - logger.error("Unable to write client {}", client.getId(), ex); - } - } - logger.info("Done writing clients"); - } + writer.name("authorities"); + writer.beginArray(); + for (GrantedAuthority authority : client.getAuthorities()) { + writer.value(authority.getAuthority()); + } + writer.endArray(); + writer.name("accessTokenValiditySeconds").value(client.getAccessTokenValiditySeconds()); + writer.name("refreshTokenValiditySeconds").value(client.getRefreshTokenValiditySeconds()); + writer.name("redirectUris"); + writeNullSafeArray(writer, client.getRedirectUris()); + writer.name("name").value(client.getClientName()); + writer.name("uri").value(client.getClientUri()); + writer.name("logoUri").value(client.getLogoUri()); + writer.name("contacts"); + writeNullSafeArray(writer, client.getContacts()); + writer.name("tosUri").value(client.getTosUri()); + writer.name("tokenEndpointAuthMethod") + .value((client.getTokenEndpointAuthMethod() != null) ? client.getTokenEndpointAuthMethod().getValue() : null); + writer.name("grantTypes"); + writer.beginArray(); + for (String s : client.getGrantTypes()) { + writer.value(s); + } + writer.endArray(); + writer.name("responseTypes"); + writer.beginArray(); + for (String s : client.getResponseTypes()) { + writer.value(s); + } + writer.endArray(); + writer.name("policyUri").value(client.getPolicyUri()); + writer.name("jwksUri").value(client.getJwksUri()); + writer.name("applicationType") + .value((client.getApplicationType() != null) ? client.getApplicationType().getValue() : null); + writer.name("sectorIdentifierUri").value(client.getSectorIdentifierUri()); + writer.name("subjectType") + .value((client.getSubjectType() != null) ? client.getSubjectType().getValue() : null); + writer.name("requestObjectSigningAlg") + .value((client.getRequestObjectSigningAlgEmbed() != null) ? client.getRequestObjectSigningAlgEmbed().getAlgorithmName() : null); + writer.name("userInfoEncryptedResponseAlg") + .value((client.getUserInfoEncryptedResponseAlgEmbed() != null) ? client.getUserInfoEncryptedResponseAlgEmbed().getAlgorithmName() : null); + writer.name("userInfoEncryptedResponseEnc") + .value((client.getUserInfoEncryptedResponseEncEmbed() != null) ? client.getUserInfoEncryptedResponseEncEmbed().getAlgorithmName() : null); + writer.name("userInfoSignedResponseAlg") + .value((client.getUserInfoSignedResponseAlgEmbed() != null) ? client.getUserInfoSignedResponseAlgEmbed().getAlgorithmName() : null); + writer.name("defaultMaxAge").value(client.getDefaultMaxAge()); + Boolean requireAuthTime = null; + try { + requireAuthTime = client.getRequireAuthTime(); + } catch (NullPointerException e) { + } + if (requireAuthTime != null) { + writer.name("requireAuthTime").value(requireAuthTime); + } + writer.name("defaultACRValues"); + writeNullSafeArray(writer, client.getDefaultACRvalues()); + writer.name("intitateLoginUri").value(client.getInitiateLoginUri()); + writer.name("postLogoutRedirectUri"); + writeNullSafeArray(writer, client.getPostLogoutRedirectUris()); + writer.name("requestUris"); + writeNullSafeArray(writer, client.getRequestUris()); + writer.name("description").value(client.getClientDescription()); + writer.name("allowIntrospection").value(client.isAllowIntrospection()); + writer.name("reuseRefreshToken").value(client.isReuseRefreshToken()); + writer.name("dynamicallyRegistered").value(client.isDynamicallyRegistered()); + writer.endObject(); + logger.debug("Wrote client {}", client.getId()); + } catch (IOException ex) { + logger.error("Unable to write client {}", client.getId(), ex); + } + } + logger.info("Done writing clients"); + } - /** - * @param writer - */ - private void writeSystemScopes(JsonWriter writer) { - for (SystemScope sysScope : sysScopeRepository.getAll()) { - try { - writer.beginObject(); - writer.name("id").value(sysScope.getId()); - writer.name("description").value(sysScope.getDescription()); - writer.name("icon").value(sysScope.getIcon()); - writer.name("value").value(sysScope.getValue()); - writer.name("allowDynReg").value(sysScope.isAllowDynReg()); - writer.name("defaultScope").value(sysScope.isDefaultScope()); - writer.endObject(); - logger.debug("Wrote system scope {}", sysScope.getId()); - } catch (IOException ex) { - logger.error("Unable to write system scope {}", sysScope.getId(), ex); - } - } - logger.info("Done writing system scopes"); - } + /** + * @param writer + */ + private void writeSystemScopes(JsonWriter writer) { + for (SystemScope sysScope : sysScopeRepository.getAll()) { + try { + writer.beginObject(); + writer.name("id").value(sysScope.getId()); + writer.name("description").value(sysScope.getDescription()); + writer.name("icon").value(sysScope.getIcon()); + writer.name("value").value(sysScope.getValue()); + writer.name("allowDynReg").value(sysScope.isAllowDynReg()); + writer.name("defaultScope").value(sysScope.isDefaultScope()); + writer.endObject(); + logger.debug("Wrote system scope {}", sysScope.getId()); + } catch (IOException ex) { + logger.error("Unable to write system scope {}", sysScope.getId(), ex); + } + } + logger.info("Done writing system scopes"); + } - /* (non-Javadoc) - * @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader) - */ - @Override - public void importData(JsonReader reader) throws IOException { + /* (non-Javadoc) + * @see org.mitre.openid.connect.service.MITREidDataService#importData(com.google.gson.stream.JsonReader) + */ + @Override + public void importData(JsonReader reader) throws IOException { - logger.info("Reading configuration for 1.0"); + logger.info("Reading configuration for 1.0"); - // this *HAS* to start as an object - reader.beginObject(); + // this *HAS* to start as an object + reader.beginObject(); - while (reader.hasNext()) { - JsonToken tok = reader.peek(); - switch (tok) { - case NAME: - String name = reader.nextName(); - // find out which member it is - if (name.equals(CLIENTS)) { - readClients(reader); - } else if (name.equals(GRANTS)) { - readGrants(reader); - } else if (name.equals(WHITELISTEDSITES)) { - readWhitelistedSites(reader); - } else if (name.equals(BLACKLISTEDSITES)) { - readBlacklistedSites(reader); - } else if (name.equals(AUTHENTICATIONHOLDERS)) { - readAuthenticationHolders(reader); - } else if (name.equals(ACCESSTOKENS)) { - readAccessTokens(reader); - } else if (name.equals(REFRESHTOKENS)) { - readRefreshTokens(reader); - } else if (name.equals(SYSTEMSCOPES)) { - readSystemScopes(reader); - } else { - // unknown token, skip it - reader.skipValue(); - } - break; - case END_OBJECT: - // the object ended, we're done here - reader.endObject(); - continue; - } - } - fixObjectReferences(); - } - private Map refreshTokenToClientRefs = new HashMap(); - private Map refreshTokenToAuthHolderRefs = new HashMap(); - private Map refreshTokenOldToNewIdMap = new HashMap(); + while (reader.hasNext()) { + JsonToken tok = reader.peek(); + switch (tok) { + case NAME: + String name = reader.nextName(); + // find out which member it is + if (name.equals(CLIENTS)) { + readClients(reader); + } else if (name.equals(GRANTS)) { + readGrants(reader); + } else if (name.equals(WHITELISTEDSITES)) { + readWhitelistedSites(reader); + } else if (name.equals(BLACKLISTEDSITES)) { + readBlacklistedSites(reader); + } else if (name.equals(AUTHENTICATIONHOLDERS)) { + readAuthenticationHolders(reader); + } else if (name.equals(ACCESSTOKENS)) { + readAccessTokens(reader); + } else if (name.equals(REFRESHTOKENS)) { + readRefreshTokens(reader); + } else if (name.equals(SYSTEMSCOPES)) { + readSystemScopes(reader); + } else { + // unknown token, skip it + reader.skipValue(); + } + break; + case END_OBJECT: + // the object ended, we're done here + reader.endObject(); + continue; + } + } + fixObjectReferences(); + } + private Map refreshTokenToClientRefs = new HashMap(); + private Map refreshTokenToAuthHolderRefs = new HashMap(); + private Map refreshTokenOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - /** - * @param reader - * @throws IOException - */ - private void readRefreshTokens(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity(); - reader.beginObject(); - Long currentId = null; - String clientId = null; - Long authHolderId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("expiration")) { - Date date = DateUtil.utcToDate(reader.nextString()); - token.setExpiration(date); - } else if (name.equals("value")) { - String value = reader.nextString(); - try { - token.setValue(value); - } catch (ParseException ex) { - logger.error("Unable to set refresh token value to {}", value, ex); - } - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("authenticationHolderId")) { - authHolderId = reader.nextLong(); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = tokenRepository.saveRefreshToken(token).getId(); - refreshTokenToClientRefs.put(currentId, clientId); - refreshTokenToAuthHolderRefs.put(currentId, authHolderId); - refreshTokenOldToNewIdMap.put(currentId, newId); - logger.debug("Read refresh token {}", currentId); - } - reader.endArray(); - logger.info("Done reading refresh tokens"); - } - private Map accessTokenToClientRefs = new HashMap(); - private Map accessTokenToAuthHolderRefs = new HashMap(); - private Map accessTokenToRefreshTokenRefs = new HashMap(); - private Map accessTokenToIdTokenRefs = new HashMap(); - private Map accessTokenOldToNewIdMap = new HashMap(); + /** + * @param reader + * @throws IOException + */ + /** + * @param reader + * @throws IOException + */ + private void readRefreshTokens(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + OAuth2RefreshTokenEntity token = new OAuth2RefreshTokenEntity(); + reader.beginObject(); + Long currentId = null; + String clientId = null; + Long authHolderId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("expiration")) { + Date date = DateUtil.utcToDate(reader.nextString()); + token.setExpiration(date); + } else if (name.equals("value")) { + String value = reader.nextString(); + try { + token.setValue(value); + } catch (ParseException ex) { + logger.error("Unable to set refresh token value to {}", value, ex); + } + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("authenticationHolderId")) { + authHolderId = reader.nextLong(); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = tokenRepository.saveRefreshToken(token).getId(); + refreshTokenToClientRefs.put(currentId, clientId); + refreshTokenToAuthHolderRefs.put(currentId, authHolderId); + refreshTokenOldToNewIdMap.put(currentId, newId); + logger.debug("Read refresh token {}", currentId); + } + reader.endArray(); + logger.info("Done reading refresh tokens"); + } + private Map accessTokenToClientRefs = new HashMap(); + private Map accessTokenToAuthHolderRefs = new HashMap(); + private Map accessTokenToRefreshTokenRefs = new HashMap(); + private Map accessTokenToIdTokenRefs = new HashMap(); + private Map accessTokenOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - /** - * @param reader - * @throws IOException - */ - private void readAccessTokens(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity(); - reader.beginObject(); - Long currentId = null; - String clientId = null; - Long authHolderId = null; - Long refreshTokenId = null; - Long idTokenId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("expiration")) { - Date date = DateUtil.utcToDate(reader.nextString()); - token.setExpiration(date); - } else if (name.equals("value")) { - String value = reader.nextString(); - try { - token.setValue(value); - } catch (ParseException ex) { - logger.error("Unable to set refresh token value to {}", value, ex); - } - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("authenticationHolderId")) { - authHolderId = reader.nextLong(); - } else if (name.equals("refreshTokenId")) { - refreshTokenId = reader.nextLong(); - } else if (name.equals("idTokenId")) { - idTokenId = reader.nextLong(); - } else if (name.equals("scope")) { - Set scope = readSet(reader); - token.setScope(scope); - } else if (name.equals("type")) { - token.setTokenType(reader.nextString()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = tokenRepository.saveAccessToken(token).getId(); - accessTokenToClientRefs.put(currentId, clientId); - accessTokenToAuthHolderRefs.put(currentId, authHolderId); - if (refreshTokenId != null) { - accessTokenToRefreshTokenRefs.put(currentId, refreshTokenId); - } - if (idTokenId != null) { - accessTokenToIdTokenRefs.put(currentId, idTokenId); - } - accessTokenOldToNewIdMap.put(currentId, newId); - logger.debug("Read access token {}", currentId); - } - reader.endArray(); - logger.info("Done reading access tokens"); - } - private Map authHolderOldToNewIdMap = new HashMap(); + /** + * @param reader + * @throws IOException + */ + /** + * @param reader + * @throws IOException + */ + private void readAccessTokens(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity(); + reader.beginObject(); + Long currentId = null; + String clientId = null; + Long authHolderId = null; + Long refreshTokenId = null; + Long idTokenId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("expiration")) { + Date date = DateUtil.utcToDate(reader.nextString()); + token.setExpiration(date); + } else if (name.equals("value")) { + String value = reader.nextString(); + try { + token.setValue(value); + } catch (ParseException ex) { + logger.error("Unable to set refresh token value to {}", value, ex); + } + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("authenticationHolderId")) { + authHolderId = reader.nextLong(); + } else if (name.equals("refreshTokenId")) { + refreshTokenId = reader.nextLong(); + } else if (name.equals("idTokenId")) { + idTokenId = reader.nextLong(); + } else if (name.equals("scope")) { + Set scope = readSet(reader); + token.setScope(scope); + } else if (name.equals("type")) { + token.setTokenType(reader.nextString()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = tokenRepository.saveAccessToken(token).getId(); + accessTokenToClientRefs.put(currentId, clientId); + accessTokenToAuthHolderRefs.put(currentId, authHolderId); + if (refreshTokenId != null) { + accessTokenToRefreshTokenRefs.put(currentId, refreshTokenId); + } + if (idTokenId != null) { + accessTokenToIdTokenRefs.put(currentId, idTokenId); + } + accessTokenOldToNewIdMap.put(currentId, newId); + logger.debug("Read access token {}", currentId); + } + reader.endArray(); + logger.info("Done reading access tokens"); + } + private Map authHolderOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - private void readAuthenticationHolders(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - AuthenticationHolderEntity ahe = new AuthenticationHolderEntity(); - reader.beginObject(); - Long currentId = null; - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("ownerId")) { - //not needed - reader.skipValue(); - } else if (name.equals("authentication")) { - OAuth2Request authorizationRequest = null; - Authentication userAuthentication = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String subName = reader.nextName(); - if (subName.equals("authorizationRequest")) { - authorizationRequest = readAuthorizationRequest(reader); - } else if (subName.equals("userAuthentication")) { - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else { - String authString = reader.nextString(); - userAuthentication = base64UrlDecodeObject(authString, Authentication.class); - } - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - OAuth2Authentication auth = new OAuth2Authentication(authorizationRequest, userAuthentication); - ahe.setAuthentication(auth); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = authHolderRepository.save(ahe).getId(); - authHolderOldToNewIdMap.put(currentId, newId); - logger.debug("Read authentication holder {}", currentId); - } - reader.endArray(); - logger.info("Done reading authentication holders"); - } + /** + * @param reader + * @throws IOException + */ + private void readAuthenticationHolders(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + AuthenticationHolderEntity ahe = new AuthenticationHolderEntity(); + reader.beginObject(); + Long currentId = null; + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("ownerId")) { + //not needed + reader.skipValue(); + } else if (name.equals("authentication")) { + OAuth2Request authorizationRequest = null; + Authentication userAuthentication = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String subName = reader.nextName(); + if (subName.equals("authorizationRequest")) { + authorizationRequest = readAuthorizationRequest(reader); + } else if (subName.equals("userAuthentication")) { + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else { + String authString = reader.nextString(); + userAuthentication = base64UrlDecodeObject(authString, Authentication.class); + } + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + OAuth2Authentication auth = new OAuth2Authentication(authorizationRequest, userAuthentication); + ahe.setAuthentication(auth); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = authHolderRepository.save(ahe).getId(); + authHolderOldToNewIdMap.put(currentId, newId); + logger.debug("Read authentication holder {}", currentId); + } + reader.endArray(); + logger.info("Done reading authentication holders"); + } - //used by readAuthenticationHolders - private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException { - Set scope = new LinkedHashSet(); - Set resourceIds = new HashSet(); - boolean approved = false; - Collection authorities = new HashSet(); - Map requestParameters = new HashMap(); - Set responseTypes = new HashSet(); - Map extensions = new HashMap(); - String redirectUri = null; - String clientId = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("requestParameters")) { - requestParameters = readMap(reader); - } else if (name.equals("clientId")) { - clientId = reader.nextString(); - } else if (name.equals("scope")) { - scope = readSet(reader); - } else if (name.equals("resourceIds")) { - resourceIds = readSet(reader); - } else if (name.equals("authorities")) { - Set authorityStrs = readSet(reader); - authorities = new HashSet(); - for (String s : authorityStrs) { - GrantedAuthority ga = new SimpleGrantedAuthority(s); - authorities.add(ga); - } - } else if (name.equals("approved")) { - approved = reader.nextBoolean(); - } else if (name.equals("denied")) { - if (approved == false) { - approved = !reader.nextBoolean(); - } - } else if (name.equals("redirectUri")) { - redirectUri = reader.nextString(); - } else if (name.equals("responseTypes")) { - responseTypes = readSet(reader); - } else if (name.equals("extensions")) { - Map extEnc = readMap(reader); - for (Entry entry : extEnc.entrySet()) { - Serializable decoded = base64UrlDecodeObject(entry.getValue(), Serializable.class); - if (decoded != null) { - extensions.put(entry.getKey(), decoded); - } - } - } else { - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - return new OAuth2Request(requestParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, extensions); - } - Map grantOldToNewIdMap = new HashMap(); - Map grantToWhitelistedSiteRefs = new HashMap(); - Map> grantToAccessTokensRefs = new HashMap>(); - /** - * @param reader - * @throws IOException - */ - private void readGrants(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - ApprovedSite site = new ApprovedSite(); - Long currentId = null; - Long whitelistedSiteId = null; - Set tokenIds = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("accessDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setAccessDate(date); - } else if (name.equals("clientId")) { - site.setClientId(reader.nextString()); - } else if (name.equals("creationDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setCreationDate(date); - } else if (name.equals("timeoutDate")) { - Date date = DateUtil.utcToDate(reader.nextString()); - site.setTimeoutDate(date); - } else if (name.equals("userId")) { - site.setUserId(reader.nextString()); - } else if (name.equals("allowedScopes")) { - Set allowedScopes = readSet(reader); - site.setAllowedScopes(allowedScopes); - } else if (name.equals("whitelistedSiteId")) { - whitelistedSiteId = reader.nextLong(); - } else if (name.equals("approvedAccessTokens")) { - tokenIds = readSet(reader); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = approvedSiteRepository.save(site).getId(); - grantOldToNewIdMap.put(currentId, newId); - if (whitelistedSiteId != null) { - grantToWhitelistedSiteRefs.put(currentId, whitelistedSiteId); - } - if (tokenIds != null) { - grantToAccessTokensRefs.put(currentId, tokenIds); - } - logger.debug("Read grant {}", currentId); - } - reader.endArray(); - logger.info("Done reading grants"); - } - Map whitelistedSiteOldToNewIdMap = new HashMap(); + //used by readAuthenticationHolders + private OAuth2Request readAuthorizationRequest(JsonReader reader) throws IOException { + Set scope = new LinkedHashSet(); + Set resourceIds = new HashSet(); + boolean approved = false; + Collection authorities = new HashSet(); + Map requestParameters = new HashMap(); + Set responseTypes = new HashSet(); + Map extensions = new HashMap(); + String redirectUri = null; + String clientId = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("requestParameters")) { + requestParameters = readMap(reader); + } else if (name.equals("clientId")) { + clientId = reader.nextString(); + } else if (name.equals("scope")) { + scope = readSet(reader); + } else if (name.equals("resourceIds")) { + resourceIds = readSet(reader); + } else if (name.equals("authorities")) { + Set authorityStrs = readSet(reader); + authorities = new HashSet(); + for (String s : authorityStrs) { + GrantedAuthority ga = new SimpleGrantedAuthority(s); + authorities.add(ga); + } + } else if (name.equals("approved")) { + approved = reader.nextBoolean(); + } else if (name.equals("denied")) { + if (approved == false) { + approved = !reader.nextBoolean(); + } + } else if (name.equals("redirectUri")) { + redirectUri = reader.nextString(); + } else if (name.equals("responseTypes")) { + responseTypes = readSet(reader); + } else if (name.equals("extensions")) { + Map extEnc = readMap(reader); + for (Entry entry : extEnc.entrySet()) { + Serializable decoded = base64UrlDecodeObject(entry.getValue(), Serializable.class); + if (decoded != null) { + extensions.put(entry.getKey(), decoded); + } + } + } else { + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + return new OAuth2Request(requestParameters, clientId, authorities, approved, scope, resourceIds, redirectUri, responseTypes, extensions); + } + Map grantOldToNewIdMap = new HashMap(); + Map grantToWhitelistedSiteRefs = new HashMap(); + Map> grantToAccessTokensRefs = new HashMap>(); + /** + * @param reader + * @throws IOException + */ + private void readGrants(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + ApprovedSite site = new ApprovedSite(); + Long currentId = null; + Long whitelistedSiteId = null; + Set tokenIds = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("accessDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setAccessDate(date); + } else if (name.equals("clientId")) { + site.setClientId(reader.nextString()); + } else if (name.equals("creationDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setCreationDate(date); + } else if (name.equals("timeoutDate")) { + Date date = DateUtil.utcToDate(reader.nextString()); + site.setTimeoutDate(date); + } else if (name.equals("userId")) { + site.setUserId(reader.nextString()); + } else if (name.equals("allowedScopes")) { + Set allowedScopes = readSet(reader); + site.setAllowedScopes(allowedScopes); + } else if (name.equals("whitelistedSiteId")) { + whitelistedSiteId = reader.nextLong(); + } else if (name.equals("approvedAccessTokens")) { + tokenIds = readSet(reader); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = approvedSiteRepository.save(site).getId(); + grantOldToNewIdMap.put(currentId, newId); + if (whitelistedSiteId != null) { + grantToWhitelistedSiteRefs.put(currentId, whitelistedSiteId); + } + if (tokenIds != null) { + grantToAccessTokensRefs.put(currentId, tokenIds); + } + logger.debug("Read grant {}", currentId); + } + reader.endArray(); + logger.info("Done reading grants"); + } + Map whitelistedSiteOldToNewIdMap = new HashMap(); - /** - * @param reader - * @throws IOException - */ - private void readWhitelistedSites(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - WhitelistedSite wlSite = new WhitelistedSite(); - Long currentId = null; - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (name.equals("id")) { - currentId = reader.nextLong(); - } else if (name.equals("clientId")) { - wlSite.setClientId(reader.nextString()); - } else if (name.equals("creatorUserId")) { - wlSite.setCreatorUserId(reader.nextString()); - } else if (name.equals("allowedScopes")) { - Set allowedScopes = readSet(reader); - wlSite.setAllowedScopes(allowedScopes); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - Long newId = wlSiteRepository.save(wlSite).getId(); - whitelistedSiteOldToNewIdMap.put(currentId, newId); - } - reader.endArray(); - logger.info("Done reading whitelisted sites"); - } + /** + * @param reader + * @throws IOException + */ + private void readWhitelistedSites(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + WhitelistedSite wlSite = new WhitelistedSite(); + Long currentId = null; + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (name.equals("id")) { + currentId = reader.nextLong(); + } else if (name.equals("clientId")) { + wlSite.setClientId(reader.nextString()); + } else if (name.equals("creatorUserId")) { + wlSite.setCreatorUserId(reader.nextString()); + } else if (name.equals("allowedScopes")) { + Set allowedScopes = readSet(reader); + wlSite.setAllowedScopes(allowedScopes); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + Long newId = wlSiteRepository.save(wlSite).getId(); + whitelistedSiteOldToNewIdMap.put(currentId, newId); + } + reader.endArray(); + logger.info("Done reading whitelisted sites"); + } - /** - * @param reader - * @throws IOException - */ - private void readBlacklistedSites(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - BlacklistedSite blSite = new BlacklistedSite(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (name.equals("id")) { - reader.skipValue(); - } else if (name.equals("uri")) { - blSite.setUri(reader.nextString()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - blSiteRepository.save(blSite); - } - reader.endArray(); - logger.info("Done reading blacklisted sites"); - } + /** + * @param reader + * @throws IOException + */ + private void readBlacklistedSites(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + BlacklistedSite blSite = new BlacklistedSite(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (name.equals("id")) { + reader.skipValue(); + } else if (name.equals("uri")) { + blSite.setUri(reader.nextString()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + blSiteRepository.save(blSite); + } + reader.endArray(); + logger.info("Done reading blacklisted sites"); + } - /** - * @param reader - * @throws IOException - */ - private void readClients(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - ClientDetailsEntity client = new ClientDetailsEntity(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("clientId")) { - client.setClientId(reader.nextString()); - } else if (name.equals("resourceIds")) { - Set resourceIds = readSet(reader); - client.setResourceIds(resourceIds); - } else if (name.equals("secret")) { - client.setClientSecret(reader.nextString()); - } else if (name.equals("scope")) { - Set scope = readSet(reader); - client.setScope(scope); - } else if (name.equals("authorities")) { - Set authorityStrs = readSet(reader); - Set authorities = new HashSet(); - for (String s : authorityStrs) { - GrantedAuthority ga = new SimpleGrantedAuthority(s); - authorities.add(ga); - } - client.setAuthorities(authorities); - } else if (name.equals("accessTokenValiditySeconds")) { - client.setAccessTokenValiditySeconds(reader.nextInt()); - } else if (name.equals("refreshTokenValiditySeconds")) { - client.setRefreshTokenValiditySeconds(reader.nextInt()); - } else if (name.equals("redirectUris")) { - Set redirectUris = readSet(reader); - client.setRedirectUris(redirectUris); - } else if (name.equals("name")) { - client.setClientName(reader.nextString()); - } else if (name.equals("uri")) { - client.setClientUri(reader.nextString()); - } else if (name.equals("logoUri")) { - client.setLogoUri(reader.nextString()); - } else if (name.equals("contacts")) { - Set contacts = readSet(reader); - client.setContacts(contacts); - } else if (name.equals("tosUri")) { - client.setTosUri(reader.nextString()); - } else if (name.equals("tokenEndpointAuthMethod")) { - AuthMethod am = AuthMethod.getByValue(reader.nextString()); - client.setTokenEndpointAuthMethod(am); - } else if (name.equals("grantTypes")) { - Set grantTypes = readSet(reader); - client.setGrantTypes(grantTypes); - } else if (name.equals("responseTypes")) { - Set responseTypes = readSet(reader); - client.setResponseTypes(responseTypes); - } else if (name.equals("policyUri")) { - client.setPolicyUri(reader.nextString()); - } else if (name.equals("applicationType")) { - AppType appType = AppType.getByValue(reader.nextString()); - client.setApplicationType(appType); - } else if (name.equals("sectorIdentifierUri")) { - client.setSectorIdentifierUri(reader.nextString()); - } else if (name.equals("subjectType")) { - SubjectType st = SubjectType.getByValue(reader.nextString()); - client.setSubjectType(st); - } else if (name.equals("requestObjectSigningAlg")) { - JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setRequestObjectSigningAlgEmbed(alg); - } else if (name.equals("userInfoEncryptedResponseAlg")) { - JWEAlgorithmEmbed alg = JWEAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoEncryptedResponseAlgEmbed(alg); - } else if (name.equals("userInfoEncryptedResponseEnc")) { - JWEEncryptionMethodEmbed alg = JWEEncryptionMethodEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoEncryptedResponseEncEmbed(alg); - } else if (name.equals("userInfoSignedResponseAlg")) { - JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); - client.setUserInfoSignedResponseAlgEmbed(alg); - } else if (name.equals("defaultMaxAge")) { - client.setDefaultMaxAge(reader.nextInt()); - } else if (name.equals("requireAuthTime")) { - client.setRequireAuthTime(reader.nextBoolean()); - } else if (name.equals("defaultACRValues")) { - Set defaultACRvalues = readSet(reader); - client.setDefaultACRvalues(defaultACRvalues); - } else if (name.equals("initiateLoginUri")) { - client.setInitiateLoginUri(reader.nextString()); - } else if (name.equals("postLogoutRedirectUri")) { - HashSet postLogoutUris = Sets.newHashSet(reader.nextString()); - client.setPostLogoutRedirectUris(postLogoutUris); - } else if (name.equals("requestUris")) { - Set requestUris = readSet(reader); - client.setRequestUris(requestUris); - } else if (name.equals("description")) { - client.setClientDescription(reader.nextString()); - } else if (name.equals("allowIntrospection")) { - client.setAllowIntrospection(reader.nextBoolean()); - } else if (name.equals("reuseRefreshToken")) { - client.setReuseRefreshToken(reader.nextBoolean()); - } else if (name.equals("dynamicallyRegistered")) { - client.setDynamicallyRegistered(reader.nextBoolean()); - } else { - logger.debug("Found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - clientRepository.saveClient(client); - } - reader.endArray(); - logger.info("Done reading clients"); - } + /** + * @param reader + * @throws IOException + */ + private void readClients(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + ClientDetailsEntity client = new ClientDetailsEntity(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("clientId")) { + client.setClientId(reader.nextString()); + } else if (name.equals("resourceIds")) { + Set resourceIds = readSet(reader); + client.setResourceIds(resourceIds); + } else if (name.equals("secret")) { + client.setClientSecret(reader.nextString()); + } else if (name.equals("scope")) { + Set scope = readSet(reader); + client.setScope(scope); + } else if (name.equals("authorities")) { + Set authorityStrs = readSet(reader); + Set authorities = new HashSet(); + for (String s : authorityStrs) { + GrantedAuthority ga = new SimpleGrantedAuthority(s); + authorities.add(ga); + } + client.setAuthorities(authorities); + } else if (name.equals("accessTokenValiditySeconds")) { + client.setAccessTokenValiditySeconds(reader.nextInt()); + } else if (name.equals("refreshTokenValiditySeconds")) { + client.setRefreshTokenValiditySeconds(reader.nextInt()); + } else if (name.equals("redirectUris")) { + Set redirectUris = readSet(reader); + client.setRedirectUris(redirectUris); + } else if (name.equals("name")) { + client.setClientName(reader.nextString()); + } else if (name.equals("uri")) { + client.setClientUri(reader.nextString()); + } else if (name.equals("logoUri")) { + client.setLogoUri(reader.nextString()); + } else if (name.equals("contacts")) { + Set contacts = readSet(reader); + client.setContacts(contacts); + } else if (name.equals("tosUri")) { + client.setTosUri(reader.nextString()); + } else if (name.equals("tokenEndpointAuthMethod")) { + AuthMethod am = AuthMethod.getByValue(reader.nextString()); + client.setTokenEndpointAuthMethod(am); + } else if (name.equals("grantTypes")) { + Set grantTypes = readSet(reader); + client.setGrantTypes(grantTypes); + } else if (name.equals("responseTypes")) { + Set responseTypes = readSet(reader); + client.setResponseTypes(responseTypes); + } else if (name.equals("policyUri")) { + client.setPolicyUri(reader.nextString()); + } else if (name.equals("applicationType")) { + AppType appType = AppType.getByValue(reader.nextString()); + client.setApplicationType(appType); + } else if (name.equals("sectorIdentifierUri")) { + client.setSectorIdentifierUri(reader.nextString()); + } else if (name.equals("subjectType")) { + SubjectType st = SubjectType.getByValue(reader.nextString()); + client.setSubjectType(st); + } else if (name.equals("requestObjectSigningAlg")) { + JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setRequestObjectSigningAlgEmbed(alg); + } else if (name.equals("userInfoEncryptedResponseAlg")) { + JWEAlgorithmEmbed alg = JWEAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoEncryptedResponseAlgEmbed(alg); + } else if (name.equals("userInfoEncryptedResponseEnc")) { + JWEEncryptionMethodEmbed alg = JWEEncryptionMethodEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoEncryptedResponseEncEmbed(alg); + } else if (name.equals("userInfoSignedResponseAlg")) { + JWSAlgorithmEmbed alg = JWSAlgorithmEmbed.getForAlgorithmName(reader.nextString()); + client.setUserInfoSignedResponseAlgEmbed(alg); + } else if (name.equals("defaultMaxAge")) { + client.setDefaultMaxAge(reader.nextInt()); + } else if (name.equals("requireAuthTime")) { + client.setRequireAuthTime(reader.nextBoolean()); + } else if (name.equals("defaultACRValues")) { + Set defaultACRvalues = readSet(reader); + client.setDefaultACRvalues(defaultACRvalues); + } else if (name.equals("initiateLoginUri")) { + client.setInitiateLoginUri(reader.nextString()); + } else if (name.equals("postLogoutRedirectUri")) { + HashSet postLogoutUris = Sets.newHashSet(reader.nextString()); + client.setPostLogoutRedirectUris(postLogoutUris); + } else if (name.equals("requestUris")) { + Set requestUris = readSet(reader); + client.setRequestUris(requestUris); + } else if (name.equals("description")) { + client.setClientDescription(reader.nextString()); + } else if (name.equals("allowIntrospection")) { + client.setAllowIntrospection(reader.nextBoolean()); + } else if (name.equals("reuseRefreshToken")) { + client.setReuseRefreshToken(reader.nextBoolean()); + } else if (name.equals("dynamicallyRegistered")) { + client.setDynamicallyRegistered(reader.nextBoolean()); + } else { + logger.debug("Found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + clientRepository.saveClient(client); + } + reader.endArray(); + logger.info("Done reading clients"); + } - /** - * Read the list of system scopes from the reader and insert them into the - * scope repository. - * - * @param reader - * @throws IOException - */ - private void readSystemScopes(JsonReader reader) throws IOException { - reader.beginArray(); - while (reader.hasNext()) { - SystemScope scope = new SystemScope(); - reader.beginObject(); - while (reader.hasNext()) { - switch (reader.peek()) { - case END_OBJECT: - continue; - case NAME: - String name = reader.nextName(); - if (reader.peek() == JsonToken.NULL) { - reader.skipValue(); - } else if (name.equals("value")) { - scope.setValue(reader.nextString()); - } else if (name.equals("description")) { - scope.setDescription(reader.nextString()); - } else if (name.equals("allowDynReg")) { - scope.setAllowDynReg(reader.nextBoolean()); - } else if (name.equals("defaultScope")) { - scope.setDefaultScope(reader.nextBoolean()); - } else if (name.equals("icon")) { - scope.setIcon(reader.nextString()); - } else { - logger.debug("found unexpected entry"); - reader.skipValue(); - } - break; - default: - logger.debug("Found unexpected entry"); - reader.skipValue(); - continue; - } - } - reader.endObject(); - sysScopeRepository.save(scope); - } - reader.endArray(); - logger.info("Done reading system scopes"); - } + /** + * Read the list of system scopes from the reader and insert them into the + * scope repository. + * + * @param reader + * @throws IOException + */ + private void readSystemScopes(JsonReader reader) throws IOException { + reader.beginArray(); + while (reader.hasNext()) { + SystemScope scope = new SystemScope(); + reader.beginObject(); + while (reader.hasNext()) { + switch (reader.peek()) { + case END_OBJECT: + continue; + case NAME: + String name = reader.nextName(); + if (reader.peek() == JsonToken.NULL) { + reader.skipValue(); + } else if (name.equals("value")) { + scope.setValue(reader.nextString()); + } else if (name.equals("description")) { + scope.setDescription(reader.nextString()); + } else if (name.equals("allowDynReg")) { + scope.setAllowDynReg(reader.nextBoolean()); + } else if (name.equals("defaultScope")) { + scope.setDefaultScope(reader.nextBoolean()); + } else if (name.equals("icon")) { + scope.setIcon(reader.nextString()); + } else { + logger.debug("found unexpected entry"); + reader.skipValue(); + } + break; + default: + logger.debug("Found unexpected entry"); + reader.skipValue(); + continue; + } + } + reader.endObject(); + sysScopeRepository.save(scope); + } + reader.endArray(); + logger.info("Done reading system scopes"); + } - private void fixObjectReferences() { - for (Long oldRefreshTokenId : refreshTokenToClientRefs.keySet()) { - String clientRef = refreshTokenToClientRefs.get(oldRefreshTokenId); - ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - refreshToken.setClient(client); - tokenRepository.saveRefreshToken(refreshToken); - } - refreshTokenToClientRefs.clear(); - for (Long oldRefreshTokenId : refreshTokenToAuthHolderRefs.keySet()) { - Long oldAuthHolderId = refreshTokenToAuthHolderRefs.get(oldRefreshTokenId); - Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); - AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - refreshToken.setAuthenticationHolder(authHolder); - tokenRepository.saveRefreshToken(refreshToken); - } - refreshTokenToAuthHolderRefs.clear(); - for (Long oldAccessTokenId : accessTokenToClientRefs.keySet()) { - String clientRef = accessTokenToClientRefs.get(oldAccessTokenId); - ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setClient(client); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToClientRefs.clear(); - for (Long oldAccessTokenId : accessTokenToAuthHolderRefs.keySet()) { - Long oldAuthHolderId = accessTokenToAuthHolderRefs.get(oldAccessTokenId); - Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); - AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setAuthenticationHolder(authHolder); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToAuthHolderRefs.clear(); - for (Long oldAccessTokenId : accessTokenToRefreshTokenRefs.keySet()) { - Long oldRefreshTokenId = accessTokenToRefreshTokenRefs.get(oldAccessTokenId); - Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); - OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setRefreshToken(refreshToken); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToRefreshTokenRefs.clear(); - refreshTokenOldToNewIdMap.clear(); - for (Long oldAccessTokenId : accessTokenToIdTokenRefs.keySet()) { - Long oldIdTokenId = accessTokenToIdTokenRefs.get(oldAccessTokenId); - Long newIdTokenId = accessTokenOldToNewIdMap.get(oldIdTokenId); - OAuth2AccessTokenEntity idToken = tokenRepository.getAccessTokenById(newIdTokenId); - Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); - accessToken.setIdToken(idToken); - tokenRepository.saveAccessToken(accessToken); - } - accessTokenToIdTokenRefs.clear(); - for (Long oldGrantId : grantToWhitelistedSiteRefs.keySet()) { - Long oldWhitelistedSiteId = grantToWhitelistedSiteRefs.get(oldGrantId); - Long newWhitelistedSiteId = whitelistedSiteOldToNewIdMap.get(oldWhitelistedSiteId); - WhitelistedSite wlSite = wlSiteRepository.getById(newWhitelistedSiteId); - Long newGrantId = grantOldToNewIdMap.get(oldGrantId); - ApprovedSite approvedSite = approvedSiteRepository.getById(newGrantId); - approvedSite.setWhitelistedSite(wlSite); - approvedSiteRepository.save(approvedSite); - } - grantToWhitelistedSiteRefs.clear(); - for (Long oldGrantId : grantToAccessTokensRefs.keySet()) { - Set oldAccessTokenIds = grantToAccessTokensRefs.get(oldGrantId); - Set tokens = new HashSet(); - for(Long oldTokenId : oldAccessTokenIds) { - Long newTokenId = accessTokenOldToNewIdMap.get(oldTokenId); - tokens.add(tokenRepository.getAccessTokenById(newTokenId)); - } - Long newGrantId = grantOldToNewIdMap.get(oldGrantId); - ApprovedSite site = approvedSiteRepository.getById(newGrantId); - site.setApprovedAccessTokens(tokens); - approvedSiteRepository.save(site); - } - accessTokenOldToNewIdMap.clear(); - grantOldToNewIdMap.clear(); - } + private void fixObjectReferences() { + for (Long oldRefreshTokenId : refreshTokenToClientRefs.keySet()) { + String clientRef = refreshTokenToClientRefs.get(oldRefreshTokenId); + ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + refreshToken.setClient(client); + tokenRepository.saveRefreshToken(refreshToken); + } + refreshTokenToClientRefs.clear(); + for (Long oldRefreshTokenId : refreshTokenToAuthHolderRefs.keySet()) { + Long oldAuthHolderId = refreshTokenToAuthHolderRefs.get(oldRefreshTokenId); + Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); + AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + refreshToken.setAuthenticationHolder(authHolder); + tokenRepository.saveRefreshToken(refreshToken); + } + refreshTokenToAuthHolderRefs.clear(); + for (Long oldAccessTokenId : accessTokenToClientRefs.keySet()) { + String clientRef = accessTokenToClientRefs.get(oldAccessTokenId); + ClientDetailsEntity client = clientRepository.getClientByClientId(clientRef); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setClient(client); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToClientRefs.clear(); + for (Long oldAccessTokenId : accessTokenToAuthHolderRefs.keySet()) { + Long oldAuthHolderId = accessTokenToAuthHolderRefs.get(oldAccessTokenId); + Long newAuthHolderId = authHolderOldToNewIdMap.get(oldAuthHolderId); + AuthenticationHolderEntity authHolder = authHolderRepository.getById(newAuthHolderId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setAuthenticationHolder(authHolder); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToAuthHolderRefs.clear(); + for (Long oldAccessTokenId : accessTokenToRefreshTokenRefs.keySet()) { + Long oldRefreshTokenId = accessTokenToRefreshTokenRefs.get(oldAccessTokenId); + Long newRefreshTokenId = refreshTokenOldToNewIdMap.get(oldRefreshTokenId); + OAuth2RefreshTokenEntity refreshToken = tokenRepository.getRefreshTokenById(newRefreshTokenId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setRefreshToken(refreshToken); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToRefreshTokenRefs.clear(); + refreshTokenOldToNewIdMap.clear(); + for (Long oldAccessTokenId : accessTokenToIdTokenRefs.keySet()) { + Long oldIdTokenId = accessTokenToIdTokenRefs.get(oldAccessTokenId); + Long newIdTokenId = accessTokenOldToNewIdMap.get(oldIdTokenId); + OAuth2AccessTokenEntity idToken = tokenRepository.getAccessTokenById(newIdTokenId); + Long newAccessTokenId = accessTokenOldToNewIdMap.get(oldAccessTokenId); + OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenById(newAccessTokenId); + accessToken.setIdToken(idToken); + tokenRepository.saveAccessToken(accessToken); + } + accessTokenToIdTokenRefs.clear(); + for (Long oldGrantId : grantToWhitelistedSiteRefs.keySet()) { + Long oldWhitelistedSiteId = grantToWhitelistedSiteRefs.get(oldGrantId); + Long newWhitelistedSiteId = whitelistedSiteOldToNewIdMap.get(oldWhitelistedSiteId); + WhitelistedSite wlSite = wlSiteRepository.getById(newWhitelistedSiteId); + Long newGrantId = grantOldToNewIdMap.get(oldGrantId); + ApprovedSite approvedSite = approvedSiteRepository.getById(newGrantId); + approvedSite.setWhitelistedSite(wlSite); + approvedSiteRepository.save(approvedSite); + } + grantToWhitelistedSiteRefs.clear(); + for (Long oldGrantId : grantToAccessTokensRefs.keySet()) { + Set oldAccessTokenIds = grantToAccessTokensRefs.get(oldGrantId); + Set tokens = new HashSet(); + for(Long oldTokenId : oldAccessTokenIds) { + Long newTokenId = accessTokenOldToNewIdMap.get(oldTokenId); + tokens.add(tokenRepository.getAccessTokenById(newTokenId)); + } + Long newGrantId = grantOldToNewIdMap.get(oldGrantId); + ApprovedSite site = approvedSiteRepository.getById(newGrantId); + site.setApprovedAccessTokens(tokens); + approvedSiteRepository.save(site); + } + accessTokenOldToNewIdMap.clear(); + grantOldToNewIdMap.clear(); + } } diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_X.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_X.java index 00f0e08a2..bb6798fd8 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_X.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/service/impl/MITREidDataService_1_X.java @@ -16,9 +16,6 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; -import com.google.common.io.BaseEncoding; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -29,109 +26,114 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; + import org.mitre.openid.connect.service.MITREidDataService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.google.common.io.BaseEncoding; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + /** * * @author arielak */ public abstract class MITREidDataService_1_X implements MITREidDataService { private static Logger logger = LoggerFactory.getLogger(MITREidDataService_1_X.class); - - protected static T base64UrlDecodeObject(String encoded, Class type) { - if (encoded == null) { - return null; - } else { - T deserialized = null; - try { - byte[] decoded = BaseEncoding.base64Url().decode(encoded); - ByteArrayInputStream bais = new ByteArrayInputStream(decoded); - ObjectInputStream ois = new ObjectInputStream(bais); - deserialized = type.cast(ois.readObject()); - ois.close(); - bais.close(); - } catch (Exception ex) { - logger.error("Unable to decode object", ex); - } - return deserialized; - } - } - - protected static String base64UrlEncodeObject(Serializable obj) { - if (obj == null) { - return null; - } else { - String encoded = null; - try { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(obj); - encoded = BaseEncoding.base64Url().encode(baos.toByteArray()); - oos.close(); - baos.close(); - } catch (IOException ex) { - logger.error("Unable to encode object", ex); - } - return encoded; - } - } - protected static Set readSet(JsonReader reader) throws IOException { - Set arraySet = null; - reader.beginArray(); - switch (reader.peek()) { - case STRING: - arraySet = new HashSet(); - while (reader.hasNext()) { - arraySet.add(reader.nextString()); - } - break; - case NUMBER: - arraySet = new HashSet(); - while (reader.hasNext()) { - arraySet.add(reader.nextLong()); - } - break; - default: - arraySet = new HashSet(); - break; - } - reader.endArray(); - return arraySet; - } - - protected static Map readMap(JsonReader reader) throws IOException { - Map map = new HashMap(); - reader.beginObject(); - while(reader.hasNext()) { - String name = reader.nextName(); - Object value = null; - switch(reader.peek()) { - case STRING: - value = reader.nextString(); - break; - case BOOLEAN: - value = reader.nextBoolean(); - break; - case NUMBER: - value = reader.nextLong(); - break; - } - map.put(name, value); - } - reader.endObject(); - return map; - } - + + protected static T base64UrlDecodeObject(String encoded, Class type) { + if (encoded == null) { + return null; + } else { + T deserialized = null; + try { + byte[] decoded = BaseEncoding.base64Url().decode(encoded); + ByteArrayInputStream bais = new ByteArrayInputStream(decoded); + ObjectInputStream ois = new ObjectInputStream(bais); + deserialized = type.cast(ois.readObject()); + ois.close(); + bais.close(); + } catch (Exception ex) { + logger.error("Unable to decode object", ex); + } + return deserialized; + } + } + + protected static String base64UrlEncodeObject(Serializable obj) { + if (obj == null) { + return null; + } else { + String encoded = null; + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(obj); + encoded = BaseEncoding.base64Url().encode(baos.toByteArray()); + oos.close(); + baos.close(); + } catch (IOException ex) { + logger.error("Unable to encode object", ex); + } + return encoded; + } + } + protected static Set readSet(JsonReader reader) throws IOException { + Set arraySet = null; + reader.beginArray(); + switch (reader.peek()) { + case STRING: + arraySet = new HashSet(); + while (reader.hasNext()) { + arraySet.add(reader.nextString()); + } + break; + case NUMBER: + arraySet = new HashSet(); + while (reader.hasNext()) { + arraySet.add(reader.nextLong()); + } + break; + default: + arraySet = new HashSet(); + break; + } + reader.endArray(); + return arraySet; + } + + protected static Map readMap(JsonReader reader) throws IOException { + Map map = new HashMap(); + reader.beginObject(); + while(reader.hasNext()) { + String name = reader.nextName(); + Object value = null; + switch(reader.peek()) { + case STRING: + value = reader.nextString(); + break; + case BOOLEAN: + value = reader.nextBoolean(); + break; + case NUMBER: + value = reader.nextLong(); + break; + } + map.put(name, value); + } + reader.endObject(); + return map; + } + protected void writeNullSafeArray(JsonWriter writer, Set items) throws IOException { if (items != null) { writer.beginArray(); - for (String s : items) { - writer.value(s); - } - writer.endArray(); + for (String s : items) { + writer.value(s); + } + writer.endArray(); } else { writer.nullValue(); } diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/token/TofuUserApprovalHandler.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/token/TofuUserApprovalHandler.java index 90a6688cc..4062a88dd 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/token/TofuUserApprovalHandler.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/token/TofuUserApprovalHandler.java @@ -277,7 +277,7 @@ public class TofuUserApprovalHandler implements UserApprovalHandler { } } } - + @Override public Map getUserApprovalRequest(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/util/DateUtil.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/util/DateUtil.java index 40799f828..0aeb8d37d 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/util/DateUtil.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/util/DateUtil.java @@ -20,6 +20,7 @@ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,29 +29,29 @@ import org.slf4j.LoggerFactory; * @author arielak */ public class DateUtil { - private static final Logger log = LoggerFactory.getLogger(DateUtil.class); - private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private static final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT); - private static final TimeZone utc = TimeZone.getTimeZone("UTC"); - - public static String toUTCString(Date date) { - if (date == null) { - return null; - } - sdf.setTimeZone(utc); - return sdf.format(date); - } + private static final Logger log = LoggerFactory.getLogger(DateUtil.class); + private static final String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; + private static final SimpleDateFormat sdf = new SimpleDateFormat(ISO_FORMAT); + private static final TimeZone utc = TimeZone.getTimeZone("UTC"); - public static Date utcToDate(String s) { - if (s == null) { - return null; - } - Date d = null; - try { - d = sdf.parse(s); - } catch(ParseException ex) { - log.error("Unable to parse date string {}", s, ex); - } - return d; - } + public static String toUTCString(Date date) { + if (date == null) { + return null; + } + sdf.setTimeZone(utc); + return sdf.format(date); + } + + public static Date utcToDate(String s) { + if (s == null) { + return null; + } + Date d = null; + try { + d = sdf.parse(s); + } catch(ParseException ex) { + log.error("Unable to parse date string {}", s, ex); + } + return d; + } } diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientEntityViewForUsers.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientEntityViewForUsers.java index e9590caad..7e3f05f47 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientEntityViewForUsers.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientEntityViewForUsers.java @@ -43,7 +43,7 @@ public class ClientEntityViewForUsers extends AbstractClientEntityView { private Set whitelistedFields = ImmutableSet.of("clientName", "clientId", "id", "clientDescription", "scope", "logoUri"); public static final String VIEWNAME = "clientEntityViewUsers"; - + /* (non-Javadoc) * @see org.mitre.openid.connect.view.AbstractClientEntityView#getExclusionStrategy() */ diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientInformationResponseView.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientInformationResponseView.java index 2753db907..f6d680112 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientInformationResponseView.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/ClientInformationResponseView.java @@ -52,7 +52,7 @@ public class ClientInformationResponseView extends AbstractView { private static Logger logger = LoggerFactory.getLogger(ClientInformationResponseView.class); public static final String VIEWNAME = "clientInformationResponseView"; - + // note that this won't serialize nulls by default private Gson gson = new Gson(); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/HttpCodeView.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/HttpCodeView.java index c01d52276..c55a30095 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/HttpCodeView.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/HttpCodeView.java @@ -37,7 +37,7 @@ import org.springframework.web.servlet.view.AbstractView; public class HttpCodeView extends AbstractView { public static final String VIEWNAME = "httpCodeView"; - + @Override protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) { HttpStatus code = (HttpStatus) model.get("code"); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonApprovedSiteView.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonApprovedSiteView.java index 29ccf8d69..8665e1c1b 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonApprovedSiteView.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonApprovedSiteView.java @@ -55,7 +55,7 @@ public class JsonApprovedSiteView extends AbstractView { private static Logger logger = LoggerFactory.getLogger(JsonApprovedSiteView.class); public static final String VIEWNAME = "jsonApprovedSiteView"; - + private Gson gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonEntityView.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonEntityView.java index 783eb8f62..62adddc33 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonEntityView.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonEntityView.java @@ -48,7 +48,7 @@ public class JsonEntityView extends AbstractView { private static Logger logger = LoggerFactory.getLogger(JsonEntityView.class); public static final String VIEWNAME = "jsonEntityView"; - + private Gson gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonErrorView.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonErrorView.java index bf84e7b77..c79b254e4 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonErrorView.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/JsonErrorView.java @@ -47,7 +47,7 @@ public class JsonErrorView extends AbstractView { private static Logger logger = LoggerFactory.getLogger(JsonEntityView.class); public static final String VIEWNAME = "jsonErrorView"; - + private Gson gson = new GsonBuilder() .setExclusionStrategies(new ExclusionStrategy() { 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 b2ee521b0..3d9a0f42f 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 @@ -62,7 +62,7 @@ public class UserInfoJwtView extends UserInfoView { private static Logger logger = LoggerFactory.getLogger(UserInfoJwtView.class); public static final String VIEWNAME = "userInfoJwtView"; - + @Autowired private JwtSigningAndValidationService jwtService; @@ -87,7 +87,7 @@ public class UserInfoJwtView extends UserInfoView { gson.toJson(json, writer); response.setContentType("application/jwt"); - + JWTClaimsSet claims = JWTClaimsSet.parse(writer.toString()); claims.setAudience(Lists.newArrayList(client.getClientId())); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoView.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoView.java index f165af496..6ef4a4b9c 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoView.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/view/UserInfoView.java @@ -49,7 +49,7 @@ public class UserInfoView extends AbstractView { private static JsonParser jsonParser = new JsonParser(); public static final String VIEWNAME = "userInfoView"; - + private static Logger logger = LoggerFactory.getLogger(UserInfoView.class); @Autowired diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientAPI.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientAPI.java index 5e011f2a1..ea38b1407 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientAPI.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientAPI.java @@ -161,20 +161,20 @@ public class ClientAPI { // if they leave the client identifier empty, force it to be generated if (Strings.isNullOrEmpty(client.getClientId())) { client = clientService.generateClientId(client); - } - - if (client.getTokenEndpointAuthMethod() == null || + } + + if (client.getTokenEndpointAuthMethod() == null || client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE)) { // we shouldn't have a secret for this client - + client.setClientSecret(null); - - } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) - || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) + + } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) + || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT)) { - + // if they've asked for us to generate a client secret (or they left it blank but require one), do so here - if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean() + if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean() || Strings.isNullOrEmpty(client.getClientSecret())) { client = clientService.generateClientSecret(client); } @@ -187,18 +187,18 @@ public class ClientAPI { m.addAttribute("errorMessage", "Can not create a client with private key authentication without registering a key via the JWS Set URI."); return JsonErrorView.VIEWNAME; } - + // otherwise we shouldn't have a secret for this client client.setClientSecret(null); - + } else { - + logger.error("unknown auth method"); m.addAttribute("code", HttpStatus.BAD_REQUEST); m.addAttribute("errorMessage", "Unknown auth method requested"); return JsonErrorView.VIEWNAME; - - + + } client.setDynamicallyRegistered(false); @@ -262,15 +262,15 @@ public class ClientAPI { if (client.getTokenEndpointAuthMethod() == null || client.getTokenEndpointAuthMethod().equals(AuthMethod.NONE)) { // we shouldn't have a secret for this client - + client.setClientSecret(null); - - } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) - || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) + + } else if (client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_BASIC) + || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_POST) || client.getTokenEndpointAuthMethod().equals(AuthMethod.SECRET_JWT)) { - + // if they've asked for us to generate a client secret (or they left it blank but require one), do so here - if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean() + if (json.has("generateClientSecret") && json.get("generateClientSecret").getAsBoolean() || Strings.isNullOrEmpty(client.getClientSecret())) { client = clientService.generateClientSecret(client); } @@ -283,18 +283,18 @@ public class ClientAPI { m.addAttribute("errorMessage", "Can not create a client with private key authentication without registering a key via the JWS Set URI."); return JsonErrorView.VIEWNAME; } - + // otherwise we shouldn't have a secret for this client client.setClientSecret(null); - + } else { - + logger.error("unknown auth method"); m.addAttribute("code", HttpStatus.BAD_REQUEST); m.addAttribute("errorMessage", "Unknown auth method requested"); return JsonErrorView.VIEWNAME; - - + + } ClientDetailsEntity newClient = clientService.updateClient(oldClient, client); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientDynamicRegistrationEndpoint.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientDynamicRegistrationEndpoint.java index 7824d08ec..4fdfd0d16 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientDynamicRegistrationEndpoint.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ClientDynamicRegistrationEndpoint.java @@ -133,7 +133,7 @@ public class ClientDynamicRegistrationEndpoint { m.addAttribute("code", ve.getStatus()); return JsonErrorView.VIEWNAME; } - + if (newClient.getTokenEndpointAuthMethod() == null) { newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); } @@ -178,11 +178,11 @@ public class ClientDynamicRegistrationEndpoint { return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("Couldn't save client", e); - + m.addAttribute("error", "invalid_client_metadata"); m.addAttribute("errorMessage", "Unable to save client due to invalid or inconsistent metadata."); m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400 - + return JsonErrorView.VIEWNAME; } } else { @@ -224,7 +224,7 @@ public class ClientDynamicRegistrationEndpoint { m.addAttribute("code", HttpStatus.INTERNAL_SERVER_ERROR); return HttpCodeView.VIEWNAME; } - + } else { // client mismatch logger.error("readClientConfiguration failed, client ID mismatch: " @@ -293,7 +293,7 @@ public class ClientDynamicRegistrationEndpoint { m.addAttribute("code", ve.getStatus()); return JsonErrorView.VIEWNAME; } - + try { // save the client ClientDetailsEntity savedClient = clientService.updateClient(oldClient, newClient); @@ -313,11 +313,11 @@ public class ClientDynamicRegistrationEndpoint { return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("Couldn't save client", e); - + m.addAttribute("error", "invalid_client_metadata"); m.addAttribute("errorMessage", "Unable to save client due to invalid or inconsistent metadata."); m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400 - + return JsonErrorView.VIEWNAME; } } else { @@ -376,17 +376,17 @@ public class ClientDynamicRegistrationEndpoint { } newClient.setScope(scopeService.toStrings(allowedScopes)); - + return newClient; } - + private ClientDetailsEntity validateResponseTypes(ClientDetailsEntity newClient) throws ValidationException { if (newClient.getResponseTypes() == null) { newClient.setResponseTypes(new HashSet()); } return newClient; } - + private ClientDetailsEntity validateGrantTypes(ClientDetailsEntity newClient) throws ValidationException { // set default grant types if needed if (newClient.getGrantTypes() == null || newClient.getGrantTypes().isEmpty()) { @@ -396,15 +396,15 @@ public class ClientDynamicRegistrationEndpoint { newClient.setGrantTypes(Sets.newHashSet("authorization_code")); // allow authorization code grant type by default } } - + // filter out unknown grant types // TODO: make this a pluggable service Set requestedGrantTypes = new HashSet(newClient.getGrantTypes()); requestedGrantTypes.retainAll( - ImmutableSet.of("authorization_code", "implicit", - "password", "client_credentials", "refresh_token", - "urn:ietf:params:oauth:grant_type:redelegate")); - + ImmutableSet.of("authorization_code", "implicit", + "password", "client_credentials", "refresh_token", + "urn:ietf:params:oauth:grant_type:redelegate")); + // don't allow "password" grant type for dynamic registration if (newClient.getGrantTypes().contains("password")) { // return an error, you can't dynamically register for the password grant @@ -425,12 +425,12 @@ public class ClientDynamicRegistrationEndpoint { // return an error, you can't have this grant type and response type together throw new ValidationException("invalid_client_metadata", "Incompatible response types requested: " + newClient.getGrantTypes() + " / " + newClient.getResponseTypes(), HttpStatus.BAD_REQUEST); } - + newClient.getResponseTypes().add("code"); - - + + } - + if (newClient.getGrantTypes().contains("implicit")) { // check for incompatible grants @@ -439,19 +439,19 @@ public class ClientDynamicRegistrationEndpoint { // return an error, you can't have these grant types together throw new ValidationException("invalid_client_metadata", "Incompatible grant types requested: " + newClient.getGrantTypes(), HttpStatus.BAD_REQUEST); } - + if (newClient.getResponseTypes().contains("code")) { // return an error, you can't have this grant type and response type together throw new ValidationException("invalid_client_metadata", "Incompatible response types requested: " + newClient.getGrantTypes() + " / " + newClient.getResponseTypes(), HttpStatus.BAD_REQUEST); } - + newClient.getResponseTypes().add("token"); - + // don't allow refresh tokens in implicit clients newClient.getGrantTypes().remove("refresh_token"); newClient.getScope().remove("offline_access"); } - + if (newClient.getGrantTypes().contains("client_credentials")) { // check for incompatible grants @@ -460,25 +460,25 @@ public class ClientDynamicRegistrationEndpoint { // return an error, you can't have these grant types together throw new ValidationException("invalid_client_metadata", "Incompatible grant types requested: " + newClient.getGrantTypes(), HttpStatus.BAD_REQUEST); } - + if (!newClient.getResponseTypes().isEmpty()) { // return an error, you can't have this grant type and response type together throw new ValidationException("invalid_client_metadata", "Incompatible response types requested: " + newClient.getGrantTypes() + " / " + newClient.getResponseTypes(), HttpStatus.BAD_REQUEST); } - + // don't allow refresh tokens or id tokens in client_credentials clients newClient.getGrantTypes().remove("refresh_token"); newClient.getScope().remove("offline_access"); newClient.getScope().remove("openid"); } - + if (newClient.getGrantTypes().isEmpty()) { // return an error, you need at least one grant type selected throw new ValidationException("invalid_client_metadata", "Clients must register at least one grant type.", HttpStatus.BAD_REQUEST); - } + } return newClient; } - + private ClientDetailsEntity validateRedirectUris(ClientDetailsEntity newClient) throws ValidationException { // check to make sure this client registered a redirect URI if using a redirect flow if (newClient.getGrantTypes().contains("authorization_code") || newClient.getGrantTypes().contains("implicit")) { @@ -492,17 +492,17 @@ public class ClientDynamicRegistrationEndpoint { // return an error throw new ValidationException("invalid_redirect_uri", "Redirect URI is not allowed: " + uri, HttpStatus.BAD_REQUEST); } - - if (uri.contains("#")) { + + if (uri.contains("#")) { // if it contains the hash symbol then it has a fragment, which isn't allowed throw new ValidationException("invalid_redirect_uri", "Redirect URI can not have a fragment", HttpStatus.BAD_REQUEST); } } } - + return newClient; } - + private ClientDetailsEntity validateAuth(ClientDetailsEntity newClient) throws ValidationException { if (newClient.getTokenEndpointAuthMethod() == null) { newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); @@ -520,7 +520,7 @@ public class ClientDynamicRegistrationEndpoint { if (Strings.isNullOrEmpty(newClient.getJwksUri())) { throw new ValidationException("invalid_client_metadata", "JWK Set URI required when using private key authentication", HttpStatus.BAD_REQUEST); } - + newClient.setClientSecret(null); } else if (newClient.getTokenEndpointAuthMethod() == AuthMethod.NONE) { newClient.setClientSecret(null); @@ -529,14 +529,14 @@ public class ClientDynamicRegistrationEndpoint { } return newClient; } - + private OAuth2AccessTokenEntity fetchValidRegistrationToken(OAuth2Authentication auth, ClientDetailsEntity client) { - + OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails(); OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue()); - + if (config.getRegTokenLifeTime() != null) { - + try { // Re-issue the token if it has been issued before [currentTime - validity] Date validToDate = new Date(System.currentTimeMillis() - config.getRegTokenLifeTime() * 1000); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/DataAPI.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/DataAPI.java index 080ecd68b..f84f351b7 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/DataAPI.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/DataAPI.java @@ -60,13 +60,13 @@ public class DataAPI { @Autowired private ConfigurationPropertiesBean config; - @Autowired + @Autowired private MITREidDataService_1_0 dataService_1_0; - - @Autowired + + @Autowired private MITREidDataService_1_1 dataService_1_1; - @Autowired + @Autowired private MITREidDataService_1_1 dataService_1_2; @RequestMapping(method = RequestMethod.POST, consumes = "application/json") @@ -79,29 +79,29 @@ public class DataAPI { while (reader.hasNext()) { JsonToken tok = reader.peek(); switch (tok) { - case NAME: - String name = reader.nextName(); - if (name.equals(MITREidDataService.MITREID_CONNECT_1_0)) { - dataService_1_0.importData(reader); - } else if (name.equals(MITREidDataService.MITREID_CONNECT_1_1)) { - dataService_1_1.importData(reader); - } else if (name.equals(MITREidDataService.MITREID_CONNECT_1_2)) { - dataService_1_2.importData(reader); - } else { - // consume the next bit silently for now - logger.debug("Skipping value for " + name); // TODO: write these out? - reader.skipValue(); - } - break; - case END_OBJECT: - reader.endObject(); - break; - case END_DOCUMENT: - break; + case NAME: + String name = reader.nextName(); + if (name.equals(MITREidDataService.MITREID_CONNECT_1_0)) { + dataService_1_0.importData(reader); + } else if (name.equals(MITREidDataService.MITREID_CONNECT_1_1)) { + dataService_1_1.importData(reader); + } else if (name.equals(MITREidDataService.MITREID_CONNECT_1_2)) { + dataService_1_2.importData(reader); + } else { + // consume the next bit silently for now + logger.debug("Skipping value for " + name); // TODO: write these out? + reader.skipValue(); + } + break; + case END_OBJECT: + reader.endObject(); + break; + case END_DOCUMENT: + break; } - } + } - return "httpCodeView"; + return "httpCodeView"; } @RequestMapping(method = RequestMethod.GET, produces = "application/json") @@ -115,7 +115,7 @@ public class DataAPI { try { - writer.beginObject(); + writer.beginObject(); writer.name("exported-at"); writer.value(dateFormat.format(new Date())); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ProtectedResourceRegistrationEndpoint.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ProtectedResourceRegistrationEndpoint.java index c605753b7..30ed917a7 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ProtectedResourceRegistrationEndpoint.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/ProtectedResourceRegistrationEndpoint.java @@ -55,7 +55,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.util.UriUtils; import com.google.common.base.Strings; -import com.google.common.collect.Sets; import com.google.gson.JsonSyntaxException; @Controller @@ -184,11 +183,11 @@ public class ProtectedResourceRegistrationEndpoint { return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("Couldn't save client", e); - + m.addAttribute("error", "invalid_client_metadata"); m.addAttribute("errorMessage", "Unable to save client due to invalid or inconsistent metadata."); m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400 - + return JsonErrorView.VIEWNAME; } } else { @@ -204,7 +203,7 @@ public class ProtectedResourceRegistrationEndpoint { private ClientDetailsEntity validateScopes(ClientDetailsEntity newClient) throws ValidationException { // note that protected resources can register for any scopes, even ones not used by the sysadmin - + // scopes that the client is asking for Set requestedScopes = scopeService.fromStrings(newClient.getScope()); @@ -214,7 +213,7 @@ public class ProtectedResourceRegistrationEndpoint { } newClient.setScope(scopeService.toStrings(requestedScopes)); - + return newClient; } @@ -363,11 +362,11 @@ public class ProtectedResourceRegistrationEndpoint { return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("Couldn't save client", e); - + m.addAttribute("error", "invalid_client_metadata"); m.addAttribute("errorMessage", "Unable to save client due to invalid or inconsistent metadata."); m.addAttribute("code", HttpStatus.BAD_REQUEST); // http 400 - + return JsonErrorView.VIEWNAME; } } else { @@ -428,7 +427,7 @@ public class ProtectedResourceRegistrationEndpoint { if (Strings.isNullOrEmpty(newClient.getJwksUri())) { throw new ValidationException("invalid_client_metadata", "JWK Set URI required when using private key authentication", HttpStatus.BAD_REQUEST); } - + newClient.setClientSecret(null); } else if (newClient.getTokenEndpointAuthMethod() == AuthMethod.NONE) { newClient.setClientSecret(null); @@ -437,14 +436,14 @@ public class ProtectedResourceRegistrationEndpoint { } return newClient; } - + private OAuth2AccessTokenEntity fetchValidRegistrationToken(OAuth2Authentication auth, ClientDetailsEntity client) { - + OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails(); OAuth2AccessTokenEntity token = tokenService.readAccessToken(details.getTokenValue()); - + if (config.getRegTokenLifeTime() != null) { - + try { // Re-issue the token if it has been issued before [currentTime - validity] Date validToDate = new Date(System.currentTimeMillis() - config.getRegTokenLifeTime() * 1000); diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoEndpoint.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoEndpoint.java index 2afa5f022..805e9df3f 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoEndpoint.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/web/UserInfoEndpoint.java @@ -99,11 +99,11 @@ public class UserInfoEndpoint { // start off by seeing if the client has registered for a signed/encrypted JWT from here ClientDetailsEntity client = clientService.loadClientByClientId(auth.getOAuth2Request().getClientId()); model.addAttribute("client", client); - + List mediaTypes = MediaType.parseMediaTypes(acceptHeader); MediaType.sortBySpecificityAndQuality(mediaTypes); - - if (client.getUserInfoSignedResponseAlg() != null + + if (client.getUserInfoSignedResponseAlg() != null || client.getUserInfoEncryptedResponseAlg() != null || client.getUserInfoEncryptedResponseEnc() != null) { // client has a preference, see if they ask for plain JSON specifically on this request @@ -114,7 +114,7 @@ public class UserInfoEndpoint { return UserInfoView.VIEWNAME; } } - + // otherwise return JWT return UserInfoJwtView.VIEWNAME; } else { diff --git a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionAuthorizer.java b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionAuthorizer.java index a3dab1395..d163f11c1 100755 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionAuthorizer.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionAuthorizer.java @@ -83,8 +83,7 @@ public class TestDefaultIntrospectionAuthorizer { String tokenClient = "token"; Set authScope = scope("scope1", "scope2"); Set tokenScope = scope("scope1", "scope2", "scope3"); - given(scopeService.scopesMatch(authScope, tokenScope)) - .willReturn(false); + given(scopeService.scopesMatch(authScope, tokenScope)).willReturn(false); // when boolean permitted = introspectionPermitter.isIntrospectionPermitted( @@ -101,8 +100,7 @@ public class TestDefaultIntrospectionAuthorizer { return client; } - private ClientDetails clientWithIdAndScope(String clientId, - Set scope) { + private ClientDetails clientWithIdAndScope(String clientId, Set scope) { ClientDetails client = clientWithId(clientId); given(client.getScope()).willReturn(scope); return client; diff --git a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionResultAssembler.java b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionResultAssembler.java index 3172539c7..4a3d32127 100644 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionResultAssembler.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultIntrospectionResultAssembler.java @@ -16,13 +16,13 @@ *******************************************************************************/ package org.mitre.oauth2.service.impl; -import com.google.common.collect.ImmutableMap; -import org.junit.Test; -import org.mitre.oauth2.model.OAuth2AccessTokenEntity; -import org.mitre.oauth2.model.OAuth2RefreshTokenEntity; -import org.mitre.openid.connect.model.UserInfo; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.oauth2.provider.OAuth2Request; +import static com.google.common.collect.Sets.newHashSet; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.BDDMockito.given; +import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.mock; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -32,209 +32,210 @@ import java.util.Set; import javax.swing.text.DateFormatter; -import static com.google.common.collect.Sets.newHashSet; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; +import org.junit.Test; +import org.mitre.oauth2.model.OAuth2AccessTokenEntity; +import org.mitre.oauth2.model.OAuth2RefreshTokenEntity; +import org.mitre.openid.connect.model.UserInfo; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.oauth2.provider.OAuth2Request; + +import com.google.common.collect.ImmutableMap; public class TestDefaultIntrospectionResultAssembler { - private DefaultIntrospectionResultAssembler assembler = new DefaultIntrospectionResultAssembler(); + private DefaultIntrospectionResultAssembler assembler = new DefaultIntrospectionResultAssembler(); - private static DateFormatter dateFormat = new DateFormatter(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")); - - @Test - public void shouldAssembleExpectedResultForAccessToken() throws ParseException { + private static DateFormatter dateFormat = new DateFormatter(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")); - // given - OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer", - authentication("name", request("clientId"))); + @Test + public void shouldAssembleExpectedResultForAccessToken() throws ParseException { - UserInfo userInfo = userInfo("sub"); + // given + OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer", + authentication("name", request("clientId"))); - // when - Map result = assembler.assembleFrom(accessToken, userInfo); + UserInfo userInfo = userInfo("sub"); + + // when + Map result = assembler.assembleFrom(accessToken, userInfo); - // then - Map expected = new ImmutableMap.Builder() - .put("sub", "sub") - .put("exp", 123L) - .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) - .put("scope", "bar foo") - .put("active", Boolean.TRUE) - .put("user_id", "name") - .put("client_id", "clientId") - .put("token_type", "Bearer") - .build(); - assertThat(result, is(equalTo(expected))); - } + // then + Map expected = new ImmutableMap.Builder() + .put("sub", "sub") + .put("exp", 123L) + .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) + .put("scope", "bar foo") + .put("active", Boolean.TRUE) + .put("user_id", "name") + .put("client_id", "clientId") + .put("token_type", "Bearer") + .build(); + assertThat(result, is(equalTo(expected))); + } - @Test - public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws ParseException { + @Test + public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws ParseException { - // given - OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer", - authentication("name", request("clientId"))); + // given + OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer", + authentication("name", request("clientId"))); - // when - Map result = assembler.assembleFrom(accessToken, null); + // when + Map result = assembler.assembleFrom(accessToken, null); - // then - Map expected = new ImmutableMap.Builder() - .put("sub", "name") - .put("exp", 123L) - .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) - .put("scope", "bar foo") - .put("active", Boolean.TRUE) - .put("user_id", "name") - .put("client_id", "clientId") - .put("token_type", "Bearer") - .build(); - assertThat(result, is(equalTo(expected))); - } + // then + Map expected = new ImmutableMap.Builder() + .put("sub", "name") + .put("exp", 123L) + .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) + .put("scope", "bar foo") + .put("active", Boolean.TRUE) + .put("user_id", "name") + .put("client_id", "clientId") + .put("token_type", "Bearer") + .build(); + assertThat(result, is(equalTo(expected))); + } - @Test - public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() { + @Test + public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() { - // given - OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), "Bearer", - authentication("name", request("clientId"))); + // given + OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), "Bearer", + authentication("name", request("clientId"))); - UserInfo userInfo = userInfo("sub"); + UserInfo userInfo = userInfo("sub"); - // when - Map result = assembler.assembleFrom(accessToken, userInfo); + // when + Map result = assembler.assembleFrom(accessToken, userInfo); - // then - Map expected = new ImmutableMap.Builder() - .put("sub", "sub") - .put("scope", "bar foo") - .put("active", Boolean.TRUE) - .put("user_id", "name") - .put("client_id", "clientId") - .put("token_type", "Bearer") - .build(); - assertThat(result, is(equalTo(expected))); - } + // then + Map expected = new ImmutableMap.Builder() + .put("sub", "sub") + .put("scope", "bar foo") + .put("active", Boolean.TRUE) + .put("user_id", "name") + .put("client_id", "clientId") + .put("token_type", "Bearer") + .build(); + assertThat(result, is(equalTo(expected))); + } - @Test - public void shouldAssembleExpectedResultForRefreshToken() throws ParseException { + @Test + public void shouldAssembleExpectedResultForRefreshToken() throws ParseException { - // given - OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L), - authentication("name", request("clientId", scopes("foo", "bar")))); + // given + OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L), + authentication("name", request("clientId", scopes("foo", "bar")))); - UserInfo userInfo = userInfo("sub"); + UserInfo userInfo = userInfo("sub"); - // when - Map result = assembler.assembleFrom(refreshToken, userInfo); + // when + Map result = assembler.assembleFrom(refreshToken, userInfo); - // then - Map expected = new ImmutableMap.Builder() - .put("sub", "sub") - .put("exp", 123L) - .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) - .put("scope", "bar foo") - .put("active", Boolean.TRUE) - .put("user_id", "name") - .put("client_id", "clientId") - .build(); - assertThat(result, is(equalTo(expected))); - } + // then + Map expected = new ImmutableMap.Builder() + .put("sub", "sub") + .put("exp", 123L) + .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) + .put("scope", "bar foo") + .put("active", Boolean.TRUE) + .put("user_id", "name") + .put("client_id", "clientId") + .build(); + assertThat(result, is(equalTo(expected))); + } - @Test - public void shouldAssembleExpectedResultForRefreshTokenWithoutUserInfo() throws ParseException { + @Test + public void shouldAssembleExpectedResultForRefreshTokenWithoutUserInfo() throws ParseException { - // given - OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L), - authentication("name", request("clientId", scopes("foo", "bar")))); + // given + OAuth2RefreshTokenEntity refreshToken = refreshToken(new Date(123 * 1000L), + authentication("name", request("clientId", scopes("foo", "bar")))); - // when - Map result = assembler.assembleFrom(refreshToken, null); + // when + Map result = assembler.assembleFrom(refreshToken, null); - // then - Map expected = new ImmutableMap.Builder() - .put("sub", "name") - .put("exp", 123L) - .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) - .put("scope", "bar foo") - .put("active", Boolean.TRUE) - .put("user_id", "name") - .put("client_id", "clientId") - .build(); - assertThat(result, is(equalTo(expected))); - } + // then + Map expected = new ImmutableMap.Builder() + .put("sub", "name") + .put("exp", 123L) + .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) + .put("scope", "bar foo") + .put("active", Boolean.TRUE) + .put("user_id", "name") + .put("client_id", "clientId") + .build(); + assertThat(result, is(equalTo(expected))); + } - @Test - public void shouldAssembleExpectedResultForRefreshTokenWithoutExpiry() { + @Test + public void shouldAssembleExpectedResultForRefreshTokenWithoutExpiry() { - // given - OAuth2RefreshTokenEntity refreshToken = refreshToken(null, - authentication("name", request("clientId", scopes("foo", "bar")))); + // given + OAuth2RefreshTokenEntity refreshToken = refreshToken(null, + authentication("name", request("clientId", scopes("foo", "bar")))); - UserInfo userInfo = userInfo("sub"); + UserInfo userInfo = userInfo("sub"); - // when - Map result = assembler.assembleFrom(refreshToken, userInfo); + // when + Map result = assembler.assembleFrom(refreshToken, userInfo); - // then - Map expected = new ImmutableMap.Builder() - .put("sub", "sub") - .put("scope", "bar foo") - .put("active", Boolean.TRUE) - .put("user_id", "name") - .put("client_id", "clientId") - .build(); - assertThat(result, is(equalTo(expected))); - } + // then + Map expected = new ImmutableMap.Builder() + .put("sub", "sub") + .put("scope", "bar foo") + .put("active", Boolean.TRUE) + .put("user_id", "name") + .put("client_id", "clientId") + .build(); + assertThat(result, is(equalTo(expected))); + } - private UserInfo userInfo(String sub) { - UserInfo userInfo = mock(UserInfo.class); - given(userInfo.getSub()).willReturn(sub); - return userInfo; - } + private UserInfo userInfo(String sub) { + UserInfo userInfo = mock(UserInfo.class); + given(userInfo.getSub()).willReturn(sub); + return userInfo; + } - private OAuth2AccessTokenEntity accessToken(Date exp, Set scopes, String tokenType, OAuth2Authentication authentication) { - OAuth2AccessTokenEntity accessToken = mock(OAuth2AccessTokenEntity.class, RETURNS_DEEP_STUBS); - given(accessToken.getExpiration()).willReturn(exp); - given(accessToken.getScope()).willReturn(scopes); - given(accessToken.getTokenType()).willReturn(tokenType); - given(accessToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication); - return accessToken; - } + private OAuth2AccessTokenEntity accessToken(Date exp, Set scopes, String tokenType, OAuth2Authentication authentication) { + OAuth2AccessTokenEntity accessToken = mock(OAuth2AccessTokenEntity.class, RETURNS_DEEP_STUBS); + given(accessToken.getExpiration()).willReturn(exp); + given(accessToken.getScope()).willReturn(scopes); + given(accessToken.getTokenType()).willReturn(tokenType); + given(accessToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication); + return accessToken; + } - private OAuth2RefreshTokenEntity refreshToken(Date exp, OAuth2Authentication authentication) { - OAuth2RefreshTokenEntity refreshToken = mock(OAuth2RefreshTokenEntity.class, RETURNS_DEEP_STUBS); - given(refreshToken.getExpiration()).willReturn(exp); - given(refreshToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication); - return refreshToken; - } - - private OAuth2Authentication authentication(String name, OAuth2Request request) { - OAuth2Authentication authentication = mock(OAuth2Authentication.class); - given(authentication.getName()).willReturn(name); - given(authentication.getOAuth2Request()).willReturn(request); - return authentication; - } + private OAuth2RefreshTokenEntity refreshToken(Date exp, OAuth2Authentication authentication) { + OAuth2RefreshTokenEntity refreshToken = mock(OAuth2RefreshTokenEntity.class, RETURNS_DEEP_STUBS); + given(refreshToken.getExpiration()).willReturn(exp); + given(refreshToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication); + return refreshToken; + } - private OAuth2Request request(String clientId) { - return request(clientId, null); - } + private OAuth2Authentication authentication(String name, OAuth2Request request) { + OAuth2Authentication authentication = mock(OAuth2Authentication.class); + given(authentication.getName()).willReturn(name); + given(authentication.getOAuth2Request()).willReturn(request); + return authentication; + } - private OAuth2Request request(String clientId, Set scopes) { - return new OAuth2Request(null, clientId, null, true, scopes, null, null, null, null); - } + private OAuth2Request request(String clientId) { + return request(clientId, null); + } - private Set scopes(String... scopes) { - return newHashSet(scopes); - } + private OAuth2Request request(String clientId, Set scopes) { + return new OAuth2Request(null, clientId, null, true, scopes, null, null, null, null); + } + + private Set scopes(String... scopes) { + return newHashSet(scopes); + } } 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 e45ea0c72..b27929aad 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 @@ -82,31 +82,31 @@ public class TestDefaultOAuth2ClientDetailsEntityService { @Before public void prepare() { Mockito.reset(clientRepository, tokenRepository, approvedSiteService, whitelistedSiteService, blacklistedSiteService, scopeService, statsService); - - Mockito.when(clientRepository.saveClient(Mockito.any(ClientDetailsEntity.class))).thenAnswer(new Answer() { + + Mockito.when(clientRepository.saveClient(Matchers.any(ClientDetailsEntity.class))).thenAnswer(new Answer() { @Override public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (ClientDetailsEntity) args[0]; } }); - - Mockito.when(clientRepository.updateClient(Mockito.anyLong(), Mockito.any(ClientDetailsEntity.class))).thenAnswer(new Answer() { + + 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(scopeService.removeRestrictedScopes(Mockito.anySet())).thenAnswer(new Answer>() { + + Mockito.when(scopeService.removeRestrictedScopes(Matchers.anySet())).thenAnswer(new Answer>() { @Override public Set answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (Set) args[0]; } }); - + } /** @@ -158,7 +158,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { public void saveNewClient_yesOfflineAccess() { ClientDetailsEntity client = new ClientDetailsEntity(); - + Set grantTypes = new HashSet(); grantTypes.add("refresh_token"); client.setGrantTypes(grantTypes); @@ -175,7 +175,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { public void saveNewClient_noOfflineAccess() { ClientDetailsEntity client = new ClientDetailsEntity(); - + client = service.saveNewClient(client); assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); @@ -293,7 +293,7 @@ public class TestDefaultOAuth2ClientDetailsEntityService { ClientDetailsEntity oldClient = new ClientDetailsEntity(); ClientDetailsEntity client = new ClientDetailsEntity(); - + Set grantTypes = new HashSet(); grantTypes.add("refresh_token"); client.setGrantTypes(grantTypes); @@ -307,11 +307,11 @@ public class TestDefaultOAuth2ClientDetailsEntityService { public void updateClient_noOfflineAccess() { ClientDetailsEntity oldClient = new ClientDetailsEntity(); - + oldClient.getScope().add(SystemScopeService.OFFLINE_ACCESS); - + ClientDetailsEntity client = new ClientDetailsEntity(); - + client = service.updateClient(oldClient, client); assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); 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 8c5924442..b3a2c776a 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 @@ -121,10 +121,10 @@ public class TestDefaultOAuth2ProviderTokenService { // by default in tests, allow refresh tokens Mockito.when(client.isAllowRefresh()).thenReturn(true); - + badClient = Mockito.mock(ClientDetailsEntity.class); Mockito.when(badClient.getClientId()).thenReturn(badClientId); - Mockito.when(clientDetailsService.loadClientByClientId(badClientId)).thenReturn(badClient); + Mockito.when(clientDetailsService.loadClientByClientId(badClientId)).thenReturn(badClient); refreshToken = Mockito.mock(OAuth2RefreshTokenEntity.class); Mockito.when(tokenRepository.getRefreshTokenByValue(refreshTokenValue)).thenReturn(refreshToken); @@ -147,8 +147,8 @@ public class TestDefaultOAuth2ProviderTokenService { Mockito.when(scopeService.removeRestrictedScopes(Matchers.anySet())).then(AdditionalAnswers.returnsFirstArg()); Mockito.when(tokenEnhancer.enhance(Matchers.any(OAuth2AccessTokenEntity.class), Matchers.any(OAuth2Authentication.class))) - .thenAnswer(new Answer(){ - @Override + .thenAnswer(new Answer(){ + @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); return (OAuth2AccessTokenEntity) args[0]; @@ -156,24 +156,24 @@ public class TestDefaultOAuth2ProviderTokenService { }); Mockito.when(tokenRepository.saveAccessToken(Matchers.any(OAuth2AccessTokenEntity.class))) - .thenAnswer(new Answer() { - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return (OAuth2AccessTokenEntity) args[0]; - } - - }); + .thenAnswer(new Answer() { + @Override + public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return (OAuth2AccessTokenEntity) args[0]; + } + + }); Mockito.when(tokenRepository.saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class))) - .thenAnswer(new Answer() { - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return (OAuth2RefreshTokenEntity) args[0]; - } - }); - + .thenAnswer(new Answer() { + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return (OAuth2RefreshTokenEntity) args[0]; + } + }); + } /** @@ -222,7 +222,7 @@ public class TestDefaultOAuth2ProviderTokenService { Mockito.verify(clientDetailsService).loadClientByClientId(Matchers.anyString()); Mockito.verify(authenticationHolderRepository).save(Matchers.any(AuthenticationHolderEntity.class)); - Mockito.verify(tokenEnhancer).enhance(Matchers.any(OAuth2AccessTokenEntity.class), Mockito.eq(authentication)); + Mockito.verify(tokenEnhancer).enhance(Matchers.any(OAuth2AccessTokenEntity.class), Matchers.eq(authentication)); Mockito.verify(tokenRepository).saveAccessToken(Matchers.any(OAuth2AccessTokenEntity.class)); Mockito.verify(tokenRepository, Mockito.never()).saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class)); @@ -326,7 +326,7 @@ public class TestDefaultOAuth2ProviderTokenService { service.refreshAccessToken(refreshTokenValue, tokenRequest); } - + @Test(expected = InvalidTokenException.class) public void refreshAccessToken_expired() { 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 838370cde..17611f681 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 @@ -83,298 +83,298 @@ import com.google.gson.stream.JsonWriter; public class TestMITREidDataService_1_0 { @Mock - private OAuth2ClientRepository clientRepository; + private OAuth2ClientRepository clientRepository; @Mock - private ApprovedSiteRepository approvedSiteRepository; - @Mock - private WhitelistedSiteRepository wlSiteRepository; - @Mock - private BlacklistedSiteRepository blSiteRepository; + private ApprovedSiteRepository approvedSiteRepository; @Mock - private AuthenticationHolderRepository authHolderRepository; + private WhitelistedSiteRepository wlSiteRepository; @Mock - private OAuth2TokenRepository tokenRepository; + private BlacklistedSiteRepository blSiteRepository; @Mock - private SystemScopeRepository sysScopeRepository; - - @Captor - private ArgumentCaptor capturedRefreshTokens; - @Captor - private ArgumentCaptor capturedAccessTokens; - @Captor - private ArgumentCaptor capturedClients; - @Captor - private ArgumentCaptor capturedBlacklistedSites; - @Captor - private ArgumentCaptor capturedWhitelistedSites; - @Captor - private ArgumentCaptor capturedApprovedSites; - @Captor - private ArgumentCaptor capturedAuthHolders; + private AuthenticationHolderRepository authHolderRepository; + @Mock + private OAuth2TokenRepository tokenRepository; + @Mock + private SystemScopeRepository sysScopeRepository; + + @Captor + private ArgumentCaptor capturedRefreshTokens; + @Captor + private ArgumentCaptor capturedAccessTokens; + @Captor + private ArgumentCaptor capturedClients; + @Captor + private ArgumentCaptor capturedBlacklistedSites; + @Captor + private ArgumentCaptor capturedWhitelistedSites; + @Captor + private ArgumentCaptor capturedApprovedSites; + @Captor + private ArgumentCaptor capturedAuthHolders; @Captor private ArgumentCaptor capturedScope; - + @InjectMocks private MITREidDataService_1_0 dataService; @Before public void prepare() { Mockito.reset(clientRepository, approvedSiteRepository, authHolderRepository, tokenRepository, sysScopeRepository, wlSiteRepository, blSiteRepository); - } + } - private class refreshTokenIdComparator implements Comparator { - @Override - public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) { - return entity1.getId().compareTo(entity2.getId()); - } - } + private class refreshTokenIdComparator implements Comparator { + @Override + public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) { + return entity1.getId().compareTo(entity2.getId()); + } + } + + @Test + public void testImportRefreshTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); + token1.setAuthenticationHolder(mockedAuthHolder1); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); + token2.setAuthenticationHolder(mockedAuthHolder2); - @Test - public void testImportRefreshTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - 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); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); - token1.setAuthenticationHolder(mockedAuthHolder1); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); - token2.setAuthenticationHolder(mockedAuthHolder2); - String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + - + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + + " ]" + "}"; - + System.err.println(configJson); - JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { - Long id = 343L; - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeDb.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 678L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); - id++; - return _auth; - } - }); + JsonReader reader = new JsonReader(new StringReader(configJson)); + + final Map fakeDb = new HashMap(); + when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + Long id = 343L; + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeDb.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeDb.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + Long id = 678L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); + when(_auth.getId()).thenReturn(id); + id++; + return _auth; + } + }); dataService.importData(reader); - //2 times for token, 2 times to update client, 2 times to update authHolder + //2 times for token, 2 times to update client, 2 times to update authHolder verify(tokenRepository, times(6)).saveRefreshToken(capturedRefreshTokens.capture()); - - List savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues(); - Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - - assertThat(savedRefreshTokens.size(), is(2)); - - assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); - assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); - assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue())); - assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); - assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); - assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue())); - } - - private class accessTokenIdComparator implements Comparator { - @Override - public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) { - return entity1.getId().compareTo(entity2.getId()); - } - } - - @Test - public void testImportAccessTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + List savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues(); + Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); - token1.setId(1L); - token1.setClient(mockedClient1); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); - token1.setAuthenticationHolder(mockedAuthHolder1); - token1.setScope(ImmutableSet.of("id-token")); - token1.setTokenType("Bearer"); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + assertThat(savedRefreshTokens.size(), is(2)); + + assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); + assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); + assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue())); + + assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); + assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); + assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue())); + } + + private class accessTokenIdComparator implements Comparator { + @Override + public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) { + return entity1.getId().compareTo(entity2.getId()); + } + } + + @Test + public void testImportAccessTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); + token1.setAuthenticationHolder(mockedAuthHolder1); + token1.setScope(ImmutableSet.of("id-token")); + token1.setTokenType("Bearer"); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); + token2.setAuthenticationHolder(mockedAuthHolder2); + token2.setIdToken(token1); + token2.setRefreshToken(mockRefreshToken2); + token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); + token2.setTokenType("Bearer"); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); - token2.setAuthenticationHolder(mockedAuthHolder2); - token2.setIdToken(token1); - token2.setRefreshToken(mockRefreshToken2); - token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); - token2.setTokenType("Bearer"); - String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," + + + "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\"," + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" + - + + "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\"," + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" + + " ]" + "}"; - - + + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - final Map fakeDb = new HashMap(); - when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { - Long id = 343L; - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeDb.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 234L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); - id++; - return _auth; - } - }); + final Map fakeDb = new HashMap(); + when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { + Long id = 343L; + @Override + public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeDb.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeDb.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + Long id = 234L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); + when(_auth.getId()).thenReturn(id); + id++; + return _auth; + } + }); dataService.importData(reader); - //2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token + //2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token verify(tokenRepository, times(8)).saveAccessToken(capturedAccessTokens.capture()); - - List savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues(); - Collections.sort(savedAccessTokens, new accessTokenIdComparator()); - - assertThat(savedAccessTokens.size(), is(2)); - - assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); - assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); - assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue())); - assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); - assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); - assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue())); - } - - - //several new client fields added in 1.1, perhaps additional tests for these should be added + List savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues(); + Collections.sort(savedAccessTokens, new accessTokenIdComparator()); + + assertThat(savedAccessTokens.size(), is(2)); + + assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); + assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); + assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue())); + + assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); + assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); + assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue())); + } + + + //several new client fields added in 1.1, perhaps additional tests for these should be added @Test public void testImportClients() throws IOException { ClientDetailsEntity client1 = new ClientDetailsEntity(); @@ -406,33 +406,33 @@ public class TestMITREidDataService_1_0 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.CLIENTS + "\": [" + - + "{\"id\":1,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client1\",\"secret\":\"clientsecret1\"," - + "\"redirectUris\":[\"http://foo.com/\"]," - + "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"]," - + "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"]," - + "\"allowIntrospection\":true}," + + + "\"redirectUris\":[\"http://foo.com/\"]," + + "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"]," + + "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"]," + + "\"allowIntrospection\":true}," + "{\"id\":2,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client2\",\"secret\":\"clientsecret2\"," - + "\"redirectUris\":[\"http://bar.baz.com/\"]," - + "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"]," - + "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"]," - + "\"allowIntrospection\":false}" + - + + "\"redirectUris\":[\"http://bar.baz.com/\"]," + + "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"]," + + "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"]," + + "\"allowIntrospection\":false}" + + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(clientRepository, times(2)).saveClient(capturedClients.capture()); - + List savedClients = capturedClients.getAllValues(); - + assertThat(savedClients.size(), is(2)); - - assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds())); + + assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds())); assertThat(savedClients.get(0).getClientId(), equalTo(client1.getClientId())); assertThat(savedClients.get(0).getClientSecret(), equalTo(client1.getClientSecret())); assertThat(savedClients.get(0).getRedirectUris(), equalTo(client1.getRedirectUris())); @@ -440,7 +440,7 @@ public class TestMITREidDataService_1_0 { assertThat(savedClients.get(0).getGrantTypes(), equalTo(client1.getGrantTypes())); assertThat(savedClients.get(0).isAllowIntrospection(), equalTo(client1.isAllowIntrospection())); - assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds())); + assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds())); assertThat(savedClients.get(1).getClientId(), equalTo(client2.getClientId())); assertThat(savedClients.get(1).getClientSecret(), equalTo(client2.getClientSecret())); assertThat(savedClients.get(1).getRedirectUris(), equalTo(client2.getRedirectUris())); @@ -452,16 +452,16 @@ public class TestMITREidDataService_1_0 { @Test public void testImportBlacklistedSites() throws IOException { BlacklistedSite site1 = new BlacklistedSite(); - site1.setId(1L); - site1.setUri("http://foo.com"); + site1.setId(1L); + site1.setUri("http://foo.com"); - BlacklistedSite site2 = new BlacklistedSite(); - site2.setId(2L); - site2.setUri("http://bar.com"); - - BlacklistedSite site3 = new BlacklistedSite(); - site3.setId(3L); - site3.setUri("http://baz.com"); + BlacklistedSite site2 = new BlacklistedSite(); + site2.setId(2L); + site2.setUri("http://bar.com"); + + BlacklistedSite site3 = new BlacklistedSite(); + site3.setId(3L); + site3.setUri("http://baz.com"); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -469,47 +469,47 @@ public class TestMITREidDataService_1_0 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [" + - + "{\"id\":1,\"uri\":\"http://foo.com\"}," + "{\"id\":2,\"uri\":\"http://bar.com\"}," + "{\"id\":3,\"uri\":\"http://baz.com\"}" + - + " ]" + "}"; - - + + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(blSiteRepository, times(3)).save(capturedBlacklistedSites.capture()); - + List savedSites = capturedBlacklistedSites.getAllValues(); - + assertThat(savedSites.size(), is(3)); - + assertThat(savedSites.get(0).getUri(), equalTo(site1.getUri())); - assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri())); + assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri())); assertThat(savedSites.get(2).getUri(), equalTo(site3.getUri())); } @Test public void testImportWhitelistedSites() throws IOException { WhitelistedSite site1 = new WhitelistedSite(); - site1.setId(1L); - site1.setClientId("foo"); + site1.setId(1L); + site1.setClientId("foo"); - WhitelistedSite site2 = new WhitelistedSite(); - site2.setId(2L); - site2.setClientId("bar"); - - WhitelistedSite site3 = new WhitelistedSite(); - site3.setId(3L); - site3.setClientId("baz"); + WhitelistedSite site2 = new WhitelistedSite(); + site2.setId(2L); + site2.setClientId("bar"); + + WhitelistedSite site3 = new WhitelistedSite(); + site3.setId(3L); + site3.setClientId("baz"); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -517,87 +517,87 @@ public class TestMITREidDataService_1_0 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [" + - + "{\"id\":1,\"clientId\":\"foo\"}," + "{\"id\":2,\"clientId\":\"bar\"}," + "{\"id\":3,\"clientId\":\"baz\"}" + - + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { - Long id = 345L; - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - 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); - } - }); - + + final Map fakeDb = new HashMap(); + when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { + Long id = 345L; + @Override + public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { + WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + 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()); - - List savedSites = capturedWhitelistedSites.getAllValues(); - - assertThat(savedSites.size(), is(3)); - - assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); - assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); - assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId())); - } - - @Test - public void testImportGrants() throws IOException { - Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); - Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); - - WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); - when(mockWlSite1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); - - ApprovedSite site1 = new ApprovedSite(); - site1.setId(1L); - site1.setClientId("foo"); - site1.setCreationDate(creationDate1); - site1.setAccessDate(accessDate1); - site1.setUserId("user1"); - site1.setWhitelistedSite(mockWlSite1); - site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); - Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); - Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); - Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); - + List savedSites = capturedWhitelistedSites.getAllValues(); + + assertThat(savedSites.size(), is(3)); + + assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); + assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); + assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId())); + } + + @Test + public void testImportGrants() throws IOException { + Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); + Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); + + WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); + when(mockWlSite1.getId()).thenReturn(1L); + + OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); + when(mockToken1.getId()).thenReturn(1L); + + ApprovedSite site1 = new ApprovedSite(); + site1.setId(1L); + site1.setClientId("foo"); + site1.setCreationDate(creationDate1); + site1.setAccessDate(accessDate1); + site1.setUserId("user1"); + site1.setWhitelistedSite(mockWlSite1); + site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); + site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); + + Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); + Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); + Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); + ApprovedSite site2 = new ApprovedSite(); - site2.setId(2L); - site2.setClientId("bar"); - site2.setCreationDate(creationDate2); - site2.setAccessDate(accessDate2); - site2.setUserId("user2"); - site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); - site2.setTimeoutDate(timeoutDate2); + site2.setId(2L); + site2.setClientId("bar"); + site2.setCreationDate(creationDate2); + site2.setAccessDate(accessDate2); + site2.setUserId("user2"); + site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); + site2.setTimeoutDate(timeoutDate2); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -605,110 +605,110 @@ public class TestMITREidDataService_1_0 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [" + - + "{\"id\":1,\"clientId\":\"foo\",\"creationDate\":\"2014-09-10T22:49:44.090+0000\",\"accessDate\":\"2014-09-10T23:49:44.090+0000\"," - + "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1," - + "\"approvedAccessTokens\":[1]}," + + + "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1," + + "\"approvedAccessTokens\":[1]}," + "{\"id\":2,\"clientId\":\"bar\",\"creationDate\":\"2014-09-11T18:49:44.090+0000\",\"accessDate\":\"2014-09-11T20:49:44.090+0000\"," - + "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\"," - + "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" + - + + "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\"," + + "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" + + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { - Long id = 343L; - @Override - public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { - ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - return _site; - } - }); - when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[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; - } - }); + + final Map fakeDb = new HashMap(); + when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { + Long id = 343L; + @Override + public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { + ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + return _site; + } + }); + when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + @Override + public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[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; + } + }); dataService.importData(reader); - //2 for sites, 1 for updating access token ref on #1, 1 more for updating whitelistedSite ref on #2 + //2 for sites, 1 for updating access token ref on #1, 1 more for updating whitelistedSite ref on #2 verify(approvedSiteRepository, times(4)).save(capturedApprovedSites.capture()); - - List savedSites = new ArrayList(fakeDb.values()); - - assertThat(savedSites.size(), is(2)); - - assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); - assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate())); - assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate())); - assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes())); - assertThat(savedSites.get(0).getIsWhitelisted(), equalTo(site1.getIsWhitelisted())); - assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate())); - assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size())); - - assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); - assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate())); - assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate())); - assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes())); - assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate())); - assertThat(savedSites.get(1).getIsWhitelisted(), equalTo(site2.getIsWhitelisted())); - assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size())); - } - - @Test - public void testImportAuthenticationHolders() throws IOException { - OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), - true, new HashSet(), new HashSet(), "http://foo.com", - new HashSet(), null); - Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); - - AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); - holder1.setId(1L); - holder1.setAuthentication(auth1); - - OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), - true, new HashSet(), new HashSet(), "http://bar.com", - new HashSet(), null); - Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); - - AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); - holder2.setId(2L); - holder2.setAuthentication(auth2); - + + List savedSites = new ArrayList(fakeDb.values()); + + assertThat(savedSites.size(), is(2)); + + assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); + assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate())); + assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate())); + assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes())); + assertThat(savedSites.get(0).getIsWhitelisted(), equalTo(site1.getIsWhitelisted())); + assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate())); + assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size())); + + assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); + assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate())); + assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate())); + assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes())); + assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate())); + assertThat(savedSites.get(1).getIsWhitelisted(), equalTo(site2.getIsWhitelisted())); + assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size())); + } + + @Test + public void testImportAuthenticationHolders() throws IOException { + OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), + true, new HashSet(), new HashSet(), "http://foo.com", + new HashSet(), null); + Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); + + AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); + holder1.setId(1L); + holder1.setAuthentication(auth1); + + OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), + true, new HashSet(), new HashSet(), "http://bar.com", + new HashSet(), null); + Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); + + AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); + holder2.setId(2L); + holder2.setAuthentication(auth2); + String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + @@ -718,41 +718,41 @@ public class TestMITREidDataService_1_0 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" + - + "{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"}," - + "\"userAuthentication\":null}}," + + + "\"userAuthentication\":null}}," + "{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"}," + "\"userAuthentication\":null}}" + " ]" + "}"; - + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { - Long id = 356L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; - if(_holder.getId() == null) { - _holder.setId(id++); - } - fakeDb.put(_holder.getId(), _holder); - return _holder; - } - }); - + + final Map fakeDb = new HashMap(); + when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + Long id = 356L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; + if(_holder.getId() == null) { + _holder.setId(id++); + } + fakeDb.put(_holder.getId(), _holder); + return _holder; + } + }); + dataService.importData(reader); verify(authHolderRepository, times(2)).save(capturedAuthHolders.capture()); - + List savedAuthHolders = capturedAuthHolders.getAllValues(); - - assertThat(savedAuthHolders.size(), is(2)); - assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId())); - assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId())); - } + + assertThat(savedAuthHolders.size(), is(2)); + assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId())); + assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId())); + } @Test public void testImportSystemScopes() throws IOException { @@ -789,23 +789,23 @@ public class TestMITREidDataService_1_0 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [" + - + "{\"id\":1,\"description\":\"Scope 1\",\"icon\":\"glass\",\"value\":\"scope1\",\"allowDynReg\":false,\"defaultScope\":false}," + "{\"id\":2,\"description\":\"Scope 2\",\"icon\":\"ball\",\"value\":\"scope2\",\"allowDynReg\":true,\"defaultScope\":false}," + "{\"id\":3,\"description\":\"Scope 3\",\"icon\":\"road\",\"value\":\"scope3\",\"allowDynReg\":true,\"defaultScope\":true}" + - + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(sysScopeRepository, times(3)).save(capturedScope.capture()); - + List savedScopes = capturedScope.getAllValues(); - + assertThat(savedScopes.size(), is(3)); assertThat(savedScopes.get(0).getValue(), equalTo(scope1.getValue())); assertThat(savedScopes.get(0).getDescription(), equalTo(scope1.getDescription())); @@ -824,145 +824,145 @@ public class TestMITREidDataService_1_0 { assertThat(savedScopes.get(2).getIcon(), equalTo(scope3.getIcon())); assertThat(savedScopes.get(2).isDefaultScope(), equalTo(scope3.isDefaultScope())); assertThat(savedScopes.get(2).isAllowDynReg(), equalTo(scope3.isAllowDynReg())); - + } - - @Test - public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - 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", - new HashSet(), null); - Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); - - AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); - holder1.setId(1L); - holder1.setAuthentication(auth1); - - OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); - token1.setId(1L); - token1.setClient(mockedClient1); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); - token1.setAuthenticationHolder(holder1); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - 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", - new HashSet(), null); - Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); - - AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); - holder2.setId(2L); - holder2.setAuthentication(auth2); - - OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); - token2.setId(2L); - token2.setClient(mockedClient2); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); - token2.setAuthenticationHolder(holder2); - + + @Test + public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + 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", + new HashSet(), null); + Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); + + AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); + holder1.setId(1L); + holder1.setAuthentication(auth1); + + OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); + token1.setId(1L); + token1.setClient(mockedClient1); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); + token1.setAuthenticationHolder(holder1); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + 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", + new HashSet(), null); + Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); + + AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); + holder2.setId(2L); + holder2.setAuthentication(auth2); + + OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); + token2.setId(2L); + token2.setClient(mockedClient2); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); + token2.setAuthenticationHolder(holder2); + String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" + - + "{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"}," - + "\"userAuthentication\":null}}," + + + "\"userAuthentication\":null}}," + "{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"}," + "\"userAuthentication\":null}}" + " ]," + "\"" + MITREidDataService.REFRESHTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + - + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + + " ]" + "}"; System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - final Map fakeRefreshTokenTable = new HashMap(); - final Map fakeAuthHolderTable = new HashMap(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { - Long id = 343L; - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeRefreshTokenTable.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeRefreshTokenTable.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { - Long id = 356L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; - if(_holder.getId() == null) { - _holder.setId(id++); - } - fakeAuthHolderTable.put(_holder.getId(), _holder); - return _holder; - } - }); - when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeAuthHolderTable.get(_id); - } - }); + final Map fakeRefreshTokenTable = new HashMap(); + final Map fakeAuthHolderTable = new HashMap(); + when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + Long id = 343L; + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeRefreshTokenTable.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeRefreshTokenTable.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + Long id = 356L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; + if(_holder.getId() == null) { + _holder.setId(id++); + } + fakeAuthHolderTable.put(_holder.getId(), _holder); + return _holder; + } + }); + when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeAuthHolderTable.get(_id); + } + }); dataService.importData(reader); - + List savedRefreshTokens = new ArrayList(fakeRefreshTokenTable.values()); //capturedRefreshTokens.getAllValues(); - Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - - assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L)); - assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L)); - } - - @Test(expected = UnsupportedOperationException.class) - public void testExportDisabled() throws IOException { - JsonWriter writer = new JsonWriter(new StringWriter()); - dataService.exportData(writer); - } - + Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); + + assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L)); + assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L)); + } + + @Test(expected = UnsupportedOperationException.class) + public void testExportDisabled() throws IOException { + JsonWriter writer = new JsonWriter(new StringWriter()); + 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 b9e1cc180..9f3cef581 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 @@ -16,14 +16,19 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.isA; +import static org.mockito.Matchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; @@ -36,13 +41,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -68,7 +67,6 @@ import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import static org.mockito.Mockito.*; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; @@ -77,41 +75,45 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; +import com.google.common.collect.ImmutableSet; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + @RunWith(MockitoJUnitRunner.class) public class TestMITREidDataService_1_1 { @Mock - private OAuth2ClientRepository clientRepository; + private OAuth2ClientRepository clientRepository; @Mock - private ApprovedSiteRepository approvedSiteRepository; - @Mock - private WhitelistedSiteRepository wlSiteRepository; - @Mock - private BlacklistedSiteRepository blSiteRepository; + private ApprovedSiteRepository approvedSiteRepository; @Mock - private AuthenticationHolderRepository authHolderRepository; + private WhitelistedSiteRepository wlSiteRepository; @Mock - private OAuth2TokenRepository tokenRepository; + private BlacklistedSiteRepository blSiteRepository; @Mock - private SystemScopeRepository sysScopeRepository; - - @Captor - private ArgumentCaptor capturedRefreshTokens; - @Captor - private ArgumentCaptor capturedAccessTokens; - @Captor - private ArgumentCaptor capturedClients; - @Captor - private ArgumentCaptor capturedBlacklistedSites; - @Captor - private ArgumentCaptor capturedWhitelistedSites; - @Captor - private ArgumentCaptor capturedApprovedSites; - @Captor - private ArgumentCaptor capturedAuthHolders; + private AuthenticationHolderRepository authHolderRepository; + @Mock + private OAuth2TokenRepository tokenRepository; + @Mock + private SystemScopeRepository sysScopeRepository; + + @Captor + private ArgumentCaptor capturedRefreshTokens; + @Captor + private ArgumentCaptor capturedAccessTokens; + @Captor + private ArgumentCaptor capturedClients; + @Captor + private ArgumentCaptor capturedBlacklistedSites; + @Captor + private ArgumentCaptor capturedWhitelistedSites; + @Captor + private ArgumentCaptor capturedApprovedSites; + @Captor + private ArgumentCaptor capturedAuthHolders; @Captor private ArgumentCaptor capturedScope; - + @InjectMocks private MITREidDataService_1_1 dataService; @@ -119,260 +121,260 @@ public class TestMITREidDataService_1_1 { public void prepare() { Mockito.reset(clientRepository, approvedSiteRepository, authHolderRepository, tokenRepository, sysScopeRepository, wlSiteRepository, blSiteRepository); } - - - private class refreshTokenIdComparator implements Comparator { - @Override - public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) { - return entity1.getId().compareTo(entity2.getId()); - } - } - @Test - public void testImportRefreshTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - 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); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); - token1.setAuthenticationHolder(mockedAuthHolder1); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); - token2.setAuthenticationHolder(mockedAuthHolder2); - + private class refreshTokenIdComparator implements Comparator { + @Override + public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) { + return entity1.getId().compareTo(entity2.getId()); + } + } + + + @Test + public void testImportRefreshTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); + token1.setAuthenticationHolder(mockedAuthHolder1); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); + token2.setAuthenticationHolder(mockedAuthHolder2); + String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + - + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + + " ]" + "}"; - + System.err.println(configJson); - JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { - Long id = 332L; - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeDb.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 131L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); - id++; - return _auth; - } - }); + JsonReader reader = new JsonReader(new StringReader(configJson)); + + final Map fakeDb = new HashMap(); + when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + Long id = 332L; + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeDb.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeDb.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + Long id = 131L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); + when(_auth.getId()).thenReturn(id); + id++; + return _auth; + } + }); dataService.importData(reader); - //2 times for token, 2 times to update client, 2 times to update authHolder + //2 times for token, 2 times to update client, 2 times to update authHolder verify(tokenRepository, times(6)).saveRefreshToken(capturedRefreshTokens.capture()); - - List savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues(); - Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - - assertThat(savedRefreshTokens.size(), is(2)); - - assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); - assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); - assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue())); - assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); - assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); - assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue())); - } - - private class accessTokenIdComparator implements Comparator { - @Override - public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) { - return entity1.getId().compareTo(entity2.getId()); - } - } - - @Test - public void testImportAccessTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + List savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues(); + Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); - token1.setId(1L); - token1.setClient(mockedClient1); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); - token1.setAuthenticationHolder(mockedAuthHolder1); - token1.setScope(ImmutableSet.of("id-token")); - token1.setTokenType("Bearer"); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + assertThat(savedRefreshTokens.size(), is(2)); + + assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); + assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); + assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue())); + + assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); + assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); + assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue())); + } + + private class accessTokenIdComparator implements Comparator { + @Override + public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) { + return entity1.getId().compareTo(entity2.getId()); + } + } + + @Test + public void testImportAccessTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); + token1.setAuthenticationHolder(mockedAuthHolder1); + token1.setScope(ImmutableSet.of("id-token")); + token1.setTokenType("Bearer"); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); + token2.setAuthenticationHolder(mockedAuthHolder2); + token2.setIdToken(token1); + token2.setRefreshToken(mockRefreshToken2); + token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); + token2.setTokenType("Bearer"); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); - token2.setAuthenticationHolder(mockedAuthHolder2); - token2.setIdToken(token1); - token2.setRefreshToken(mockRefreshToken2); - token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); - token2.setTokenType("Bearer"); - String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," + + + "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\"," + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" + - + + "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\"," + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" + + " ]" + "}"; - - + + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - final Map fakeDb = new HashMap(); - when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { - Long id = 324L; - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeDb.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 133L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); - id++; - return _auth; - } - }); + final Map fakeDb = new HashMap(); + when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { + Long id = 324L; + @Override + public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeDb.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeDb.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + Long id = 133L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); + when(_auth.getId()).thenReturn(id); + id++; + return _auth; + } + }); dataService.importData(reader); - //2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token + //2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token verify(tokenRepository, times(8)).saveAccessToken(capturedAccessTokens.capture()); - - List savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues(); - Collections.sort(savedAccessTokens, new accessTokenIdComparator()); - - assertThat(savedAccessTokens.size(), is(2)); - - assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); - assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); - assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue())); - assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); - assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); - assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue())); - } - + List savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues(); + Collections.sort(savedAccessTokens, new accessTokenIdComparator()); + + assertThat(savedAccessTokens.size(), is(2)); + + assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); + assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); + assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue())); + + assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); + assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); + assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue())); + } + @Test public void testImportClients() throws IOException { ClientDetailsEntity client1 = new ClientDetailsEntity(); @@ -404,33 +406,33 @@ public class TestMITREidDataService_1_1 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.CLIENTS + "\": [" + - + "{\"id\":1,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client1\",\"secret\":\"clientsecret1\"," - + "\"redirectUris\":[\"http://foo.com/\"]," - + "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"]," - + "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"]," - + "\"allowIntrospection\":true}," + + + "\"redirectUris\":[\"http://foo.com/\"]," + + "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"]," + + "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"]," + + "\"allowIntrospection\":true}," + "{\"id\":2,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client2\",\"secret\":\"clientsecret2\"," - + "\"redirectUris\":[\"http://bar.baz.com/\"]," - + "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"]," - + "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"]," - + "\"allowIntrospection\":false}" + - + + "\"redirectUris\":[\"http://bar.baz.com/\"]," + + "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"]," + + "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"]," + + "\"allowIntrospection\":false}" + + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(clientRepository, times(2)).saveClient(capturedClients.capture()); - + List savedClients = capturedClients.getAllValues(); - + assertThat(savedClients.size(), is(2)); - - assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds())); + + assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds())); assertThat(savedClients.get(0).getClientId(), equalTo(client1.getClientId())); assertThat(savedClients.get(0).getClientSecret(), equalTo(client1.getClientSecret())); assertThat(savedClients.get(0).getRedirectUris(), equalTo(client1.getRedirectUris())); @@ -438,7 +440,7 @@ public class TestMITREidDataService_1_1 { assertThat(savedClients.get(0).getGrantTypes(), equalTo(client1.getGrantTypes())); assertThat(savedClients.get(0).isAllowIntrospection(), equalTo(client1.isAllowIntrospection())); - assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds())); + assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds())); assertThat(savedClients.get(1).getClientId(), equalTo(client2.getClientId())); assertThat(savedClients.get(1).getClientSecret(), equalTo(client2.getClientSecret())); assertThat(savedClients.get(1).getRedirectUris(), equalTo(client2.getRedirectUris())); @@ -446,20 +448,20 @@ public class TestMITREidDataService_1_1 { assertThat(savedClients.get(1).getGrantTypes(), equalTo(client2.getGrantTypes())); assertThat(savedClients.get(1).isAllowIntrospection(), equalTo(client2.isAllowIntrospection())); } - + @Test public void testImportBlacklistedSites() throws IOException { BlacklistedSite site1 = new BlacklistedSite(); - site1.setId(1L); - site1.setUri("http://foo.com"); + site1.setId(1L); + site1.setUri("http://foo.com"); - BlacklistedSite site2 = new BlacklistedSite(); - site2.setId(2L); - site2.setUri("http://bar.com"); - - BlacklistedSite site3 = new BlacklistedSite(); - site3.setId(3L); - site3.setUri("http://baz.com"); + BlacklistedSite site2 = new BlacklistedSite(); + site2.setId(2L); + site2.setUri("http://bar.com"); + + BlacklistedSite site3 = new BlacklistedSite(); + site3.setId(3L); + site3.setUri("http://baz.com"); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -467,48 +469,48 @@ public class TestMITREidDataService_1_1 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [" + - + "{\"id\":1,\"uri\":\"http://foo.com\"}," + "{\"id\":2,\"uri\":\"http://bar.com\"}," + "{\"id\":3,\"uri\":\"http://baz.com\"}" + - + " ]" + "}"; - - + + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(blSiteRepository, times(3)).save(capturedBlacklistedSites.capture()); - + List savedSites = capturedBlacklistedSites.getAllValues(); - + assertThat(savedSites.size(), is(3)); - + assertThat(savedSites.get(0).getUri(), equalTo(site1.getUri())); - assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri())); + assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri())); assertThat(savedSites.get(2).getUri(), equalTo(site3.getUri())); } - + @Test public void testImportWhitelistedSites() throws IOException { WhitelistedSite site1 = new WhitelistedSite(); - site1.setId(1L); - site1.setClientId("foo"); + site1.setId(1L); + site1.setClientId("foo"); - WhitelistedSite site2 = new WhitelistedSite(); - site2.setId(2L); - site2.setClientId("bar"); - - WhitelistedSite site3 = new WhitelistedSite(); - site3.setId(3L); - site3.setClientId("baz"); - //site3.setAllowedScopes(null); + WhitelistedSite site2 = new WhitelistedSite(); + site2.setId(2L); + site2.setClientId("bar"); + + WhitelistedSite site3 = new WhitelistedSite(); + site3.setId(3L); + site3.setClientId("baz"); + //site3.setAllowedScopes(null); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -516,87 +518,87 @@ public class TestMITREidDataService_1_1 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [" + - + "{\"id\":1,\"clientId\":\"foo\"}," + "{\"id\":2,\"clientId\":\"bar\"}," + "{\"id\":3,\"clientId\":\"baz\"}" + - + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { - Long id = 333L; - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - 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); - } - }); - + + final Map fakeDb = new HashMap(); + when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { + Long id = 333L; + @Override + public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { + WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + 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()); - - List savedSites = capturedWhitelistedSites.getAllValues(); - - assertThat(savedSites.size(), is(3)); - - assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); - assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); - assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId())); - } - - @Test - public void testImportGrants() throws IOException { - Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); - Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); - - WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); - when(mockWlSite1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); - - ApprovedSite site1 = new ApprovedSite(); - site1.setId(1L); - site1.setClientId("foo"); - site1.setCreationDate(creationDate1); - site1.setAccessDate(accessDate1); - site1.setUserId("user1"); - site1.setWhitelistedSite(mockWlSite1); - site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); - Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); - Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); - Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); - + List savedSites = capturedWhitelistedSites.getAllValues(); + + assertThat(savedSites.size(), is(3)); + + assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); + assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); + assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId())); + } + + @Test + public void testImportGrants() throws IOException { + Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); + Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); + + WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); + when(mockWlSite1.getId()).thenReturn(1L); + + OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); + when(mockToken1.getId()).thenReturn(1L); + + ApprovedSite site1 = new ApprovedSite(); + site1.setId(1L); + site1.setClientId("foo"); + site1.setCreationDate(creationDate1); + site1.setAccessDate(accessDate1); + site1.setUserId("user1"); + site1.setWhitelistedSite(mockWlSite1); + site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); + site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); + + Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); + Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); + Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); + ApprovedSite site2 = new ApprovedSite(); - site2.setId(2L); - site2.setClientId("bar"); - site2.setCreationDate(creationDate2); - site2.setAccessDate(accessDate2); - site2.setUserId("user2"); - site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); - site2.setTimeoutDate(timeoutDate2); + site2.setId(2L); + site2.setClientId("bar"); + site2.setCreationDate(creationDate2); + site2.setAccessDate(accessDate2); + site2.setUserId("user2"); + site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); + site2.setTimeoutDate(timeoutDate2); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -604,110 +606,110 @@ public class TestMITREidDataService_1_1 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [" + - + "{\"id\":1,\"clientId\":\"foo\",\"creationDate\":\"2014-09-10T22:49:44.090+0000\",\"accessDate\":\"2014-09-10T23:49:44.090+0000\"," - + "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1," - + "\"approvedAccessTokens\":[1]}," + + + "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1," + + "\"approvedAccessTokens\":[1]}," + "{\"id\":2,\"clientId\":\"bar\",\"creationDate\":\"2014-09-11T18:49:44.090+0000\",\"accessDate\":\"2014-09-11T20:49:44.090+0000\"," - + "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\"," - + "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" + - + + "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\"," + + "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" + + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { - Long id = 364L; - @Override - public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { - ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - return _site; - } - }); - when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - 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; - } - }); + + final Map fakeDb = new HashMap(); + when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { + Long id = 364L; + @Override + public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { + ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + return _site; + } + }); + when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + @Override + public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + 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; + } + }); dataService.importData(reader); - //2 for sites, 1 for updating access token ref on #1, 1 more for updating whitelistedSite ref on #2 + //2 for sites, 1 for updating access token ref on #1, 1 more for updating whitelistedSite ref on #2 verify(approvedSiteRepository, times(4)).save(capturedApprovedSites.capture()); - - List savedSites = new ArrayList(fakeDb.values()); - - assertThat(savedSites.size(), is(2)); - - assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); - assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate())); - assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate())); - assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes())); - assertThat(savedSites.get(0).getIsWhitelisted(), equalTo(site1.getIsWhitelisted())); - assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate())); - assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size())); - - assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); - assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate())); - assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate())); - assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes())); - assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate())); - assertThat(savedSites.get(1).getIsWhitelisted(), equalTo(site2.getIsWhitelisted())); - assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size())); - } - - @Test - public void testImportAuthenticationHolders() throws IOException { - OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), - true, new HashSet(), new HashSet(), "http://foo.com", - new HashSet(), null); - Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); - - AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); - holder1.setId(1L); - holder1.setAuthentication(auth1); - - OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), - true, new HashSet(), new HashSet(), "http://bar.com", - new HashSet(), null); - Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); - - AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); - holder2.setId(2L); - holder2.setAuthentication(auth2); - + + List savedSites = new ArrayList(fakeDb.values()); + + assertThat(savedSites.size(), is(2)); + + assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); + assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate())); + assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate())); + assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes())); + assertThat(savedSites.get(0).getIsWhitelisted(), equalTo(site1.getIsWhitelisted())); + assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate())); + assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size())); + + assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); + assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate())); + assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate())); + assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes())); + assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate())); + assertThat(savedSites.get(1).getIsWhitelisted(), equalTo(site2.getIsWhitelisted())); + assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size())); + } + + @Test + public void testImportAuthenticationHolders() throws IOException { + OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), + true, new HashSet(), new HashSet(), "http://foo.com", + new HashSet(), null); + Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); + + AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); + holder1.setId(1L); + holder1.setAuthentication(auth1); + + OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), + true, new HashSet(), new HashSet(), "http://bar.com", + new HashSet(), null); + Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); + + AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); + holder2.setId(2L); + holder2.setAuthentication(auth2); + String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + @@ -717,42 +719,42 @@ public class TestMITREidDataService_1_1 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" + - + "{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"}," - + "\"userAuthentication\":null}}," + + + "\"userAuthentication\":null}}," + "{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"}," + "\"userAuthentication\":null}}" + " ]" + "}"; - + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { - Long id = 243L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _site = (AuthenticationHolderEntity) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - return _site; - } - }); - + + final Map fakeDb = new HashMap(); + when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + Long id = 243L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _site = (AuthenticationHolderEntity) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + return _site; + } + }); + dataService.importData(reader); verify(authHolderRepository, times(2)).save(capturedAuthHolders.capture()); - + List savedAuthHolders = capturedAuthHolders.getAllValues(); - + assertThat(savedAuthHolders.size(), is(2)); assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId())); assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId())); - } - + } + @Test public void testImportSystemScopes() throws IOException { SystemScope scope1 = new SystemScope(); @@ -788,23 +790,23 @@ public class TestMITREidDataService_1_1 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [" + - + "{\"id\":1,\"description\":\"Scope 1\",\"icon\":\"glass\",\"value\":\"scope1\",\"allowDynReg\":false,\"defaultScope\":false}," + "{\"id\":2,\"description\":\"Scope 2\",\"icon\":\"ball\",\"value\":\"scope2\",\"allowDynReg\":true,\"defaultScope\":false}," + "{\"id\":3,\"description\":\"Scope 3\",\"icon\":\"road\",\"value\":\"scope3\",\"allowDynReg\":true,\"defaultScope\":true}" + - + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(sysScopeRepository, times(3)).save(capturedScope.capture()); - + List savedScopes = capturedScope.getAllValues(); - + assertThat(savedScopes.size(), is(3)); assertThat(savedScopes.get(0).getValue(), equalTo(scope1.getValue())); assertThat(savedScopes.get(0).getDescription(), equalTo(scope1.getDescription())); @@ -823,153 +825,145 @@ public class TestMITREidDataService_1_1 { assertThat(savedScopes.get(2).getIcon(), equalTo(scope3.getIcon())); assertThat(savedScopes.get(2).isDefaultScope(), equalTo(scope3.isDefaultScope())); assertThat(savedScopes.get(2).isAllowDynReg(), equalTo(scope3.isAllowDynReg())); - + } - - @Test - public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - 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", - new HashSet(), null); - Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); - - AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); - holder1.setId(1L); - holder1.setAuthentication(auth1); - - OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); - token1.setId(1L); - token1.setClient(mockedClient1); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); - token1.setAuthenticationHolder(holder1); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - 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", - new HashSet(), null); - Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); - - AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); - holder2.setId(2L); - holder2.setAuthentication(auth2); - - OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); - token2.setId(2L); - token2.setClient(mockedClient2); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); - token2.setAuthenticationHolder(holder2); - + + @Test + public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + 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", + new HashSet(), null); + Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); + + AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); + holder1.setId(1L); + holder1.setAuthentication(auth1); + + OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); + token1.setId(1L); + token1.setClient(mockedClient1); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); + token1.setAuthenticationHolder(holder1); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + 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", + new HashSet(), null); + Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); + + AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); + holder2.setId(2L); + holder2.setAuthentication(auth2); + + OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); + token2.setId(2L); + token2.setClient(mockedClient2); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); + token2.setAuthenticationHolder(holder2); + String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" + - + "{\"id\":1,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"}," - + "\"userAuthentication\":null}}," + + + "\"userAuthentication\":null}}," + "{\"id\":2,\"authentication\":{\"clientAuthorization\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"}," + "\"userAuthentication\":null}}" + " ]," + "\"" + MITREidDataService.REFRESHTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + - + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + + " ]" + "}"; System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - final Map fakeRefreshTokenTable = new HashMap(); - final Map fakeAuthHolderTable = new HashMap(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { - Long id = 343L; - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeRefreshTokenTable.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeRefreshTokenTable.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { - Long id = 356L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; - if(_holder.getId() == null) { - _holder.setId(id++); - } - fakeAuthHolderTable.put(_holder.getId(), _holder); - return _holder; - } - }); - when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeAuthHolderTable.get(_id); - } - }); + final Map fakeRefreshTokenTable = new HashMap(); + final Map fakeAuthHolderTable = new HashMap(); + when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + Long id = 343L; + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeRefreshTokenTable.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeRefreshTokenTable.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + Long id = 356L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; + if(_holder.getId() == null) { + _holder.setId(id++); + } + fakeAuthHolderTable.put(_holder.getId(), _holder); + return _holder; + } + }); + when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeAuthHolderTable.get(_id); + } + }); dataService.importData(reader); - + List savedRefreshTokens = new ArrayList(fakeRefreshTokenTable.values()); //capturedRefreshTokens.getAllValues(); - Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - - assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L)); - assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L)); - } - - private Set jsonArrayToStringSet(JsonArray a) { - Set s = new HashSet(); - for (JsonElement jsonElement : a) { - s.add(jsonElement.getAsString()); - } - return s; + Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); + + assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L)); + assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L)); + } + + @Test(expected = UnsupportedOperationException.class) + public void testExportDisabled() throws IOException { + JsonWriter writer = new JsonWriter(new StringWriter()); + dataService.exportData(writer); } - @Test(expected = UnsupportedOperationException.class) - public void testExportDisabled() throws IOException { - JsonWriter writer = new JsonWriter(new StringWriter()); - dataService.exportData(writer); - } - } 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 e9cdf5da5..6e4651f5c 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 @@ -16,14 +16,23 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Matchers.anyLong; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.isA; +import static org.mockito.Matchers.isNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; + import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; @@ -37,12 +46,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -68,7 +72,6 @@ import org.mockito.Captor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import static org.mockito.Mockito.*; import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; import org.mockito.stubbing.Answer; @@ -77,41 +80,50 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.OAuth2Request; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + @RunWith(MockitoJUnitRunner.class) public class TestMITREidDataService_1_2 { @Mock - private OAuth2ClientRepository clientRepository; + private OAuth2ClientRepository clientRepository; @Mock - private ApprovedSiteRepository approvedSiteRepository; - @Mock - private WhitelistedSiteRepository wlSiteRepository; - @Mock - private BlacklistedSiteRepository blSiteRepository; + private ApprovedSiteRepository approvedSiteRepository; @Mock - private AuthenticationHolderRepository authHolderRepository; + private WhitelistedSiteRepository wlSiteRepository; @Mock - private OAuth2TokenRepository tokenRepository; + private BlacklistedSiteRepository blSiteRepository; @Mock - private SystemScopeRepository sysScopeRepository; - - @Captor - private ArgumentCaptor capturedRefreshTokens; - @Captor - private ArgumentCaptor capturedAccessTokens; - @Captor - private ArgumentCaptor capturedClients; - @Captor - private ArgumentCaptor capturedBlacklistedSites; - @Captor - private ArgumentCaptor capturedWhitelistedSites; - @Captor - private ArgumentCaptor capturedApprovedSites; - @Captor - private ArgumentCaptor capturedAuthHolders; + private AuthenticationHolderRepository authHolderRepository; + @Mock + private OAuth2TokenRepository tokenRepository; + @Mock + private SystemScopeRepository sysScopeRepository; + + @Captor + private ArgumentCaptor capturedRefreshTokens; + @Captor + private ArgumentCaptor capturedAccessTokens; + @Captor + private ArgumentCaptor capturedClients; + @Captor + private ArgumentCaptor capturedBlacklistedSites; + @Captor + private ArgumentCaptor capturedWhitelistedSites; + @Captor + private ArgumentCaptor capturedApprovedSites; + @Captor + private ArgumentCaptor capturedAuthHolders; @Captor private ArgumentCaptor capturedScope; - + @InjectMocks private MITREidDataService_1_2 dataService; @@ -119,43 +131,43 @@ public class TestMITREidDataService_1_2 { public void prepare() { Mockito.reset(clientRepository, approvedSiteRepository, authHolderRepository, tokenRepository, sysScopeRepository, wlSiteRepository, blSiteRepository); } - - @Test - public void testExportRefreshTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - 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); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); - token1.setAuthenticationHolder(mockedAuthHolder1); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); - token2.setAuthenticationHolder(mockedAuthHolder2); - - Set allRefreshTokens = ImmutableSet.of(token1, token2); - + + @Test + public void testExportRefreshTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); + token1.setAuthenticationHolder(mockedAuthHolder1); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); + token2.setAuthenticationHolder(mockedAuthHolder2); + + Set allRefreshTokens = ImmutableSet.of(token1, token2); + Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet()); Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet()); @@ -164,7 +176,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(allRefreshTokens); Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -172,37 +184,37 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); - + // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our refresh token list (this test) JsonArray refreshTokens = config.get(MITREidDataService.REFRESHTOKENS).getAsJsonArray(); @@ -219,187 +231,187 @@ public class TestMITREidDataService_1_2 { } else if (token.get("id").getAsLong() == token2.getId()) { compare = token2; } - + if (compare == null) { fail("Could not find matching id: " + token.get("id").getAsString()); } else { assertThat(token.get("id").getAsLong(), equalTo(compare.getId())); assertThat(token.get("clientId").getAsString(), equalTo(compare.getClient().getClientId())); - assertThat(token.get("expiration").getAsString(), equalTo(DateUtil.toUTCString(compare.getExpiration()))); + assertThat(token.get("expiration").getAsString(), equalTo(DateUtil.toUTCString(compare.getExpiration()))); assertThat(token.get("value").getAsString(), equalTo(compare.getValue())); assertThat(token.get("authenticationHolderId").getAsLong(), equalTo(compare.getAuthenticationHolder().getId())); checked.add(compare); } } // make sure all of our refresh tokens were found - assertThat(checked.containsAll(allRefreshTokens), is(true)); - } + assertThat(checked.containsAll(allRefreshTokens), is(true)); + } - private class refreshTokenIdComparator implements Comparator { - @Override - public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) { - return entity1.getId().compareTo(entity2.getId()); - } - } + private class refreshTokenIdComparator implements Comparator { + @Override + public int compare(OAuth2RefreshTokenEntity entity1, OAuth2RefreshTokenEntity entity2) { + return entity1.getId().compareTo(entity2.getId()); + } + } - @Test - public void testImportRefreshTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - 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); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); - token1.setAuthenticationHolder(mockedAuthHolder1); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); - token2.setAuthenticationHolder(mockedAuthHolder2); - + @Test + public void testImportRefreshTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); + token1.setAuthenticationHolder(mockedAuthHolder1); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); + token2.setAuthenticationHolder(mockedAuthHolder2); + String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + - + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + + " ]" + "}"; - + System.err.println(configJson); - JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { - Long id = 332L; - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeDb.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 131L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); - id++; - return _auth; - } - }); + JsonReader reader = new JsonReader(new StringReader(configJson)); + + final Map fakeDb = new HashMap(); + when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + Long id = 332L; + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeDb.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeDb.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + Long id = 131L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); + when(_auth.getId()).thenReturn(id); + id++; + return _auth; + } + }); dataService.importData(reader); - //2 times for token, 2 times to update client, 2 times to update authHolder + //2 times for token, 2 times to update client, 2 times to update authHolder verify(tokenRepository, times(6)).saveRefreshToken(capturedRefreshTokens.capture()); - - List savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues(); - Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - - assertThat(savedRefreshTokens.size(), is(2)); - - assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); - assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); - assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue())); - assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); - assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); - assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue())); - } - - @Test - public void testExportAccessTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + List savedRefreshTokens = new ArrayList(fakeDb.values()); //capturedRefreshTokens.getAllValues(); + Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); - token1.setId(1L); - token1.setClient(mockedClient1); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); - token1.setAuthenticationHolder(mockedAuthHolder1); - token1.setScope(ImmutableSet.of("id-token")); - token1.setTokenType("Bearer"); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + assertThat(savedRefreshTokens.size(), is(2)); + + assertThat(savedRefreshTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); + assertThat(savedRefreshTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); + assertThat(savedRefreshTokens.get(0).getValue(), equalTo(token1.getValue())); + + assertThat(savedRefreshTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); + assertThat(savedRefreshTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); + assertThat(savedRefreshTokens.get(1).getValue(), equalTo(token2.getValue())); + } + + @Test + public void testExportAccessTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); + token1.setAuthenticationHolder(mockedAuthHolder1); + token1.setScope(ImmutableSet.of("id-token")); + token1.setTokenType("Bearer"); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); + token2.setAuthenticationHolder(mockedAuthHolder2); + token2.setIdToken(token1); + token2.setRefreshToken(mockRefreshToken2); + token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); + token2.setTokenType("Bearer"); + + Set allAccessTokens = ImmutableSet.of(token1, token2); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); - token2.setAuthenticationHolder(mockedAuthHolder2); - token2.setIdToken(token1); - token2.setRefreshToken(mockRefreshToken2); - token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); - token2.setTokenType("Bearer"); - - Set allAccessTokens = ImmutableSet.of(token1, token2); - Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet()); Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet()); @@ -408,7 +420,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(allAccessTokens); Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -416,37 +428,37 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); - + // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our access token list (this test) JsonArray accessTokens = config.get(MITREidDataService.ACCESSTOKENS).getAsJsonArray(); @@ -463,167 +475,167 @@ public class TestMITREidDataService_1_2 { } else if (token.get("id").getAsLong() == token2.getId().longValue()) { compare = token2; } - + if (compare == null) { fail("Could not find matching id: " + token.get("id").getAsString()); } else { assertThat(token.get("id").getAsLong(), equalTo(compare.getId())); assertThat(token.get("clientId").getAsString(), equalTo(compare.getClient().getClientId())); - assertThat(token.get("expiration").getAsString(), equalTo(DateUtil.toUTCString(compare.getExpiration()))); + assertThat(token.get("expiration").getAsString(), equalTo(DateUtil.toUTCString(compare.getExpiration()))); assertThat(token.get("value").getAsString(), equalTo(compare.getValue())); - assertThat(token.get("type").getAsString(), equalTo(compare.getTokenType())); + assertThat(token.get("type").getAsString(), equalTo(compare.getTokenType())); assertThat(token.get("authenticationHolderId").getAsLong(), equalTo(compare.getAuthenticationHolder().getId())); - assertTrue(token.get("scope").isJsonArray()); - assertThat(jsonArrayToStringSet(token.getAsJsonArray("scope")), equalTo(compare.getScope())); - if(token.get("idTokenId").isJsonNull()) { - assertNull(compare.getIdToken()); - } else { - assertThat(token.get("idTokenId").getAsLong(), equalTo(compare.getIdToken().getId())); - } - if(token.get("refreshTokenId").isJsonNull()) { - assertNull(compare.getIdToken()); - } else { - assertThat(token.get("refreshTokenId").getAsLong(), equalTo(compare.getRefreshToken().getId())); - } + assertTrue(token.get("scope").isJsonArray()); + assertThat(jsonArrayToStringSet(token.getAsJsonArray("scope")), equalTo(compare.getScope())); + if(token.get("idTokenId").isJsonNull()) { + assertNull(compare.getIdToken()); + } else { + assertThat(token.get("idTokenId").getAsLong(), equalTo(compare.getIdToken().getId())); + } + if(token.get("refreshTokenId").isJsonNull()) { + assertNull(compare.getIdToken()); + } else { + assertThat(token.get("refreshTokenId").getAsLong(), equalTo(compare.getRefreshToken().getId())); + } checked.add(compare); } } // make sure all of our access tokens were found - assertThat(checked.containsAll(allAccessTokens), is(true)); - } - - private class accessTokenIdComparator implements Comparator { - @Override - public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) { - return entity1.getId().compareTo(entity2.getId()); - } - } - - @Test - public void testImportAccessTokens() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + assertThat(checked.containsAll(allAccessTokens), is(true)); + } - AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); - token1.setId(1L); - token1.setClient(mockedClient1); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); - token1.setAuthenticationHolder(mockedAuthHolder1); - token1.setScope(ImmutableSet.of("id-token")); - token1.setTokenType("Bearer"); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + private class accessTokenIdComparator implements Comparator { + @Override + public int compare(OAuth2AccessTokenEntity entity1, OAuth2AccessTokenEntity entity2) { + return entity1.getId().compareTo(entity2.getId()); + } + } + + @Test + public void testImportAccessTokens() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); + 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); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0"); + token1.setAuthenticationHolder(mockedAuthHolder1); + token1.setScope(ImmutableSet.of("id-token")); + token1.setTokenType("Bearer"); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); + 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); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); + token2.setAuthenticationHolder(mockedAuthHolder2); + token2.setIdToken(token1); + token2.setRefreshToken(mockRefreshToken2); + token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); + token2.setTokenType("Bearer"); - 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); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ"); - token2.setAuthenticationHolder(mockedAuthHolder2); - token2.setIdToken(token1); - token2.setRefreshToken(mockRefreshToken2); - token2.setScope(ImmutableSet.of("openid", "offline_access", "email", "profile")); - token2.setTokenType("Bearer"); - String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," + + + "\"refreshTokenId\":null,\"idTokenId\":null,\"scope\":[\"id-token\"],\"type\":\"Bearer\"," + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3ODk5NjgsInN1YiI6IjkwMzQyLkFTREZKV0ZBIiwiYXRfaGFzaCI6InptTmt1QmNRSmNYQktNaVpFODZqY0EiLCJhdWQiOlsiY2xpZW50Il0sImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDgwXC9vcGVuaWQtY29ubmVjdC1zZXJ2ZXItd2ViYXBwXC8iLCJpYXQiOjE0MTI3ODkzNjh9.xkEJ9IMXpH7qybWXomfq9WOOlpGYnrvGPgey9UQ4GLzbQx7JC0XgJK83PmrmBZosvFPCmota7FzI_BtwoZLgAZfFiH6w3WIlxuogoH-TxmYbxEpTHoTsszZppkq9mNgOlArV4jrR9y3TPo4MovsH71dDhS_ck-CvAlJunHlqhs0\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" + - + + "\"refreshTokenId\":1,\"idTokenId\":1,\"scope\":[\"openid\",\"offline_access\",\"email\",\"profile\"],\"type\":\"Bearer\"," + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJSUzI1NiJ9.eyJleHAiOjE0MTI3OTI5NjgsImF1ZCI6WyJjbGllbnQiXSwiaXNzIjoiaHR0cDpcL1wvbG9jYWxob3N0OjgwODBcL29wZW5pZC1jb25uZWN0LXNlcnZlci13ZWJhcHBcLyIsImp0aSI6IjBmZGE5ZmRiLTYyYzItNGIzZS05OTdiLWU0M2VhMDUwMzNiOSIsImlhdCI6MTQxMjc4OTM2OH0.xgaVpRLYE5MzbgXfE0tZt823tjAm6Oh3_kdR1P2I9jRLR6gnTlBQFlYi3Y_0pWNnZSerbAE8Tn6SJHZ9k-curVG0-ByKichV7CNvgsE5X_2wpEaUzejvKf8eZ-BammRY-ie6yxSkAarcUGMvGGOLbkFcz5CtrBpZhfd75J49BIQ\"}" + + " ]" + "}"; - - + + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - final Map fakeDb = new HashMap(); - when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { - Long id = 324L; - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeDb.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeDb.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { - Long id = 133L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); - id++; - return _auth; - } - }); + final Map fakeDb = new HashMap(); + when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { + Long id = 324L; + @Override + public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2AccessTokenEntity _token = (OAuth2AccessTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeDb.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeDb.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + Long id = 133L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); + when(_auth.getId()).thenReturn(id); + id++; + return _auth; + } + }); dataService.importData(reader); - //2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token + //2 times for token, 2 times to update client, 2 times to update authHolder, 2 times to update id token, 2 times to update refresh token verify(tokenRepository, times(8)).saveAccessToken(capturedAccessTokens.capture()); - - List savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues(); - Collections.sort(savedAccessTokens, new accessTokenIdComparator()); - - assertThat(savedAccessTokens.size(), is(2)); - - assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); - assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); - assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue())); - assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); - assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); - assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue())); - } - + List savedAccessTokens = new ArrayList(fakeDb.values()); //capturedAccessTokens.getAllValues(); + Collections.sort(savedAccessTokens, new accessTokenIdComparator()); + + assertThat(savedAccessTokens.size(), is(2)); + + assertThat(savedAccessTokens.get(0).getClient().getClientId(), equalTo(token1.getClient().getClientId())); + assertThat(savedAccessTokens.get(0).getExpiration(), equalTo(token1.getExpiration())); + assertThat(savedAccessTokens.get(0).getValue(), equalTo(token1.getValue())); + + assertThat(savedAccessTokens.get(1).getClient().getClientId(), equalTo(token2.getClient().getClientId())); + assertThat(savedAccessTokens.get(1).getExpiration(), equalTo(token2.getExpiration())); + assertThat(savedAccessTokens.get(1).getValue(), equalTo(token2.getValue())); + } + @Test public void testExportClients() throws IOException { ClientDetailsEntity client1 = new ClientDetailsEntity(); @@ -646,8 +658,8 @@ public class TestMITREidDataService_1_2 { client2.setGrantTypes(ImmutableSet.of("client_credentials", "urn:ietf:params:oauth:grant_type:redelegate")); client2.setAllowIntrospection(false); - Set allClients = ImmutableSet.of(client1, client2); - + Set allClients = ImmutableSet.of(client1, client2); + Mockito.when(clientRepository.getAllClients()).thenReturn(allClients); Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet()); @@ -656,7 +668,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -664,37 +676,37 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); - + // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our client list (this test) JsonArray clients = config.get(MITREidDataService.CLIENTS).getAsJsonArray(); @@ -711,7 +723,7 @@ public class TestMITREidDataService_1_2 { } else if (client.get("clientId").getAsString().equals(client2.getClientId())) { compare = client2; } - + if (compare == null) { fail("Could not find matching clientId: " + client.get("clientId").getAsString()); } else { @@ -726,9 +738,9 @@ public class TestMITREidDataService_1_2 { } } // make sure all of our clients were found - assertThat(checked.containsAll(allClients), is(true)); + assertThat(checked.containsAll(allClients), is(true)); } - + @Test public void testImportClients() throws IOException { ClientDetailsEntity client1 = new ClientDetailsEntity(); @@ -760,33 +772,33 @@ public class TestMITREidDataService_1_2 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.CLIENTS + "\": [" + - + "{\"id\":1,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client1\",\"secret\":\"clientsecret1\"," - + "\"redirectUris\":[\"http://foo.com/\"]," - + "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"]," - + "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"]," - + "\"allowIntrospection\":true}," + + + "\"redirectUris\":[\"http://foo.com/\"]," + + "\"scope\":[\"foo\",\"bar\",\"baz\",\"dolphin\"]," + + "\"grantTypes\":[\"implicit\",\"authorization_code\",\"urn:ietf:params:oauth:grant_type:redelegate\",\"refresh_token\"]," + + "\"allowIntrospection\":true}," + "{\"id\":2,\"accessTokenValiditySeconds\":3600,\"clientId\":\"client2\",\"secret\":\"clientsecret2\"," - + "\"redirectUris\":[\"http://bar.baz.com/\"]," - + "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"]," - + "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"]," - + "\"allowIntrospection\":false}" + - + + "\"redirectUris\":[\"http://bar.baz.com/\"]," + + "\"scope\":[\"foo\",\"dolphin\",\"electric-wombat\"]," + + "\"grantTypes\":[\"client_credentials\",\"urn:ietf:params:oauth:grant_type:redelegate\"]," + + "\"allowIntrospection\":false}" + + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(clientRepository, times(2)).saveClient(capturedClients.capture()); - + List savedClients = capturedClients.getAllValues(); - + assertThat(savedClients.size(), is(2)); - - assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds())); + + assertThat(savedClients.get(0).getAccessTokenValiditySeconds(), equalTo(client1.getAccessTokenValiditySeconds())); assertThat(savedClients.get(0).getClientId(), equalTo(client1.getClientId())); assertThat(savedClients.get(0).getClientSecret(), equalTo(client1.getClientSecret())); assertThat(savedClients.get(0).getRedirectUris(), equalTo(client1.getRedirectUris())); @@ -794,7 +806,7 @@ public class TestMITREidDataService_1_2 { assertThat(savedClients.get(0).getGrantTypes(), equalTo(client1.getGrantTypes())); assertThat(savedClients.get(0).isAllowIntrospection(), equalTo(client1.isAllowIntrospection())); - assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds())); + assertThat(savedClients.get(1).getAccessTokenValiditySeconds(), equalTo(client2.getAccessTokenValiditySeconds())); assertThat(savedClients.get(1).getClientId(), equalTo(client2.getClientId())); assertThat(savedClients.get(1).getClientSecret(), equalTo(client2.getClientSecret())); assertThat(savedClients.get(1).getRedirectUris(), equalTo(client2.getRedirectUris())); @@ -802,23 +814,23 @@ public class TestMITREidDataService_1_2 { assertThat(savedClients.get(1).getGrantTypes(), equalTo(client2.getGrantTypes())); assertThat(savedClients.get(1).isAllowIntrospection(), equalTo(client2.isAllowIntrospection())); } - - @Test - public void testExportBlacklistedSites() throws IOException { - BlacklistedSite site1 = new BlacklistedSite(); - site1.setId(1L); - site1.setUri("http://foo.com"); - BlacklistedSite site2 = new BlacklistedSite(); - site2.setId(2L); - site2.setUri("http://bar.com"); - - BlacklistedSite site3 = new BlacklistedSite(); - site3.setId(3L); - site3.setUri("http://baz.com"); + @Test + public void testExportBlacklistedSites() throws IOException { + BlacklistedSite site1 = new BlacklistedSite(); + site1.setId(1L); + site1.setUri("http://foo.com"); + + BlacklistedSite site2 = new BlacklistedSite(); + site2.setId(2L); + site2.setUri("http://bar.com"); + + BlacklistedSite site3 = new BlacklistedSite(); + site3.setId(3L); + site3.setUri("http://baz.com"); Set allBlacklistedSites = ImmutableSet.of(site1, site2, site3); - + Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet()); Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet()); @@ -827,7 +839,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -835,36 +847,36 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our scope list (this test) JsonArray sites = config.get(MITREidDataService.BLACKLISTEDSITES).getAsJsonArray(); @@ -883,7 +895,7 @@ public class TestMITREidDataService_1_2 { } else if (site.get("id").getAsLong() == site3.getId().longValue()) { compare = site3; } - + if (compare == null) { fail("Could not find matching blacklisted site id: " + site.get("id").getAsString()); } else { @@ -893,22 +905,22 @@ public class TestMITREidDataService_1_2 { } // make sure all of our clients were found assertThat(checked.containsAll(allBlacklistedSites), is(true)); - + } @Test public void testImportBlacklistedSites() throws IOException { BlacklistedSite site1 = new BlacklistedSite(); - site1.setId(1L); - site1.setUri("http://foo.com"); + site1.setId(1L); + site1.setUri("http://foo.com"); - BlacklistedSite site2 = new BlacklistedSite(); - site2.setId(2L); - site2.setUri("http://bar.com"); - - BlacklistedSite site3 = new BlacklistedSite(); - site3.setId(3L); - site3.setUri("http://baz.com"); + BlacklistedSite site2 = new BlacklistedSite(); + site2.setId(2L); + site2.setUri("http://bar.com"); + + BlacklistedSite site3 = new BlacklistedSite(); + site3.setId(3L); + site3.setUri("http://baz.com"); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -916,50 +928,50 @@ public class TestMITREidDataService_1_2 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [" + - + "{\"id\":1,\"uri\":\"http://foo.com\"}," + "{\"id\":2,\"uri\":\"http://bar.com\"}," + "{\"id\":3,\"uri\":\"http://baz.com\"}" + - + " ]" + "}"; - - + + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(blSiteRepository, times(3)).save(capturedBlacklistedSites.capture()); - + List savedSites = capturedBlacklistedSites.getAllValues(); - + assertThat(savedSites.size(), is(3)); - + assertThat(savedSites.get(0).getUri(), equalTo(site1.getUri())); - assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri())); + assertThat(savedSites.get(1).getUri(), equalTo(site2.getUri())); assertThat(savedSites.get(2).getUri(), equalTo(site3.getUri())); } - - @Test - public void testExportWhitelistedSites() throws IOException { - WhitelistedSite site1 = new WhitelistedSite(); - site1.setId(1L); - site1.setClientId("foo"); - WhitelistedSite site2 = new WhitelistedSite(); - site2.setId(2L); - site2.setClientId("bar"); - - WhitelistedSite site3 = new WhitelistedSite(); - site3.setId(3L); - site3.setClientId("baz"); + @Test + public void testExportWhitelistedSites() throws IOException { + WhitelistedSite site1 = new WhitelistedSite(); + site1.setId(1L); + site1.setClientId("foo"); + + WhitelistedSite site2 = new WhitelistedSite(); + site2.setId(2L); + site2.setClientId("bar"); + + WhitelistedSite site3 = new WhitelistedSite(); + site3.setId(3L); + site3.setClientId("baz"); Set allWhitelistedSites = ImmutableSet.of(site1, site2, site3); - + Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet()); Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet()); @@ -968,7 +980,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -976,36 +988,36 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our scope list (this test) JsonArray sites = config.get(MITREidDataService.WHITELISTEDSITES).getAsJsonArray(); @@ -1024,7 +1036,7 @@ public class TestMITREidDataService_1_2 { } else if (site.get("id").getAsLong() == site3.getId().longValue()) { compare = site3; } - + if (compare == null) { fail("Could not find matching whitelisted site id: " + site.get("id").getAsString()); } else { @@ -1034,23 +1046,23 @@ public class TestMITREidDataService_1_2 { } // make sure all of our clients were found assertThat(checked.containsAll(allWhitelistedSites), is(true)); - + } @Test public void testImportWhitelistedSites() throws IOException { WhitelistedSite site1 = new WhitelistedSite(); - site1.setId(1L); - site1.setClientId("foo"); + site1.setId(1L); + site1.setClientId("foo"); - WhitelistedSite site2 = new WhitelistedSite(); - site2.setId(2L); - site2.setClientId("bar"); - - WhitelistedSite site3 = new WhitelistedSite(); - site3.setId(3L); - site3.setClientId("baz"); - //site3.setAllowedScopes(null); + WhitelistedSite site2 = new WhitelistedSite(); + site2.setId(2L); + site2.setClientId("bar"); + + WhitelistedSite site3 = new WhitelistedSite(); + site3.setId(3L); + site3.setClientId("baz"); + //site3.setAllowedScopes(null); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -1058,90 +1070,90 @@ public class TestMITREidDataService_1_2 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [" + - + "{\"id\":1,\"clientId\":\"foo\"}," + "{\"id\":2,\"clientId\":\"bar\"}," + "{\"id\":3,\"clientId\":\"baz\"}" + - + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { - Long id = 333L; - @Override - public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { - WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - 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); - } - }); - + + final Map fakeDb = new HashMap(); + when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { + Long id = 333L; + @Override + public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { + WhitelistedSite _site = (WhitelistedSite) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + 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()); - - List savedSites = capturedWhitelistedSites.getAllValues(); - - assertThat(savedSites.size(), is(3)); - - assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); - assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); - assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId())); - } - - @Test - public void testExportGrants() throws IOException { - Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); - Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); - - WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); - when(mockWlSite1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); - - ApprovedSite site1 = new ApprovedSite(); - site1.setId(1L); - site1.setClientId("foo"); - site1.setCreationDate(creationDate1); - site1.setAccessDate(accessDate1); - site1.setUserId("user1"); - site1.setWhitelistedSite(mockWlSite1); - site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); - Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); - Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); - Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); - + List savedSites = capturedWhitelistedSites.getAllValues(); + + assertThat(savedSites.size(), is(3)); + + assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); + assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); + assertThat(savedSites.get(2).getClientId(), equalTo(site3.getClientId())); + } + + @Test + public void testExportGrants() throws IOException { + Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); + Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); + + WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); + when(mockWlSite1.getId()).thenReturn(1L); + + OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); + when(mockToken1.getId()).thenReturn(1L); + + ApprovedSite site1 = new ApprovedSite(); + site1.setId(1L); + site1.setClientId("foo"); + site1.setCreationDate(creationDate1); + site1.setAccessDate(accessDate1); + site1.setUserId("user1"); + site1.setWhitelistedSite(mockWlSite1); + site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); + site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); + + Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); + Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); + Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); + ApprovedSite site2 = new ApprovedSite(); - site2.setId(2L); - site2.setClientId("bar"); - site2.setCreationDate(creationDate2); - site2.setAccessDate(accessDate2); - site2.setUserId("user2"); - site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); - site2.setTimeoutDate(timeoutDate2); + site2.setId(2L); + site2.setClientId("bar"); + site2.setCreationDate(creationDate2); + site2.setAccessDate(accessDate2); + site2.setUserId("user2"); + site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); + site2.setTimeoutDate(timeoutDate2); Set allApprovedSites = ImmutableSet.of(site1, site2); - + Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet()); Mockito.when(approvedSiteRepository.getAll()).thenReturn(allApprovedSites); Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet()); @@ -1150,7 +1162,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -1158,36 +1170,36 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our scope list (this test) JsonArray sites = config.get(MITREidDataService.GRANTS).getAsJsonArray(); @@ -1204,75 +1216,75 @@ public class TestMITREidDataService_1_2 { } else if (site.get("id").getAsLong() == site2.getId().longValue()) { compare = site2; } - + if (compare == null) { fail("Could not find matching whitelisted site id: " + site.get("id").getAsString()); } else { assertThat(site.get("clientId").getAsString(), equalTo(compare.getClientId())); - assertThat(site.get("creationDate").getAsString(), equalTo(DateUtil.toUTCString(compare.getCreationDate()))); - assertThat(site.get("accessDate").getAsString(), equalTo(DateUtil.toUTCString(compare.getAccessDate()))); - if(site.get("timeoutDate").isJsonNull()) { - assertNull(compare.getTimeoutDate()); - } else { - assertThat(site.get("timeoutDate").getAsString(), equalTo(DateUtil.toUTCString(compare.getTimeoutDate()))); - } - assertThat(site.get("userId").getAsString(), equalTo(compare.getUserId())); - assertThat(jsonArrayToStringSet(site.getAsJsonArray("allowedScopes")), equalTo(compare.getAllowedScopes())); - if (site.get("whitelistedSiteId").isJsonNull()) { - assertNull(compare.getWhitelistedSite()); - } else { - assertThat(site.get("whitelistedSiteId").getAsLong(), equalTo(compare.getWhitelistedSite().getId())); - } - if (site.get("approvedAccessTokens").isJsonNull() || site.getAsJsonArray("approvedAccessTokens") == null) { - assertTrue(compare.getApprovedAccessTokens() == null || compare.getApprovedAccessTokens().isEmpty()); - } else { - assertNotNull(compare.getApprovedAccessTokens()); - Set tokenIds = new HashSet(); - for(OAuth2AccessTokenEntity entity : compare.getApprovedAccessTokens()) { - tokenIds.add(entity.getId().toString()); - } - assertThat(jsonArrayToStringSet(site.getAsJsonArray("approvedAccessTokens")), equalTo(tokenIds)); - } + assertThat(site.get("creationDate").getAsString(), equalTo(DateUtil.toUTCString(compare.getCreationDate()))); + assertThat(site.get("accessDate").getAsString(), equalTo(DateUtil.toUTCString(compare.getAccessDate()))); + if(site.get("timeoutDate").isJsonNull()) { + assertNull(compare.getTimeoutDate()); + } else { + assertThat(site.get("timeoutDate").getAsString(), equalTo(DateUtil.toUTCString(compare.getTimeoutDate()))); + } + assertThat(site.get("userId").getAsString(), equalTo(compare.getUserId())); + assertThat(jsonArrayToStringSet(site.getAsJsonArray("allowedScopes")), equalTo(compare.getAllowedScopes())); + if (site.get("whitelistedSiteId").isJsonNull()) { + assertNull(compare.getWhitelistedSite()); + } else { + assertThat(site.get("whitelistedSiteId").getAsLong(), equalTo(compare.getWhitelistedSite().getId())); + } + if (site.get("approvedAccessTokens").isJsonNull() || site.getAsJsonArray("approvedAccessTokens") == null) { + assertTrue(compare.getApprovedAccessTokens() == null || compare.getApprovedAccessTokens().isEmpty()); + } else { + assertNotNull(compare.getApprovedAccessTokens()); + Set tokenIds = new HashSet(); + for(OAuth2AccessTokenEntity entity : compare.getApprovedAccessTokens()) { + tokenIds.add(entity.getId().toString()); + } + assertThat(jsonArrayToStringSet(site.getAsJsonArray("approvedAccessTokens")), equalTo(tokenIds)); + } checked.add(compare); } } // make sure all of our clients were found assertThat(checked.containsAll(allApprovedSites), is(true)); - } - - @Test - public void testImportGrants() throws IOException { - Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); - Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); - - WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); - when(mockWlSite1.getId()).thenReturn(1L); - - OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); - - ApprovedSite site1 = new ApprovedSite(); - site1.setId(1L); - site1.setClientId("foo"); - site1.setCreationDate(creationDate1); - site1.setAccessDate(accessDate1); - site1.setUserId("user1"); - site1.setWhitelistedSite(mockWlSite1); - site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); + } + + @Test + public void testImportGrants() throws IOException { + Date creationDate1 = DateUtil.utcToDate("2014-09-10T22:49:44.090+0000"); + Date accessDate1 = DateUtil.utcToDate("2014-09-10T23:49:44.090+0000"); + + WhitelistedSite mockWlSite1 = mock(WhitelistedSite.class); + when(mockWlSite1.getId()).thenReturn(1L); + + OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); + when(mockToken1.getId()).thenReturn(1L); + + ApprovedSite site1 = new ApprovedSite(); + site1.setId(1L); + site1.setClientId("foo"); + site1.setCreationDate(creationDate1); + site1.setAccessDate(accessDate1); + site1.setUserId("user1"); + site1.setWhitelistedSite(mockWlSite1); + site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); + site1.setApprovedAccessTokens(ImmutableSet.of(mockToken1)); + + Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); + Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); + Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); - Date creationDate2 = DateUtil.utcToDate("2014-09-11T18:49:44.090+0000"); - Date accessDate2 = DateUtil.utcToDate("2014-09-11T20:49:44.090+0000"); - Date timeoutDate2 = DateUtil.utcToDate("2014-10-01T20:49:44.090+0000"); - ApprovedSite site2 = new ApprovedSite(); - site2.setId(2L); - site2.setClientId("bar"); - site2.setCreationDate(creationDate2); - site2.setAccessDate(accessDate2); - site2.setUserId("user2"); - site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); - site2.setTimeoutDate(timeoutDate2); + site2.setId(2L); + site2.setClientId("bar"); + site2.setCreationDate(creationDate2); + site2.setAccessDate(accessDate2); + site2.setUserId("user2"); + site2.setAllowedScopes(ImmutableSet.of("openid", "offline_access", "email", "profile")); + site2.setTimeoutDate(timeoutDate2); String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + @@ -1280,112 +1292,112 @@ public class TestMITREidDataService_1_2 { "\"" + MITREidDataService.REFRESHTOKENS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + - "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [" + - + "{\"id\":1,\"clientId\":\"foo\",\"creationDate\":\"2014-09-10T22:49:44.090+0000\",\"accessDate\":\"2014-09-10T23:49:44.090+0000\"," - + "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1," - + "\"approvedAccessTokens\":[1]}," + + + "\"userId\":\"user1\",\"whitelistedSiteId\":null,\"allowedScopes\":[\"openid\",\"phone\"], \"whitelistedSiteId\":1," + + "\"approvedAccessTokens\":[1]}," + "{\"id\":2,\"clientId\":\"bar\",\"creationDate\":\"2014-09-11T18:49:44.090+0000\",\"accessDate\":\"2014-09-11T20:49:44.090+0000\"," - + "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\"," - + "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" + - + + "\"timeoutDate\":\"2014-10-01T20:49:44.090+0000\",\"userId\":\"user2\"," + + "\"allowedScopes\":[\"openid\",\"offline_access\",\"email\",\"profile\"]}" + + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { - Long id = 364L; - @Override - public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { - ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - return _site; - } - }); - when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - 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; - } - }); + + final Map fakeDb = new HashMap(); + when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { + Long id = 364L; + @Override + public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { + ApprovedSite _site = (ApprovedSite) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + return _site; + } + }); + when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + @Override + public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + 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; + } + }); dataService.importData(reader); - //2 for sites, 1 for updating access token ref on #1, 1 more for updating whitelistedSite ref on #2 + //2 for sites, 1 for updating access token ref on #1, 1 more for updating whitelistedSite ref on #2 verify(approvedSiteRepository, times(4)).save(capturedApprovedSites.capture()); - - List savedSites = new ArrayList(fakeDb.values()); - - assertThat(savedSites.size(), is(2)); - - assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); - assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate())); - assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate())); - assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes())); - assertThat(savedSites.get(0).getIsWhitelisted(), equalTo(site1.getIsWhitelisted())); - assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate())); - assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size())); - - assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); - assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate())); - assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate())); - assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes())); - assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate())); - assertThat(savedSites.get(1).getIsWhitelisted(), equalTo(site2.getIsWhitelisted())); - assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size())); - } - - @Test - public void testExportAuthenticationHolders() throws IOException { - OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), - true, new HashSet(), new HashSet(), "http://foo.com", - new HashSet(), null); - Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); - - AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); - holder1.setId(1L); - holder1.setAuthentication(auth1); - - OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), - true, new HashSet(), new HashSet(), "http://bar.com", - new HashSet(), null); - Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); - - AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); - holder2.setId(2L); - holder2.setAuthentication(auth2); - + + List savedSites = new ArrayList(fakeDb.values()); + + assertThat(savedSites.size(), is(2)); + + assertThat(savedSites.get(0).getClientId(), equalTo(site1.getClientId())); + assertThat(savedSites.get(0).getAccessDate(), equalTo(site1.getAccessDate())); + assertThat(savedSites.get(0).getCreationDate(), equalTo(site1.getCreationDate())); + assertThat(savedSites.get(0).getAllowedScopes(), equalTo(site1.getAllowedScopes())); + assertThat(savedSites.get(0).getIsWhitelisted(), equalTo(site1.getIsWhitelisted())); + assertThat(savedSites.get(0).getTimeoutDate(), equalTo(site1.getTimeoutDate())); + assertThat(savedSites.get(0).getApprovedAccessTokens().size(), equalTo(site1.getApprovedAccessTokens().size())); + + assertThat(savedSites.get(1).getClientId(), equalTo(site2.getClientId())); + assertThat(savedSites.get(1).getAccessDate(), equalTo(site2.getAccessDate())); + assertThat(savedSites.get(1).getCreationDate(), equalTo(site2.getCreationDate())); + assertThat(savedSites.get(1).getAllowedScopes(), equalTo(site2.getAllowedScopes())); + assertThat(savedSites.get(1).getTimeoutDate(), equalTo(site2.getTimeoutDate())); + assertThat(savedSites.get(1).getIsWhitelisted(), equalTo(site2.getIsWhitelisted())); + assertThat(savedSites.get(1).getApprovedAccessTokens().size(), equalTo(site2.getApprovedAccessTokens().size())); + } + + @Test + public void testExportAuthenticationHolders() throws IOException { + OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), + true, new HashSet(), new HashSet(), "http://foo.com", + new HashSet(), null); + Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); + + AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); + holder1.setId(1L); + holder1.setAuthentication(auth1); + + OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), + true, new HashSet(), new HashSet(), "http://bar.com", + new HashSet(), null); + Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); + + AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); + holder2.setId(2L); + holder2.setAuthentication(auth2); + List allAuthHolders = ImmutableList.of(holder1, holder2); - + Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet()); Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet()); @@ -1394,7 +1406,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -1402,37 +1414,37 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our holder list (this test) JsonArray holders = config.get(MITREidDataService.AUTHENTICATIONHOLDERS).getAsJsonArray(); @@ -1449,7 +1461,7 @@ public class TestMITREidDataService_1_2 { } else if (holder.get("id").getAsLong() == holder2.getId()) { compare = holder2; } - + if (compare == null) { fail("Could not find matching authentication holder id: " + holder.get("id").getAsString()); } else { @@ -1459,30 +1471,30 @@ public class TestMITREidDataService_1_2 { } // make sure all of our clients were found assertThat(checked.containsAll(allAuthHolders), is(true)); - } - - @Test - public void testImportAuthenticationHolders() throws IOException { - OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), - true, new HashSet(), new HashSet(), "http://foo.com", - new HashSet(), null); - Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); - - AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); - holder1.setId(1L); - holder1.setAuthentication(auth1); - - OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), - true, new HashSet(), new HashSet(), "http://bar.com", - new HashSet(), null); - Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); - - AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); - holder2.setId(2L); - holder2.setAuthentication(auth2); - + } + + @Test + public void testImportAuthenticationHolders() throws IOException { + OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), + true, new HashSet(), new HashSet(), "http://foo.com", + new HashSet(), null); + Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); + + AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); + holder1.setId(1L); + holder1.setAuthentication(auth1); + + OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), + true, new HashSet(), new HashSet(), "http://bar.com", + new HashSet(), null); + Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); + + AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); + holder2.setId(2L); + holder2.setAuthentication(auth2); + String configJson = "{" + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + @@ -1492,44 +1504,44 @@ public class TestMITREidDataService_1_2 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" + - + "{\"id\":1,\"authentication\":{\"authorizationRequest\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"}," - + "\"userAuthentication\":null}}," + + + "\"userAuthentication\":null}}," + "{\"id\":2,\"authentication\":{\"authorizationRequest\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"}," + "\"userAuthentication\":null}}" + " ]" + "}"; - + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - - final Map fakeDb = new HashMap(); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { - Long id = 243L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _site = (AuthenticationHolderEntity) invocation.getArguments()[0]; - if(_site.getId() == null) { - _site.setId(id++); - } - fakeDb.put(_site.getId(), _site); - return _site; - } - }); - + + final Map fakeDb = new HashMap(); + when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + Long id = 243L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _site = (AuthenticationHolderEntity) invocation.getArguments()[0]; + if(_site.getId() == null) { + _site.setId(id++); + } + fakeDb.put(_site.getId(), _site); + return _site; + } + }); + dataService.importData(reader); verify(authHolderRepository, times(2)).save(capturedAuthHolders.capture()); - + List savedAuthHolders = capturedAuthHolders.getAllValues(); - + assertThat(savedAuthHolders.size(), is(2)); assertThat(savedAuthHolders.get(0).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder1.getAuthentication().getOAuth2Request().getClientId())); assertThat(savedAuthHolders.get(1).getAuthentication().getOAuth2Request().getClientId(), equalTo(holder2.getAuthentication().getOAuth2Request().getClientId())); - } - + } + @Test - public void testExportSystemScopes() throws IOException { + public void testExportSystemScopes() throws IOException { SystemScope scope1 = new SystemScope(); scope1.setId(1L); scope1.setValue("scope1"); @@ -1555,7 +1567,7 @@ public class TestMITREidDataService_1_2 { scope3.setIcon("road"); Set allScopes = ImmutableSet.of(scope1, scope2, scope3); - + Mockito.when(clientRepository.getAllClients()).thenReturn(new HashSet()); Mockito.when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet()); @@ -1564,7 +1576,7 @@ public class TestMITREidDataService_1_2 { Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); Mockito.when(sysScopeRepository.getAll()).thenReturn(allScopes); - + // do the data export StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); @@ -1572,37 +1584,37 @@ public class TestMITREidDataService_1_2 { dataService.exportData(writer); writer.endObject(); writer.close(); - + // parse the output as a JSON object for testing JsonElement elem = new JsonParser().parse(stringWriter.toString()); JsonObject root = elem.getAsJsonObject(); // make sure the root is there assertThat(root.has(MITREidDataService.MITREID_CONNECT_1_2), is(true)); - + JsonObject config = root.get(MITREidDataService.MITREID_CONNECT_1_2).getAsJsonObject(); - + // make sure all the root elements are there assertThat(config.has(MITREidDataService.CLIENTS), is(true)); assertThat(config.has(MITREidDataService.GRANTS), is(true)); - assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); - assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.WHITELISTEDSITES), is(true)); + assertThat(config.has(MITREidDataService.BLACKLISTEDSITES), is(true)); assertThat(config.has(MITREidDataService.REFRESHTOKENS), is(true)); assertThat(config.has(MITREidDataService.ACCESSTOKENS), is(true)); assertThat(config.has(MITREidDataService.SYSTEMSCOPES), is(true)); assertThat(config.has(MITREidDataService.AUTHENTICATIONHOLDERS), is(true)); - + // make sure the root elements are all arrays assertThat(config.get(MITREidDataService.CLIENTS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.GRANTS).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); - assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.WHITELISTEDSITES).isJsonArray(), is(true)); + assertThat(config.get(MITREidDataService.BLACKLISTEDSITES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.REFRESHTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.ACCESSTOKENS).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.SYSTEMSCOPES).isJsonArray(), is(true)); assertThat(config.get(MITREidDataService.AUTHENTICATIONHOLDERS).isJsonArray(), is(true)); - + // check our scope list (this test) JsonArray scopes = config.get(MITREidDataService.SYSTEMSCOPES).getAsJsonArray(); @@ -1621,7 +1633,7 @@ public class TestMITREidDataService_1_2 { } else if (scope.get("value").getAsString().equals(scope3.getValue())) { compare = scope3; } - + if (compare == null) { fail("Could not find matching scope value: " + scope.get("value").getAsString()); } else { @@ -1635,7 +1647,7 @@ public class TestMITREidDataService_1_2 { } // make sure all of our clients were found assertThat(checked.containsAll(allScopes), is(true)); - + } @Test @@ -1673,23 +1685,23 @@ public class TestMITREidDataService_1_2 { "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [], " + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [" + - + "{\"id\":1,\"description\":\"Scope 1\",\"icon\":\"glass\",\"value\":\"scope1\",\"allowDynReg\":false,\"defaultScope\":false}," + "{\"id\":2,\"description\":\"Scope 2\",\"icon\":\"ball\",\"value\":\"scope2\",\"allowDynReg\":true,\"defaultScope\":false}," + "{\"id\":3,\"description\":\"Scope 3\",\"icon\":\"road\",\"value\":\"scope3\",\"allowDynReg\":true,\"defaultScope\":true}" + - + " ]" + - "}"; - + "}"; + System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - + dataService.importData(reader); verify(sysScopeRepository, times(3)).save(capturedScope.capture()); - + List savedScopes = capturedScope.getAllValues(); - + assertThat(savedScopes.size(), is(3)); assertThat(savedScopes.get(0).getValue(), equalTo(scope1.getValue())); assertThat(savedScopes.get(0).getDescription(), equalTo(scope1.getDescription())); @@ -1708,141 +1720,141 @@ public class TestMITREidDataService_1_2 { assertThat(savedScopes.get(2).getIcon(), equalTo(scope3.getIcon())); assertThat(savedScopes.get(2).isDefaultScope(), equalTo(scope3.isDefaultScope())); assertThat(savedScopes.get(2).isAllowDynReg(), equalTo(scope3.isAllowDynReg())); - + } - - @Test - public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { - String expiration1 = "2014-09-10T22:49:44.090+0000"; - Date expirationDate1 = DateUtil.utcToDate(expiration1); - - 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", - new HashSet(), null); - Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); - - AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); - holder1.setId(1L); - holder1.setAuthentication(auth1); - - OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); - token1.setId(1L); - token1.setClient(mockedClient1); - token1.setExpiration(expirationDate1); - token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); - token1.setAuthenticationHolder(holder1); - - String expiration2 = "2015-01-07T18:31:50.079+0000"; - Date expirationDate2 = DateUtil.utcToDate(expiration2); - - 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", - new HashSet(), null); - Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); - OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); - - AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); - holder2.setId(2L); - holder2.setAuthentication(auth2); - - OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); - token2.setId(2L); - token2.setClient(mockedClient2); - token2.setExpiration(expirationDate2); - token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); - token2.setAuthenticationHolder(holder2); - + + @Test + public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException, ParseException { + String expiration1 = "2014-09-10T22:49:44.090+0000"; + Date expirationDate1 = DateUtil.utcToDate(expiration1); + + 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", + new HashSet(), null); + Authentication mockAuth1 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth1 = new OAuth2Authentication(req1, mockAuth1); + + AuthenticationHolderEntity holder1 = new AuthenticationHolderEntity(); + holder1.setId(1L); + holder1.setAuthentication(auth1); + + OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); + token1.setId(1L); + token1.setClient(mockedClient1); + token1.setExpiration(expirationDate1); + token1.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ."); + token1.setAuthenticationHolder(holder1); + + String expiration2 = "2015-01-07T18:31:50.079+0000"; + Date expirationDate2 = DateUtil.utcToDate(expiration2); + + 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", + new HashSet(), null); + Authentication mockAuth2 = mock(Authentication.class, withSettings().serializable()); + OAuth2Authentication auth2 = new OAuth2Authentication(req2, mockAuth2); + + AuthenticationHolderEntity holder2 = new AuthenticationHolderEntity(); + holder2.setId(2L); + holder2.setAuthentication(auth2); + + OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); + token2.setId(2L); + token2.setClient(mockedClient2); + token2.setExpiration(expirationDate2); + token2.setValue("eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ."); + token2.setAuthenticationHolder(holder2); + String configJson = "{" + "\"" + MITREidDataService.SYSTEMSCOPES + "\": [], " + "\"" + MITREidDataService.ACCESSTOKENS + "\": [], " + - "\"" + MITREidDataService.CLIENTS + "\": [], " + + "\"" + MITREidDataService.CLIENTS + "\": [], " + "\"" + MITREidDataService.GRANTS + "\": [], " + "\"" + MITREidDataService.WHITELISTEDSITES + "\": [], " + "\"" + MITREidDataService.BLACKLISTEDSITES + "\": [], " + "\"" + MITREidDataService.AUTHENTICATIONHOLDERS + "\": [" + - + "{\"id\":1,\"authentication\":{\"authorizationRequest\":{\"clientId\":\"client1\",\"redirectUri\":\"http://foo.com\"}," - + "\"userAuthentication\":null}}," + + + "\"userAuthentication\":null}}," + "{\"id\":2,\"authentication\":{\"authorizationRequest\":{\"clientId\":\"client2\",\"redirectUri\":\"http://bar.com\"}," + "\"userAuthentication\":null}}" + " ]," + "\"" + MITREidDataService.REFRESHTOKENS + "\": [" + - + "{\"id\":1,\"clientId\":\"mocked_client_1\",\"expiration\":\"2014-09-10T22:49:44.090+0000\"," - + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + + + "\"authenticationHolderId\":1,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJmOTg4OWQyOS0xMTk1LTQ4ODEtODgwZC1lZjVlYzAwY2Y4NDIifQ.\"}," + "{\"id\":2,\"clientId\":\"mocked_client_2\",\"expiration\":\"2015-01-07T18:31:50.079+0000\"," - + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + - + + "\"authenticationHolderId\":2,\"value\":\"eyJhbGciOiJub25lIn0.eyJqdGkiOiJlYmEyYjc3My0xNjAzLTRmNDAtOWQ3MS1hMGIxZDg1OWE2MDAifQ.\"}" + + " ]" + "}"; System.err.println(configJson); - + JsonReader reader = new JsonReader(new StringReader(configJson)); - final Map fakeRefreshTokenTable = new HashMap(); - final Map fakeAuthHolderTable = new HashMap(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { - Long id = 343L; - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; - if(_token.getId() == null) { - _token.setId(id++); - } - fakeRefreshTokenTable.put(_token.getId(), _token); - return _token; - } - }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { - @Override - public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeRefreshTokenTable.get(_id); - } - }); - when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { - @Override - 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; - } - }); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { - Long id = 356L; - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; - if(_holder.getId() == null) { - _holder.setId(id++); - } - fakeAuthHolderTable.put(_holder.getId(), _holder); - return _holder; - } - }); - when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { - @Override - public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { - Long _id = (Long) invocation.getArguments()[0]; - return fakeAuthHolderTable.get(_id); - } - }); + final Map fakeRefreshTokenTable = new HashMap(); + final Map fakeAuthHolderTable = new HashMap(); + when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + Long id = 343L; + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + OAuth2RefreshTokenEntity _token = (OAuth2RefreshTokenEntity) invocation.getArguments()[0]; + if(_token.getId() == null) { + _token.setId(id++); + } + fakeRefreshTokenTable.put(_token.getId(), _token); + return _token; + } + }); + when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + @Override + public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeRefreshTokenTable.get(_id); + } + }); + when(clientRepository.getClientByClientId(anyString())).thenAnswer(new Answer() { + @Override + 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; + } + }); + when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + Long id = 356L; + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + AuthenticationHolderEntity _holder = (AuthenticationHolderEntity) invocation.getArguments()[0]; + if(_holder.getId() == null) { + _holder.setId(id++); + } + fakeAuthHolderTable.put(_holder.getId(), _holder); + return _holder; + } + }); + when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { + @Override + public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { + Long _id = (Long) invocation.getArguments()[0]; + return fakeAuthHolderTable.get(_id); + } + }); dataService.importData(reader); - + List savedRefreshTokens = new ArrayList(fakeRefreshTokenTable.values()); //capturedRefreshTokens.getAllValues(); - Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); - - assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L)); - assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L)); - } - + Collections.sort(savedRefreshTokens, new refreshTokenIdComparator()); + + assertThat(savedRefreshTokens.get(0).getAuthenticationHolder().getId(), equalTo(356L)); + assertThat(savedRefreshTokens.get(1).getAuthenticationHolder().getId(), equalTo(357L)); + } + private Set jsonArrayToStringSet(JsonArray a) { Set s = new HashSet(); for (JsonElement jsonElement : a) { diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/util/TestIdTokenHashUtils.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/util/TestIdTokenHashUtils.java index b8f412981..047af1db7 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/util/TestIdTokenHashUtils.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/util/TestIdTokenHashUtils.java @@ -52,13 +52,13 @@ public class TestIdTokenHashUtils { public void prepare() throws ParseException { /* - Claims for first token: - + Claims for first token: + claims.setType("JWT"); claims.setIssuer("www.example.com"); claims.setSubject("example_user"); claims.setClaim("alg", "HS256"); - */ + */ Mockito.when(mockToken256.getJwt()).thenReturn(JWTParser.parse("eyJhbGciOiJub25lIn0.eyJhbGciOiJIUzI1NiIsInN1YiI6ImV4YW1wbGVfdXNlciIsImlzcyI6Ind3dy5leGFtcGxlLmNvbSIsInR5cCI6IkpXVCJ9.")); /* @@ -85,12 +85,7 @@ public class TestIdTokenHashUtils { @Test public void getAccessTokenHash256() { - /* - * independently generate hash - ascii of token = eyJhbGciOiJub25lIn0.eyJhbGciOiJIUzI1NiIsInN1YiI6ImV4YW1wbGVfdXNlciIsImlzcyI6Ind3dy5leGFtcGxlLmNvbSIsInR5cCI6IkpXVCJ9. - base64url of hash = EP1gXNeESRH-n57baopfTQ - */ - String token = mockToken256.getJwt().serialize(); + mockToken256.getJwt().serialize(); Base64URL expectedHash = new Base64URL("EP1gXNeESRH-n57baopfTQ"); Base64URL resultHash = IdTokenHashUtils.getAccessTokenHash(JWSAlgorithm.HS256, mockToken256); @@ -107,7 +102,7 @@ public class TestIdTokenHashUtils { base64url of hash = BWfFK73PQI36M1rg9R6VjMyWOE0-XvBK */ - String token = mockToken384.getJwt().serialize(); + mockToken384.getJwt().serialize(); Base64URL expectedHash = new Base64URL("BWfFK73PQI36M1rg9R6VjMyWOE0-XvBK"); Base64URL resultHash = IdTokenHashUtils.getAccessTokenHash(JWSAlgorithm.ES384, mockToken384); @@ -124,7 +119,7 @@ public class TestIdTokenHashUtils { base64url of hash = vGH3QMY-knpACkLgzdkTqu3C9jtvbf2Wk_RSu2vAx8k */ - String token = mockToken512.getJwt().serialize(); + mockToken512.getJwt().serialize(); Base64URL expectedHash = new Base64URL("vGH3QMY-knpACkLgzdkTqu3C9jtvbf2Wk_RSu2vAx8k"); Base64URL resultHash = IdTokenHashUtils.getAccessTokenHash(JWSAlgorithm.RS512, mockToken512);