diff --git a/openid-connect-client/pom.xml b/openid-connect-client/pom.xml index 649f00297a..0df0ec1e41 100644 --- a/openid-connect-client/pom.xml +++ b/openid-connect-client/pom.xml @@ -22,7 +22,7 @@ openid-connect-parent org.mitre - 1.3.7.cnaf-20250915 + 1.4.0.cnaf-20251012 .. openid-connect-client diff --git a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridClientConfigurationService.java b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridClientConfigurationService.java index f7455981d9..542352b28d 100644 --- a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridClientConfigurationService.java +++ b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridClientConfigurationService.java @@ -17,22 +17,24 @@ *******************************************************************************/ package org.mitre.openid.connect.client.service.impl; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mitre.oauth2.model.RegisteredClient; import org.mitre.openid.connect.config.ServerConfiguration; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import org.mockito.junit.MockitoJUnitRunner; /** * @author wkim @@ -41,77 +43,80 @@ @RunWith(MockitoJUnitRunner.class) public class TestHybridClientConfigurationService { - @Mock - private StaticClientConfigurationService mockStaticService; + @Mock + private StaticClientConfigurationService mockStaticService; - @Mock - private DynamicRegistrationClientConfigurationService mockDynamicService; + @Mock + private DynamicRegistrationClientConfigurationService mockDynamicService; - @InjectMocks - private HybridClientConfigurationService hybridService; + @InjectMocks + private HybridClientConfigurationService hybridService; - // test fixture + // test fixture - @Mock - private RegisteredClient mockClient; + @Mock + private RegisteredClient mockClient; - @Mock - private ServerConfiguration mockServerConfig; + @Mock + private ServerConfiguration mockServerConfig; - private String issuer = "https://www.example.com/"; + private String issuer = "https://www.example.com/"; - @Before - public void prepare() { + @Before + public void prepare() { - Mockito.reset(mockDynamicService, mockStaticService); + reset(mockDynamicService, mockStaticService); - Mockito.when(mockServerConfig.getIssuer()).thenReturn(issuer); + lenient().when(mockServerConfig.getIssuer()).thenReturn(issuer); - } + } - @Test - public void getClientConfiguration_useStatic() { + @Test + public void getClientConfiguration_useStatic() { - Mockito.when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient); + lenient().when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient); - RegisteredClient result = hybridService.getClientConfiguration(mockServerConfig); + RegisteredClient result = hybridService.getClientConfiguration(mockServerConfig); - Mockito.verify(mockStaticService).getClientConfiguration(mockServerConfig); - Mockito.verify(mockDynamicService, Mockito.never()).getClientConfiguration(Matchers.any(ServerConfiguration.class)); - assertEquals(mockClient, result); - } + verify(mockStaticService).getClientConfiguration(mockServerConfig); + verify(mockDynamicService, Mockito.never()) + .getClientConfiguration(any(ServerConfiguration.class)); + assertEquals(mockClient, result); + } - @Test - public void getClientConfiguration_useDynamic() { + @Test + public void getClientConfiguration_useDynamic() { - Mockito.when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(null); - Mockito.when(mockDynamicService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient); + lenient().when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(null); + lenient().when(mockDynamicService.getClientConfiguration(mockServerConfig)) + .thenReturn(mockClient); - RegisteredClient result = hybridService.getClientConfiguration(mockServerConfig); + RegisteredClient result = hybridService.getClientConfiguration(mockServerConfig); - Mockito.verify(mockStaticService).getClientConfiguration(mockServerConfig); - Mockito.verify(mockDynamicService).getClientConfiguration(mockServerConfig); - assertEquals(mockClient, result); - } + verify(mockStaticService).getClientConfiguration(mockServerConfig); + verify(mockDynamicService).getClientConfiguration(mockServerConfig); + assertEquals(mockClient, result); + } - /** - * Checks the behavior when the issuer is not known. - */ - @Test - public void getClientConfiguration_noIssuer() { + /** + * Checks the behavior when the issuer is not known. + */ + @Test + public void getClientConfiguration_noIssuer() { - // The mockServerConfig is known to both services - Mockito.when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient); - Mockito.when(mockDynamicService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient); + // The mockServerConfig is known to both services + lenient().when(mockStaticService.getClientConfiguration(mockServerConfig)).thenReturn(mockClient); + lenient().when(mockDynamicService.getClientConfiguration(mockServerConfig)) + .thenReturn(mockClient); - // But oh noes! We're going to ask it to find us some other issuer - ServerConfiguration badIssuer = Mockito.mock(ServerConfiguration.class); - Mockito.when(badIssuer.getIssuer()).thenReturn("www.badexample.com"); + // But oh noes! We're going to ask it to find us some other issuer + ServerConfiguration badIssuer = Mockito.mock(ServerConfiguration.class); + lenient().when(badIssuer.getIssuer()).thenReturn("www.badexample.com"); - RegisteredClient result = hybridService.getClientConfiguration(badIssuer); + RegisteredClient result = hybridService.getClientConfiguration(badIssuer); - Mockito.verify(mockStaticService).getClientConfiguration(badIssuer); - Mockito.verify(mockDynamicService).getClientConfiguration(badIssuer); - assertThat(result, is(nullValue())); - } + verify(mockStaticService).getClientConfiguration(badIssuer); + verify(mockDynamicService).getClientConfiguration(badIssuer); + assertThat(result, is(nullValue())); + } } diff --git a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridServerConfigurationService.java b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridServerConfigurationService.java index c14e756f14..652f6e9334 100644 --- a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridServerConfigurationService.java +++ b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestHybridServerConfigurationService.java @@ -18,21 +18,23 @@ package org.mitre.openid.connect.client.service.impl; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mitre.openid.connect.config.ServerConfiguration; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import org.mockito.junit.MockitoJUnitRunner; /** * @author wkim @@ -41,68 +43,68 @@ @RunWith(MockitoJUnitRunner.class) public class TestHybridServerConfigurationService { - @Mock - private StaticServerConfigurationService mockStaticService; + @Mock + private StaticServerConfigurationService mockStaticService; - @Mock - private DynamicServerConfigurationService mockDynamicService; + @Mock + private DynamicServerConfigurationService mockDynamicService; - @InjectMocks - private HybridServerConfigurationService hybridService; + @InjectMocks + private HybridServerConfigurationService hybridService; - @Mock - private ServerConfiguration mockServerConfig; + @Mock + private ServerConfiguration mockServerConfig; - private String issuer = "https://www.example.com/"; + private String issuer = "https://www.example.com/"; - @Before - public void prepare() { + @Before + public void prepare() { - Mockito.reset(mockDynamicService, mockStaticService); + reset(mockDynamicService, mockStaticService); - } + } - @Test - public void getServerConfiguration_useStatic() { + @Test + public void getServerConfiguration_useStatic() { - Mockito.when(mockStaticService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); + lenient().when(mockStaticService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); - ServerConfiguration result = hybridService.getServerConfiguration(issuer); + ServerConfiguration result = hybridService.getServerConfiguration(issuer); - Mockito.verify(mockStaticService).getServerConfiguration(issuer); - Mockito.verify(mockDynamicService, Mockito.never()).getServerConfiguration(Matchers.anyString()); - assertEquals(mockServerConfig, result); - } + verify(mockStaticService).getServerConfiguration(issuer); + verify(mockDynamicService, Mockito.never()).getServerConfiguration(any(String.class)); + assertEquals(mockServerConfig, result); + } - @Test - public void getServerConfiguration_useDynamic() { + @Test + public void getServerConfiguration_useDynamic() { - Mockito.when(mockStaticService.getServerConfiguration(issuer)).thenReturn(null); - Mockito.when(mockDynamicService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); + lenient().when(mockStaticService.getServerConfiguration(issuer)).thenReturn(null); + lenient().when(mockDynamicService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); - ServerConfiguration result = hybridService.getServerConfiguration(issuer); + ServerConfiguration result = hybridService.getServerConfiguration(issuer); - Mockito.verify(mockStaticService).getServerConfiguration(issuer); - Mockito.verify(mockDynamicService).getServerConfiguration(issuer); - assertEquals(mockServerConfig, result); - } + verify(mockStaticService).getServerConfiguration(issuer); + verify(mockDynamicService).getServerConfiguration(issuer); + assertEquals(mockServerConfig, result); + } - /** - * Checks the behavior when the issuer is not known. - */ - @Test - public void getServerConfiguration_noIssuer() { + /** + * Checks the behavior when the issuer is not known. + */ + @Test + public void getServerConfiguration_noIssuer() { - Mockito.when(mockStaticService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); - Mockito.when(mockDynamicService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); + lenient().when(mockStaticService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); + lenient().when(mockDynamicService.getServerConfiguration(issuer)).thenReturn(mockServerConfig); - String badIssuer = "www.badexample.com"; + String badIssuer = "www.badexample.com"; - ServerConfiguration result = hybridService.getServerConfiguration(badIssuer); + ServerConfiguration result = hybridService.getServerConfiguration(badIssuer); - Mockito.verify(mockStaticService).getServerConfiguration(badIssuer); - Mockito.verify(mockDynamicService).getServerConfiguration(badIssuer); - assertThat(result, is(nullValue())); - } + verify(mockStaticService).getServerConfiguration(badIssuer); + verify(mockDynamicService).getServerConfiguration(badIssuer); + assertThat(result, is(nullValue())); + } } diff --git a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticClientConfigurationService.java b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticClientConfigurationService.java index 4f251a4e3c..e530c12690 100644 --- a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticClientConfigurationService.java +++ b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticClientConfigurationService.java @@ -17,6 +17,12 @@ *******************************************************************************/ package org.mitre.openid.connect.client.service.impl; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + import java.util.HashMap; import java.util.Map; @@ -27,14 +33,7 @@ import org.mitre.openid.connect.config.ServerConfiguration; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import org.mockito.junit.MockitoJUnitRunner; /** * @author wkim diff --git a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticServerConfigurationService.java b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticServerConfigurationService.java index 9f86bd3469..4d9c51197d 100644 --- a/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticServerConfigurationService.java +++ b/openid-connect-client/src/test/java/org/mitre/openid/connect/client/service/impl/TestStaticServerConfigurationService.java @@ -17,6 +17,12 @@ *******************************************************************************/ package org.mitre.openid.connect.client.service.impl; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + import java.util.HashMap; import java.util.Map; @@ -25,14 +31,7 @@ import org.junit.runner.RunWith; import org.mitre.openid.connect.config.ServerConfiguration; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import org.mockito.junit.MockitoJUnitRunner; /** * @author wkim diff --git a/openid-connect-common/pom.xml b/openid-connect-common/pom.xml index 30cc0d65c6..8a7c657169 100644 --- a/openid-connect-common/pom.xml +++ b/openid-connect-common/pom.xml @@ -22,7 +22,7 @@ openid-connect-parent org.mitre - 1.3.7.cnaf-20250915 + 1.4.0.cnaf-20251012 .. openid-connect-common diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientLastUsedEntity.java b/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientLastUsedEntity.java index e632ac7ae2..5ed9b6042a 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientLastUsedEntity.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/model/ClientLastUsedEntity.java @@ -30,48 +30,48 @@ @Table(name = "client_last_used") public class ClientLastUsedEntity { - @Id - @Column(name = "client_details_id") - private Long id; + @Id + @Column(name = "client_details_id") + private Long id; - @OneToOne(cascade = CascadeType.ALL) - @MapsId - @JoinColumn(name = "client_details_id") - private ClientDetailsEntity client; + @OneToOne(cascade = CascadeType.ALL) + @MapsId + @JoinColumn(name = "client_details_id") + private ClientDetailsEntity client; - @Column(name = "last_used", nullable = false) - private LocalDate lastUsed; + @Column(name = "last_used", nullable = false) + private LocalDate lastUsed; - public ClientLastUsedEntity() { - // empty constructor - } + public ClientLastUsedEntity() { + // empty constructor + } - public ClientLastUsedEntity(ClientDetailsEntity client, LocalDate lastUsed) { - this.client = client; - this.lastUsed = lastUsed; - } + public ClientLastUsedEntity(ClientDetailsEntity client, LocalDate lastUsed) { + this.client = client; + this.lastUsed = lastUsed; + } - public Long getId() { - return id; - } + public Long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public ClientDetailsEntity getClient() { - return client; - } + public ClientDetailsEntity getClient() { + return client; + } - public void setClient(ClientDetailsEntity client) { - this.client = client; - } + public void setClient(ClientDetailsEntity client) { + this.client = client; + } - public LocalDate getLastUsed() { - return lastUsed; - } + public LocalDate getLastUsed() { + return lastUsed; + } - public void setLastUsed(LocalDate lastUsed) { - this.lastUsed = lastUsed; - } + public void setLastUsed(LocalDate lastUsed) { + this.lastUsed = lastUsed; + } } diff --git a/openid-connect-common/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java b/openid-connect-common/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java index 2695c18a2e..062ef6a950 100644 --- a/openid-connect-common/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java +++ b/openid-connect-common/src/main/java/org/mitre/oauth2/model/OAuth2AccessTokenEntity.java @@ -62,296 +62,307 @@ * @author jricher * */ +@SuppressWarnings("deprecation") @Entity @Table(name = "access_token") @NamedQueries({ - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_ALL, query = "select a from OAuth2AccessTokenEntity a"), - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_EXPIRED_BY_DATE, query = "select a from OAuth2AccessTokenEntity a where a.expiration <= :" + OAuth2AccessTokenEntity.PARAM_DATE), - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_REFRESH_TOKEN, query = "select a from OAuth2AccessTokenEntity a where a.refreshToken = :" + OAuth2AccessTokenEntity.PARAM_REFRESH_TOKEN), - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_CLIENT, query = "select a from OAuth2AccessTokenEntity a where a.client = :" + OAuth2AccessTokenEntity.PARAM_CLIENT), - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_TOKEN_VALUE_HASH, query = "select a from OAuth2AccessTokenEntity a where a.tokenValueHash = :" + OAuth2AccessTokenEntity.PARAM_TOKEN_VALUE_HASH), - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_APPROVED_SITE, query = "select a from OAuth2AccessTokenEntity a where a.approvedSite = :" + OAuth2AccessTokenEntity.PARAM_APPROVED_SITE), - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, query = "select a from OAuth2AccessTokenEntity a join a.permissions p where p.resourceSet.id = :" + OAuth2AccessTokenEntity.PARAM_RESOURCE_SET_ID), - @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_NAME, query = "select r from OAuth2AccessTokenEntity r where r.authenticationHolder.userAuth.name = :" + OAuth2AccessTokenEntity.PARAM_NAME), - @NamedQuery(name = OAuth2AccessTokenEntity.DELETE_BY_REFRESH_TOKEN, query = "delete from OAuth2AccessTokenEntity a where a.refreshToken = :" + OAuth2AccessTokenEntity.PARAM_REFRESH_TOKEN) -}) -@com.fasterxml.jackson.databind.annotation.JsonSerialize(using = OAuth2AccessTokenJackson2Serializer.class) -@com.fasterxml.jackson.databind.annotation.JsonDeserialize(using = OAuth2AccessTokenJackson2Deserializer.class) + @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_ALL, + query = "select a from OAuth2AccessTokenEntity a"), + @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_EXPIRED_BY_DATE, + query = "select a from OAuth2AccessTokenEntity a where a.expiration <= :" + + OAuth2AccessTokenEntity.PARAM_DATE), + @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_REFRESH_TOKEN, + query = "select a from OAuth2AccessTokenEntity a where a.refreshToken = :" + + OAuth2AccessTokenEntity.PARAM_REFRESH_TOKEN), + @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_CLIENT, + query = "select a from OAuth2AccessTokenEntity a where a.client = :" + + OAuth2AccessTokenEntity.PARAM_CLIENT), + @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_TOKEN_VALUE_HASH, + query = "select a from OAuth2AccessTokenEntity a where a.tokenValueHash = :" + + OAuth2AccessTokenEntity.PARAM_TOKEN_VALUE_HASH), + @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_APPROVED_SITE, + query = "select a from OAuth2AccessTokenEntity a where a.approvedSite = :" + + OAuth2AccessTokenEntity.PARAM_APPROVED_SITE), + @NamedQuery(name = OAuth2AccessTokenEntity.QUERY_BY_NAME, + query = "select r from OAuth2AccessTokenEntity r where r.authenticationHolder.userAuth.name = :" + + OAuth2AccessTokenEntity.PARAM_NAME), + @NamedQuery(name = OAuth2AccessTokenEntity.DELETE_BY_REFRESH_TOKEN, + query = "delete from OAuth2AccessTokenEntity a where a.refreshToken = :" + + OAuth2AccessTokenEntity.PARAM_REFRESH_TOKEN)}) +@com.fasterxml.jackson.databind.annotation.JsonSerialize( + using = OAuth2AccessTokenJackson2Serializer.class) +@com.fasterxml.jackson.databind.annotation.JsonDeserialize( + using = OAuth2AccessTokenJackson2Deserializer.class) public class OAuth2AccessTokenEntity implements OAuth2AccessToken { - public static final String QUERY_BY_APPROVED_SITE = "OAuth2AccessTokenEntity.getByApprovedSite"; - public static final String QUERY_BY_TOKEN_VALUE_HASH = "OAuth2AccessTokenEntity.getByTokenValue"; - public static final String QUERY_BY_CLIENT = "OAuth2AccessTokenEntity.getByClient"; - public static final String QUERY_BY_REFRESH_TOKEN = "OAuth2AccessTokenEntity.getByRefreshToken"; - public static final String QUERY_EXPIRED_BY_DATE = "OAuth2AccessTokenEntity.getAllExpiredByDate"; - public static final String QUERY_ALL = "OAuth2AccessTokenEntity.getAll"; - public static final String QUERY_BY_RESOURCE_SET = "OAuth2AccessTokenEntity.getByResourceSet"; - public static final String QUERY_BY_NAME = "OAuth2AccessTokenEntity.getByName"; - public static final String DELETE_BY_REFRESH_TOKEN = "OAuth2AccessTokenEntity.deleteByRefreshToken"; - - public static final String PARAM_TOKEN_VALUE_HASH = "tokenValueHash"; - public static final String PARAM_CLIENT = "client"; - public static final String PARAM_REFRESH_TOKEN = "refreshToken"; - public static final String PARAM_DATE = "date"; - public static final String PARAM_RESOURCE_SET_ID = "rsid"; - public static final String PARAM_APPROVED_SITE = "approvedSite"; - public static final String PARAM_NAME = "name"; - - public static final String ID_TOKEN_FIELD_NAME = "id_token"; - - private Long id; - - private ClientDetailsEntity client; - - private AuthenticationHolderEntity authenticationHolder; // the authentication that made this access - - private JWT jwtValue; // JWT-encoded access token value - - private String tokenValueHash; // hash of access token value - - private Date expiration; - - private String tokenType = OAuth2AccessToken.BEARER_TYPE; - - private OAuth2RefreshTokenEntity refreshToken; - - private Set scope; - - private Set permissions; - - private ApprovedSite approvedSite; - - private Map additionalInformation = new HashMap<>(); // ephemeral map of items to be added to the OAuth token response - - /** - * Create a new, blank access token - */ - public OAuth2AccessTokenEntity() { - - } - - /** - * @return the id - */ - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id") - public Long getId() { - return id; - } - - /** - * @param id the id to set - */ - public void setId(Long id) { - this.id = id; - } - - /** - * Get all additional information to be sent to the serializer as part of the token response. - * This map is not persisted to the database. - */ - @Override - @Transient - public Map getAdditionalInformation() { - return additionalInformation; - } - - /** - * The authentication in place when this token was created. - * @return the authentication - */ - @ManyToOne - @JoinColumn(name = "auth_holder_id") - public AuthenticationHolderEntity getAuthenticationHolder() { - return authenticationHolder; - } - - /** - * @param authentication the authentication to set - */ - public void setAuthenticationHolder(AuthenticationHolderEntity authenticationHolder) { - this.authenticationHolder = authenticationHolder; - } - - /** - * @return the client - */ - @ManyToOne - @JoinColumn(name = "client_id") - public ClientDetailsEntity getClient() { - return client; - } - - /** - * @param client the client to set - */ - public void setClient(ClientDetailsEntity client) { - this.client = client; - } - - /** - * Get the string-encoded value of this access token. - */ - @Override - @Transient - public String getValue() { - return jwtValue.serialize(); - } - - @Override - @Basic - @Temporal(javax.persistence.TemporalType.TIMESTAMP) - @Column(name = "expiration") - public Date getExpiration() { - return expiration; - } - - public void setExpiration(Date expiration) { - this.expiration = expiration; - } - - @Override - @Basic - @Column(name="token_type") - public String getTokenType() { - return tokenType; - } - - public void setTokenType(String tokenType) { - this.tokenType = tokenType; - } - - @Override - @ManyToOne - @JoinColumn(name="refresh_token_id") - public OAuth2RefreshTokenEntity getRefreshToken() { - return refreshToken; - } - - public void setRefreshToken(OAuth2RefreshTokenEntity refreshToken) { - this.refreshToken = refreshToken; - } - - public void setRefreshToken(OAuth2RefreshToken refreshToken) { - if (!(refreshToken instanceof OAuth2RefreshTokenEntity)) { - throw new IllegalArgumentException("Not a storable refresh token entity!"); - } - // force a pass through to the entity version - setRefreshToken((OAuth2RefreshTokenEntity)refreshToken); - } - - @Override - @ElementCollection(fetch=FetchType.EAGER) - @CollectionTable( - joinColumns=@JoinColumn(name="owner_id"), - name="token_scope" - ) - public Set getScope() { - return scope; - } - - public void setScope(Set scope) { - this.scope = scope; - } - - @Override - @Transient - public boolean isExpired() { - return getExpiration() == null ? false : System.currentTimeMillis() > getExpiration().getTime(); - } - - /** - * @return the jwtValue - */ - @Basic - @Column(name="token_value") - @Convert(converter = JWTStringConverter.class) - public JWT getJwt() { - return jwtValue; - } - - /** - * @param jwtValue the jwtValue to set - */ - public void setJwt(JWT jwt) { - this.jwtValue = jwt; - } - - /** - * @return the tokenValueHash - */ - @Basic - @Column(name = "token_value_hash", length = 64) - public String getTokenValueHash() { - return tokenValueHash; - } - - public void setTokenValueHash(String hash) { - this.tokenValueHash = hash; - } - - @Override - @Transient - public int getExpiresIn() { - - if (getExpiration() == null) { - return -1; // no expiration time - } else { - int secondsRemaining = (int) ((getExpiration().getTime() - System.currentTimeMillis()) / 1000); - if (isExpired()) { - return 0; // has an expiration time and expired - } else { // has an expiration time and not expired - return secondsRemaining; - } - } - } - - /** - * @return the permissions - */ - @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) - @JoinTable( - name = "access_token_permissions", - joinColumns = @JoinColumn(name = "access_token_id"), - inverseJoinColumns = @JoinColumn(name = "permission_id") - ) - public Set getPermissions() { - return permissions; - } - - /** - * @param permissions the permissions to set - */ - public void setPermissions(Set permissions) { - this.permissions = permissions; - } - - @ManyToOne - @JoinColumn(name="approved_site_id") - public ApprovedSite getApprovedSite() { - return approvedSite; - } - - public void setApprovedSite(ApprovedSite approvedSite) { - this.approvedSite = approvedSite; - } - - /** - * Add the ID Token to the additionalInformation map for a token response. - * @param idToken - */ - @Transient - public void setIdToken(JWT idToken) { - if (idToken != null) { - additionalInformation.put(ID_TOKEN_FIELD_NAME, idToken.serialize()); - } - } + public static final String QUERY_BY_APPROVED_SITE = "OAuth2AccessTokenEntity.getByApprovedSite"; + public static final String QUERY_BY_TOKEN_VALUE_HASH = "OAuth2AccessTokenEntity.getByTokenValue"; + public static final String QUERY_BY_CLIENT = "OAuth2AccessTokenEntity.getByClient"; + public static final String QUERY_BY_REFRESH_TOKEN = "OAuth2AccessTokenEntity.getByRefreshToken"; + public static final String QUERY_EXPIRED_BY_DATE = "OAuth2AccessTokenEntity.getAllExpiredByDate"; + public static final String QUERY_ALL = "OAuth2AccessTokenEntity.getAll"; + public static final String QUERY_BY_NAME = "OAuth2AccessTokenEntity.getByName"; + public static final String DELETE_BY_REFRESH_TOKEN = + "OAuth2AccessTokenEntity.deleteByRefreshToken"; + + public static final String PARAM_TOKEN_VALUE_HASH = "tokenValueHash"; + public static final String PARAM_CLIENT = "client"; + public static final String PARAM_REFRESH_TOKEN = "refreshToken"; + public static final String PARAM_DATE = "date"; + public static final String PARAM_RESOURCE_SET_ID = "rsid"; + public static final String PARAM_APPROVED_SITE = "approvedSite"; + public static final String PARAM_NAME = "name"; + + public static final String ID_TOKEN_FIELD_NAME = "id_token"; + + private Long id; + + private ClientDetailsEntity client; + + private AuthenticationHolderEntity authenticationHolder; + + private JWT jwtValue; // JWT-encoded access token value + + private String tokenValueHash; // hash of access token value + + private Date expiration; + + private String tokenType = OAuth2AccessToken.BEARER_TYPE; + + private OAuth2RefreshTokenEntity refreshToken; + + private Set scope; + + private ApprovedSite approvedSite; + + private Map additionalInformation = new HashMap<>(); + + /** + * Create a new, blank access token + */ + public OAuth2AccessTokenEntity() { + + } + + public OAuth2AccessTokenEntity(OAuth2AccessToken token, ClientDetailsEntity client) { + this.setExpiration(token.getExpiration()); + this.setScope(token.getScope()); + this.setTokenType(token.getTokenType()); + this.setRefreshToken(token.getRefreshToken()); + this.additionalInformation.clear(); + this.additionalInformation.putAll(token.getAdditionalInformation()); + this.tokenValueHash = sha256(token.getValue()); + this.client = client; + } + + /** + * @return the id + */ + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * Get all additional information to be sent to the serializer as part of the token response. This + * map is not persisted to the database. + */ + @Override + @Transient + public Map getAdditionalInformation() { + return additionalInformation; + } + + /** + * The authentication in place when this token was created. + * + * @return the authentication + */ + @ManyToOne(cascade = CascadeType.PERSIST) + @JoinColumn(name = "auth_holder_id") + public AuthenticationHolderEntity getAuthenticationHolder() { + return authenticationHolder; + } + + /** + * @param authentication the authentication to set + */ + public void setAuthenticationHolder(AuthenticationHolderEntity authenticationHolder) { + this.authenticationHolder = authenticationHolder; + } + + /** + * @return the client + */ + @ManyToOne + @JoinColumn(name = "client_id") + public ClientDetailsEntity getClient() { + return client; + } + + /** + * @param client the client to set + */ + public void setClient(ClientDetailsEntity client) { + this.client = client; + } + + /** + * Get the string-encoded value of this access token. + */ + @Override + @Transient + public String getValue() { + return jwtValue.serialize(); + } + + @Override + @Basic + @Temporal(javax.persistence.TemporalType.TIMESTAMP) + @Column(name = "expiration") + public Date getExpiration() { + return expiration; + } + + public void setExpiration(Date expiration) { + this.expiration = expiration; + } + + @Override + @Basic + @Column(name = "token_type") + public String getTokenType() { + return tokenType; + } + + public void setTokenType(String tokenType) { + this.tokenType = tokenType; + } + + @Override + @ManyToOne + @JoinColumn(name = "refresh_token_id") + public OAuth2RefreshTokenEntity getRefreshToken() { + return refreshToken; + } + + public void setRefreshToken(OAuth2RefreshTokenEntity refreshToken) { + this.refreshToken = refreshToken; + } + + public void setRefreshToken(OAuth2RefreshToken refreshToken) { + if (refreshToken == null) { + return; + } + if (!(refreshToken instanceof OAuth2RefreshTokenEntity)) { + throw new IllegalArgumentException("Not a storable refresh token entity!"); + } + // force a pass through to the entity version + setRefreshToken((OAuth2RefreshTokenEntity) refreshToken); + } + + @Override + @ElementCollection(fetch = FetchType.EAGER) + @CollectionTable(joinColumns = @JoinColumn(name = "owner_id"), name = "token_scope") + public Set getScope() { + return scope; + } + + public void setScope(Set scope) { + this.scope = scope; + } + + @Override + @Transient + public boolean isExpired() { + return getExpiration() == null ? false : System.currentTimeMillis() > getExpiration().getTime(); + } + + /** + * @return the jwtValue + */ + @Basic + @Column(name = "token_value") + @Convert(converter = JWTStringConverter.class) + public JWT getJwt() { + return jwtValue; + } + + /** + * @param jwtValue the jwtValue to set + */ + public void setJwt(JWT jwt) { + this.jwtValue = jwt; + } + + /** + * @return the tokenValueHash + */ + @Basic + @Column(name = "token_value_hash", length = 64) + public String getTokenValueHash() { + return tokenValueHash; + } + + public void setTokenValueHash(String hash) { + this.tokenValueHash = hash; + } + + @Override + @Transient + public int getExpiresIn() { + + if (getExpiration() == null) { + return -1; // no expiration time + } else { + int secondsRemaining = + (int) ((getExpiration().getTime() - System.currentTimeMillis()) / 1000); + if (isExpired()) { + return 0; // has an expiration time and expired + } else { // has an expiration time and not expired + return secondsRemaining; + } + } + } + + @ManyToOne + @JoinColumn(name = "approved_site_id") + public ApprovedSite getApprovedSite() { + return approvedSite; + } + + public void setApprovedSite(ApprovedSite approvedSite) { + this.approvedSite = approvedSite; + } + + /** + * Add the ID Token to the additionalInformation map for a token response. + * + * @param idToken + */ + @Transient + public void setIdToken(JWT idToken) { + if (idToken != null) { + additionalInformation.put(ID_TOKEN_FIELD_NAME, idToken.serialize()); + } + } public void hashMe() { if (jwtValue != null) { - this.tokenValueHash = - Hashing.sha256().hashString(jwtValue.serialize(), StandardCharsets.UTF_8).toString(); + this.tokenValueHash = sha256(jwtValue.serialize()); } } + + public static String sha256(String tokenString) { + return Hashing.sha256().hashString(tokenString, StandardCharsets.UTF_8).toString(); + } } 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 1b217de3e2..87481b0ae7 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 @@ -23,15 +23,17 @@ import org.mitre.oauth2.model.AuthenticationHolderEntity; public interface AuthenticationHolderRepository { - public List getAll(); - public AuthenticationHolderEntity getById(Long id); + public List getAll(); - public void remove(AuthenticationHolderEntity a); + public AuthenticationHolderEntity getById(Long id); - public AuthenticationHolderEntity save(AuthenticationHolderEntity a); + public void remove(AuthenticationHolderEntity a); - public List getOrphanedAuthenticationHolders(); + public AuthenticationHolderEntity save(AuthenticationHolderEntity a); - public List getOrphanedAuthenticationHolders(PageCriteria pageCriteria); + public List getOrphanedAuthenticationHolders(); + + public List getOrphanedAuthenticationHolders( + PageCriteria pageCriteria); } 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 cf0e5169f0..0cc8d43157 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 @@ -28,41 +28,45 @@ import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; +import com.nimbusds.jwt.SignedJWT; + @SuppressWarnings("deprecation") -public interface OAuth2TokenEntityService extends AuthorizationServerTokenServices, ResourceServerTokenServices { +public interface OAuth2TokenEntityService + extends AuthorizationServerTokenServices, ResourceServerTokenServices { - @Override - public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue); + @Override + public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue); - public OAuth2RefreshTokenEntity getRefreshToken(String refreshTokenValue); + @Override + public OAuth2AccessTokenEntity getAccessToken(OAuth2Authentication authentication); - public void revokeRefreshToken(OAuth2RefreshTokenEntity refreshToken); + public OAuth2RefreshTokenEntity getRefreshToken(String refreshTokenValue); - public void revokeAccessToken(OAuth2AccessTokenEntity accessToken); + public void revokeRefreshToken(OAuth2RefreshTokenEntity refreshToken); - public List getAccessTokensForClient(ClientDetailsEntity client); + public void revokeAccessToken(OAuth2AccessTokenEntity accessToken); - public List getRefreshTokensForClient(ClientDetailsEntity client); + public List getAccessTokensForClient(ClientDetailsEntity client); - public void clearExpiredTokens(); + public List getRefreshTokensForClient(ClientDetailsEntity client); - public OAuth2AccessTokenEntity saveAccessToken(OAuth2AccessTokenEntity accessToken); + public void clearExpiredTokens(); - public OAuth2RefreshTokenEntity saveRefreshToken(OAuth2RefreshTokenEntity refreshToken); + public OAuth2AccessTokenEntity saveAccessToken(OAuth2AccessTokenEntity accessToken); - @Override - public OAuth2AccessTokenEntity getAccessToken(OAuth2Authentication authentication); + public OAuth2RefreshTokenEntity saveRefreshToken(OAuth2RefreshTokenEntity refreshToken); - public OAuth2AccessTokenEntity getAccessTokenById(Long id); + public OAuth2AccessTokenEntity getAccessTokenById(Long id); - public OAuth2RefreshTokenEntity getRefreshTokenById(Long id); + public OAuth2RefreshTokenEntity getRefreshTokenById(Long id); - public Set getAllAccessTokensForUser(String name); + public Set getAllAccessTokensForUser(String name); - public Set getAllRefreshTokensForUser(String name); + public Set getAllRefreshTokensForUser(String name); - public OAuth2AccessTokenEntity getRegistrationAccessTokenForClient(ClientDetailsEntity client); + public OAuth2AccessTokenEntity getRegistrationAccessTokenForClient(ClientDetailsEntity client); - public OAuth2RefreshTokenEntity createRefreshToken(ClientDetailsEntity client, AuthenticationHolderEntity authHolder); + public OAuth2RefreshTokenEntity createRefreshToken(ClientDetailsEntity client, + AuthenticationHolderEntity authHolder); } diff --git a/openid-connect-server/pom.xml b/openid-connect-server/pom.xml index f02bfacaa3..2bdf0f637e 100644 --- a/openid-connect-server/pom.xml +++ b/openid-connect-server/pom.xml @@ -23,7 +23,7 @@ org.mitre openid-connect-parent - 1.3.7.cnaf-20250915 + 1.4.0.cnaf-20251012 .. @@ -74,7 +74,7 @@ - org.apache.commons + commons-io commons-io diff --git a/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaOAuth2TokenRepository.java b/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaOAuth2TokenRepository.java index becb26710c..61abc0249b 100644 --- a/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaOAuth2TokenRepository.java +++ b/openid-connect-server/src/main/java/org/mitre/oauth2/repository/impl/JpaOAuth2TokenRepository.java @@ -267,14 +267,8 @@ public Set getAllExpiredRefreshTokens( } @Override - public Set getAccessTokensForResourceSet( - ResourceSet rs) { - TypedQuery query = manager.createNamedQuery( - OAuth2AccessTokenEntity.QUERY_BY_RESOURCE_SET, - OAuth2AccessTokenEntity.class); - query.setParameter(OAuth2AccessTokenEntity.PARAM_RESOURCE_SET_ID, - rs.getId()); - return new LinkedHashSet<>(query.getResultList()); + public Set getAccessTokensForResourceSet(ResourceSet rs) { + return Set.of(); } @Override 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 ea36949fb6..20477b29ec 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 @@ -25,7 +25,6 @@ import org.mitre.oauth2.model.OAuth2RefreshTokenEntity; import org.mitre.oauth2.service.IntrospectionResultAssembler; import org.mitre.openid.connect.model.UserInfo; -import org.mitre.uma.model.Permission; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.oauth2.provider.OAuth2Authentication; @@ -53,26 +52,9 @@ public Map assembleFrom(OAuth2AccessTokenEntity accessToken, Use result.put(ACTIVE, true); - if (accessToken.getPermissions() != null && !accessToken.getPermissions().isEmpty()) { + Set scopes = Sets.intersection(authScopes, accessToken.getScope()); - Set permissions = Sets.newHashSet(); - - for (Permission perm : accessToken.getPermissions()) { - Map o = newLinkedHashMap(); - o.put("resource_set_id", perm.getResourceSet().getId().toString()); - Set scopes = Sets.newHashSet(perm.getScopes()); - o.put("scopes", scopes); - permissions.add(o); - } - - result.put("permissions", permissions); - - } else { - Set scopes = Sets.intersection(authScopes, accessToken.getScope()); - - result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes)); - - } + result.put(SCOPE, Joiner.on(SCOPE_SEPARATOR).join(scopes)); if (accessToken.getExpiration() != null) { try { 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 09ef334d52..c32e047947 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 @@ -30,6 +30,7 @@ import java.util.Collection; import java.util.Date; import java.util.List; +import java.util.Optional; import java.util.Set; import java.util.UUID; @@ -46,8 +47,6 @@ import org.mitre.oauth2.service.ClientDetailsEntityService; import org.mitre.oauth2.service.OAuth2TokenEntityService; import org.mitre.oauth2.service.SystemScopeService; -import org.mitre.openid.connect.model.ApprovedSite; -import org.mitre.openid.connect.service.ApprovedSiteService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -100,9 +99,6 @@ public class DefaultOAuth2ProviderTokenService implements OAuth2TokenEntityServi @Autowired private SystemScopeService scopeService; - @Autowired - private ApprovedSiteService approvedSiteService; - @Override public Set getAllAccessTokensForUser(String userName) { return tokenRepository.getAccessTokensByUserName(userName); @@ -123,40 +119,6 @@ public OAuth2RefreshTokenEntity getRefreshTokenById(Long id) { return tokenRepository.getRefreshTokenById(id); } - /** - * Utility function to delete an access token that's expired before returning it. - * - * @param token the token to check - * @return null if the token is null or expired, the input token (unchanged) if it hasn't - */ - protected OAuth2AccessTokenEntity clearExpiredAccessToken(OAuth2AccessTokenEntity token) { - if (token == null) { - return null; - } - if (!token.isExpired()) { - return token; - } - revokeAccessToken(token); - return null; - } - - /** - * Utility function to delete a refresh token that's expired before returning it. - * - * @param token the token to check - * @return null if the token is null or expired, the input token (unchanged) if it hasn't - */ - protected OAuth2RefreshTokenEntity clearExpiredRefreshToken(OAuth2RefreshTokenEntity token) { - if (token == null) { - return null; - } - if (!token.isExpired()) { - return token; - } - revokeRefreshToken(token); - return null; - } - @Override @Transactional(value = "defaultTransactionManager") public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentication) @@ -206,66 +168,35 @@ public OAuth2AccessTokenEntity createAccessToken(OAuth2Authentication authentica } - OAuth2AccessTokenEntity token = new OAuth2AccessTokenEntity();// accessTokenFactory.createNewAccessToken(); - - // attach the client - token.setClient(client); - - // inherit the scope from the auth, but make a new set so it is - // not unmodifiable. Unmodifiables don't play nicely with Eclipselink, which - // wants to use the clone operation. + OAuth2AccessTokenEntity at = new OAuth2AccessTokenEntity(); + // client + at.setClient(client); + // scopes Set scopes = scopeService.fromStrings(request.getScope()); - - // remove any of the special system scopes scopes = scopeService.removeReservedScopes(scopes); + at.setScope(scopeService.toStrings(scopes)); + // expiration + at.setExpiration(computeExpiration(client)); - token.setScope(scopeService.toStrings(scopes)); - token.setExpiration(computeExpiration(client)); - - // attach the authorization so that we can look it up later + // create AuthenticationHolderEntity for refresh token AuthenticationHolderEntity authHolder = new AuthenticationHolderEntity(); authHolder.setAuthentication(authentication); - authHolder = authenticationHolderRepository.save(authHolder); - - token.setAuthenticationHolder(authHolder); + at.setAuthenticationHolder(authHolder); // attach a refresh token, if this client is allowed to request them, the user gets the // offline scope and grant type differs from client credentials - if (client.isAllowRefresh() && token.getScope().contains(SystemScopeService.OFFLINE_ACCESS) + if (client.isAllowRefresh() && at.getScope().contains(SystemScopeService.OFFLINE_ACCESS) && !request.getGrantType().equals("client_credentials")) { - token.setRefreshToken(createRefreshToken(client, authHolder)); + at.setRefreshToken(createRefreshToken(client, authHolder)); } - // Add approved site reference, if any - OAuth2Request originalAuthRequest = authHolder.getAuthentication().getOAuth2Request(); - - if (originalAuthRequest.getExtensions() != null - && originalAuthRequest.getExtensions().containsKey("approved_site")) { - - Long apId = - Long.parseLong((String) originalAuthRequest.getExtensions().get("approved_site")); - ApprovedSite ap = approvedSiteService.getById(apId); - - token.setApprovedSite(ap); - } - - OAuth2AccessTokenEntity enhancedToken = - (OAuth2AccessTokenEntity) tokenEnhancer.enhance(token, authentication); - - OAuth2AccessTokenEntity savedToken = saveAccessToken(enhancedToken); - - if (savedToken.getRefreshToken() != null) { - tokenRepository.saveRefreshToken(savedToken.getRefreshToken()); - } - - return savedToken; + return (OAuth2AccessTokenEntity) tokenEnhancer.enhance(at, authentication); } throw new AuthenticationCredentialsNotFoundException("No authentication credentials found"); } - public OAuth2RefreshTokenEntity createRefreshToken(ClientDetailsEntity client, AuthenticationHolderEntity authHolder) { OAuth2RefreshTokenEntity refreshToken = new OAuth2RefreshTokenEntity(); // refreshTokenFactory.createNewRefreshToken(); @@ -293,8 +224,6 @@ public OAuth2RefreshTokenEntity createRefreshToken(ClientDetailsEntity client, refreshToken.setAuthenticationHolder(authHolder); refreshToken.setClient(client); - // save the token first so that we can set it to a member of the access token (NOTE: is this - // step necessary?) return tokenRepository.saveRefreshToken(refreshToken); } @@ -336,11 +265,6 @@ public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, throw new InvalidClientException("Client does not allow refreshing access token!"); } - // clear out any access tokens - if (client.isClearAccessTokensOnRefresh()) { - tokenRepository.clearAccessTokensForRefreshToken(refreshToken); - } - if (refreshToken.isExpired()) { tokenRepository.removeRefreshToken(refreshToken); throw new InvalidTokenException("Expired refresh token: " + refreshTokenValue); @@ -360,7 +284,6 @@ public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, if (authRequest.getScope() != null) { requestedScopes.addAll(authRequest.getScope()); } - requestedScopes.removeAll(reservedScopes); if (!requestedScopes.isEmpty()) { @@ -397,10 +320,7 @@ public OAuth2AccessTokenEntity refreshAccessToken(String refreshTokenValue, authHolder.getAuthentication().getOAuth2Request().refresh(authRequest); OAuth2Authentication newOAuth2Authentication = new OAuth2Authentication(newOAuth2Request, authHolder.getUserAuth()); - OAuth2AccessTokenEntity enhancedToken = - (OAuth2AccessTokenEntity) tokenEnhancer.enhance(token, newOAuth2Authentication); - tokenRepository.saveAccessToken(enhancedToken); - return enhancedToken; + return (OAuth2AccessTokenEntity) tokenEnhancer.enhance(token, newOAuth2Authentication); } private Date computeExpiration(ClientDetailsEntity client) { @@ -420,10 +340,9 @@ public OAuth2Authentication loadAuthentication(String accessTokenValue) OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenByValue(accessTokenValue); if (accessToken == null) { - throw new InvalidTokenException("Invalid access token: " + accessTokenValue); - } else { - return accessToken.getAuthenticationHolder().getAuthentication(); + throw new InvalidTokenException("Invalid access token value"); } + return accessToken.getAuthenticationHolder().getAuthentication(); } @@ -433,13 +352,13 @@ public OAuth2Authentication loadAuthentication(String accessTokenValue) @Override public OAuth2AccessTokenEntity readAccessToken(String accessTokenValue) throws AuthenticationException { - OAuth2AccessTokenEntity accessToken = tokenRepository.getAccessTokenByValue(accessTokenValue); - if (accessToken == null) { - throw new InvalidTokenException( - "Access token for value " + accessTokenValue + " was not found"); - } else { - return accessToken; + + Optional accessToken = + Optional.ofNullable(tokenRepository.getAccessTokenByValue(accessTokenValue)); + if (accessToken.isEmpty()) { + throw new InvalidTokenException("Access token not found"); } + return accessToken.get(); } /** @@ -552,16 +471,8 @@ public void doOperation(AuthenticationHolderEntity item) { @Override @Transactional(value = "defaultTransactionManager") public OAuth2AccessTokenEntity saveAccessToken(OAuth2AccessTokenEntity accessToken) { - OAuth2AccessTokenEntity newToken = tokenRepository.saveAccessToken(accessToken); - - // if the old token has any additional information for the return from the token endpoint, carry - // it through here after save - if (accessToken.getAdditionalInformation() != null - && !accessToken.getAdditionalInformation().isEmpty()) { - newToken.getAdditionalInformation().putAll(accessToken.getAdditionalInformation()); - } - - return newToken; + + return accessToken; } /* diff --git a/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaApprovedSiteRepository.java b/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaApprovedSiteRepository.java index de30df5130..db5d1ae6cc 100644 --- a/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaApprovedSiteRepository.java +++ b/openid-connect-server/src/main/java/org/mitre/openid/connect/repository/impl/JpaApprovedSiteRepository.java @@ -39,66 +39,71 @@ @Repository public class JpaApprovedSiteRepository implements ApprovedSiteRepository { - @PersistenceContext(unitName="defaultPersistenceUnit") - private EntityManager manager; - - @Override - @Transactional(value="defaultTransactionManager") - public Collection getAll() { - TypedQuery query = manager.createNamedQuery(ApprovedSite.QUERY_ALL, ApprovedSite.class); - return query.getResultList(); - } - - @Override - @Transactional(value="defaultTransactionManager") - public ApprovedSite getById(Long id) { - return manager.find(ApprovedSite.class, id); - } - - @Override - @Transactional(value="defaultTransactionManager") - public void remove(ApprovedSite approvedSite) { - ApprovedSite found = manager.find(ApprovedSite.class, approvedSite.getId()); - - if (found != null) { - manager.remove(found); - } else { - throw new IllegalArgumentException(); - } - } - - @Override - @Transactional(value="defaultTransactionManager") - public ApprovedSite save(ApprovedSite approvedSite) { - return saveOrUpdate(approvedSite.getId(), manager, approvedSite); - } - - @Override - public Collection getByClientIdAndUserId(String clientId, String userId) { - - TypedQuery query = manager.createNamedQuery(ApprovedSite.QUERY_BY_CLIENT_ID_AND_USER_ID, ApprovedSite.class); - query.setParameter(ApprovedSite.PARAM_USER_ID, userId); - query.setParameter(ApprovedSite.PARAM_CLIENT_ID, clientId); - - return query.getResultList(); - } - - @Override - @Transactional(value="defaultTransactionManager") - public Collection getByUserId(String userId) { - TypedQuery query = manager.createNamedQuery(ApprovedSite.QUERY_BY_USER_ID, ApprovedSite.class); - query.setParameter(ApprovedSite.PARAM_USER_ID, userId); - - return query.getResultList(); - - } - - @Override - @Transactional(value="defaultTransactionManager") - public Collection getByClientId(String clientId) { - TypedQuery query = manager.createNamedQuery(ApprovedSite.QUERY_BY_CLIENT_ID, ApprovedSite.class); - query.setParameter(ApprovedSite.PARAM_CLIENT_ID, clientId); - - return query.getResultList(); - } + @PersistenceContext(unitName = "defaultPersistenceUnit") + private EntityManager manager; + + @Override + @Transactional(value = "defaultTransactionManager") + public Collection getAll() { + TypedQuery query = + manager.createNamedQuery(ApprovedSite.QUERY_ALL, ApprovedSite.class); + return query.getResultList(); + } + + @Override + @Transactional(value = "defaultTransactionManager") + public ApprovedSite getById(Long id) { + return manager.find(ApprovedSite.class, id); + } + + @Override + @Transactional(value = "defaultTransactionManager") + public void remove(ApprovedSite approvedSite) { + ApprovedSite found = manager.find(ApprovedSite.class, approvedSite.getId()); + + if (found != null) { + manager.remove(found); + } else { + throw new IllegalArgumentException(); + } + } + + @Override + @Transactional(value = "defaultTransactionManager") + public ApprovedSite save(ApprovedSite approvedSite) { + return saveOrUpdate(approvedSite.getId(), manager, approvedSite); + } + + @Override + @Transactional(value = "defaultTransactionManager") + public Collection getByClientIdAndUserId(String clientId, String userId) { + + TypedQuery query = + manager.createNamedQuery(ApprovedSite.QUERY_BY_CLIENT_ID_AND_USER_ID, ApprovedSite.class); + query.setParameter(ApprovedSite.PARAM_USER_ID, userId); + query.setParameter(ApprovedSite.PARAM_CLIENT_ID, clientId); + + return query.getResultList(); + } + + @Override + @Transactional(value = "defaultTransactionManager") + public Collection getByUserId(String userId) { + TypedQuery query = + manager.createNamedQuery(ApprovedSite.QUERY_BY_USER_ID, ApprovedSite.class); + query.setParameter(ApprovedSite.PARAM_USER_ID, userId); + + return query.getResultList(); + + } + + @Override + @Transactional(value = "defaultTransactionManager") + public Collection getByClientId(String clientId) { + TypedQuery query = + manager.createNamedQuery(ApprovedSite.QUERY_BY_CLIENT_ID, ApprovedSite.class); + query.setParameter(ApprovedSite.PARAM_CLIENT_ID, clientId); + + return query.getResultList(); + } } 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 218e40fb35..5084888909 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 @@ -257,8 +257,7 @@ private OAuth2AccessTokenEntity createAssociatedToken(ClientDetailsEntity client // create a new token - Map authorizationParameters = Maps.newHashMap(); - OAuth2Request clientAuth = new OAuth2Request(authorizationParameters, client.getClientId(), + OAuth2Request clientAuth = new OAuth2Request(Map.of(), client.getClientId(), Sets.newHashSet(new SimpleGrantedAuthority("ROLE_CLIENT")), true, scope, null, null, null, null); OAuth2Authentication authentication = new OAuth2Authentication(clientAuth, null); 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 081e5aeea2..0b97393ace 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 @@ -58,397 +58,430 @@ @RequestMapping(value = ProtectedResourceRegistrationEndpoint.URL) public class ProtectedResourceRegistrationEndpoint { - /** - * - */ - public static final String URL = "resource"; - - @Autowired - private ClientDetailsEntityService clientService; - - @Autowired - private OAuth2TokenEntityService tokenService; - - @Autowired - private SystemScopeService scopeService; - - @Autowired - private ConfigurationPropertiesBean config; - - @Autowired - private OIDCTokenService connectTokenService; - - /** - * Logger for this class - */ - private static final Logger logger = LoggerFactory.getLogger(ProtectedResourceRegistrationEndpoint.class); - - /** - * Create a new Client, issue a client ID, and create a registration access token. - * @param jsonString - * @param m - * @param p - * @return - */ - @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) - public String registerNewProtectedResource(@RequestBody String jsonString, Model m) { - - ClientDetailsEntity newClient = null; - try { - newClient = ClientDetailsEntityJsonProcessor.parse(jsonString); - } catch (JsonSyntaxException e) { - // bad parse - // didn't parse, this is a bad request - logger.error("registerNewProtectedResource failed; submitted JSON is malformed"); - m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 - return HttpCodeView.VIEWNAME; - } - - if (newClient != null) { - // it parsed! - - // - // Now do some post-processing consistency checks on it - // - - // clear out any spurious id/secret (clients don't get to pick) - newClient.setClientId(null); - newClient.setClientSecret(null); - - // do validation on the fields - try { - newClient = validateScopes(newClient); - newClient = validateAuth(newClient); - } catch (ValidationException ve) { - // validation failed, return an error - m.addAttribute(JsonErrorView.ERROR, ve.getError()); - m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription()); - m.addAttribute(HttpCodeView.CODE, ve.getStatus()); - return JsonErrorView.VIEWNAME; - } - - - // no grant types are allowed - newClient.setGrantTypes(new HashSet()); - newClient.setResponseTypes(new HashSet()); - newClient.setRedirectUris(new HashSet()); - - // don't issue tokens to this client - newClient.setAccessTokenValiditySeconds(0); - newClient.setIdTokenValiditySeconds(0); - newClient.setRefreshTokenValiditySeconds(0); - - // clear out unused fields - newClient.setDefaultACRvalues(new HashSet()); - newClient.setDefaultMaxAge(null); - newClient.setIdTokenEncryptedResponseAlg(null); - newClient.setIdTokenEncryptedResponseEnc(null); - newClient.setIdTokenSignedResponseAlg(null); - newClient.setInitiateLoginUri(null); - newClient.setPostLogoutRedirectUris(null); - newClient.setRequestObjectSigningAlg(null); - newClient.setRequireAuthTime(null); - newClient.setReuseRefreshToken(false); - newClient.setSectorIdentifierUri(null); - newClient.setSubjectType(null); - newClient.setUserInfoEncryptedResponseAlg(null); - newClient.setUserInfoEncryptedResponseEnc(null); - newClient.setUserInfoSignedResponseAlg(null); - - // this client has been dynamically registered (obviously) - newClient.setDynamicallyRegistered(true); - - // this client has access to the introspection endpoint - newClient.setAllowIntrospection(true); - - // now save it - try { - ClientDetailsEntity savedClient = clientService.saveNewClient(newClient); - - // generate the registration access token - OAuth2AccessTokenEntity token = connectTokenService.createResourceAccessToken(savedClient); - tokenService.saveAccessToken(token); - - // send it all out to the view - - RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8")); - m.addAttribute("client", registered); - m.addAttribute(HttpCodeView.CODE, HttpStatus.CREATED); // http 201 - - return ClientInformationResponseView.VIEWNAME; - } catch (IllegalArgumentException e) { - logger.error("Couldn't save client", e); - - m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata"); - m.addAttribute(JsonErrorView.ERROR_MESSAGE, "Unable to save client due to invalid or inconsistent metadata."); - m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 - - return JsonErrorView.VIEWNAME; - } - } else { - // didn't parse, this is a bad request - logger.error("registerNewClient failed; submitted JSON is malformed"); - m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 - - return HttpCodeView.VIEWNAME; - } - - } - - private ClientDetailsEntity validateScopes(ClientDetailsEntity newClient) throws ValidationException { - // scopes that the client is asking for - Set requestedScopes = scopeService.fromStrings(newClient.getScope()); - - // the scopes that the client can have must be a subset of the dynamically allowed scopes - Set allowedScopes = scopeService.removeRestrictedAndReservedScopes(requestedScopes); - - // if the client didn't ask for any, give them the defaults - if (allowedScopes == null || allowedScopes.isEmpty()) { - allowedScopes = scopeService.getDefaults(); - } - - newClient.setScope(scopeService.toStrings(allowedScopes)); - - return newClient; - } - - /** - * Get the meta information for a client. - * @param clientId - * @param m - * @param auth - * @return - */ - @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')") - @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) - public String readResourceConfiguration(@PathVariable("id") String clientId, Model m, OAuth2Authentication auth) { - - ClientDetailsEntity client = clientService.loadClientByClientId(clientId); - - if (client != null && client.getClientId().equals(auth.getOAuth2Request().getClientId())) { - - // possibly update the token - OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, client); - - RegisteredClient registered = new RegisteredClient(client, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(client.getClientId(), "UTF-8")); - - // send it all out to the view - m.addAttribute("client", registered); - m.addAttribute(HttpCodeView.CODE, HttpStatus.OK); // http 200 - - return ClientInformationResponseView.VIEWNAME; - - } else { - // client mismatch - logger.error("readResourceConfiguration failed, client ID mismatch: " - + clientId + " and " + auth.getOAuth2Request().getClientId() + " do not match."); - m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403 - - return HttpCodeView.VIEWNAME; - } - } - - /** - * Update the metainformation for a given client. - * @param clientId - * @param jsonString - * @param m - * @param auth - * @return - */ - @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')") - @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) - public String updateProtectedResource(@PathVariable("id") String clientId, @RequestBody String jsonString, Model m, OAuth2Authentication auth) { - - - ClientDetailsEntity newClient = null; - try { - newClient = ClientDetailsEntityJsonProcessor.parse(jsonString); - } catch (JsonSyntaxException e) { - // bad parse - // didn't parse, this is a bad request - logger.error("updateProtectedResource failed; submitted JSON is malformed"); - m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 - return HttpCodeView.VIEWNAME; - } - - ClientDetailsEntity oldClient = clientService.loadClientByClientId(clientId); - - if (newClient != null && oldClient != null // we have an existing client and the new one parsed - && oldClient.getClientId().equals(auth.getOAuth2Request().getClientId()) // the client passed in the URI matches the one in the auth - && oldClient.getClientId().equals(newClient.getClientId()) // the client passed in the body matches the one in the URI - ) { - - // a client can't ask to update its own client secret to any particular value - newClient.setClientSecret(oldClient.getClientSecret()); - - newClient.setCreatedAt(oldClient.getCreatedAt()); - - // no grant types are allowed - newClient.setGrantTypes(new HashSet()); - newClient.setResponseTypes(new HashSet()); - newClient.setRedirectUris(new HashSet()); - - // don't issue tokens to this client - newClient.setAccessTokenValiditySeconds(0); - newClient.setIdTokenValiditySeconds(0); - newClient.setRefreshTokenValiditySeconds(0); - - // clear out unused fields - newClient.setDefaultACRvalues(new HashSet()); - newClient.setDefaultMaxAge(null); - newClient.setIdTokenEncryptedResponseAlg(null); - newClient.setIdTokenEncryptedResponseEnc(null); - newClient.setIdTokenSignedResponseAlg(null); - newClient.setInitiateLoginUri(null); - newClient.setPostLogoutRedirectUris(null); - newClient.setRequestObjectSigningAlg(null); - newClient.setRequireAuthTime(null); - newClient.setReuseRefreshToken(false); - newClient.setSectorIdentifierUri(null); - newClient.setSubjectType(null); - newClient.setUserInfoEncryptedResponseAlg(null); - newClient.setUserInfoEncryptedResponseEnc(null); - newClient.setUserInfoSignedResponseAlg(null); - - // this client has been dynamically registered (obviously) - newClient.setDynamicallyRegistered(true); - - // this client has access to the introspection endpoint - newClient.setAllowIntrospection(true); - - // do validation on the fields - try { - newClient = validateScopes(newClient); - newClient = validateAuth(newClient); - } catch (ValidationException ve) { - // validation failed, return an error - m.addAttribute(JsonErrorView.ERROR, ve.getError()); - m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription()); - m.addAttribute(HttpCodeView.CODE, ve.getStatus()); - return JsonErrorView.VIEWNAME; - } - - - try { - // save the client - ClientDetailsEntity savedClient = clientService.updateClient(oldClient, newClient); - - // possibly update the token - OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, savedClient); - - RegisteredClient registered = new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8")); - - // send it all out to the view - m.addAttribute("client", registered); - m.addAttribute(HttpCodeView.CODE, HttpStatus.OK); // http 200 - - return ClientInformationResponseView.VIEWNAME; - } catch (IllegalArgumentException e) { - logger.error("Couldn't save client", e); - - m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata"); - m.addAttribute(JsonErrorView.ERROR_MESSAGE, "Unable to save client due to invalid or inconsistent metadata."); - m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 - - return JsonErrorView.VIEWNAME; - } - } else { - // client mismatch - logger.error("updateProtectedResource" + - " failed, client ID mismatch: " - + clientId + " and " + auth.getOAuth2Request().getClientId() + " do not match."); - m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403 - - return HttpCodeView.VIEWNAME; - } - } - - /** - * Delete the indicated client from the system. - * @param clientId - * @param m - * @param auth - * @return - */ - @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')") - @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE) - public String deleteResource(@PathVariable("id") String clientId, Model m, OAuth2Authentication auth) { - - ClientDetailsEntity client = clientService.loadClientByClientId(clientId); - - if (client != null && client.getClientId().equals(auth.getOAuth2Request().getClientId())) { - - clientService.deleteClient(client); - - m.addAttribute(HttpCodeView.CODE, HttpStatus.NO_CONTENT); // http 204 - - return HttpCodeView.VIEWNAME; - } else { - // client mismatch - logger.error("readClientConfiguration failed, client ID mismatch: " - + clientId + " and " + auth.getOAuth2Request().getClientId() + " do not match."); - m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403 - - return HttpCodeView.VIEWNAME; - } - } - - private ClientDetailsEntity validateAuth(ClientDetailsEntity newClient) throws ValidationException { - if (newClient.getTokenEndpointAuthMethod() == null) { - newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); - } - - if (newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_BASIC || - newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_JWT || - newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_POST) { - - if (Strings.isNullOrEmpty(newClient.getClientSecret())) { - // no secret yet, we need to generate a secret - newClient = clientService.generateClientSecret(newClient); - } - } else if (newClient.getTokenEndpointAuthMethod() == AuthMethod.PRIVATE_KEY) { - if (Strings.isNullOrEmpty(newClient.getJwksUri()) && newClient.getJwks() == null) { - 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); - } else { - throw new ValidationException("invalid_client_metadata", "Unknown authentication method", HttpStatus.BAD_REQUEST); - } - 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); - if(token.getJwt().getJWTClaimsSet().getIssueTime().before(validToDate)) { - logger.info("Rotating the registration access token for " + client.getClientId()); - tokenService.revokeAccessToken(token); - OAuth2AccessTokenEntity newToken = connectTokenService.createResourceAccessToken(client); - tokenService.saveAccessToken(newToken); - return newToken; - } else { - // it's not expired, keep going - return token; - } - } catch (ParseException e) { - logger.error("Couldn't parse a known-valid token?", e); - return token; - } - } else { - // tokens don't expire, just return it - return token; - } - } + /** + * + */ + public static final String URL = "resource"; + + @Autowired + private ClientDetailsEntityService clientService; + + @Autowired + private OAuth2TokenEntityService tokenService; + + @Autowired + private SystemScopeService scopeService; + + @Autowired + private ConfigurationPropertiesBean config; + + @Autowired + private OIDCTokenService connectTokenService; + + /** + * Logger for this class + */ + private static final Logger logger = + LoggerFactory.getLogger(ProtectedResourceRegistrationEndpoint.class); + + /** + * Create a new Client, issue a client ID, and create a registration access token. + * + * @param jsonString + * @param m + * @param p + * @return + */ + @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE) + public String registerNewProtectedResource(@RequestBody String jsonString, Model m) { + + ClientDetailsEntity newClient = null; + try { + newClient = ClientDetailsEntityJsonProcessor.parse(jsonString); + } catch (JsonSyntaxException e) { + // bad parse + // didn't parse, this is a bad request + logger.error("registerNewProtectedResource failed; submitted JSON is malformed"); + m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 + return HttpCodeView.VIEWNAME; + } + + if (newClient != null) { + // it parsed! + + // + // Now do some post-processing consistency checks on it + // + + // clear out any spurious id/secret (clients don't get to pick) + newClient.setClientId(null); + newClient.setClientSecret(null); + + // do validation on the fields + try { + newClient = validateScopes(newClient); + newClient = validateAuth(newClient); + } catch (ValidationException ve) { + // validation failed, return an error + m.addAttribute(JsonErrorView.ERROR, ve.getError()); + m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription()); + m.addAttribute(HttpCodeView.CODE, ve.getStatus()); + return JsonErrorView.VIEWNAME; + } + + + // no grant types are allowed + newClient.setGrantTypes(new HashSet()); + newClient.setResponseTypes(new HashSet()); + newClient.setRedirectUris(new HashSet()); + + // don't issue tokens to this client + newClient.setAccessTokenValiditySeconds(0); + newClient.setIdTokenValiditySeconds(0); + newClient.setRefreshTokenValiditySeconds(0); + + // clear out unused fields + newClient.setDefaultACRvalues(new HashSet()); + newClient.setDefaultMaxAge(null); + newClient.setIdTokenEncryptedResponseAlg(null); + newClient.setIdTokenEncryptedResponseEnc(null); + newClient.setIdTokenSignedResponseAlg(null); + newClient.setInitiateLoginUri(null); + newClient.setPostLogoutRedirectUris(null); + newClient.setRequestObjectSigningAlg(null); + newClient.setRequireAuthTime(null); + newClient.setReuseRefreshToken(false); + newClient.setSectorIdentifierUri(null); + newClient.setSubjectType(null); + newClient.setUserInfoEncryptedResponseAlg(null); + newClient.setUserInfoEncryptedResponseEnc(null); + newClient.setUserInfoSignedResponseAlg(null); + + // this client has been dynamically registered (obviously) + newClient.setDynamicallyRegistered(true); + + // this client has access to the introspection endpoint + newClient.setAllowIntrospection(true); + + // now save it + try { + ClientDetailsEntity savedClient = clientService.saveNewClient(newClient); + + // generate the registration access token + OAuth2AccessTokenEntity token = connectTokenService.createResourceAccessToken(savedClient); + tokenService.saveAccessToken(token); + + // send it all out to the view + + RegisteredClient registered = + new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8")); + m.addAttribute("client", registered); + m.addAttribute(HttpCodeView.CODE, HttpStatus.CREATED); // http 201 + + return ClientInformationResponseView.VIEWNAME; + } catch (IllegalArgumentException e) { + logger.error("Couldn't save client", e); + + m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata"); + m.addAttribute(JsonErrorView.ERROR_MESSAGE, + "Unable to save client due to invalid or inconsistent metadata."); + m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 + + return JsonErrorView.VIEWNAME; + } + } else { + // didn't parse, this is a bad request + logger.error("registerNewClient failed; submitted JSON is malformed"); + m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 + + return HttpCodeView.VIEWNAME; + } + + } + + private ClientDetailsEntity validateScopes(ClientDetailsEntity newClient) + throws ValidationException { + // scopes that the client is asking for + Set requestedScopes = scopeService.fromStrings(newClient.getScope()); + + // the scopes that the client can have must be a subset of the dynamically allowed scopes + Set allowedScopes = + scopeService.removeRestrictedAndReservedScopes(requestedScopes); + + // if the client didn't ask for any, give them the defaults + if (allowedScopes == null || allowedScopes.isEmpty()) { + allowedScopes = scopeService.getDefaults(); + } + + newClient.setScope(scopeService.toStrings(allowedScopes)); + + return newClient; + } + + /** + * Get the meta information for a client. + * + * @param clientId + * @param m + * @param auth + * @return + */ + @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')") + @RequestMapping(value = "/{id}", method = RequestMethod.GET, + produces = MediaType.APPLICATION_JSON_VALUE) + public String readResourceConfiguration(@PathVariable("id") String clientId, Model m, + OAuth2Authentication auth) { + + ClientDetailsEntity client = clientService.loadClientByClientId(clientId); + + if (client != null && client.getClientId().equals(auth.getOAuth2Request().getClientId())) { + + // possibly update the token + OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, client); + + RegisteredClient registered = + new RegisteredClient(client, token.getValue(), config.getIssuer() + "resource/" + + UriUtils.encodePathSegment(client.getClientId(), "UTF-8")); + + // send it all out to the view + m.addAttribute("client", registered); + m.addAttribute(HttpCodeView.CODE, HttpStatus.OK); // http 200 + + return ClientInformationResponseView.VIEWNAME; + + } else { + // client mismatch + logger.error("readResourceConfiguration failed, client ID mismatch: " + clientId + " and " + + auth.getOAuth2Request().getClientId() + " do not match."); + m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403 + + return HttpCodeView.VIEWNAME; + } + } + + /** + * Update the metainformation for a given client. + * + * @param clientId + * @param jsonString + * @param m + * @param auth + * @return + */ + @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')") + @RequestMapping(value = "/{id}", method = RequestMethod.PUT, + produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) + public String updateProtectedResource(@PathVariable("id") String clientId, + @RequestBody String jsonString, Model m, OAuth2Authentication auth) { + + + ClientDetailsEntity newClient = null; + try { + newClient = ClientDetailsEntityJsonProcessor.parse(jsonString); + } catch (JsonSyntaxException e) { + // bad parse + // didn't parse, this is a bad request + logger.error("updateProtectedResource failed; submitted JSON is malformed"); + m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 + return HttpCodeView.VIEWNAME; + } + + ClientDetailsEntity oldClient = clientService.loadClientByClientId(clientId); + + if (newClient != null && oldClient != null // we have an existing client and the new one parsed + && oldClient.getClientId().equals(auth.getOAuth2Request().getClientId()) // the client + // passed in the + // URI matches the + // one in the auth + && oldClient.getClientId().equals(newClient.getClientId()) // the client passed in the body + // matches the one in the URI + ) { + + // a client can't ask to update its own client secret to any particular value + newClient.setClientSecret(oldClient.getClientSecret()); + + newClient.setCreatedAt(oldClient.getCreatedAt()); + + // no grant types are allowed + newClient.setGrantTypes(new HashSet()); + newClient.setResponseTypes(new HashSet()); + newClient.setRedirectUris(new HashSet()); + + // don't issue tokens to this client + newClient.setAccessTokenValiditySeconds(0); + newClient.setIdTokenValiditySeconds(0); + newClient.setRefreshTokenValiditySeconds(0); + + // clear out unused fields + newClient.setDefaultACRvalues(new HashSet()); + newClient.setDefaultMaxAge(null); + newClient.setIdTokenEncryptedResponseAlg(null); + newClient.setIdTokenEncryptedResponseEnc(null); + newClient.setIdTokenSignedResponseAlg(null); + newClient.setInitiateLoginUri(null); + newClient.setPostLogoutRedirectUris(null); + newClient.setRequestObjectSigningAlg(null); + newClient.setRequireAuthTime(null); + newClient.setReuseRefreshToken(false); + newClient.setSectorIdentifierUri(null); + newClient.setSubjectType(null); + newClient.setUserInfoEncryptedResponseAlg(null); + newClient.setUserInfoEncryptedResponseEnc(null); + newClient.setUserInfoSignedResponseAlg(null); + + // this client has been dynamically registered (obviously) + newClient.setDynamicallyRegistered(true); + + // this client has access to the introspection endpoint + newClient.setAllowIntrospection(true); + + // do validation on the fields + try { + newClient = validateScopes(newClient); + newClient = validateAuth(newClient); + } catch (ValidationException ve) { + // validation failed, return an error + m.addAttribute(JsonErrorView.ERROR, ve.getError()); + m.addAttribute(JsonErrorView.ERROR_MESSAGE, ve.getErrorDescription()); + m.addAttribute(HttpCodeView.CODE, ve.getStatus()); + return JsonErrorView.VIEWNAME; + } + + + try { + // save the client + ClientDetailsEntity savedClient = clientService.updateClient(oldClient, newClient); + + // possibly update the token + OAuth2AccessTokenEntity token = fetchValidRegistrationToken(auth, savedClient); + + RegisteredClient registered = + new RegisteredClient(savedClient, token.getValue(), config.getIssuer() + "resource/" + + UriUtils.encodePathSegment(savedClient.getClientId(), "UTF-8")); + + // send it all out to the view + m.addAttribute("client", registered); + m.addAttribute(HttpCodeView.CODE, HttpStatus.OK); // http 200 + + return ClientInformationResponseView.VIEWNAME; + } catch (IllegalArgumentException e) { + logger.error("Couldn't save client", e); + + m.addAttribute(JsonErrorView.ERROR, "invalid_client_metadata"); + m.addAttribute(JsonErrorView.ERROR_MESSAGE, + "Unable to save client due to invalid or inconsistent metadata."); + m.addAttribute(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); // http 400 + + return JsonErrorView.VIEWNAME; + } + } else { + // client mismatch + logger.error("updateProtectedResource" + " failed, client ID mismatch: " + clientId + " and " + + auth.getOAuth2Request().getClientId() + " do not match."); + m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403 + + return HttpCodeView.VIEWNAME; + } + } + + /** + * Delete the indicated client from the system. + * + * @param clientId + * @param m + * @param auth + * @return + */ + @PreAuthorize("hasRole('ROLE_CLIENT') and #oauth2.hasScope('" + + SystemScopeService.RESOURCE_TOKEN_SCOPE + "')") + @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, + produces = MediaType.APPLICATION_JSON_VALUE) + public String deleteResource(@PathVariable("id") String clientId, Model m, + OAuth2Authentication auth) { + + ClientDetailsEntity client = clientService.loadClientByClientId(clientId); + + if (client != null && client.getClientId().equals(auth.getOAuth2Request().getClientId())) { + + clientService.deleteClient(client); + + m.addAttribute(HttpCodeView.CODE, HttpStatus.NO_CONTENT); // http 204 + + return HttpCodeView.VIEWNAME; + } else { + // client mismatch + logger.error("readClientConfiguration failed, client ID mismatch: " + clientId + " and " + + auth.getOAuth2Request().getClientId() + " do not match."); + m.addAttribute(HttpCodeView.CODE, HttpStatus.FORBIDDEN); // http 403 + + return HttpCodeView.VIEWNAME; + } + } + + private ClientDetailsEntity validateAuth(ClientDetailsEntity newClient) + throws ValidationException { + if (newClient.getTokenEndpointAuthMethod() == null) { + newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); + } + + if (newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_BASIC + || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_JWT + || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_POST) { + + if (Strings.isNullOrEmpty(newClient.getClientSecret())) { + // no secret yet, we need to generate a secret + newClient = clientService.generateClientSecret(newClient); + } + } else if (newClient.getTokenEndpointAuthMethod() == AuthMethod.PRIVATE_KEY) { + if (Strings.isNullOrEmpty(newClient.getJwksUri()) && newClient.getJwks() == null) { + 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); + } else { + throw new ValidationException("invalid_client_metadata", "Unknown authentication method", + HttpStatus.BAD_REQUEST); + } + 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); + if (token.getJwt().getJWTClaimsSet().getIssueTime().before(validToDate)) { + logger.info("Rotating the registration access token for " + client.getClientId()); + tokenService.revokeAccessToken(token); + OAuth2AccessTokenEntity newToken = connectTokenService.createResourceAccessToken(client); + tokenService.saveAccessToken(newToken); + return newToken; + } else { + // it's not expired, keep going + return token; + } + } catch (ParseException e) { + logger.error("Couldn't parse a known-valid token?", e); + return token; + } + } else { + // tokens don't expire, just return it + return token; + } + } } diff --git a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java index 1d00a5a3d8..143109bb3a 100644 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestBlacklistAwareRedirectResolver.java @@ -18,7 +18,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.anyString; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import org.junit.Before; @@ -28,7 +28,7 @@ import org.mitre.openid.connect.service.BlacklistedSiteService; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.oauth2.common.exceptions.InvalidRequestException; import org.springframework.security.oauth2.provider.ClientDetails; 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 423cab6da0..59dc7ec0c4 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,7 +16,12 @@ package org.mitre.oauth2.service.impl; 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; @@ -38,15 +43,6 @@ import org.springframework.security.oauth2.provider.OAuth2Request; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; - -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; -import static org.mockito.Mockito.mock; - -import static org.junit.Assert.assertThat; public class TestDefaultIntrospectionResultAssembler { @@ -58,7 +54,7 @@ public class TestDefaultIntrospectionResultAssembler { public void shouldAssembleExpectedResultForAccessToken() throws ParseException { // given - OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), null, "Bearer", + OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer", oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); UserInfo userInfo = userInfo("sub"); @@ -83,50 +79,11 @@ public void shouldAssembleExpectedResultForAccessToken() throws ParseException { assertThat(result, is(equalTo(expected))); } - @Test - public void shouldAssembleExpectedResultForAccessToken_withPermissions() throws ParseException { - - // given - OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), - permissions(permission(1L, "foo", "bar")), - "Bearer", oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); - - UserInfo userInfo = userInfo("sub"); - - Set authScopes = scopes("foo", "bar", "baz"); - - // when - Map result = assembler.assembleFrom(accessToken, userInfo, authScopes); - - - // then - Map expected = new ImmutableMap.Builder() - .put("sub", "sub") - .put("exp", 123L) - .put("expires_at", dateFormat.valueToString(new Date(123 * 1000L))) - .put("permissions", new ImmutableSet.Builder<>() - .add(new ImmutableMap.Builder() - .put("resource_set_id", "1") // note that the resource ID comes out as a string - .put("scopes", new ImmutableSet.Builder<>() - .add("bar") - .add("foo") - .build()) - .build()) - .build()) - // note that scopes are not included if permissions are included - .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 { // given - OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), null, "Bearer", + OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer", oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); Set authScopes = scopes("foo", "bar", "baz"); @@ -153,7 +110,7 @@ public void shouldAssembleExpectedResultForAccessTokenWithoutUserInfo() throws P public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() { // given - OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), null, "Bearer", + OAuth2AccessTokenEntity accessToken = accessToken(null, scopes("foo", "bar"), "Bearer", oauth2AuthenticationWithUser(oauth2Request("clientId"), "name")); UserInfo userInfo = userInfo("sub"); @@ -179,7 +136,7 @@ public void shouldAssembleExpectedResultForAccessTokenWithoutExpiry() { @Test public void shouldAssembleExpectedResultForAccessTokenWithoutUserAuthentication() throws ParseException { // given - OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), null, "Bearer", + OAuth2AccessTokenEntity accessToken = accessToken(new Date(123 * 1000L), scopes("foo", "bar"), "Bearer", oauth2Authentication(oauth2Request("clientId"), null)); Set authScopes = scopes("foo", "bar", "baz"); @@ -311,11 +268,10 @@ private UserInfo userInfo(String sub) { return userInfo; } - private OAuth2AccessTokenEntity accessToken(Date exp, Set scopes, Set permissions, String tokenType, OAuth2Authentication authentication) { + 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.getPermissions()).willReturn(permissions); given(accessToken.getTokenType()).willReturn(tokenType); given(accessToken.getAuthenticationHolder().getAuthentication()).willReturn(authentication); return accessToken; 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 6ec31ca806..471ab7864d 100644 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ClientDetailsEntityService.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultOAuth2ClientDetailsEntityService.java @@ -17,6 +17,19 @@ *******************************************************************************/ package org.mitre.oauth2.service.impl; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; + import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; @@ -40,24 +53,15 @@ import org.mitre.uma.service.ResourceSetService; import org.mockito.AdditionalAnswers; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.security.oauth2.common.exceptions.InvalidClientException; import com.google.common.collect.Sets; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; -import static org.hamcrest.CoreMatchers.nullValue; - -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; - /** * @author wkim * @@ -65,568 +69,576 @@ @RunWith(MockitoJUnitRunner.class) public class TestDefaultOAuth2ClientDetailsEntityService { - @Mock - private OAuth2ClientRepository clientRepository; - - @Mock - private OAuth2TokenRepository tokenRepository; - - @Mock - private ApprovedSiteService approvedSiteService; - - @Mock - private WhitelistedSiteService whitelistedSiteService; - - @Mock - private BlacklistedSiteService blacklistedSiteService; - - @Mock - private SystemScopeService scopeService; - - @Mock - private ResourceSetService resourceSetService; - - @Mock - private StatsService statsService; - - @Mock - private ConfigurationPropertiesBean config; - - @InjectMocks - private DefaultOAuth2ClientDetailsEntityService service; - - @Before - public void prepare() { - Mockito.reset(clientRepository, tokenRepository, approvedSiteService, whitelistedSiteService, blacklistedSiteService, scopeService, statsService); - - 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(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]; - } - }); + @Mock + private OAuth2ClientRepository clientRepository; + + @Mock + private OAuth2TokenRepository tokenRepository; + + @Mock + private ApprovedSiteService approvedSiteService; + + @Mock + private WhitelistedSiteService whitelistedSiteService; + + @Mock + private BlacklistedSiteService blacklistedSiteService; + + @Mock + private SystemScopeService scopeService; + + @Mock + private ResourceSetService resourceSetService; + + @Mock + private StatsService statsService; + + @Mock + private ConfigurationPropertiesBean config; + + @InjectMocks + private DefaultOAuth2ClientDetailsEntityService service; + + @Before + public void prepare() { + Mockito.reset(clientRepository, tokenRepository, approvedSiteService, whitelistedSiteService, + blacklistedSiteService, scopeService, statsService); + + lenient().when(clientRepository.saveClient(any(ClientDetailsEntity.class))) + .thenAnswer(new Answer() { + @Override + public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return (ClientDetailsEntity) args[0]; + } + }); + + lenient().when(clientRepository.updateClient(anyLong(), any(ClientDetailsEntity.class))) + .thenAnswer(new Answer() { + @Override + public ClientDetailsEntity answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + return (ClientDetailsEntity) args[1]; + } + }); + + lenient().when(scopeService.fromStrings(anySet())).thenAnswer(new Answer>() { + @Override + public Set answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + Set input = (Set) args[0]; + Set output = new HashSet<>(); + for (String scope : input) { + output.add(new SystemScope(scope)); + } + return output; + } + }); - Mockito.when(scopeService.fromStrings(Matchers.anySet())).thenAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Set input = (Set) args[0]; - Set output = new HashSet<>(); - for (String scope : input) { - output.add(new SystemScope(scope)); - } - return output; - } - }); + lenient().when(scopeService.toStrings(anySet())).thenAnswer(new Answer>() { + @Override + public Set answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + Set input = (Set) args[0]; + Set output = new HashSet<>(); + for (SystemScope scope : input) { + output.add(scope.getValue()); + } + return output; + } + }); + + // we're not testing reserved scopes here, just pass through when it's called + lenient().when(scopeService.removeReservedScopes(anySet())) + .then(AdditionalAnswers.returnsFirstArg()); + + lenient().when(config.isHeartMode()).thenReturn(false); + + } + + /** + * Failure case of existing client id. + */ + @Test(expected = IllegalArgumentException.class) + public void saveNewClient_badId() { + + // Set up a mock client. + ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); + Mockito.when(client.getId()).thenReturn(12345L); // any non-null ID will work + + service.saveNewClient(client); + } + + /** + * Failure case of blacklisted client uri. + */ + @Test(expected = IllegalArgumentException.class) + public void saveNewClient_blacklisted() { + + ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); + Mockito.when(client.getId()).thenReturn(null); + + String badUri = "badplace.xxx"; + + Mockito.when(blacklistedSiteService.isBlacklisted(badUri)).thenReturn(true); + Mockito.when(client.getRegisteredRedirectUri()).thenReturn(Sets.newHashSet(badUri)); + + service.saveNewClient(client); + } + + @Test + public void saveNewClient_idWasAssigned() { + + // Set up a mock client. + ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); + Mockito.when(client.getId()).thenReturn(null); + + service.saveNewClient(client); + + Mockito.verify(client).setClientId(anyString()); + } + + /** + * Makes sure client has offline access granted scope if allowed refresh tokens. + */ + @Test + public void saveNewClient_yesOfflineAccess() { + + ClientDetailsEntity client = new ClientDetailsEntity(); + + Set grantTypes = new HashSet<>(); + grantTypes.add("refresh_token"); + client.setGrantTypes(grantTypes); + + client = service.saveNewClient(client); + + assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(true))); + } + + /** + * Makes sure client does not have offline access if not allowed to have refresh tokens. + */ + @Test + public void saveNewClient_noOfflineAccess() { + + ClientDetailsEntity client = new ClientDetailsEntity(); + + client = service.saveNewClient(client); + + Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(anySet()); + + assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); + } + + @Test + public void loadClientByClientId_badId() { - Mockito.when(scopeService.toStrings(Matchers.anySet())).thenAnswer(new Answer>() { - @Override - public Set answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Set input = (Set) args[0]; - Set output = new HashSet<>(); - for (SystemScope scope : input) { - output.add(scope.getValue()); - } - return output; - } - }); + // null id + try { + service.loadClientByClientId(null); + fail("Null client id. Expected an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + assertThat(e, is(notNullValue())); + } - // we're not testing reserved scopes here, just pass through when it's called - Mockito.when(scopeService.removeReservedScopes(Matchers.anySet())).then(AdditionalAnswers.returnsFirstArg()); - - Mockito.when(config.isHeartMode()).thenReturn(false); - - } - - /** - * Failure case of existing client id. - */ - @Test(expected = IllegalArgumentException.class) - public void saveNewClient_badId() { - - // Set up a mock client. - ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); - Mockito.when(client.getId()).thenReturn(12345L); // any non-null ID will work - - service.saveNewClient(client); - } - - /** - * Failure case of blacklisted client uri. - */ - @Test(expected = IllegalArgumentException.class) - public void saveNewClient_blacklisted() { - - ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); - Mockito.when(client.getId()).thenReturn(null); - - String badUri = "badplace.xxx"; - - Mockito.when(blacklistedSiteService.isBlacklisted(badUri)).thenReturn(true); - Mockito.when(client.getRegisteredRedirectUri()).thenReturn(Sets.newHashSet(badUri)); - - service.saveNewClient(client); - } - - @Test - public void saveNewClient_idWasAssigned() { - - // Set up a mock client. - ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); - Mockito.when(client.getId()).thenReturn(null); - - service.saveNewClient(client); - - Mockito.verify(client).setClientId(Matchers.anyString()); - } - - /** - * Makes sure client has offline access granted scope if allowed refresh tokens. - */ - @Test - public void saveNewClient_yesOfflineAccess() { - - ClientDetailsEntity client = new ClientDetailsEntity(); - - Set grantTypes = new HashSet<>(); - grantTypes.add("refresh_token"); - client.setGrantTypes(grantTypes); - - client = service.saveNewClient(client); - - assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(true))); - } - - /** - * Makes sure client does not have offline access if not allowed to have refresh tokens. - */ - @Test - public void saveNewClient_noOfflineAccess() { - - ClientDetailsEntity client = new ClientDetailsEntity(); - - client = service.saveNewClient(client); - - Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); - - assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); - } - - @Test - public void loadClientByClientId_badId() { + // empty id + try { + service.loadClientByClientId(""); + fail("Empty client id. Expected an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + assertThat(e, is(notNullValue())); + } - // null id - try { - service.loadClientByClientId(null); - fail("Null client id. Expected an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - assertThat(e, is(notNullValue())); - } + // id not found + String clientId = "b00g3r"; + Mockito.when(clientRepository.getClientByClientId(clientId)).thenReturn(null); + try { + service.loadClientByClientId(clientId); + fail("Client id not found. Expected an InvalidClientException."); + } catch (InvalidClientException e) { + assertThat(e, is(notNullValue())); + } - // empty id - try { - service.loadClientByClientId(""); - fail("Empty client id. Expected an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - assertThat(e, is(notNullValue())); - } + } - // id not found - String clientId = "b00g3r"; - Mockito.when(clientRepository.getClientByClientId(clientId)).thenReturn(null); - try { - service.loadClientByClientId(clientId); - fail("Client id not found. Expected an InvalidClientException."); - } catch (InvalidClientException e) { - assertThat(e, is(notNullValue())); - } + @Test(expected = InvalidClientException.class) + public void deleteClient_badId() { - } + Long id = 12345L; + ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); + Mockito.when(client.getId()).thenReturn(id); + Mockito.when(clientRepository.getById(id)).thenReturn(null); - @Test(expected = InvalidClientException.class) - public void deleteClient_badId() { + service.deleteClient(client); + } - Long id = 12345L; - ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); - Mockito.when(client.getId()).thenReturn(id); - Mockito.when(clientRepository.getById(id)).thenReturn(null); + @Test + public void deleteClient() { - service.deleteClient(client); - } + Long id = 12345L; + String clientId = "b00g3r"; - @Test - public void deleteClient() { + ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); + Mockito.when(client.getId()).thenReturn(id); + Mockito.when(client.getClientId()).thenReturn(clientId); - Long id = 12345L; - String clientId = "b00g3r"; + Mockito.when(clientRepository.getById(id)).thenReturn(client); - ClientDetailsEntity client = Mockito.mock(ClientDetailsEntity.class); - Mockito.when(client.getId()).thenReturn(id); - Mockito.when(client.getClientId()).thenReturn(clientId); + WhitelistedSite site = Mockito.mock(WhitelistedSite.class); + Mockito.when(whitelistedSiteService.getByClientId(clientId)).thenReturn(site); - Mockito.when(clientRepository.getById(id)).thenReturn(client); + Mockito.when(resourceSetService.getAllForClient(client)).thenReturn(new HashSet()); - WhitelistedSite site = Mockito.mock(WhitelistedSite.class); - Mockito.when(whitelistedSiteService.getByClientId(clientId)).thenReturn(site); + service.deleteClient(client); - Mockito.when(resourceSetService.getAllForClient(client)).thenReturn(new HashSet()); + Mockito.verify(tokenRepository).clearTokensForClient(client); + Mockito.verify(approvedSiteService).clearApprovedSitesForClient(client); + Mockito.verify(whitelistedSiteService).remove(site); + Mockito.verify(clientRepository).deleteClient(client); + } - service.deleteClient(client); + @Test + public void updateClient_nullClients() { - Mockito.verify(tokenRepository).clearTokensForClient(client); - Mockito.verify(approvedSiteService).clearApprovedSitesForClient(client); - Mockito.verify(whitelistedSiteService).remove(site); - Mockito.verify(clientRepository).deleteClient(client); - } + ClientDetailsEntity oldClient = Mockito.mock(ClientDetailsEntity.class); + ClientDetailsEntity newClient = Mockito.mock(ClientDetailsEntity.class); - @Test - public void updateClient_nullClients() { + try { + service.updateClient(oldClient, null); + fail("New client is null. Expected an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + assertThat(e, is(notNullValue())); + } - ClientDetailsEntity oldClient = Mockito.mock(ClientDetailsEntity.class); - ClientDetailsEntity newClient = Mockito.mock(ClientDetailsEntity.class); + try { + service.updateClient(null, newClient); + fail("Old client is null. Expected an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + assertThat(e, is(notNullValue())); + } - try { - service.updateClient(oldClient, null); - fail("New client is null. Expected an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - assertThat(e, is(notNullValue())); - } + try { + service.updateClient(null, null); + fail("Both clients are null. Expected an IllegalArgumentException."); + } catch (IllegalArgumentException e) { + assertThat(e, is(notNullValue())); + } + } - try { - service.updateClient(null, newClient); - fail("Old client is null. Expected an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - assertThat(e, is(notNullValue())); - } + @Test(expected = IllegalArgumentException.class) + public void updateClient_blacklistedUri() { - try { - service.updateClient(null, null); - fail("Both clients are null. Expected an IllegalArgumentException."); - } catch (IllegalArgumentException e) { - assertThat(e, is(notNullValue())); - } - } + ClientDetailsEntity oldClient = Mockito.mock(ClientDetailsEntity.class); + ClientDetailsEntity newClient = Mockito.mock(ClientDetailsEntity.class); - @Test(expected = IllegalArgumentException.class) - public void updateClient_blacklistedUri() { + String badSite = "badsite.xxx"; - ClientDetailsEntity oldClient = Mockito.mock(ClientDetailsEntity.class); - ClientDetailsEntity newClient = Mockito.mock(ClientDetailsEntity.class); + Mockito.when(newClient.getRegisteredRedirectUri()).thenReturn(Sets.newHashSet(badSite)); + Mockito.when(blacklistedSiteService.isBlacklisted(badSite)).thenReturn(true); - String badSite = "badsite.xxx"; + service.updateClient(oldClient, newClient); + } - Mockito.when(newClient.getRegisteredRedirectUri()).thenReturn(Sets.newHashSet(badSite)); - Mockito.when(blacklistedSiteService.isBlacklisted(badSite)).thenReturn(true); + @Test + public void updateClient_yesOfflineAccess() { - service.updateClient(oldClient, newClient); - } + ClientDetailsEntity oldClient = new ClientDetailsEntity(); + ClientDetailsEntity client = new ClientDetailsEntity(); - @Test - public void updateClient_yesOfflineAccess() { + Set grantTypes = new HashSet<>(); + grantTypes.add("refresh_token"); + client.setGrantTypes(grantTypes); - ClientDetailsEntity oldClient = new ClientDetailsEntity(); - ClientDetailsEntity client = new ClientDetailsEntity(); + Mockito.when(clientRepository.updateClient(any(), eq(client))).thenReturn(client); - Set grantTypes = new HashSet<>(); - grantTypes.add("refresh_token"); - client.setGrantTypes(grantTypes); + client = service.updateClient(oldClient, client); - client = service.updateClient(oldClient, client); + Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(anySet()); - Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); + assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(true))); + } - assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(true))); - } + @Test + public void updateClient_noOfflineAccess() { - @Test - public void updateClient_noOfflineAccess() { + ClientDetailsEntity oldClient = new ClientDetailsEntity(); - ClientDetailsEntity oldClient = new ClientDetailsEntity(); + oldClient.getScope().add(SystemScopeService.OFFLINE_ACCESS); - oldClient.getScope().add(SystemScopeService.OFFLINE_ACCESS); + ClientDetailsEntity client = new ClientDetailsEntity(); - ClientDetailsEntity client = new ClientDetailsEntity(); + Mockito.when(clientRepository.updateClient(any(), eq(client))).thenReturn(client); - client = service.updateClient(oldClient, client); + client = service.updateClient(oldClient, client); - Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(Matchers.anySet()); + Mockito.verify(scopeService, Mockito.atLeastOnce()).removeReservedScopes(anySet()); - assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); - } + assertThat(client.getScope().contains(SystemScopeService.OFFLINE_ACCESS), is(equalTo(false))); + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_authcode_invalidGrants() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_authcode_invalidGrants() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - grantTypes.add("implicit"); - grantTypes.add("client_credentials"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + grantTypes.add("implicit"); + grantTypes.add("client_credentials"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_implicit_invalidGrants() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_implicit_invalidGrants() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("implicit"); - grantTypes.add("authorization_code"); - grantTypes.add("client_credentials"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("implicit"); + grantTypes.add("authorization_code"); + grantTypes.add("client_credentials"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.NONE); + client.setTokenEndpointAuthMethod(AuthMethod.NONE); - client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_clientcreds_invalidGrants() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_clientcreds_invalidGrants() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("client_credentials"); - grantTypes.add("authorization_code"); - grantTypes.add("implicit"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("client_credentials"); + grantTypes.add("authorization_code"); + grantTypes.add("implicit"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_authcode_authMethod() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_authcode_authMethod() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.SECRET_POST); + client.setTokenEndpointAuthMethod(AuthMethod.SECRET_POST); - client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_implicit_authMethod() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_implicit_authMethod() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("implicit"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("implicit"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_clientcreds_authMethod() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_clientcreds_authMethod() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("client_credentials"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("client_credentials"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); + client.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC); - client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_authcode_redirectUris() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_authcode_redirectUris() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_implicit_redirectUris() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_implicit_redirectUris() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("implicit"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("implicit"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.NONE); + client.setTokenEndpointAuthMethod(AuthMethod.NONE); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_clientcreds_redirectUris() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_clientcreds_redirectUris() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("client_credentials"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("client_credentials"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_clientSecret() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_clientSecret() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); - client.setClientSecret("secret!"); + client.setClientSecret("secret!"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_noJwks() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_noJwks() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); - client.setJwks(null); - client.setJwksUri(null); + client.setJwks(null); + client.setJwksUri(null); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test - public void heartMode_validAuthcodeClient() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test + public void heartMode_validAuthcodeClient() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - grantTypes.add("refresh_token"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + grantTypes.add("refresh_token"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("https://foo.bar/")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - assertThat(client.getClientId(), is(notNullValue(String.class))); - assertThat(client.getClientSecret(), is(nullValue())); - } + assertThat(client.getClientId(), is(notNullValue(String.class))); + assertThat(client.getClientSecret(), is(nullValue())); + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_nonLocalHttpRedirect() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_nonLocalHttpRedirect() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - grantTypes.add("refresh_token"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + grantTypes.add("refresh_token"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); + client.setRedirectUris(Sets.newHashSet("http://foo.bar/")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } - @Test(expected = IllegalArgumentException.class) - public void heartMode_multipleRedirectClass() { - Mockito.when(config.isHeartMode()).thenReturn(true); + @Test(expected = IllegalArgumentException.class) + public void heartMode_multipleRedirectClass() { + Mockito.when(config.isHeartMode()).thenReturn(true); - ClientDetailsEntity client = new ClientDetailsEntity(); - Set grantTypes = new LinkedHashSet<>(); - grantTypes.add("authorization_code"); - grantTypes.add("refresh_token"); - client.setGrantTypes(grantTypes); + ClientDetailsEntity client = new ClientDetailsEntity(); + Set grantTypes = new LinkedHashSet<>(); + grantTypes.add("authorization_code"); + grantTypes.add("refresh_token"); + client.setGrantTypes(grantTypes); - client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); + client.setTokenEndpointAuthMethod(AuthMethod.PRIVATE_KEY); - client.setRedirectUris(Sets.newHashSet("http://localhost/", "https://foo.bar", "foo://bar")); + client.setRedirectUris(Sets.newHashSet("http://localhost/", "https://foo.bar", "foo://bar")); - client.setJwksUri("https://foo.bar/jwks"); + client.setJwksUri("https://foo.bar/jwks"); - service.saveNewClient(client); + service.saveNewClient(client); - } + } } 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 b3702668ea..0e9f53cbc0 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 @@ -28,9 +28,10 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.AdditionalAnswers.returnsFirstArg; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anySetOf; -import static org.mockito.Matchers.anyString; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anySet; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -58,11 +59,10 @@ import org.mitre.oauth2.service.SystemScopeService; import org.mitre.openid.connect.service.ApprovedSiteService; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException; import org.springframework.security.oauth2.common.exceptions.InvalidClientException; @@ -138,8 +138,10 @@ public void prepare() { scopeService, approvedSiteService, authentication); OAuth2Request clientAuth = - new OAuth2Request(null, clientId, null, true, scope, null, null, null, null); + new OAuth2Request(Map.of(), clientId, Set.of(), true, scope, Set.of(), null, Set.of(), Map.of()); when(authentication.getOAuth2Request()).thenReturn(clientAuth); + when(authentication.getCredentials()).thenReturn(""); + when(authentication.getPrincipal()).thenReturn(clientId); client = Mockito.mock(ClientDetailsEntity.class); when(client.getClientId()).thenReturn(clientId); @@ -150,9 +152,6 @@ public void prepare() { // by default in tests, allow refresh tokens when(client.isAllowRefresh()).thenReturn(true); - // by default, clear access tokens on refresh - when(client.isClearAccessTokensOnRefresh()).thenReturn(true); - badClient = Mockito.mock(ClientDetailsEntity.class); when(badClient.getClientId()).thenReturn(badClientId); when(clientDetailsService.loadClientByClientId(badClientId)).thenReturn(badClient); @@ -175,10 +174,7 @@ public void prepare() { when(storedAuthHolder.getAuthentication()).thenReturn(storedAuthentication); when(storedAuthentication.getOAuth2Request()).thenReturn(storedAuthRequest); - when(authenticationHolderRepository.save(any(AuthenticationHolderEntity.class))) - .thenReturn(storedAuthHolder); - - when(scopeService.fromStrings(anySetOf(String.class))) + when(scopeService.fromStrings(anySet())) .thenAnswer(new Answer>() { @Override @SuppressWarnings("unchecked") @@ -193,7 +189,7 @@ public Set answer(InvocationOnMock invocation) throws Throwable { } }); - when(scopeService.toStrings(anySetOf(SystemScope.class))).thenAnswer(new Answer>() { + when(scopeService.toStrings(anySet())).thenAnswer(new Answer>() { @Override @SuppressWarnings("unchecked") public Set answer(InvocationOnMock invocation) throws Throwable { @@ -207,7 +203,7 @@ public Set answer(InvocationOnMock invocation) throws Throwable { } }); - when(scopeService.scopesMatch(anySetOf(String.class), anySetOf(String.class))) + when(scopeService.scopesMatch(anySet(), anySet())) .thenAnswer(new Answer() { @Override @SuppressWarnings("unchecked") @@ -220,9 +216,7 @@ public Boolean answer(InvocationOnMock invocation) throws Throwable { }); // we're not testing restricted or reserved scopes here, just pass through - when(scopeService.removeReservedScopes(anySetOf(SystemScope.class))).then(returnsFirstArg()); - when(scopeService.removeRestrictedAndReservedScopes(anySetOf(SystemScope.class))) - .then(returnsFirstArg()); + when(scopeService.removeReservedScopes(anySet())).then(returnsFirstArg()); when(tokenEnhancer.enhance(any(OAuth2AccessTokenEntity.class), any(OAuth2Authentication.class))) .thenAnswer(new Answer() { @@ -233,16 +227,6 @@ public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwa } }); - when(tokenRepository.saveAccessToken(any(OAuth2AccessTokenEntity.class))) - .thenAnswer(new Answer() { - @Override - public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - return (OAuth2AccessTokenEntity) args[0]; - } - - }); - when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))) .thenAnswer(new Answer() { @Override @@ -297,12 +281,12 @@ public void createAccessToken_noRefresh() { OAuth2AccessTokenEntity token = service.createAccessToken(authentication); verify(clientDetailsService).loadClientByClientId(anyString()); - verify(authenticationHolderRepository).save(any(AuthenticationHolderEntity.class)); - verify(tokenEnhancer).enhance(any(OAuth2AccessTokenEntity.class), Matchers.eq(authentication)); - verify(tokenRepository).saveAccessToken(any(OAuth2AccessTokenEntity.class)); - verify(scopeService, atLeastOnce()).removeReservedScopes(anySetOf(SystemScope.class)); + verify(tokenEnhancer).enhance(any(OAuth2AccessTokenEntity.class), eq(authentication)); + verify(scopeService, atLeastOnce()).removeReservedScopes(anySet()); - verify(tokenRepository, Mockito.never()).saveRefreshToken(any(OAuth2RefreshTokenEntity.class)); + verify(authenticationHolderRepository, never()).save(any(AuthenticationHolderEntity.class)); + verify(tokenRepository, never()).saveAccessToken(any(OAuth2AccessTokenEntity.class)); + verify(tokenRepository, never()).saveRefreshToken(any(OAuth2RefreshTokenEntity.class)); assertThat(token.getRefreshToken(), is(nullValue())); } @@ -324,7 +308,7 @@ public void createAccessToken_yesRefresh() { // Note: a refactor may be appropriate to only save refresh tokens once to the repository during // creation. verify(tokenRepository, atLeastOnce()).saveRefreshToken(any(OAuth2RefreshTokenEntity.class)); - verify(scopeService, atLeastOnce()).removeReservedScopes(anySetOf(SystemScope.class)); + verify(scopeService, atLeastOnce()).removeReservedScopes(anySet()); assertThat(token.getRefreshToken(), is(notNullValue())); } @@ -356,7 +340,7 @@ public void createAccessToken_expiration() { Date lowerBoundRefreshTokens = new Date(start + (refreshTokenValiditySeconds * 1000L) - DELTA); Date upperBoundRefreshTokens = new Date(end + (refreshTokenValiditySeconds * 1000L) + DELTA); - verify(scopeService, atLeastOnce()).removeReservedScopes(anySetOf(SystemScope.class)); + verify(scopeService, atLeastOnce()).removeReservedScopes(anySet()); assertTrue(token.getExpiration().after(lowerBoundAccessTokens) && token.getExpiration().before(upperBoundAccessTokens)); @@ -373,7 +357,7 @@ public void createAccessToken_checkClient() { when(authentication.getOAuth2Request()).thenReturn(clientAuth); OAuth2AccessTokenEntity token = service.createAccessToken(authentication); - verify(scopeService, atLeastOnce()).removeReservedScopes(anySetOf(SystemScope.class)); + verify(scopeService, atLeastOnce()).removeReservedScopes(anySet()); assertThat(token.getClient().getClientId(), equalTo(clientId)); } @@ -387,29 +371,28 @@ public void createAccessToken_checkScopes() { when(authentication.getOAuth2Request()).thenReturn(clientAuth); OAuth2AccessTokenEntity token = service.createAccessToken(authentication); - verify(scopeService, atLeastOnce()).removeReservedScopes(anySetOf(SystemScope.class)); + verify(scopeService, atLeastOnce()).removeReservedScopes(anySet()); assertThat(token.getScope(), equalTo(scope)); } @Test public void createAccessToken_checkAttachedAuthentication() { - AuthenticationHolderEntity authHolder = mock(AuthenticationHolderEntity.class); - when(authHolder.getAuthentication()).thenReturn(authentication); - - when(authenticationHolderRepository.save(any(AuthenticationHolderEntity.class))) - .thenReturn(authHolder); - Map requestParameters = new HashMap(); - requestParameters.put("grant_type", "authorization_code"); + AuthenticationHolderEntity authHolder = mock(AuthenticationHolderEntity.class); OAuth2Request clientAuth = - new OAuth2Request(requestParameters, clientId, null, true, scope, null, null, null, null); + new OAuth2Request(Map.of("grant_type", "authorization_code"), clientId, Set.of(), true, scope, Set.of(), null, Set.of(), Map.of()); when(authentication.getOAuth2Request()).thenReturn(clientAuth); + OAuth2AccessTokenEntity token = service.createAccessToken(authentication); - assertThat(token.getAuthenticationHolder().getAuthentication(), equalTo(authentication)); - verify(authenticationHolderRepository).save(any(AuthenticationHolderEntity.class)); - verify(scopeService, atLeastOnce()).removeReservedScopes(anySetOf(SystemScope.class)); + verify(authenticationHolderRepository, never()).save(any(AuthenticationHolderEntity.class)); + verify(scopeService, atLeastOnce()).removeReservedScopes(anySet()); + assertThat(token.getAuthenticationHolder().getAuthentication().getAuthorities(), equalTo(authentication.getAuthorities())); + assertThat(token.getAuthenticationHolder().getAuthentication().getCredentials(), equalTo(authentication.getCredentials())); + assertThat(token.getAuthenticationHolder().getAuthentication().getOAuth2Request(), equalTo(authentication.getOAuth2Request())); + assertThat(token.getAuthenticationHolder().getAuthentication().getPrincipal(), equalTo(authentication.getPrincipal())); + assertThat(token.getAuthenticationHolder().getAuthentication().getUserAuthentication(), equalTo(authentication.getUserAuthentication())); } @Test(expected = InvalidTokenException.class) @@ -444,14 +427,10 @@ public void refreshAccessToken_expired() { public void refreshAccessToken_verifyAcessToken() { OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); - verify(tokenRepository).clearAccessTokensForRefreshToken(refreshToken); - assertThat(token.getClient(), equalTo(client)); assertThat(token.getRefreshToken(), equalTo(refreshToken)); assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder)); - verify(tokenRepository).saveAccessToken(token); - } @Test @@ -460,21 +439,19 @@ public void refreshAccessToken_rotateRefreshToken() { OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); - verify(tokenRepository).clearAccessTokensForRefreshToken(refreshToken); + verify(tokenRepository, never()).clearAccessTokensForRefreshToken(refreshToken); assertThat(token.getClient(), equalTo(client)); assertThat(token.getRefreshToken(), not(equalTo(refreshToken))); assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder)); - verify(tokenRepository).saveAccessToken(token); + verify(tokenRepository, never()).saveAccessToken(token); verify(tokenRepository).removeRefreshToken(refreshToken); } @Test public void refreshAccessToken_keepAccessTokens() { - when(client.isClearAccessTokensOnRefresh()).thenReturn(false); - OAuth2AccessTokenEntity token = service.refreshAccessToken(refreshTokenValue, tokenRequest); verify(tokenRepository, never()).clearAccessTokensForRefreshToken(refreshToken); @@ -483,7 +460,7 @@ public void refreshAccessToken_keepAccessTokens() { assertThat(token.getRefreshToken(), equalTo(refreshToken)); assertThat(token.getAuthenticationHolder(), equalTo(storedAuthHolder)); - verify(tokenRepository).saveAccessToken(token); + verify(tokenRepository, never()).saveAccessToken(token); } diff --git a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultSystemScopeService.java b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultSystemScopeService.java index 808d96b581..06d2c5844a 100644 --- a/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultSystemScopeService.java +++ b/openid-connect-server/src/test/java/org/mitre/oauth2/service/impl/TestDefaultSystemScopeService.java @@ -17,6 +17,11 @@ *******************************************************************************/ package org.mitre.oauth2.service.impl; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.junit.Assert.assertThat; + import java.util.Set; import org.junit.Before; @@ -27,16 +32,10 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.google.common.collect.Sets; -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.nullValue; - -import static org.junit.Assert.assertThat; - /** * @author wkim * diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/assertion/TestJWTBearerAuthenticationProvider.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/assertion/TestJWTBearerAuthenticationProvider.java index fde99f499e..f317532f5a 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/assertion/TestJWTBearerAuthenticationProvider.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/assertion/TestJWTBearerAuthenticationProvider.java @@ -5,7 +5,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.startsWith; import static org.junit.Assert.assertThat; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import java.util.Arrays; @@ -24,7 +24,7 @@ import org.mitre.openid.connect.config.ConfigurationPropertiesBean; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/config/TestJsonMessageSource.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/config/TestJsonMessageSource.java index 04d7735d2f..cdeaea11d4 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/config/TestJsonMessageSource.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/config/TestJsonMessageSource.java @@ -1,20 +1,20 @@ package org.mitre.openid.connect.config; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.text.MessageFormat; +import java.util.Locale; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Spy; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; -import java.text.MessageFormat; -import java.util.Locale; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - @RunWith(MockitoJUnitRunner.class) public class TestJsonMessageSource { diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java index 8524145f0b..35f2deb8fc 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultApprovedSiteService.java @@ -17,7 +17,9 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; -import static org.mockito.Matchers.any; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import java.util.HashSet; import java.util.List; @@ -36,15 +38,12 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.annotation.Rollback; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; - @RunWith(MockitoJUnitRunner.class) public class TestDefaultApprovedSiteService { @@ -123,7 +122,6 @@ public void clearApprovedSitesForClient_null() { String otherId = "a different id"; client.setClientId(otherId); service.clearApprovedSitesForClient(client); - Mockito.when(repository.getByClientId(otherId)).thenReturn(new HashSet()); Mockito.verify(repository, never()).remove(any(ApprovedSite.class)); } diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultBlacklistedSiteService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultBlacklistedSiteService.java index 79656cdddc..efa0610adc 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultBlacklistedSiteService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultBlacklistedSiteService.java @@ -17,6 +17,10 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.times; + import java.util.Set; import org.junit.Before; @@ -27,15 +31,10 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.google.common.collect.Sets; -import static org.mockito.Mockito.times; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - /** * @author wkim * diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultOIDCTokenService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultOIDCTokenService.java index 5914ff0e18..d05cac2856 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultOIDCTokenService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultOIDCTokenService.java @@ -27,7 +27,7 @@ import org.mitre.openid.connect.config.ConfigurationPropertiesBean; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.oauth2.provider.OAuth2Request; import com.nimbusds.jose.JWSAlgorithm; diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java index b5c1ae6b32..4492f2ac1d 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultStatsService.java @@ -17,6 +17,9 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assert.assertThat; + import java.util.HashSet; import java.util.Map; @@ -29,14 +32,10 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.google.common.collect.Sets; -import static org.hamcrest.CoreMatchers.is; - -import static org.junit.Assert.assertThat; - /** * @author wkim * @@ -103,11 +102,6 @@ public void prepare() { Mockito.when(approvedSiteService.getAll()).thenReturn(Sets.newHashSet(ap1, ap2, ap3, ap4)); - Mockito.when(client1.getId()).thenReturn(1L); - Mockito.when(client2.getId()).thenReturn(2L); - Mockito.when(client3.getId()).thenReturn(3L); - Mockito.when(client4.getId()).thenReturn(4L); - Mockito.when(approvedSiteService.getByClientId(clientId1)).thenReturn(Sets.newHashSet(ap1, ap2)); Mockito.when(approvedSiteService.getByClientId(clientId2)).thenReturn(Sets.newHashSet(ap3)); Mockito.when(approvedSiteService.getByClientId(clientId3)).thenReturn(Sets.newHashSet(ap4)); diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultUserInfoService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultUserInfoService.java index e5e7070832..5ebecb004d 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultUserInfoService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultUserInfoService.java @@ -20,6 +20,10 @@ */ package org.mitre.openid.connect.service.impl; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.any; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -31,16 +35,12 @@ import org.mitre.openid.connect.repository.UserInfoRepository; import org.mitre.openid.connect.service.PairwiseIdentiferService; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - /** * @author jricher * @@ -189,7 +189,7 @@ public void getByUsernameAndClientId_publicClients() { Mockito.when(userInfoRepository.getByUsername(regularUsername)).thenReturn(userInfoRegular); - Mockito.verify(pairwiseIdentiferService, Mockito.never()).getIdentifier(Matchers.any(UserInfo.class), Matchers.any(ClientDetailsEntity.class)); + Mockito.verify(pairwiseIdentiferService, Mockito.never()).getIdentifier(any(UserInfo.class), any(ClientDetailsEntity.class)); UserInfo user1 = service.getByUsernameAndClientId(regularUsername, publicClientId1); UserInfo user2 = service.getByUsernameAndClientId(regularUsername, publicClientId2); diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultWhitelistedSiteService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultWhitelistedSiteService.java index 40e8d65087..2ff7801efd 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultWhitelistedSiteService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestDefaultWhitelistedSiteService.java @@ -17,6 +17,11 @@ *******************************************************************************/ package org.mitre.openid.connect.service.impl; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.fail; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -25,13 +30,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.notNullValue; - -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import org.mockito.junit.MockitoJUnitRunner; /** * @author wkim 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 b8ed64b211..e1f02d473b 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 @@ -20,10 +20,10 @@ 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -69,7 +69,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.datetime.DateFormatter; @@ -145,10 +145,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse("2014-09-10T22:49:44.090+00:00", Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -160,10 +160,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse("2015-01-07T18:31:50.079+00:00", Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -194,7 +194,7 @@ public void testImportRefreshTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 343L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -206,28 +206,28 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(any())).thenAnswer(new Answer() { Long id = 678L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -263,10 +263,10 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse("2014-09-10T22:49:44.090+00:00", Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -281,13 +281,13 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); + lenient().when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -325,7 +325,7 @@ public void testImportAccessTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveAccessToken(any(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { Long id = 343L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -337,28 +337,28 @@ public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwa return _token; } }); - when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(any())).thenAnswer(new Answer() { Long id = 234L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -541,7 +541,7 @@ public void testImportWhitelistedSites() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.save(any(WhitelistedSite.class))).thenAnswer(new Answer() { Long id = 345L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { @@ -553,7 +553,7 @@ public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; @@ -580,7 +580,7 @@ public void testImportGrants() throws IOException, ParseException { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); + lenient().when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -589,7 +589,7 @@ public void testImportGrants() throws IOException, ParseException { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); + lenient().when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+00:00", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+00:00", Locale.ENGLISH); @@ -629,7 +629,7 @@ public void testImportGrants() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { + lenient().when(approvedSiteRepository.save(any(ApprovedSite.class))).thenAnswer(new Answer() { Long id = 343L; @Override public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { @@ -641,32 +641,32 @@ public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().when(wlSiteRepository.getById(any())).thenAnswer(new Answer() { Long id = 244L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); + lenient().when(_site.getId()).thenReturn(id++); return _site; } }); - when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.getAccessTokenById(any())).thenAnswer(new Answer() { Long id = 221L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); + lenient().when(_token.getId()).thenReturn(id++); return _token; } }); - when(tokenRepository.getAccessTokensForApprovedSite(site1)).thenReturn(Lists.newArrayList(mockToken1)); + lenient().when(tokenRepository.getAccessTokensForApprovedSite(site1)).thenReturn(Lists.newArrayList(mockToken1)); dataService.importData(reader); //2 for sites, 1 for updating access token ref on #1 @@ -733,7 +733,7 @@ public void testImportAuthenticationHolders() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 356L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -836,7 +836,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -859,7 +859,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -906,7 +906,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException 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() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 343L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -918,23 +918,23 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 356L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -946,7 +946,7 @@ public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Thr return _holder; } }); - when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; 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 3876138527..26b2b53c6b 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 @@ -20,14 +20,13 @@ 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; 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; @@ -69,7 +68,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.springframework.format.annotation.DateTimeFormat.ISO; import org.springframework.format.datetime.DateFormatter; @@ -147,10 +146,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -163,10 +162,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -197,7 +196,7 @@ public void testImportRefreshTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 332L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -209,28 +208,28 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(null)).thenAnswer(new Answer() { Long id = 131L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -267,10 +266,10 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -285,13 +284,13 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); + lenient().when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -329,7 +328,7 @@ public void testImportAccessTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveAccessToken(any(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { Long id = 324L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -341,28 +340,28 @@ public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwa return _token; } }); - when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(any())).thenAnswer(new Answer() { Long id = 133L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -544,7 +543,7 @@ public void testImportWhitelistedSites() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.save(any(WhitelistedSite.class))).thenAnswer(new Answer() { Long id = 333L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { @@ -556,7 +555,7 @@ public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; @@ -583,7 +582,7 @@ public void testImportGrants() throws IOException, ParseException { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); + lenient().when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -592,7 +591,7 @@ public void testImportGrants() throws IOException, ParseException { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); + lenient().when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+00:00", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+00:00", Locale.ENGLISH); @@ -632,7 +631,7 @@ public void testImportGrants() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { + lenient().when(approvedSiteRepository.save(any(ApprovedSite.class))).thenAnswer(new Answer() { Long id = 364L; @Override public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { @@ -644,28 +643,28 @@ public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().when(wlSiteRepository.getById(any())).thenAnswer(new Answer() { Long id = 432L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); + lenient().when(_site.getId()).thenReturn(id++); return _site; } }); - when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.getAccessTokenById(any())).thenAnswer(new Answer() { Long id = 245L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); + lenient().when(_token.getId()).thenReturn(id++); return _token; } }); @@ -735,7 +734,7 @@ public void testImportAuthenticationHolders() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 243L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -838,7 +837,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -861,7 +860,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -908,7 +907,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException 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() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 343L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -920,23 +919,23 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 356L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -948,7 +947,7 @@ public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Thr return _holder; } }); - when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; 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 ffb9304fdc..0e997b505d 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 @@ -18,14 +18,13 @@ 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; 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; @@ -67,7 +66,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -149,10 +148,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -165,10 +164,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -199,7 +198,7 @@ public void testImportRefreshTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 332L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -211,28 +210,28 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(null)).thenAnswer(new Answer() { Long id = 131L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -269,10 +268,10 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -287,13 +286,13 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); + lenient().when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -331,7 +330,7 @@ public void testImportAccessTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveAccessToken(any(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { Long id = 324L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -343,28 +342,28 @@ public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwa return _token; } }); - when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(null)).thenAnswer(new Answer() { Long id = 133L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -546,7 +545,7 @@ public void testImportWhitelistedSites() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.save(any(WhitelistedSite.class))).thenAnswer(new Answer() { Long id = 333L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { @@ -558,7 +557,7 @@ public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; @@ -585,7 +584,7 @@ public void testImportGrants() throws IOException, ParseException { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); + lenient().when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -594,7 +593,7 @@ public void testImportGrants() throws IOException, ParseException { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); + lenient().when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+00:00", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+00:00", Locale.ENGLISH); @@ -634,7 +633,7 @@ public void testImportGrants() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { + lenient().when(approvedSiteRepository.save(any(ApprovedSite.class))).thenAnswer(new Answer() { Long id = 364L; @Override public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { @@ -646,28 +645,28 @@ public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().when(wlSiteRepository.getById(null)).thenAnswer(new Answer() { Long id = 432L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); + lenient().when(_site.getId()).thenReturn(id++); return _site; } }); - when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.getAccessTokenById(null)).thenAnswer(new Answer() { Long id = 245L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); + lenient().when(_token.getId()).thenReturn(id++); return _token; } }); @@ -737,7 +736,7 @@ public void testImportAuthenticationHolders() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 243L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -840,7 +839,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -863,7 +862,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -910,7 +909,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException 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() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 343L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -922,23 +921,23 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 356L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -950,7 +949,7 @@ public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Thr return _holder; } }); - when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java index 2413cc1884..267a74285e 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestMITREidDataService_1_3.java @@ -21,10 +21,10 @@ 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.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -72,7 +72,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -152,10 +152,10 @@ public void testExportRefreshTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -168,10 +168,10 @@ public void testExportRefreshTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -182,14 +182,14 @@ public void testExportRefreshTokens() throws IOException, ParseException { 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()); - Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet()); - Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList()); - Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); - Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(allRefreshTokens); - Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); + lenient().when(clientRepository.getAllClients()).thenReturn(new HashSet()); + lenient().when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(blSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(authHolderRepository.getAll()).thenReturn(new ArrayList()); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(allRefreshTokens); + lenient().when(sysScopeRepository.getAll()).thenReturn(new HashSet()); // do the data export StringWriter stringWriter = new StringWriter(); @@ -276,10 +276,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2RefreshTokenEntity token1 = new OAuth2RefreshTokenEntity(); token1.setId(1L); @@ -292,10 +292,10 @@ public void testImportRefreshTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity token2 = new OAuth2RefreshTokenEntity(); token2.setId(2L); @@ -326,7 +326,7 @@ public void testImportRefreshTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveRefreshToken(isA(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 332L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -338,28 +338,28 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(any())).thenAnswer(new Answer() { Long id = 131L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -389,10 +389,10 @@ public void testExportAccessTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -407,13 +407,13 @@ public void testExportAccessTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); + lenient().when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -427,14 +427,14 @@ public void testExportAccessTokens() throws IOException, ParseException { 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()); - Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet()); - Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList()); - Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); - Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(allAccessTokens); - Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); + lenient().when(clientRepository.getAllClients()).thenReturn(new HashSet()); + lenient().when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(blSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(authHolderRepository.getAll()).thenReturn(new ArrayList()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(allAccessTokens); + lenient().when(sysScopeRepository.getAll()).thenReturn(new HashSet()); // do the data export StringWriter stringWriter = new StringWriter(); @@ -528,10 +528,10 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); AuthenticationHolderEntity mockedAuthHolder1 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder1.getId()).thenReturn(1L); + lenient().when(mockedAuthHolder1.getId()).thenReturn(1L); OAuth2AccessTokenEntity token1 = new OAuth2AccessTokenEntity(); token1.setId(1L); @@ -546,13 +546,13 @@ public void testImportAccessTokens() throws IOException, ParseException { Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); AuthenticationHolderEntity mockedAuthHolder2 = mock(AuthenticationHolderEntity.class); - when(mockedAuthHolder2.getId()).thenReturn(2L); + lenient().when(mockedAuthHolder2.getId()).thenReturn(2L); OAuth2RefreshTokenEntity mockRefreshToken2 = mock(OAuth2RefreshTokenEntity.class); - when(mockRefreshToken2.getId()).thenReturn(1L); + lenient().when(mockRefreshToken2.getId()).thenReturn(1L); OAuth2AccessTokenEntity token2 = new OAuth2AccessTokenEntity(); token2.setId(2L); @@ -590,7 +590,7 @@ public void testImportAccessTokens() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(tokenRepository.saveAccessToken(isA(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.saveAccessToken(any(OAuth2AccessTokenEntity.class))).thenAnswer(new Answer() { Long id = 324L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -602,28 +602,28 @@ public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwa return _token; } }); - when(tokenRepository.getAccessTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.getById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(any())).thenAnswer(new Answer() { Long id = 133L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { AuthenticationHolderEntity _auth = mock(AuthenticationHolderEntity.class); - when(_auth.getId()).thenReturn(id); + lenient().when(_auth.getId()).thenReturn(id); id++; return _auth; } @@ -671,14 +671,14 @@ public void testExportClients() throws IOException { 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()); - Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet()); - Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList()); - Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); - Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); - Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); + lenient().when(clientRepository.getAllClients()).thenReturn(allClients); + lenient().when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(blSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(authHolderRepository.getAll()).thenReturn(new ArrayList()); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); + lenient().when(sysScopeRepository.getAll()).thenReturn(new HashSet()); // do the data export StringWriter stringWriter = new StringWriter(); @@ -843,14 +843,14 @@ public void testExportBlacklistedSites() throws IOException { 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()); - Mockito.when(blSiteRepository.getAll()).thenReturn(allBlacklistedSites); - Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList()); - Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); - Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); - Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); + lenient().when(clientRepository.getAllClients()).thenReturn(new HashSet()); + lenient().when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(blSiteRepository.getAll()).thenReturn(allBlacklistedSites); + lenient().when(authHolderRepository.getAll()).thenReturn(new ArrayList()); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); + lenient().when(sysScopeRepository.getAll()).thenReturn(new HashSet()); // do the data export StringWriter stringWriter = new StringWriter(); @@ -984,14 +984,14 @@ public void testExportWhitelistedSites() throws IOException { 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()); - Mockito.when(wlSiteRepository.getAll()).thenReturn(allWhitelistedSites); - Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList()); - Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); - Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); - Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); + lenient().when(clientRepository.getAllClients()).thenReturn(new HashSet()); + lenient().when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(blSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(allWhitelistedSites); + lenient().when(authHolderRepository.getAll()).thenReturn(new ArrayList()); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); + lenient().when(sysScopeRepository.getAll()).thenReturn(new HashSet()); // do the data export StringWriter stringWriter = new StringWriter(); @@ -1098,7 +1098,7 @@ public void testImportWhitelistedSites() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(wlSiteRepository.save(isA(WhitelistedSite.class))).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.save(any(WhitelistedSite.class))).thenAnswer(new Answer() { Long id = 333L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { @@ -1110,7 +1110,7 @@ public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(wlSiteRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; @@ -1137,7 +1137,7 @@ public void testExportGrants() throws IOException, ParseException { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); + lenient().when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -1146,7 +1146,7 @@ public void testExportGrants() throws IOException, ParseException { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); + lenient().when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+00:00", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+00:00", Locale.ENGLISH); @@ -1163,14 +1163,14 @@ public void testExportGrants() throws IOException, ParseException { 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()); - Mockito.when(wlSiteRepository.getAll()).thenReturn(new HashSet()); - Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList()); - Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); - Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); - Mockito.when(sysScopeRepository.getAll()).thenReturn(new HashSet()); + lenient().when(clientRepository.getAllClients()).thenReturn(new HashSet()); + lenient().when(approvedSiteRepository.getAll()).thenReturn(allApprovedSites); + lenient().when(blSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(authHolderRepository.getAll()).thenReturn(new ArrayList()); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); + lenient().when(sysScopeRepository.getAll()).thenReturn(new HashSet()); // do the data export StringWriter stringWriter = new StringWriter(); @@ -1253,7 +1253,7 @@ public void testImportGrants() throws IOException, ParseException { Date accessDate1 = formatter.parse("2014-09-10T23:49:44.090+00:00", Locale.ENGLISH); OAuth2AccessTokenEntity mockToken1 = mock(OAuth2AccessTokenEntity.class); - when(mockToken1.getId()).thenReturn(1L); + lenient().when(mockToken1.getId()).thenReturn(1L); ApprovedSite site1 = new ApprovedSite(); site1.setId(1L); @@ -1262,7 +1262,7 @@ public void testImportGrants() throws IOException, ParseException { site1.setAccessDate(accessDate1); site1.setUserId("user1"); site1.setAllowedScopes(ImmutableSet.of("openid", "phone")); - when(mockToken1.getApprovedSite()).thenReturn(site1); + lenient().when(mockToken1.getApprovedSite()).thenReturn(site1); Date creationDate2 = formatter.parse("2014-09-11T18:49:44.090+00:00", Locale.ENGLISH); Date accessDate2 = formatter.parse("2014-09-11T20:49:44.090+00:00", Locale.ENGLISH); @@ -1302,7 +1302,7 @@ public void testImportGrants() throws IOException, ParseException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(approvedSiteRepository.save(isA(ApprovedSite.class))).thenAnswer(new Answer() { + lenient().when(approvedSiteRepository.save(any(ApprovedSite.class))).thenAnswer(new Answer() { Long id = 364L; @Override public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { @@ -1314,28 +1314,28 @@ public ApprovedSite answer(InvocationOnMock invocation) throws Throwable { return _site; } }); - when(approvedSiteRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().when(wlSiteRepository.getById(any())).thenAnswer(new Answer() { Long id = 432L; @Override public WhitelistedSite answer(InvocationOnMock invocation) throws Throwable { WhitelistedSite _site = mock(WhitelistedSite.class); - when(_site.getId()).thenReturn(id++); + lenient().when(_site.getId()).thenReturn(id++); return _site; } }); - when(tokenRepository.getAccessTokenById(isNull(Long.class))).thenAnswer(new Answer() { + lenient().when(tokenRepository.getAccessTokenById(any())).thenAnswer(new Answer() { Long id = 245L; @Override public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable { OAuth2AccessTokenEntity _token = mock(OAuth2AccessTokenEntity.class); - when(_token.getId()).thenReturn(id++); + lenient().when(_token.getId()).thenReturn(id++); return _token; } }); @@ -1384,14 +1384,14 @@ public void testExportAuthenticationHolders() throws IOException { List allAuthHolders = ImmutableList.of(holder1, holder2); - when(clientRepository.getAllClients()).thenReturn(new HashSet()); - when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); - when(wlSiteRepository.getAll()).thenReturn(new HashSet()); - when(blSiteRepository.getAll()).thenReturn(new HashSet()); - when(authHolderRepository.getAll()).thenReturn(allAuthHolders); - when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); - when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); - when(sysScopeRepository.getAll()).thenReturn(new HashSet()); + lenient().when(clientRepository.getAllClients()).thenReturn(new HashSet()); + lenient().when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(blSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(authHolderRepository.getAll()).thenReturn(allAuthHolders); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); + lenient().when(sysScopeRepository.getAll()).thenReturn(new HashSet()); // do the data export StringWriter stringWriter = new StringWriter(); @@ -1512,7 +1512,7 @@ public void testImportAuthenticationHolders() throws IOException { JsonReader reader = new JsonReader(new StringReader(configJson)); final Map fakeDb = new HashMap<>(); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 243L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -1563,14 +1563,14 @@ public void testExportSystemScopes() throws IOException { 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()); - Mockito.when(blSiteRepository.getAll()).thenReturn(new HashSet()); - Mockito.when(authHolderRepository.getAll()).thenReturn(new ArrayList()); - Mockito.when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); - Mockito.when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); - Mockito.when(sysScopeRepository.getAll()).thenReturn(allScopes); + lenient().when(clientRepository.getAllClients()).thenReturn(new HashSet()); + lenient().when(approvedSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(wlSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(blSiteRepository.getAll()).thenReturn(new HashSet()); + lenient().when(authHolderRepository.getAll()).thenReturn(new ArrayList()); + lenient().when(tokenRepository.getAllAccessTokens()).thenReturn(new HashSet()); + lenient().when(tokenRepository.getAllRefreshTokens()).thenReturn(new HashSet()); + lenient().when(sysScopeRepository.getAll()).thenReturn(allScopes); // do the data export StringWriter stringWriter = new StringWriter(); @@ -1725,7 +1725,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate1 = formatter.parse(expiration1, Locale.ENGLISH); ClientDetailsEntity mockedClient1 = mock(ClientDetailsEntity.class); - when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); + lenient().when(mockedClient1.getClientId()).thenReturn("mocked_client_1"); OAuth2Request req1 = new OAuth2Request(new HashMap(), "client1", new ArrayList(), true, new HashSet(), new HashSet(), "http://foo.com", @@ -1748,7 +1748,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException Date expirationDate2 = formatter.parse(expiration2, Locale.ENGLISH); ClientDetailsEntity mockedClient2 = mock(ClientDetailsEntity.class); - when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); + lenient().when(mockedClient2.getClientId()).thenReturn("mocked_client_2"); OAuth2Request req2 = new OAuth2Request(new HashMap(), "client2", new ArrayList(), true, new HashSet(), new HashSet(), "http://bar.com", @@ -1795,7 +1795,7 @@ public void testFixRefreshTokenAuthHolderReferencesOnImport() throws IOException 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() { + lenient().when(tokenRepository.saveRefreshToken(any(OAuth2RefreshTokenEntity.class))).thenAnswer(new Answer() { Long id = 343L; @Override public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable { @@ -1807,23 +1807,23 @@ public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throw return _token; } }); - when(tokenRepository.getRefreshTokenById(anyLong())).thenAnswer(new Answer() { + lenient().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() { + lenient().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); + lenient().when(_client.getClientId()).thenReturn(_clientId); return _client; } }); - when(authHolderRepository.save(isA(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { + lenient().when(authHolderRepository.save(any(AuthenticationHolderEntity.class))).thenAnswer(new Answer() { Long id = 356L; @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { @@ -1835,7 +1835,7 @@ public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Thr return _holder; } }); - when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { + lenient().when(authHolderRepository.getById(anyLong())).thenAnswer(new Answer() { @Override public AuthenticationHolderEntity answer(InvocationOnMock invocation) throws Throwable { Long _id = (Long) invocation.getArguments()[0]; diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestUUIDPairwiseIdentiferService.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestUUIDPairwiseIdentiferService.java index 30e9f5f514..a0fcb35744 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestUUIDPairwiseIdentiferService.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/service/impl/TestUUIDPairwiseIdentiferService.java @@ -20,6 +20,10 @@ */ package org.mitre.openid.connect.service.impl; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.mockito.ArgumentMatchers.any; + import java.util.Set; import java.util.UUID; @@ -33,16 +37,12 @@ import org.mitre.openid.connect.model.UserInfo; import org.mitre.openid.connect.repository.PairwiseIdentifierRepository; import org.mockito.InjectMocks; -import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.google.common.collect.ImmutableSet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; - /** * @author jricher * @@ -153,7 +153,7 @@ public void testGetIdentifier_existingEqual() { public void testGetIdentifier_newEqual() { String pairwise1 = service.getIdentifier(userInfoRegular, pairwiseClient1); - Mockito.verify(pairwiseIdentifierRepository, Mockito.atLeast(1)).save(Matchers.any(PairwiseIdentifier.class)); + Mockito.verify(pairwiseIdentifierRepository, Mockito.atLeast(1)).save(any(PairwiseIdentifier.class)); PairwiseIdentifier pairwiseId = new PairwiseIdentifier(); pairwiseId.setUserSub(regularSub); diff --git a/openid-connect-server/src/test/java/org/mitre/openid/connect/token/TestConnectTokenEnhancer.java b/openid-connect-server/src/test/java/org/mitre/openid/connect/token/TestConnectTokenEnhancer.java index 7e1acbfd99..7bf4ae5d5b 100644 --- a/openid-connect-server/src/test/java/org/mitre/openid/connect/token/TestConnectTokenEnhancer.java +++ b/openid-connect-server/src/test/java/org/mitre/openid/connect/token/TestConnectTokenEnhancer.java @@ -19,28 +19,25 @@ import java.text.ParseException; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.mitre.jwt.signer.service.JWTSigningAndValidationService; import org.mitre.oauth2.model.ClientDetailsEntity; import org.mitre.oauth2.model.OAuth2AccessTokenEntity; import org.mitre.oauth2.service.ClientDetailsEntityService; import org.mitre.openid.connect.config.ConfigurationPropertiesBean; -import org.mitre.openid.connect.model.UserInfo; import org.mitre.openid.connect.service.OIDCTokenService; import org.mitre.openid.connect.service.UserInfoService; -import org.springframework.security.oauth2.provider.OAuth2Authentication; -import org.springframework.security.oauth2.provider.OAuth2Request; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.oauth2.provider.OAuth2Request; import com.nimbusds.jose.JWSAlgorithm; -import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet.Builder; @RunWith(MockitoJUnitRunner.class) 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 b8ccbfd4ca..df2ea5a320 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 @@ -18,6 +18,8 @@ package org.mitre.openid.connect.util; +import static org.junit.Assert.assertEquals; + import java.text.ParseException; import org.junit.Before; @@ -26,14 +28,12 @@ import org.mitre.oauth2.model.OAuth2AccessTokenEntity; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.util.Base64URL; import com.nimbusds.jwt.JWTParser; -import static org.junit.Assert.assertEquals; - /** * * @author wkim diff --git a/pom.xml b/pom.xml index f816249ce4..08408d0f8d 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ 4.0.0 org.mitre openid-connect-parent - 1.3.7.cnaf-20250915 + 1.4.0.cnaf-20251012 MITREid Connect pom @@ -93,7 +93,7 @@ org.jacoco jacoco-maven-plugin - 0.8.7 + 0.8.11 org.apache.maven.plugins @@ -451,7 +451,7 @@ org.postgresql postgresql - 42.0.0.jre7 + 42.2.28 com.oracle @@ -538,8 +538,8 @@ org.mockito - mockito-all - 1.9.5 + mockito-core + 4.0.0 test @@ -612,7 +612,7 @@ org.bouncycastle bcprov-jdk15on - 1.58 + 1.69 org.eclipse.persistence @@ -620,9 +620,9 @@ 2.7.4 - org.apache.commons + commons-io commons-io - 1.3.2 + 2.11.0 ro.isdc.wro4j @@ -681,7 +681,7 @@ org.mockito - mockito-all + mockito-core org.slf4j