From 2d1d8b338edc0184cb8831bd9812568d57345fbb Mon Sep 17 00:00:00 2001 From: Duane May Date: Wed, 3 Jun 2026 22:01:45 -0400 Subject: [PATCH 1/7] Migrate code to Java 25 Syntax Rewrite Rules applied - Replace unused variables with underscore - Migrate to IO utility class - Use switch expression --- .../identity/uaa/metrics/MetricsQueue.java | 2 +- .../uaa/oauth/client/OAuth2RestTemplate.java | 4 +- .../AuthorizationCodeAccessTokenProvider.java | 2 +- .../oauth/client/http/OAuth2ErrorHandler.java | 6 +-- .../common/DefaultOAuth2AccessToken.java | 2 +- ...OAuth2AccessTokenJackson2Deserializer.java | 2 +- .../oauth/token/OAuth2AccessTokenSupport.java | 2 +- .../SamlIdentityProviderDefinition.java | 4 +- .../identity/uaa/util/UaaStringUtils.java | 2 +- .../uaa/zone/IdentityZoneConfiguration.java | 2 +- .../identity/uaa/zone/SamlConfig.java | 12 ++--- .../uaa/account/AccountsController.java | 4 +- .../uaa/account/ChangeEmailController.java | 4 +- .../uaa/account/ChangePasswordController.java | 2 +- .../account/EmailAccountCreationService.java | 2 +- .../uaa/account/EmailChangeEmailService.java | 2 +- .../uaa/account/PasswordResetEndpoint.java | 8 +-- .../uaa/account/ProfileController.java | 2 +- .../uaa/account/ResetPasswordController.java | 4 +- .../uaa/account/UaaResetPasswordService.java | 4 +- .../event/PasswordChangeEventPublisher.java | 2 +- .../uaa/alias/EntityAliasHandler.java | 2 +- .../uaa/approval/ApprovalsAdminEndpoints.java | 2 +- .../uaa/approval/JdbcApprovalStore.java | 2 +- .../uaa/audit/event/AbstractUaaEvent.java | 4 +- ...ibleTokenEndpointAuthenticationFilter.java | 2 +- .../ClientBasicAuthenticationFilter.java | 4 +- .../EmptyPasswordAwareEncoder.java | 2 +- .../identity/uaa/authentication/Origin.java | 2 +- .../PasscodeAuthenticationFilter.java | 2 +- .../RemoteAuthenticationEndpoint.java | 6 +-- .../authentication/SessionResetFilter.java | 2 +- .../uaa/authentication/UaaLoginHint.java | 4 +- .../WhitelistLogoutSuccessHandler.java | 4 +- .../event/UserNotFoundEvent.java | 2 +- .../manager/AuthzAuthenticationManager.java | 2 +- .../AutologinAuthenticationManager.java | 4 +- .../CheckIdpEnabledAuthenticationManager.java | 2 +- ...DynamicZoneAwareAuthenticationManager.java | 2 +- .../ExternalLoginAuthenticationManager.java | 4 +- .../manager/LoginAuthenticationManager.java | 4 +- .../PasswordGrantAuthenticationManager.java | 2 +- .../uaa/client/ClientAdminBootstrap.java | 6 +-- .../uaa/client/ClientAdminEndpoints.java | 20 ++++---- .../client/ClientAdminEndpointsValidator.java | 28 +++++------ .../client/ClientAuthenticationFilter.java | 2 +- .../client/ClientMetadataAdminEndpoints.java | 4 +- .../JdbcClientMetadataProvisioning.java | 2 +- .../event/ClientAdminEventPublisher.java | 2 +- .../uaa/codestore/CodeStoreEndpoints.java | 8 +-- .../uaa/codestore/JdbcExpiringCodeStore.java | 4 +- .../db/V2_7_3__StoreSubDomainAsLowerCase.java | 2 +- .../identity/uaa/error/UaaException.java | 2 +- .../config/CustomPropertyConstructor.java | 2 +- .../config/IdentityProviderBootstrap.java | 2 +- .../IdentityZoneConfigurationBootstrap.java | 2 +- .../uaa/impl/config/UaaConfiguration.java | 4 +- .../config/YamlServletProfileInitializer.java | 18 +++---- .../invitations/EmailInvitationsService.java | 2 +- .../invitations/InvitationsController.java | 8 +-- .../uaa/invitations/InvitationsEndpoint.java | 6 +-- .../uaa/login/LoginConsentHashUtil.java | 2 +- .../identity/uaa/login/LoginInfoEndpoint.java | 16 +++--- .../uaa/message/util/FakeJavaMailSender.java | 2 +- .../uaa/oauth/IntrospectEndpoint.java | 2 +- .../identity/uaa/oauth/KeyInfo.java | 2 +- .../uaa/oauth/TokenValidationService.java | 2 +- .../uaa/oauth/UaaAuthorizationEndpoint.java | 10 ++-- .../oauth/UaaAuthorizationRequestManager.java | 4 +- .../identity/uaa/oauth/UaaTokenServices.java | 2 +- .../identity/uaa/oauth/UaaTokenStore.java | 4 +- .../oauth/beans/LegacyRedirectResolver.java | 4 +- .../endpoint/DefaultRedirectResolver.java | 2 +- .../oauth/jwt/JwtClientAuthentication.java | 4 +- .../identity/uaa/oauth/jwt/JwtHelper.java | 2 +- .../uaa/oauth/jwt/SignatureVerifier.java | 2 +- .../uaa/oauth/openid/IdTokenGranter.java | 2 +- .../OAuth2AuthenticationManager.java | 2 +- .../client/OAuth2ClientContextFilter.java | 2 +- .../code/JdbcAuthorizationCodeServices.java | 2 +- .../ResourceOwnerPasswordTokenGranter.java | 2 +- .../provider/refresh/RefreshTokenGranter.java | 2 +- .../uaa/oauth/token/TokenExchangeGranter.java | 6 +-- .../IdentityProviderAliasHandler.java | 2 +- .../provider/IdentityProviderEndpoints.java | 6 +-- .../JdbcIdentityProviderProvisioning.java | 2 +- .../ldap/DynamicPasswordComparator.java | 4 +- .../provider/ldap/ExtendedLdapUserMapper.java | 2 +- .../ldap/PasswordComparisonAuthenticator.java | 2 +- .../extension/SpringSecurityLdapTemplate.java | 2 +- .../ExternalOAuthAuthenticationManager.java | 50 +++++++++---------- .../oauth/OauthIDPWrapperFactoryBean.java | 2 +- .../BootstrapSamlIdentityProviderData.java | 2 +- .../saml/OpenSaml5AuthenticationProvider.java | 4 +- .../saml/OpenSamlVerificationUtils.java | 4 +- .../uaa/provider/saml/OpenSamlXmlUtils.java | 42 ++++++++-------- .../saml/RelyingPartyRegistrationBuilder.java | 2 +- .../uaa/provider/saml/SamlConfiguration.java | 2 +- .../SamlIdentityProviderConfigurator.java | 6 +-- .../provider/saml/SamlKeyManagerFactory.java | 2 +- .../uaa/provider/saml/SamlRedirectUtils.java | 2 +- .../SamlUaaAuthenticationUserManager.java | 2 +- .../InternalLimiterFactoriesSupplier.java | 2 +- .../limitertracking/ExpirationBuckets.java | 2 +- .../uaa/ratelimiting/util/IntUtils.java | 2 +- .../uaa/ratelimiting/util/SourcedFile.java | 2 +- .../ratelimiting/util/StringUtilities.java | 13 ++--- .../uaa/resources/SearchResultsFactory.java | 2 +- .../uaa/resources/jdbc/JdbcPagingList.java | 2 +- .../jdbc/SimpleSearchQueryConverter.java | 39 ++++++--------- .../uaa/scim/ScimUserAliasHandler.java | 4 +- .../bootstrap/ScimExternalGroupBootstrap.java | 2 +- .../scim/bootstrap/ScimGroupBootstrap.java | 6 +-- .../uaa/scim/bootstrap/ScimUserBootstrap.java | 12 ++--- .../scim/endpoints/ScimGroupEndpoints.java | 8 +-- .../uaa/scim/endpoints/ScimUserEndpoints.java | 12 ++--- ...dbcScimGroupExternalMembershipManager.java | 6 +-- .../jdbc/JdbcScimGroupMembershipManager.java | 10 ++-- .../scim/jdbc/JdbcScimGroupProvisioning.java | 12 ++--- .../scim/jdbc/JdbcScimUserProvisioning.java | 8 +-- .../uaa/scim/services/ScimUserService.java | 2 +- .../identity/uaa/security/IsSelfCheck.java | 2 +- .../uaa/security/ScimUserUpdateDiff.java | 2 +- .../X509ExpiryCheckingTrustManager.java | 2 +- .../identity/uaa/security/web/CorsFilter.java | 2 +- .../web/SecurityFilterChainPostProcessor.java | 11 ++-- .../uaa/user/JdbcUaaUserDatabase.java | 10 ++-- .../uaa/user/UaaUserApprovalHandler.java | 2 +- .../uaa/util/JwtTokenSignedByThisUAA.java | 28 +++++------ .../identity/uaa/util/KeyWithCert.java | 23 +++++---- .../uaa/util/LinkedMaskingMultiValueMap.java | 2 +- .../identity/uaa/util/MapCollector.java | 2 +- .../uaa/util/UaaHttpRequestUtils.java | 8 +-- .../identity/uaa/util/UaaUrlUtils.java | 12 ++--- .../uaa/web/AuthorizationManagersUtils.java | 4 +- .../web/SelfCheckAuthorizationManager.java | 2 +- .../uaa/zone/IdentityZoneEndpoints.java | 2 +- .../uaa/zone/IdentityZoneResolvingFilter.java | 2 +- .../uaa/zone/IdentityZoneSwitchingFilter.java | 2 +- .../uaa/zone/LoginConsentValidator.java | 4 +- .../MultitenantJdbcClientDetailsService.java | 2 +- .../uaa/zone/ZonePathHttpSession.java | 2 +- .../identity/statsd/MBeanMap.java | 4 +- .../identity/statsd/UaaMetricsEmitter.java | 2 +- .../identity/uaa/brave/WebMvcRuntime.java | 2 +- 145 files changed, 372 insertions(+), 384 deletions(-) diff --git a/metrics-data/src/main/java/org/cloudfoundry/identity/uaa/metrics/MetricsQueue.java b/metrics-data/src/main/java/org/cloudfoundry/identity/uaa/metrics/MetricsQueue.java index f388ce4e1ad..2c15e9cac9f 100644 --- a/metrics-data/src/main/java/org/cloudfoundry/identity/uaa/metrics/MetricsQueue.java +++ b/metrics-data/src/main/java/org/cloudfoundry/identity/uaa/metrics/MetricsQueue.java @@ -92,7 +92,7 @@ public RequestMetricSummary getTotals() { MutableDouble averageDatabaseQueryTime = new MutableDouble(0); MutableLong databaseIntolerableQueryCount = new MutableLong(0); MutableDouble averageDatabaseIntolerableQueryTime = new MutableDouble(0); - statistics.forEach((key, summary) -> { + statistics.forEach((_, summary) -> { averageTime.set(addAverages(count.get(), averageTime.get(), summary.getCount(), diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplate.java b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplate.java index 9e4ffe5088a..76915ee7a1c 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplate.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplate.java @@ -139,7 +139,7 @@ protected T doExecute(URI url, String uriTemplate, HttpMethod method, Reques catch (AccessTokenRequiredException | OAuth2AccessDeniedException e) { rethrow = e; } - catch (InvalidTokenException e) { + catch (InvalidTokenException _) { // Don't reveal the token value in case it is logged rethrow = new OAuth2AccessDeniedException("Invalid token for client=" + getClientId()); } @@ -148,7 +148,7 @@ protected T doExecute(URI url, String uriTemplate, HttpMethod method, Reques try { return super.doExecute(url, uriTemplate, method, requestCallback, responseExtractor); } - catch (InvalidTokenException e) { + catch (InvalidTokenException _) { // Don't reveal the token value in case it is logged rethrow = new OAuth2AccessDeniedException("Invalid token for client=" + getClientId()); } diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/grant/AuthorizationCodeAccessTokenProvider.java b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/grant/AuthorizationCodeAccessTokenProvider.java index 1f3954f0913..699c49eae4b 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/grant/AuthorizationCodeAccessTokenProvider.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/grant/AuthorizationCodeAccessTokenProvider.java @@ -147,7 +147,7 @@ public OAuth2AccessToken refreshAccessToken(OAuth2ProtectedResourceDetails resou try { return retrieveToken(request, resource, form, getHeadersForTokenRequest()); } - catch (OAuth2AccessDeniedException e) { + catch (OAuth2AccessDeniedException _) { throw getRedirectForAuthorization((AuthorizationCodeResourceDetails) resource, request); } } diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandler.java b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandler.java index 34ed729c75a..b77ec1d43dc 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandler.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandler.java @@ -126,10 +126,10 @@ public int getRawStatusCode() throws IOException { throw oauth2Exception; } } - catch (RestClientException e) { + catch (RestClientException _) { // ignore } - catch (HttpMessageConversionException e) { + catch (HttpMessageConversionException _) { // ignore } @@ -145,7 +145,7 @@ public int getRawStatusCode() throws IOException { // then delegate to the custom handler errorHandler.handleError(url, method, bufferedResponse); } - catch (InvalidTokenException ex) { + catch (InvalidTokenException _) { // Special case: an invalid token can be renewed so tell the caller what to do throw new AccessTokenRequiredException(resource); } diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/DefaultOAuth2AccessToken.java b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/DefaultOAuth2AccessToken.java index 4b7a3453fa5..ebe74a57da3 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/DefaultOAuth2AccessToken.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/DefaultOAuth2AccessToken.java @@ -144,7 +144,7 @@ public static OAuth2AccessToken valueOf(Map tokenParams) { // Convert to string before parseLong, tokenParams is not always a Map might contain Integer expiration = Long.parseLong(String.valueOf(tokenParams.get(EXPIRES_IN))); } - catch (NumberFormatException e) { + catch (NumberFormatException _) { // fall through... } token.setExpiration(new Date(System.currentTimeMillis() + (expiration * 1000L))); diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2Deserializer.java b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2Deserializer.java index 472fa805962..910ce30c8ef 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2Deserializer.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2Deserializer.java @@ -57,7 +57,7 @@ public OAuth2AccessToken deserialize(JsonParser jp, DeserializationContext ctxt) } else if (OAuth2AccessToken.EXPIRES_IN.equals(name)) { try { expiresIn = jp.getLongValue(); - } catch (StreamReadException e) { + } catch (StreamReadException _) { expiresIn = Long.valueOf(jp.getString()); } } else if (OAuth2AccessToken.SCOPE.equals(name)) { diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupport.java b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupport.java index 02581a46bc8..1eb02989fe2 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupport.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupport.java @@ -240,7 +240,7 @@ public void handleError(URI url, HttpMethod method, ClientHttpResponse response) try { ex = ((HttpMessageConverter) converter).read(OAuth2Exception.class, response); } - catch (Exception e) { + catch (Exception _) { // ignore continue; } diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/provider/SamlIdentityProviderDefinition.java b/model/src/main/java/org/cloudfoundry/identity/uaa/provider/SamlIdentityProviderDefinition.java index 42cc1116a7b..034e5712909 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/provider/SamlIdentityProviderDefinition.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/provider/SamlIdentityProviderDefinition.java @@ -104,7 +104,7 @@ public static MetadataLocation getType(String urlOrXmlData) { // Check if it is a valid URL new URL(trimmedValue); return MetadataLocation.URL; - } catch (MalformedURLException e) { + } catch (MalformedURLException _) { //invalid URL } } @@ -128,7 +128,7 @@ private static boolean validateXml(String xml) { try { DocumentBuilder builder = ObjectUtils.getDocumentBuilder(); builder.parse(new InputSource(new StringReader(xml))); - } catch (ParserConfigurationException | SAXException | IOException e) { + } catch (ParserConfigurationException | SAXException | IOException _) { return false; } diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/util/UaaStringUtils.java b/model/src/main/java/org/cloudfoundry/identity/uaa/util/UaaStringUtils.java index 3f7661196e1..79e2c157bd7 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/util/UaaStringUtils.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/util/UaaStringUtils.java @@ -243,7 +243,7 @@ public static String getHostIfArgIsURL(String arg) { try { URL uri = new URL(arg); return uri.getHost(); - } catch (MalformedURLException ignored) { + } catch (MalformedURLException _) { } return arg; } diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneConfiguration.java b/model/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneConfiguration.java index dde8aed2345..e0884e951f1 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneConfiguration.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneConfiguration.java @@ -80,7 +80,7 @@ public void setIssuer(String issuer) { try { new URL(issuer); this.issuer = issuer; - } catch (MalformedURLException e) { + } catch (MalformedURLException _) { throw new IllegalArgumentException("Invalid issuer format. Must be valid URL."); } } diff --git a/model/src/main/java/org/cloudfoundry/identity/uaa/zone/SamlConfig.java b/model/src/main/java/org/cloudfoundry/identity/uaa/zone/SamlConfig.java index 085c5a1f8c6..f5841d5d22c 100644 --- a/model/src/main/java/org/cloudfoundry/identity/uaa/zone/SamlConfig.java +++ b/model/src/main/java/org/cloudfoundry/identity/uaa/zone/SamlConfig.java @@ -65,9 +65,9 @@ public void setEntityID(String entityID) { @JsonProperty("certificate") public void setCertificate(String certificate) { if (hasText(certificate)) { - keys.computeIfAbsent(LEGACY_KEY_ID, k -> new SamlKey()); + keys.computeIfAbsent(LEGACY_KEY_ID, _ -> new SamlKey()); } - keys.computeIfPresent(LEGACY_KEY_ID, (k, v) -> { + keys.computeIfPresent(LEGACY_KEY_ID, (_, v) -> { v.setCertificate(certificate); return v; }); @@ -76,9 +76,9 @@ public void setCertificate(String certificate) { @JsonProperty("privateKey") public void setPrivateKey(String privateKey) { if (hasText(privateKey)) { - keys.computeIfAbsent(LEGACY_KEY_ID, k -> new SamlKey()); + keys.computeIfAbsent(LEGACY_KEY_ID, _ -> new SamlKey()); } - keys.computeIfPresent(LEGACY_KEY_ID, (k, v) -> { + keys.computeIfPresent(LEGACY_KEY_ID, (_, v) -> { v.setKey(privateKey); return v; }); @@ -87,9 +87,9 @@ public void setPrivateKey(String privateKey) { @JsonProperty("privateKeyPassword") public void setPrivateKeyPassword(String privateKeyPassword) { if (hasText(privateKeyPassword)) { - keys.computeIfAbsent(LEGACY_KEY_ID, k -> new SamlKey()); + keys.computeIfAbsent(LEGACY_KEY_ID, _ -> new SamlKey()); } - keys.computeIfPresent(LEGACY_KEY_ID, (k, v) -> { + keys.computeIfPresent(LEGACY_KEY_ID, (_, v) -> { v.setPassphrase(privateKeyPassword); return v; }); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/AccountsController.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/AccountsController.java index 1431b2ebcf9..975be8c2494 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/AccountsController.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/AccountsController.java @@ -90,7 +90,7 @@ public String sendActivationEmail(Model model, HttpServletResponse response, } try { accountCreationService.beginActivation(email.getEmail(), password, clientId, redirectUri); - } catch (UaaException e) { + } catch (UaaException _) { return handleUnprocessableEntity(model, response, "error_message_code", "username_exists"); } catch (InvalidPasswordException e) { return handleUnprocessableEntity(model, response, "error_message", e.getMessagesAsOneString()); @@ -117,7 +117,7 @@ public String verifyUser(Model model, AccountCreationService.AccountCreationResponse accountCreation; try { accountCreation = accountCreationService.completeActivation(code); - } catch (HttpClientErrorException e) { + } catch (HttpClientErrorException _) { model.addAttribute("error_message_code", "code_expired"); model.addAttribute("signupLink", environment.getProperty("links.signup")); response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value()); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java index 6be1cf79163..e00a7abe32f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangeEmailController.java @@ -93,14 +93,14 @@ public String verifyEmail(Model model, @RequestParam String code, RedirectAttrib try { response = changeEmailService.completeVerification(code); - } catch (UaaException e) { + } catch (UaaException _) { return handleExceptionConsideringAuthentication(model, httpServletResponse); } UaaUser user; try { user = uaaUserDatabase.retrieveUserById(response.get("userId")); - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { return handleExceptionConsideringAuthentication(model, httpServletResponse); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangePasswordController.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangePasswordController.java index 87427ad2b12..3fadaf2945f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangePasswordController.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ChangePasswordController.java @@ -61,7 +61,7 @@ public String changePassword( } securityContext.setAuthentication(authentication); return "redirect:profile"; - } catch (BadCredentialsException e) { + } catch (BadCredentialsException _) { model.addAttribute("message_code", "unauthorized"); } catch (InvalidPasswordException e) { model.addAttribute("message", e.getMessagesAsOneString()); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailAccountCreationService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailAccountCreationService.java index b114ffb3473..fab9727183c 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailAccountCreationService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailAccountCreationService.java @@ -80,7 +80,7 @@ public void beginActivation(String email, String password, String clientId, Stri try { ScimUser scimUser = createUser(email, password, OriginKeys.UAA); generateAndSendCode(email, clientId, subject, scimUser.getId(), redirectUri, identityZoneManager.getCurrentIdentityZone()); - } catch (ScimResourceAlreadyExistsException e) { + } catch (ScimResourceAlreadyExistsException _) { List users = scimUserProvisioning.retrieveByUsernameAndOriginAndZone(email, OriginKeys.UAA, identityZoneManager.getCurrentIdentityZoneId()); if (!users.isEmpty()) { if (users.getFirst().isVerified()) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java index 31b649a7d73..da7257c6f14 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java @@ -128,7 +128,7 @@ public Map completeVerification(String code) { clientDetails.getRegisteredRedirectUri(); String changeEmailRedirectUrl = (String) clientDetails.getAdditionalInformation().get(CHANGE_EMAIL_REDIRECT_URL); redirectLocation = findMatchingRedirectUri(redirectUris, redirectUri, changeEmailRedirectUrl); - } catch (NoSuchClientException ignored) { + } catch (NoSuchClientException _) { } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/PasswordResetEndpoint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/PasswordResetEndpoint.java index edc49655c87..a00b28a415b 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/PasswordResetEndpoint.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/PasswordResetEndpoint.java @@ -82,7 +82,7 @@ public ResponseEntity resetPassword(@RequestBody String e } catch (ConflictException e) { response.setUserId(e.getUserId()); return new ResponseEntity<>(response, CONFLICT); - } catch (NotFoundException e) { + } catch (NotFoundException _) { return new ResponseEntity<>(NOT_FOUND); } } @@ -110,13 +110,13 @@ public ResponseEntity changePassword(@RequestBody Lo response.setEmail(user.getPrimaryEmail()); response.setLoginCode(loginCode.getCode()); return new ResponseEntity<>(response, OK); - } catch (BadCredentialsException e) { + } catch (BadCredentialsException _) { return new ResponseEntity<>(UNAUTHORIZED); - } catch (ScimResourceNotFoundException e) { + } catch (ScimResourceNotFoundException _) { return new ResponseEntity<>(NOT_FOUND); } catch (InvalidPasswordException | InvalidCodeException e) { throw e; - } catch (Exception e) { + } catch (Exception _) { return new ResponseEntity<>(INTERNAL_SERVER_ERROR); } } else { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ProfileController.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ProfileController.java index b85e85ae0fc..7447a37e074 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ProfileController.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ProfileController.java @@ -149,7 +149,7 @@ private Map> getCurrentApprovalsForUser(String u for (DescribedApproval approval : approvals) { List clientApprovals = result.computeIfAbsent( approval.getClientId(), - k -> new ArrayList<>() + _ -> new ArrayList<>() ); String scope = approval.getScope(); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ResetPasswordController.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ResetPasswordController.java index 04b7bb1b04f..360dc613fc5 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/ResetPasswordController.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/ResetPasswordController.java @@ -109,7 +109,7 @@ private void forgotPassword(String username, String clientId, String redirectUri email = e.getEmail(); htmlContent = getResetUnavailableEmailHtml(email); userId = e.getUserId(); - } catch (NotFoundException e) { + } catch (NotFoundException _) { logger.error("User with email address {} not found.", username); } @@ -210,7 +210,7 @@ private ExpiringCode checkIfUserExists(ExpiringCode code) { String userId = data.get("user_id"); try { userDatabase.retrieveUserById(userId); - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { logger.debug("reset_password ExpiringCode[{}] user_id is invalid. Aborting.", code.getCode()); return null; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java index 3f34284f2df..5ebf434a29e 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java @@ -96,7 +96,7 @@ private ResetPasswordResponse changePasswordCodeAuthenticated(ExpiringCode expir PasswordChange change; try { change = JsonUtils.readValue(expiringCode.getData(), PasswordChange.class); - } catch (JsonUtils.JsonUtilException x) { + } catch (JsonUtils.JsonUtilException _) { throw new InvalidCodeException("invalid_code", "Sorry, your reset password link is no longer valid. Please request a new one", 422); } userId = change.getUserId(); @@ -131,7 +131,7 @@ private ResetPasswordResponse changePasswordCodeAuthenticated(ExpiringCode expir if (matchingRedirectUri != null) { redirectLocation = matchingRedirectUri; } - } catch (NoSuchClientException nsce) { + } catch (NoSuchClientException _) { } } return new ResetPasswordResponse(user, redirectLocation, clientId); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/event/PasswordChangeEventPublisher.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/event/PasswordChangeEventPublisher.java index c3f47b4771e..2bde0b57da4 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/event/PasswordChangeEventPublisher.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/event/PasswordChangeEventPublisher.java @@ -76,7 +76,7 @@ UaaUser getUser(String userId) { scimUser.getSalt(), scimUser.getPasswordLastModified()); } - } catch (ScimResourceNotFoundException e) { + } catch (ScimResourceNotFoundException _) { // ignore } return null; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandler.java b/server/src/main/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandler.java index 5870e1426d6..22a2443fc8b 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandler.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandler.java @@ -76,7 +76,7 @@ public final boolean aliasPropertiesAreValid( // the referenced zone must exist try { identityZoneProvisioning.retrieve(requestBody.getAliasZid()); - } catch (final ZoneDoesNotExistsException e) { + } catch (final ZoneDoesNotExistsException _) { LOGGER.debug("Zone referenced in alias zone ID does not exist."); return false; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/approval/ApprovalsAdminEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/approval/ApprovalsAdminEndpoints.java index 6bd274cf44d..735b7e13101 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/approval/ApprovalsAdminEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/approval/ApprovalsAdminEndpoints.java @@ -187,7 +187,7 @@ private boolean isValidUser(String userId) { try { userDatabase.retrieveUserById(userId); return true; - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { return false; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/approval/JdbcApprovalStore.java b/server/src/main/java/org/cloudfoundry/identity/uaa/approval/JdbcApprovalStore.java index cacfd295403..4c0d30d77c0 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/approval/JdbcApprovalStore.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/approval/JdbcApprovalStore.java @@ -113,7 +113,7 @@ public boolean addApproval(final Approval approval, final String zoneId) { } try { refreshApproval(approval, zoneId); // try to refresh the approval - } catch (DataIntegrityViolationException ex) { // could not find the + } catch (DataIntegrityViolationException _) { // could not find the // approval. add it. int count = jdbcTemplate.update(ADD_AUTHZ_SQL, ps -> { ps.setString(1, approval.getUserId()); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/audit/event/AbstractUaaEvent.java b/server/src/main/java/org/cloudfoundry/identity/uaa/audit/event/AbstractUaaEvent.java index a86a0bda9ce..a8b0d4fcbda 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/audit/event/AbstractUaaEvent.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/audit/event/AbstractUaaEvent.java @@ -126,7 +126,7 @@ private String getAuthenticationString(Authentication caller) { builder.append("remoteAddress=").append(map.get("remoteAddress")).append(", "); } builder.append("type=").append(caller.getDetails().getClass().getSimpleName()); - } catch (Exception e) { + } catch (Exception _) { // ignore builder.append(caller.getDetails()); } @@ -152,7 +152,7 @@ protected void appendTokenDetails(Authentication caller, StringBuilder builder) String issuer = claims.get(ClaimConstants.ISS).toString(); String subject = claims.get(ClaimConstants.SUB).toString(); builder.append(", sub=").append(subject).append(", ").append("iss=").append(issuer); - } catch (Exception e) { + } catch (Exception _) { builder.append(", "); } } else { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/BackwardsCompatibleTokenEndpointAuthenticationFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/BackwardsCompatibleTokenEndpointAuthenticationFilter.java index 2dc25064d86..b228dca2253 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/BackwardsCompatibleTokenEndpointAuthenticationFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/BackwardsCompatibleTokenEndpointAuthenticationFilter.java @@ -337,7 +337,7 @@ protected TokenExchangeData getSubjectToken(HttpServletRequest request) { RevocableToken revocableToken = revocableTokenProvisioning.retrieve( subjectToken, IdentityZoneHolder.get().getId()); subjectToken = revocableToken.getValue(); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { log.debug("Opaque subject_token not found in revocable token store, passing through unchanged"); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilter.java index 352497bb412..2bc0a9d9e4b 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilter.java @@ -104,7 +104,7 @@ protected void doFilterInternal(HttpServletRequest request, try { clientId = URLDecoder.decode(tokens[0], getCredentialsCharset(request)); clientSecret = URLDecoder.decode(tokens[1], getCredentialsCharset(request)); - } catch (UnsupportedEncodingException | IllegalArgumentException e) { + } catch (UnsupportedEncodingException | IllegalArgumentException _) { throw new BadCredentialsException("Failed to URL Decode credentials"); } } @@ -155,7 +155,7 @@ private String[] extractAndDecodeHeader(String header, HttpServletRequest reques try { decoded = Base64.getDecoder().decode(base64Token); } - catch (IllegalArgumentException e) { + catch (IllegalArgumentException _) { throw new BadCredentialsException( "Failed to decode basic authentication token"); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/EmptyPasswordAwareEncoder.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/EmptyPasswordAwareEncoder.java index d70d028ef7a..d4275d3e9ae 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/EmptyPasswordAwareEncoder.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/EmptyPasswordAwareEncoder.java @@ -68,7 +68,7 @@ private boolean isBcryptHash(String value) { private boolean bcryptMatchesEmpty(String hash) { try { return BCrypt.checkpw("", hash); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { return false; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java index 97393699288..0cf1a854487 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java @@ -50,7 +50,7 @@ public static String getUserIdThroughReflection(Authentication authentication, S if (id != null) { return id.toString(); } - } catch (Exception ignored) { + } catch (Exception _) { } return null; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/PasscodeAuthenticationFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/PasscodeAuthenticationFilter.java index b7532a4eb64..f727afd43d4 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/PasscodeAuthenticationFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/PasscodeAuthenticationFilter.java @@ -210,7 +210,7 @@ public Authentication authenticate(Authentication authentication) throws Authent try { UaaUser user = uaaUserDatabase.retrieveUserById(pi.getUserId()); authorities = user.getAuthorities(); - } catch (UsernameNotFoundException x) { + } catch (UsernameNotFoundException _) { throw new BadCredentialsException("Invalid user."); } Authentication result = new UsernamePasswordAuthenticationToken( diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/RemoteAuthenticationEndpoint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/RemoteAuthenticationEndpoint.java index 74f2779a40c..1f4c03104e2 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/RemoteAuthenticationEndpoint.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/RemoteAuthenticationEndpoint.java @@ -63,10 +63,10 @@ public HttpEntity authenticate(HttpServletRequest reques } processAdditionalInformation(response, a); status = HttpStatus.OK; - } catch (AccountNotVerifiedException e) { + } catch (AccountNotVerifiedException _) { response.setError("account not verified"); status = HttpStatus.FORBIDDEN; - } catch (AuthenticationException e) { + } catch (AuthenticationException _) { response.setError("authentication failed"); } catch (Exception e) { logger.debug("Failed to authenticate user ", e); @@ -104,7 +104,7 @@ public HttpEntity authenticate(HttpServletRequest reques response.setUsername(a.getName()); processAdditionalInformation(response, a); status = HttpStatus.OK; - } catch (AuthenticationException e) { + } catch (AuthenticationException _) { response.setError("authentication failed"); } catch (Exception e) { logger.debug("Failed to authenticate user ", e); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/SessionResetFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/SessionResetFilter.java index ad21cec9249..1afa3e0f87f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/SessionResetFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/SessionResetFilter.java @@ -84,7 +84,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse redirect = true; } } - } catch (UsernameNotFoundException x) { + } catch (UsernameNotFoundException _) { logger.info("Authenticated user [{}] was not found in DB.", userId); redirect = true; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/UaaLoginHint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/UaaLoginHint.java index db03a5f9cca..6a1f254a36a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/UaaLoginHint.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/UaaLoginHint.java @@ -22,7 +22,7 @@ public static UaaLoginHint parseRequestParameter(String loginHint) { try { loginHint = URLDecoder.decode(loginHint, StandardCharsets.UTF_8); return mapper.readValue(loginHint, UaaLoginHint.class); - } catch (JacksonException e) { + } catch (JacksonException _) { return null; } } @@ -46,7 +46,7 @@ public void setOrigin(String origin) { public String toString() { try { return mapper.writeValueAsString(this); - } catch (JacksonException e) { + } catch (JacksonException _) { return super.toString(); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/WhitelistLogoutSuccessHandler.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/WhitelistLogoutSuccessHandler.java index 1ad34b5a109..263a235d9fa 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/WhitelistLogoutSuccessHandler.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/WhitelistLogoutSuccessHandler.java @@ -62,7 +62,7 @@ private Set getClientWhitelist(HttpServletRequest request) { List signatureVerifiers = keys.values().stream().map(KeyInfo::getVerifier).toList(); JwtTokenSignedByThisUAA jwtToken = buildIdTokenValidator(idToken, new ChainedSignatureVerifier(signatureVerifiers), keyInfoService); clientId = (String) jwtToken.getClaims().get(ClaimConstants.AZP); - } catch (InvalidTokenException e) { + } catch (InvalidTokenException _) { log.debug("Invalid token (could not verify signature)"); } } else { @@ -73,7 +73,7 @@ private Set getClientWhitelist(HttpServletRequest request) { try { ClientDetails client = clientDetailsService.loadClientByClientId(clientId, IdentityZoneHolder.get().getId()); redirectUris = client.getRegisteredRedirectUri(); - } catch (NoSuchClientException x) { + } catch (NoSuchClientException _) { log.debug("Unable to find client with ID:%s for logout redirect".formatted(clientId)); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/event/UserNotFoundEvent.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/event/UserNotFoundEvent.java index 1ffc903f9ec..8f7288920f4 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/event/UserNotFoundEvent.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/event/UserNotFoundEvent.java @@ -43,7 +43,7 @@ public AuditEvent getAuditEvent() { // Store hash of name, to conceal accidental entry of sensitive info // (e.g. password) name = Utf8.decode(Base64.getEncoder().encode(MessageDigest.getInstance("SHA-1").digest(Utf8.encode(name)))); - } catch (NoSuchAlgorithmException shouldNeverHappen) { + } catch (NoSuchAlgorithmException _) { name = "NOSHA"; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManager.java index f847109f163..bbefba8e4f8 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManager.java @@ -166,7 +166,7 @@ private UaaUser getUaaUser(Authentication req) { if (user != null) { return user; } - } catch (UsernameNotFoundException ignored) { + } catch (UsernameNotFoundException _) { } return null; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinAuthenticationManager.java index 513c8cd6add..722347362d7 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinAuthenticationManager.java @@ -108,7 +108,7 @@ public Authentication authenticate(Authentication authentication) throws Authent try { clientDetailsService.loadClientByClientId(clientId, IdentityZoneHolder.get().getId()); - } catch (NoSuchClientException x) { + } catch (NoSuchClientException _) { throw new BadCredentialsException("Cannot redeem provided code for user, client is missing"); } @@ -116,7 +116,7 @@ public Authentication authenticate(Authentication authentication) throws Authent try { user = userDatabase.retrieveUserById(userId); - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { throw new BadCredentialsException("Cannot redeem provided code for user, user is missing"); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManager.java index 010e8d08783..0c02b012ce1 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManager.java @@ -49,7 +49,7 @@ public Authentication authenticate(final Authentication authentication) throws A if (!idp.isActive()) { throw new ProviderNotFoundException("Identity Provider \"" + idp.getName() + "\" has been disabled by administrator."); } - } catch (EmptyResultDataAccessException x) { + } catch (EmptyResultDataAccessException _) { throw new ProviderNotFoundException("Unable to find identity provider for origin: " + getOrigin()); } return delegate.authenticate(authentication); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java index 00f35bce8f3..d6279f395a8 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java @@ -137,7 +137,7 @@ protected IdentityProvider getProvider(String origin, IdentityZone zone) { if (result != null) { return result; } - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { } IdentityProvider provider = new IdentityProvider(); provider.setOriginKey(origin); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManager.java index 6def53fc23e..3d9380b0c28 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManager.java @@ -111,7 +111,7 @@ public Authentication authenticate(Authentication request) throws Authentication try { logger.debug("Searching for user by (username:{} , origin:{})", userFromRequest.getUsername(), origin); userFromDb = userDatabase.retrieveUserByName(userFromRequest.getUsername(), origin); - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { logger.debug("Searching for user by (email:{} , origin:{})", userFromRequest.getEmail(), origin); userFromDb = userDatabase.retrieveUserByEmail(userFromRequest.getEmail(), origin); } @@ -124,7 +124,7 @@ public Authentication authenticate(Authentication request) throws Authentication publish(new NewUserAuthenticatedEvent(userFromRequest.authorities(List.of()))); try { userFromDb = userDatabase.retrieveUserByName(userFromRequest.getUsername(), origin); - } catch (UsernameNotFoundException ex) { + } catch (UsernameNotFoundException _) { throw new BadCredentialsException("Unable to register user in internal UAA store."); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManager.java index 483622285bd..8fa13acc21c 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManager.java @@ -86,14 +86,14 @@ public Authentication authenticate(Authentication request) throws Authentication addNewAccounts = false; user = userDatabase.retrieveUserById(user.getId()); } - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { // Not necessarily fatal if (addNewAccounts) { // Register new users automatically publish(new NewUserAuthenticatedEvent(user)); try { user = userDatabase.retrieveUserByName(user.getUsername(), user.getOrigin()); - } catch (UsernameNotFoundException ex) { + } catch (UsernameNotFoundException _) { throw new BadCredentialsException("Bad credentials"); } } else { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManager.java index 87db9773f22..3aeb3dd215a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManager.java @@ -98,7 +98,7 @@ && providerSupportsPasswordGrant(retrievedByOrigin) && (allowedProviders == null || allowedProviders.contains(useOrigin))) { return retrievedByOrigin; } - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrap.java b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrap.java index 955596874b9..92daa4a23bc 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrap.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrap.java @@ -121,7 +121,7 @@ private void updateAutoApproveClients() { base.addAdditionalInformation(ClientConstants.AUTO_APPROVE, true); logger.debug("Adding autoapprove flag to client: {}", clientId); clientRegistrationService.updateClientDetails(base, IdentityZone.getUaaZoneId()); - } catch (NoSuchClientException n) { + } catch (NoSuchClientException _) { logger.debug("Client not found, unable to set autoapprove: {}", clientId); } } @@ -135,7 +135,7 @@ private void updateAllowedPublicClients() { base.addAdditionalInformation(ClientConstants.ALLOW_PUBLIC, true); logger.debug("Adding allowpublic flag to client: {}", clientId); clientRegistrationService.updateClientDetails(base, IdentityZone.getUaaZoneId()); - } catch (NoSuchClientException n) { + } catch (NoSuchClientException _) { logger.debug("Client not found, unable to set allowpublic: {}", clientId); } } @@ -326,7 +326,7 @@ public void onApplicationEvent(ContextRefreshedEvent ignored) { logger.debug("Deleting client from manifest:{}", clientId); EntityDeletedEvent delete = new EntityDeletedEvent<>(client, auth, IdentityZoneHolder.getCurrentZoneId()); publish(delete); - } catch (NoSuchClientException e) { + } catch (NoSuchClientException _) { logger.debug("Ignoring delete for non existent client:{}", clientId); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpoints.java index 93a3a57c559..5d1c8e3d616 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpoints.java @@ -199,9 +199,9 @@ public Map getErrorCounts() { public ClientDetails getClientDetails(@PathVariable String client) { try { return removeSecret(clientDetailsService.retrieve(client, identityZoneManager.getCurrentIdentityZoneId())); - } catch (InvalidClientException e) { + } catch (InvalidClientException _) { throw new NoSuchClientException("No such client: " + client); - } catch (BadClientCredentialsException e) { + } catch (BadClientCredentialsException _) { // Defensive check, in case the clientDetailsService starts throwing // these instead throw new NoSuchClientException("No such client: " + client); @@ -429,7 +429,7 @@ public ClientDetailsModification[] changeSecretTx(@RequestBody SecretChangeReque } clientDetails[i] = removeSecret(clientDetails[i]); } - } catch (InvalidClientException e) { + } catch (InvalidClientException _) { throw new NoSuchClientException("No such client: " + clientId); } clientSecretChanges.getAndAdd(change.length); @@ -472,7 +472,7 @@ public SearchResults listClientDetails( if (count > clients.size()) { count = clients.size(); } - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { String msg = "Invalid filter expression: [" + filter + "]"; if (StringUtils.hasText(sortBy)) { msg += " [" + sortBy + "]"; @@ -492,7 +492,7 @@ public SearchResults listClientDetails( try { return SearchResultsFactory.buildSearchResultFrom(result, startIndex, count, clients.size(), attributes, attributeNameMapper, Collections.singletonList(SCIM_CLIENTS_SCHEMA_URI)); - } catch (SpelEvaluationException | SpelParseException e) { + } catch (SpelEvaluationException | SpelParseException _) { throw new UaaException("Invalid attributes: [" + attributesCommaSeparated + "]", HttpStatus.BAD_REQUEST.value()); } @@ -505,7 +505,7 @@ public ActionResult changeSecret(@PathVariable String client_id, @RequestBody Se ClientDetails clientDetails; try { clientDetails = clientDetailsService.retrieve(client_id, identityZoneManager.getCurrentIdentityZoneId()); - } catch (InvalidClientException e) { + } catch (InvalidClientException _) { throw new NoSuchClientException("No such client: " + client_id); } @@ -552,7 +552,7 @@ public ActionResult changeClientJwt(@PathVariable String client_id, @RequestBody UaaClientDetails uaaUaaClientDetails; try { uaaUaaClientDetails = (UaaClientDetails) clientDetailsService.retrieve(client_id, identityZoneManager.getCurrentIdentityZoneId()); - } catch (InvalidClientException e) { + } catch (InvalidClientException _) { throw new NoSuchClientException("No such client: " + client_id); } @@ -638,7 +638,7 @@ public ResponseEntity handleClientAlreadyExists(C private void incrementErrorCounts(Exception e) { String series = UaaStringUtils.getErrorName(e); - errorCounts.computeIfAbsent(series, k -> new AtomicInteger()).incrementAndGet(); + errorCounts.computeIfAbsent(series, _ -> new AtomicInteger()).incrementAndGet(); } @@ -670,13 +670,13 @@ private boolean authenticateClient(String clientId, String clientSecret) { if (curRequest != null) { authentication.setDetails(new UaaAuthenticationDetails(curRequest, clientId)); } - } catch (IllegalStateException x) { + } catch (IllegalStateException _) { //ignore - means no thread bound request found } try { Authentication auth = authenticationManager.authenticate(authentication); return auth.isAuthenticated(); - } catch (AuthenticationException e) { + } catch (AuthenticationException _) { return false; } catch (Exception e) { logger.debug("Unable to authenticate/validate {}", clientId, e); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidator.java b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidator.java index 3b0b5d05c4f..9f66ee9d340 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidator.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidator.java @@ -188,7 +188,7 @@ public ClientDetails validate(ClientDetails prototype, boolean create, boolean c ClientDetails caller = null; try { caller = clientDetailsService.retrieve(callerId, identityZoneManager.getCurrentIdentityZoneId()); - } catch (Exception e) { + } catch (Exception _) { // best effort to get the caller, but the caller might not belong to this zone. } if (callerId != null && caller != null) { @@ -284,20 +284,20 @@ public ClientDetails validate(ClientDetails prototype, boolean create, boolean c if (cjc != null) { try { ClientJwtConfiguration fromNested; - if (cjc instanceof String s) { - fromNested = ClientJwtConfiguration.readValue(s); - } else if (cjc instanceof Map map) { - fromNested = ClientJwtConfiguration.readValue( - JsonUtils.writeValueAsString(cjc)); - ClientJwtConfiguration credsOnly = ClientJwtConfiguration.fromJwtCredsValue( - map.get(ClientJwtConfiguration.JWT_CREDS)); - if (credsOnly != null) { - fromNested = ClientJwtConfiguration.merge( - fromNested != null ? fromNested : new ClientJwtConfiguration(), - credsOnly, false); + switch (cjc) { + case String s -> fromNested = ClientJwtConfiguration.readValue(s); + case Map map -> { + fromNested = ClientJwtConfiguration.readValue( + JsonUtils.writeValueAsString(cjc)); + ClientJwtConfiguration credsOnly = ClientJwtConfiguration.fromJwtCredsValue( + map.get(ClientJwtConfiguration.JWT_CREDS)); + if (credsOnly != null) { + fromNested = ClientJwtConfiguration.merge( + fromNested != null ? fromNested : new ClientJwtConfiguration(), + credsOnly, false); + } } - } else { - throw new InvalidClientDetailsException( + case null, default -> throw new InvalidClientDetailsException( "Invalid client_jwt_config in additionalInformation: expected String or Map"); } if (fromNested != null) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAuthenticationFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAuthenticationFilter.java index 13e5b98a838..5d8ad74ac78 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAuthenticationFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientAuthenticationFilter.java @@ -86,7 +86,7 @@ public void afterPropertiesSet() { try { oauth2Available = ClassUtils.isPresent(AccessTokenRequiredException.class.getName(), ClassUtils.getDefaultClassLoader()); - } catch (NoClassDefFoundError e) { + } catch (NoClassDefFoundError _) { // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientMetadataAdminEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientMetadataAdminEndpoints.java index 0f5921dd9e7..a9284385e1e 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientMetadataAdminEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/client/ClientMetadataAdminEndpoints.java @@ -44,7 +44,7 @@ public ClientMetadataAdminEndpoints(final @Qualifier("jdbcClientMetadataProvisio public ClientMetadata retrieveClientMetadata(@PathVariable("client") String clientId) { try { return clientMetadataProvisioning.retrieve(clientId, IdentityZoneHolder.get().getId()); - } catch (EmptyResultDataAccessException erdae) { + } catch (EmptyResultDataAccessException _) { throw new ClientMetadataException("No client metadata found for " + clientId, HttpStatus.NOT_FOUND); } } @@ -72,7 +72,7 @@ public ClientMetadata updateClientMetadata(@RequestBody ClientMetadata clientMet } try { return clientMetadataProvisioning.update(clientMetadata, IdentityZoneHolder.get().getId()); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new ClientMetadataException("No client with ID " + clientMetadata.getClientId(), HttpStatus.NOT_FOUND); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioning.java b/server/src/main/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioning.java index 1ce1e95b486..d580fea95b1 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioning.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioning.java @@ -114,7 +114,7 @@ public ClientMetadata mapRow(ResultSet rs, int rowNum) throws SQLException { clientMetadata.setShowOnHomePage(rs.getBoolean("show_on_home_page")); try { clientMetadata.setAppLaunchUrl(new URL(rs.getString("app_launch_url"))); - } catch (MalformedURLException mue) { + } catch (MalformedURLException _) { // it is safe to ignore this as client_metadata rows are always created from a ClientMetadata instance whose launch url property is strongly typed to URL } byte[] iconBytes = rs.getBytes("app_icon"); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/client/event/ClientAdminEventPublisher.java b/server/src/main/java/org/cloudfoundry/identity/uaa/client/event/ClientAdminEventPublisher.java index 02dd434e6d0..9e5940781fe 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/client/event/ClientAdminEventPublisher.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/client/event/ClientAdminEventPublisher.java @@ -123,7 +123,7 @@ public void clientJwtChange(String clientId) { private ClientDetails getClient(String clientId) { try { return clientDetailsService.loadClientByClientId(clientId, identityZoneManager.getCurrentIdentityZoneId()); - } catch (InvalidClientException e) { + } catch (InvalidClientException _) { return null; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/CodeStoreEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/CodeStoreEndpoints.java index bafa7dbbf16..f9b47ac1524 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/CodeStoreEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/CodeStoreEndpoints.java @@ -35,11 +35,11 @@ public class CodeStoreEndpoints { public ExpiringCode generateCode(@RequestBody ExpiringCode expiringCode) { try { return expiringCodeStore.generateCode(expiringCode.getData(), expiringCode.getExpiresAt(), null, identityZoneManager.getCurrentIdentityZoneId()); - } catch (NullPointerException e) { + } catch (NullPointerException _) { throw new CodeStoreException("data and expiresAt are required.", HttpStatus.BAD_REQUEST); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { throw new CodeStoreException("expiresAt must be in the future.", HttpStatus.BAD_REQUEST); - } catch (DataIntegrityViolationException e) { + } catch (DataIntegrityViolationException _) { throw new CodeStoreException("Duplicate code generated.", HttpStatus.INTERNAL_SERVER_ERROR); } } @@ -50,7 +50,7 @@ public ExpiringCode retrieveCode(@PathVariable String code) { ExpiringCode result; try { result = expiringCodeStore.retrieveCode(code, identityZoneManager.getCurrentIdentityZoneId()); - } catch (NullPointerException e) { + } catch (NullPointerException _) { throw new CodeStoreException("code is required.", HttpStatus.BAD_REQUEST); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStore.java b/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStore.java index 8b743de3bef..f0625e5a626 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStore.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStore.java @@ -126,7 +126,7 @@ public ExpiringCode peekCode(String code, String zoneId) { expiringCode = null; } return expiringCode; - } catch (EmptyResultDataAccessException x) { + } catch (EmptyResultDataAccessException _) { return null; } } @@ -148,7 +148,7 @@ public ExpiringCode retrieveCode(String code, String zoneId) { expiringCode = null; } return expiringCode; - } catch (EmptyResultDataAccessException x) { + } catch (EmptyResultDataAccessException _) { return null; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase.java b/server/src/main/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase.java index 316459a3e27..c307ddff8ac 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase.java @@ -133,7 +133,7 @@ private void addToMap(IdentityZone zone, Map> zones, } } - private final RowMapper mapper = (rs, rowNum) -> { + private final RowMapper mapper = (rs, _) -> { IdentityZone identityZone = new IdentityZone(); identityZone.setId(rs.getString(1).trim()); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/error/UaaException.java b/server/src/main/java/org/cloudfoundry/identity/uaa/error/UaaException.java index c6c5a972642..ccce21df86a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/error/UaaException.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/error/UaaException.java @@ -101,7 +101,7 @@ public static UaaException valueOf(Map errorParams) { if (errorParams.containsKey(STATUS_STRING)) { try { status = Integer.valueOf(errorParams.get(STATUS_STRING)); - } catch (NumberFormatException e) { + } catch (NumberFormatException _) { // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/CustomPropertyConstructor.java b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/CustomPropertyConstructor.java index debf643b5c3..3c2f95147d1 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/CustomPropertyConstructor.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/CustomPropertyConstructor.java @@ -61,7 +61,7 @@ TypeDescription createTypeDescription(Class clazz) { * @param name the bean property name */ protected final void addPropertyAlias(String alias, Class type, String name) { - Map typeMap = properties.computeIfAbsent(type, k -> new HashMap<>()); + Map typeMap = properties.computeIfAbsent(type, _ -> new HashMap<>()); Property property = propertyUtils.getProperty(type, name); typeMap.put(alias, property); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityProviderBootstrap.java b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityProviderBootstrap.java index 3e51c16bbbf..ba664f3f057 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityProviderBootstrap.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityProviderBootstrap.java @@ -247,7 +247,7 @@ public void afterPropertiesSet() throws Exception { public IdentityProvider getProviderByOriginIgnoreActiveFlag(String origin, String zoneId) { try { return provisioning.retrieveByOriginIgnoreActiveFlag(origin, zoneId); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { return null; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityZoneConfigurationBootstrap.java b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityZoneConfigurationBootstrap.java index 0e68c76f8d0..8726a2e600f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityZoneConfigurationBootstrap.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/IdentityZoneConfigurationBootstrap.java @@ -75,7 +75,7 @@ public class IdentityZoneConfigurationBootstrap implements InitializingBean { private UserConfig defaultUserConfig; - private IdentityZoneValidator validator = (config, mode) -> config; + private IdentityZoneValidator validator = (config, _) -> config; private Map branding; public IdentityZoneConfigurationBootstrap(IdentityZoneProvisioning provisioning) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfiguration.java b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfiguration.java index 2502e546322..b204d2c480f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfiguration.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfiguration.java @@ -351,7 +351,7 @@ public Object construct(Node node) { } } - public static void main(String[] args) throws Exception { + void main(String[] args) throws Exception { if (args.length != 1) { throw new IllegalArgumentException("YAML file required"); } @@ -362,7 +362,7 @@ public static void main(String[] args) throws Exception { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set> errors = validator.validate(config); - System.out.println(errors); + IO.println(errors); } } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializer.java b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializer.java index 9ff8e6d4975..2b4bc84b899 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializer.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializer.java @@ -88,7 +88,7 @@ public void initialize(ConfigurableWebApplicationContext applicationContext) { ServletConfig servletConfig = null; try { servletConfig = applicationContext.getServletConfig(); - } catch (UnsupportedOperationException ignore) { + } catch (UnsupportedOperationException _) { System.err.println("Unable to load Servlet Context - are you testing?"); } WebApplicationContextUtils.initServletPropertySources(applicationContext.getEnvironment().getPropertySources(), @@ -111,7 +111,7 @@ public void initialize(ConfigurableWebApplicationContext applicationContext) { } try { - System.out.println("Loading YAML environment properties from location: " + resources.toString()); + IO.println("Loading YAML environment properties from location: " + resources.toString()); YamlMapFactoryBean factory = new YamlMapFactoryBean(); factory.setResolutionMethod(YamlProcessor.ResolutionMethod.OVERRIDE_AND_IGNORE); @@ -138,14 +138,14 @@ private static List getSecretsFiles( .getEnvironment() .resolvePlaceholders(SECRETS_DIR_VAR); - System.out.println(SECRETS_DIR_VAR + " resolves to " + resolvedSecretsLocation); + IO.println(SECRETS_DIR_VAR + " resolves to " + resolvedSecretsLocation); final File[] secretFiles = - ofNullable(new File(resolvedSecretsLocation).listFiles((dir, name) -> name != null && name.endsWith(".yml"))) + ofNullable(new File(resolvedSecretsLocation).listFiles((_, name) -> name != null && name.endsWith(".yml"))) .orElse(new File[]{}); if (secretFiles.length == 0) { - System.out.println("Found no .yml files in " + SECRETS_DIR_VAR); + IO.println("Found no .yml files in " + SECRETS_DIR_VAR); } return Arrays.stream(secretFiles) @@ -195,15 +195,15 @@ private void applyLog4jConfiguration(ConfigurableEnvironment environment, String if (location != null && !location.trim().isEmpty()) { PropertySource environmentPropertySource = environment.getPropertySources().get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); if (location.startsWith("-D") && environmentPropertySource != null && location.equals(environmentPropertySource.getProperty("LOGGING_CONFIG"))) { - System.out.println("Ignoring Log Config Location: " + location + ". Location is suspect to be a Tomcat startup script environment variable"); + IO.println("Ignoring Log Config Location: " + location + ". Location is suspect to be a Tomcat startup script environment variable"); } else { - System.out.println("Setting Log Config Location: " + location + " based on logging.config setting."); + IO.println("Setting Log Config Location: " + location + " based on logging.config setting."); log4jConfigLocation = environment.getProperty("logging.config"); } } } - System.out.println("Loading log4j config from location: " + log4jConfigLocation); + IO.println("Loading log4j config from location: " + log4jConfigLocation); try { String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(log4jConfigLocation); URL url = ResourceUtils.getURL(resolvedLocation); @@ -244,7 +244,7 @@ static void applySpringProfiles(ConfigurableEnvironment environment) { private static void setActiveProfiles( final ConfigurableEnvironment environment, final String[] profiles) { - System.out.println("Setting active profiles: " + Arrays.toString(profiles)); + IO.println("Setting active profiles: " + Arrays.toString(profiles)); environment.setActiveProfiles(profiles); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/EmailInvitationsService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/EmailInvitationsService.java index 5cf72fe9a6c..8b8c594d1e0 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/EmailInvitationsService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/EmailInvitationsService.java @@ -81,7 +81,7 @@ public AcceptedInvitation acceptInvitation(String code, String password) { ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId, identityZoneManager.getCurrentIdentityZoneId()); Set redirectUris = clientDetails.getRegisteredRedirectUri(); redirectLocation = UaaUrlUtils.findMatchingRedirectUri(redirectUris, redirectUri, redirectLocation); - } catch (NoSuchClientException x) { + } catch (NoSuchClientException _) { logger.debug("Unable to find client_id for invitation:{}", clientId); } catch (Exception x) { logger.error("Unable to resolve redirect for clientID:{}", clientId, x); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsController.java b/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsController.java index e66afe37e56..e17d5bbb956 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsController.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsController.java @@ -168,7 +168,7 @@ public String acceptInvitePage(@RequestParam String code, Model model, HttpServl } updateModelWithConsentAttributes(model); return "invitations/accept_invite"; - } catch (EmptyResultDataAccessException noProviderFound) { + } catch (EmptyResultDataAccessException _) { log.debug("No available invitation providers for email:%s, id:%s".formatted(codeData.get(EMAIL), codeData.get("user_id"))); return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite"); } @@ -282,7 +282,7 @@ public String acceptInvitation(@RequestParam("password") String password, AcceptedInvitation invitation; try { invitation = invitationsService.acceptInvitation(newCode, password); - } catch (HttpClientErrorException e) { + } catch (HttpClientErrorException _) { return handleUnprocessableEntity(model, response, "error_message_code", "code_expired", "invitations/accept_invite"); } String res = "redirect:/login?success=invite_accepted"; @@ -303,7 +303,7 @@ private String processErrorReload(String code, Model model, RedirectAttributes r redirectAttributes.addAttribute("code", newCode); //return an absolute, within the app, link return "redirect:/invitations/accept"; - } catch (EmptyResultDataAccessException noProviderFound) { + } catch (EmptyResultDataAccessException _) { log.debug("No available invitation providers for email:%s, id:%s".formatted(codeData.get(EMAIL), codeData.get("user_id"))); return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite"); } @@ -330,7 +330,7 @@ public String acceptLdapInvitation(@RequestParam("enterprise_username") String u ldapProvider = identityProviderProvisioning.retrieveByOrigin(OriginKeys.LDAP, identityZoneManager.getCurrentIdentityZoneId()); zoneAwareAuthenticationManager.getLdapAuthenticationManager(identityZoneManager.getCurrentIdentityZone(), ldapProvider).getLdapAuthenticationManager(); authenticationManager = zoneAwareAuthenticationManager.getLdapAuthenticationManager(identityZoneManager.getCurrentIdentityZone(), ldapProvider).getLdapManagerActual(); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { //ldap provider was not available return handleUnprocessableEntity(model, response, "error_message_code", "no_suitable_idp", "invitations/accept_invite"); } catch (Exception x) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpoint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpoint.java index c7415a606f9..b87a446d6c0 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpoint.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpoint.java @@ -119,7 +119,7 @@ public ResponseEntity inviteUsers(@RequestBody InvitationsR try { URL inviteLink = new URL(invitationLink); invitationsResponse.getNewInvites().add(InvitationsResponse.success(user.getPrimaryEmail(), user.getId(), user.getOrigin(), inviteLink)); - } catch (MalformedURLException mue) { + } catch (MalformedURLException _) { invitationsResponse.getFailedInvites().add(InvitationsResponse.failure(email, "invitation.exception.url", "Malformed url: %s".formatted(invitationLink))); } } else if (providers.isEmpty()) { @@ -131,7 +131,7 @@ public ResponseEntity inviteUsers(@RequestBody InvitationsR invitationsResponse.getFailedInvites().add(InvitationsResponse.failure(email, "email.invalid", email + " is invalid email.")); } - } catch (ScimResourceConflictException x) { + } catch (ScimResourceConflictException _) { invitationsResponse.getFailedInvites().add(InvitationsResponse.failure(email, "user.ambiguous", "Multiple users with the same origin matched to the email address.")); } catch (UaaException uaae) { invitationsResponse.getFailedInvites().add(InvitationsResponse.failure(email, "invitation.exception", uaae.getMessage())); @@ -164,7 +164,7 @@ private boolean validateEmail(String email) { try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); - } catch (AddressException e) { + } catch (AddressException _) { valid = false; } return valid; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtil.java b/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtil.java index 4a5415ba1cd..f67f15a969b 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtil.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtil.java @@ -109,7 +109,7 @@ public static long parseDurationToSeconds(String duration) { case "y" -> value * 365 * 24 * 60 * 60; // years (365 days) default -> DEFAULT_SESSION_DURATION; }; - } catch (NumberFormatException e) { + } catch (NumberFormatException _) { return DEFAULT_SESSION_DURATION; // Default: if not parsable } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java index ed6d80d0500..76e5f630748 100755 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpoint.java @@ -181,7 +181,7 @@ public LoginInfoEndpoint( private static Properties tryLoadAllProperties(final String fileName) { try { return PropertiesLoaderUtils.loadAllProperties(fileName); - } catch (IOException ignored) { + } catch (IOException _) { return new Properties(); } } @@ -192,7 +192,7 @@ private static List getSavedAccounts(Cookie[] .map(c -> { try { return JsonUtils.readValue(decodeCookieValue(c.getValue()), clazz); - } catch (JsonUtilException e) { + } catch (JsonUtilException _) { return null; } }) @@ -315,7 +315,7 @@ private String login(Model model, Principal principal, List excludedProm samlIdentityProviders.put(idp.getOriginKey(), samlConfig); } } - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { // ignore } } @@ -356,7 +356,7 @@ private String login(Model model, Principal principal, List excludedProm ldapIdentityProvider = providerProvisioning.retrieveByOrigin( OriginKeys.LDAP, IdentityZoneHolder.get().getId() ); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { // ignore } IdentityProvider uaaIdentityProvider = @@ -692,7 +692,7 @@ private IdentityProvider getIdentityProviderByOrigin(List allowedIdps, S if (originKey != null && (allowedIdps == null || allowedIdps.contains(originKey))) { identityProvider = providerProvisioning.retrieveByOrigin(originKey, IdentityZoneHolder.get().getId()); } - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { // ignore } return identityProvider; @@ -728,7 +728,7 @@ private Map getClientInfo(HttpSession session) { try { ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientIds[0], IdentityZoneHolder.get().getId()); return clientDetails.getAdditionalInformation(); - } catch (NoSuchClientException x) { + } catch (NoSuchClientException _) { return null; } } @@ -787,7 +787,7 @@ private void populatePrompts( IdentityProvider providerForOrigin = null; try { providerForOrigin = providerProvisioning.retrieveByOrigin(origin, IdentityZoneHolder.get().getId()); - } catch (DataAccessException ignored) { + } catch (DataAccessException _) { // ignore } if (providerForOrigin != null && providerForOrigin.getConfig() instanceof OIDCIdentityProviderDefinition oidcConfig) { @@ -845,7 +845,7 @@ public String discoverIdentityProvider(@RequestParam String email, @RequestParam String[] clientIds = savedRequest.getParameterValues(CLIENT_ID_PARAMETER); try { clientDetails = clientDetailsService.loadClientByClientId(clientIds[0], IdentityZoneHolder.get().getId()); - } catch (NoSuchClientException ignored) { + } catch (NoSuchClientException _) { // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/message/util/FakeJavaMailSender.java b/server/src/main/java/org/cloudfoundry/identity/uaa/message/util/FakeJavaMailSender.java index 0cef4203f29..13e9c84750a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/message/util/FakeJavaMailSender.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/message/util/FakeJavaMailSender.java @@ -147,7 +147,7 @@ public String toString() { sb.append("From=").append(Arrays.toString(getFrom().toArray())); sb.append("; To=").append(Arrays.toString(getRecipients(Message.RecipientType.TO).toArray())); sb.append("; Content=").append(getContentString()); - } catch (MessagingException | IOException x) { + } catch (MessagingException | IOException _) { sb.append("Message=").append(mimeMessage); } sb.append('}'); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/IntrospectEndpoint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/IntrospectEndpoint.java index 7b5943625a4..ead54a4c11e 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/IntrospectEndpoint.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/IntrospectEndpoint.java @@ -42,7 +42,7 @@ public IntrospectionClaims introspect(@RequestParam String token) { resourceServerTokenServices.loadAuthentication(token); introspectionClaims = UaaTokenUtils.getClaims(oAuth2AccessToken.getValue(), IntrospectionClaims.class); introspectionClaims.setActive(true); - } catch (InvalidTokenException e) { + } catch (InvalidTokenException _) { introspectionClaims.setActive(false); return introspectionClaims; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/KeyInfo.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/KeyInfo.java index 1dd28e49f61..1055a7c0e88 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/KeyInfo.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/KeyInfo.java @@ -186,7 +186,7 @@ private Optional getValidX509Certificate(String pemEncoded) { x509Certificate.checkValidity(); return Optional.of(x509Certificate); } - } catch (RuntimeException | CertificateExpiredException | CertificateNotYetValidException e) { + } catch (RuntimeException | CertificateExpiredException | CertificateNotYetValidException _) { // ignore } return Optional.empty(); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/TokenValidationService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/TokenValidationService.java index d4b98528924..2f068efe943 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/TokenValidationService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/TokenValidationService.java @@ -42,7 +42,7 @@ public JwtTokenSignedByThisUAA validateToken(String token, boolean isAccessToken RevocableToken revocableToken; try { revocableToken = revocableTokenProvisioning.retrieve(token, IdentityZoneHolder.get().getId()); - } catch (EmptyResultDataAccessException ex) { + } catch (EmptyResultDataAccessException _) { throw new TokenRevokedException("The token expired, was revoked, or the token ID is incorrect."); } token = revocableToken.getValue(); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpoint.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpoint.java index 9ac74102177..237a1da78c2 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpoint.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpoint.java @@ -173,7 +173,7 @@ public ModelAndView authorize(Map model, AuthorizationRequest authorizationRequest; try { authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters); - } catch (DisallowedIdpException x) { + } catch (DisallowedIdpException _) { return switchIdp(model, client, clientId, request); } @@ -195,7 +195,7 @@ public ModelAndView authorize(Map model, String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); try { resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); - } catch (RedirectMismatchException rme) { + } catch (RedirectMismatchException _) { throw new RedirectMismatchException( "Invalid redirect " + redirectUriParameter + " did not match one of the registered values"); } @@ -331,7 +331,7 @@ public void commence(HttpServletRequest request, HttpServletResponse response, A String resolvedRedirect; try { resolvedRedirect = redirectResolver.resolveRedirect(redirectUri, client); - } catch (RedirectMismatchException rme) { + } catch (RedirectMismatchException _) { logger.debug("[prompt=none] Invalid redirect " + redirectUri + " did not match one of the registered values"); response.setStatus(HttpStatus.BAD_REQUEST.value()); return; @@ -804,7 +804,7 @@ private ModelAndView handleException(Exception e, ServletWebRequest webRequest) String redirect = getUnsuccessfulRedirect(authorizationRequest, translate.getBody(), authorizationRequest .getResponseTypes().contains("token")); return new ModelAndView(new RedirectView(redirect, false, true, false)); - } catch (OAuth2Exception ex) { + } catch (OAuth2Exception _) { // If an AuthorizationRequest cannot be created from the incoming parameters it must be // an error. OAuth2Exception can be handled this way. Other exceptions will generate a standard 500 // response. @@ -832,7 +832,7 @@ private AuthorizationRequest getAuthorizationRequestForError(ServletWebRequest w try { return getOAuth2RequestFactory().createAuthorizationRequest(parameters); - } catch (Exception e) { + } catch (Exception _) { return getDefaultOAuth2RequestFactory().createAuthorizationRequest(parameters); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManager.java index ecac542b4ce..936a1d8a73a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManager.java @@ -210,7 +210,7 @@ protected void checkClientIdpAuthorization(UaaClientDetails client, UaaUser user if (provider == null || !allowedProviders.contains(provider.getOriginKey())) { throw new DisallowedIdpException("Client is not authorized for specified user's identity provider."); } - } catch (EmptyResultDataAccessException x) { + } catch (EmptyResultDataAccessException _) { //this should not happen...but if it does throw new UnauthorizedClientException("User does not belong to a valid identity provider."); } @@ -317,7 +317,7 @@ public TokenRequest createTokenRequest(Map requestParameters, Cl if (hasText(audience)) { try { targetClient = clientDetailsService.loadClientByClientId(audience, identityZoneManager.getCurrentIdentityZoneId()); - } catch (ClientRegistrationException r) { + } catch (ClientRegistrationException _) { throw new InvalidClientException("Invalid audience("+audience+") for "+ GRANT_TYPE_TOKEN_EXCHANGE+ " grant."); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServices.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServices.java index f38dce28336..c6cbebdd8b1 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServices.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServices.java @@ -492,7 +492,7 @@ private CompositeToken createCompositeToken(String tokenId, IdToken idTokenContent; try { idTokenContent = idTokenCreator.create(clientDetails, user, userAuthenticationData, tokenActor); - } catch (RuntimeException | IdTokenCreationException ignored) { + } catch (RuntimeException | IdTokenCreationException _) { throw new IllegalStateException("Cannot convert id token to JSON"); } String encodedIdTokenContent = JwtHelper.encode(idTokenContent.getClaimMap(), keyInfoService.getActiveKey()).getEncoded(); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java index f7b37a86077..14cb7a01779 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java @@ -154,7 +154,7 @@ public OAuth2Authentication consumeAuthorizationCode(String code) throws Invalid template.update(SQL_DELETE_STATEMENT, code); } } - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { } throw new InvalidGrantException("Invalid authorization code: " + code); } @@ -246,7 +246,7 @@ private void actuallyPerformExpirationClean(Instant now) { logger.debug("[oauth_code] Removed {} expired entries.", expired); expired = template.update(SQL_CLEAN_STATEMENT, Timestamp.from(now.minus(LEGACY_CODE_EXPIRATION_TIME))); logger.debug("[oauth_code] Removed {} old entries.", expired); - } catch (DeadlockLoserDataAccessException e) { + } catch (DeadlockLoserDataAccessException _) { logger.debug("[oauth code] Deadlock trying to expire entries, ignored."); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolver.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolver.java index d8b639b6b03..27d1c56c886 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolver.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolver.java @@ -131,7 +131,7 @@ private static String normalizeWildcardUri(String uriClient) { if (hasWildcarPort) { uriComponentsBuilder.port(99999); } - } catch (NullPointerException e) { + } catch (NullPointerException _) { throw new IllegalArgumentException("URI host and scheme must not be null"); } @@ -150,7 +150,7 @@ private static void redactQueryParams(UriComponentsBuilder builder) { MultiValueMap originalParams = builder.build().getQueryParams(); Map> redactedParams = originalParams.entrySet() .stream() - .map(e -> new SimpleEntry<>(e.getKey(), e.getValue().stream().map(v -> "REDACTED").toList())) + .map(e -> new SimpleEntry<>(e.getKey(), e.getValue().stream().map(_ -> "REDACTED").toList())) .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); builder.replaceQueryParams(new LinkedMultiValueMap<>(redactedParams)); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java index 1f9f2b29802..a3e5f7d5cf0 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java @@ -129,7 +129,7 @@ protected boolean redirectMatches(String requestedRedirect, String redirectUri) return StringUtils.cleanPath(req.getPath()).startsWith(StringUtils.cleanPath(reg.getPath())); } } - catch (MalformedURLException ignored) { + catch (MalformedURLException _) { } return requestedRedirect.equals(redirectUri); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthentication.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthentication.java index 5278d8b5e83..081e244c31c 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthentication.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthentication.java @@ -226,7 +226,7 @@ private boolean validateFederatedClientJWT(JWT jwtAssertion, JWTClaimsSet client JWKSet jwkSet = retrieveJwkSet(clientClaims); String expectedAud = Optional.ofNullable(jwtFederation.getAudience()).orElse(keyInfoService.getTokenEndpointUrl()); return validateClientJWToken(jwtAssertion, jwkSet, JWT_RFC7523_CLAIMS, jwtFederation.getSubject(), jwtFederation.getIssuer(), expectedAud) != null; - } catch (MalformedURLException | IllegalArgumentException | URISyntaxException e) { + } catch (MalformedURLException | IllegalArgumentException | URISyntaxException _) { return false; } } @@ -247,7 +247,7 @@ private JWKSet getTrustedJwksSet(String issuer) throws OidcMetadataFetchingExcep if (idp.getConfig() instanceof OIDCIdentityProviderDefinition oidcDefinition) { def = oidcDefinition; } - } catch (DataRetrievalFailureException dataRetrievalFailureException) { + } catch (DataRetrievalFailureException _) { // ignore, but retrieve trust by OIDC compliant issuer } if (def == null) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelper.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelper.java index 0c2c91d3765..77e9ccafea0 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelper.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelper.java @@ -262,7 +262,7 @@ private JWTClaimsSet validateClientJWToken(JWT jwtAssertion, JWKSet jwkSet) { return jwtProcessor.process(jwtAssertion, null); } catch (BadJWSException | BadJWTException jwtException) { // signature failed throw new InvalidSignatureException("Unauthorized token", jwtException); - } catch (KeyLengthException ke) { + } catch (KeyLengthException _) { return UaaMacSigner.verify(jwtAssertion.getParsedString(), jwkSet); } catch (BadJOSEException | JOSEException e) { // key resolution, structure of JWT failed throw new InvalidSignatureException("Untrusted token", e); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifier.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifier.java index 1087f2e4e76..ab04fc0216a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifier.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifier.java @@ -90,7 +90,7 @@ public JWKSet getJwkSet(String keyId) { Map keyMap = new HashMap<>(delegate.getKeyProperties()); keyMap.put(HeaderParameterNames.KEY_ID, keyId); return new JWKSet(JWK.parse(keyMap)); - } catch (ParseException e) { + } catch (ParseException _) { // ignore } return new JWKSet(); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenGranter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenGranter.java index 670b9473ddd..564791cc651 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenGranter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenGranter.java @@ -52,7 +52,7 @@ public boolean shouldSendIdToken(UaaUser user, approvalService.ensureRequiredApprovals( user.getId(), Sets.newHashSet(REQUIRED_OPENID_SCOPE), requestedGrantType, clientDetails ); - } catch (InvalidTokenException e) { + } catch (InvalidTokenException _) { return false; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/authentication/OAuth2AuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/authentication/OAuth2AuthenticationManager.java index 45e0951d3d4..72324584d55 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/authentication/OAuth2AuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/authentication/OAuth2AuthenticationManager.java @@ -94,7 +94,7 @@ private void checkClientDetails(OAuth2Authentication auth) { try { client = clientDetailsService.loadClientByClientId(auth.getOAuth2Request().getClientId()); } - catch (ClientRegistrationException e) { + catch (ClientRegistrationException _) { throw new OAuth2AccessDeniedException("Invalid token contains invalid client id"); } Set allowed = client.getScope(); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilter.java index fbc2495cd47..ee3242845bc 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilter.java @@ -128,7 +128,7 @@ protected String calculateCurrentUri(HttpServletRequest request) { UriComponents uri = null; try { uri = builder.replaceQueryParam("code").build(true); - } catch (IllegalArgumentException ex) { + } catch (IllegalArgumentException _) { // ignore failures to parse the url (including query string). does't // make sense for redirection purposes anyway. return null; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/code/JdbcAuthorizationCodeServices.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/code/JdbcAuthorizationCodeServices.java index 5e226422358..8ecc78acee9 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/code/JdbcAuthorizationCodeServices.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/code/JdbcAuthorizationCodeServices.java @@ -56,7 +56,7 @@ public OAuth2Authentication mapRow(ResultSet rs, int rowNum) return SerializationUtils.deserialize(rs.getBytes("authentication")); } }, code); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { return null; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranter.java index be93a629df1..ada20446ada 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranter.java @@ -68,7 +68,7 @@ protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, Tok // If the username/password are wrong the spec says we should send 400/invalid grant throw new InvalidGrantException(e.getMessage()); } - catch (UsernameNotFoundException e) { + catch (UsernameNotFoundException _) { // If the user is not found, report a generic error message throw new InvalidGrantException("username not found"); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranter.java index f323593a1f3..8f5cfcb1502 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranter.java @@ -41,7 +41,7 @@ protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest to catch (AccountStatusException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { // If the user is not found, report a generic error message throw new InvalidGrantException("user not found"); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/TokenExchangeGranter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/TokenExchangeGranter.java index 37cc0d0057e..882c01a72b6 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/TokenExchangeGranter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/token/TokenExchangeGranter.java @@ -82,14 +82,14 @@ protected Authentication validateRequest(TokenRequest request) { if (!client.getAuthorizedGrantTypes().contains(GRANT_TYPE_TOKEN_EXCHANGE)) { throw new InvalidGrantException("Unsupported grant type"); } - } catch (ClientRegistrationException e) { + } catch (ClientRegistrationException _) { throw new InvalidGrantException("Invalid client_id"); } String audience = request.getRequestParameters().get("audience"); if (hasText(audience)) { try { clientDetailsService.loadClientByClientId(audience); - } catch (ClientRegistrationException e) { + } catch (ClientRegistrationException _) { throw new InvalidGrantException("Invalid audience"); } String requiredImpersonationAuthority = @@ -139,7 +139,7 @@ protected TokenActor getTokenActor(TokenRequest tokenRequest) { try { RevocableToken revocableToken = revocableTokenProvisioning.retrieve(subjectToken, IdentityZoneHolder.get().getId()); subjectToken = revocableToken.getValue(); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new InvalidGrantException("Invalid subject_token: not a JWT and not found in the revocable token store"); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandler.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandler.java index 40da5581fd1..e870a372f02 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandler.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandler.java @@ -79,7 +79,7 @@ protected Optional> retrieveEntity(final String id, final St final IdentityProvider identityProvider; try { identityProvider = identityProviderProvisioning.retrieve(id, zoneId); - } catch (final EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException _) { LOGGER.warn("The IdP with ID '{}' does not exist in the zone '{}'.", id, zoneId); return Optional.empty(); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpoints.java index b34e1f01c2d..71d688efc21 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpoints.java @@ -232,11 +232,11 @@ private ResponseEntity persistIdentityProviderChange(IdentityP IdentityProvider existing, HttpStatus status) { final IdentityProvider updatedIdp; try { - updatedIdp = transactionTemplate.execute(txStatus -> { + updatedIdp = transactionTemplate.execute(_ -> { final IdentityProvider updatedOriginalIdp = status == CREATED ? identityProviderProvisioning.create(body, zoneId) : identityProviderProvisioning.update(body, zoneId); return idpAliasHandler.ensureConsistencyOfAliasEntity(updatedOriginalIdp, existing); }); - } catch (final IdpAlreadyExistsException e) { + } catch (final IdpAlreadyExistsException _) { return new ResponseEntity<>(body, CONFLICT); } catch (final EntityAliasFailedException e) { logger.warn("Could not create alias for %s".formatted(e.getMessage())); @@ -337,7 +337,7 @@ public ResponseEntity testIdentityProvider(@RequestBody IdentityProvider if ((result == null) || (!result.isAuthenticated())) { status = EXPECTATION_FAILED; } - } catch (BadCredentialsException x) { + } catch (BadCredentialsException _) { status = EXPECTATION_FAILED; exception = "bad credentials"; } catch (InternalAuthenticationServiceException x) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioning.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioning.java index 7eb8d22b34b..a3068b769a7 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioning.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioning.java @@ -99,7 +99,7 @@ public List retrieveActiveByTypes(final String zoneId, final S final Set typesAsSet = new HashSet<>(Arrays.asList(types)); // adjust the number of SQL parameters in the prepared statement - final String sqlPlaceholdersForTypes = typesAsSet.stream().map(type -> "?").collect(joining(",")); + final String sqlPlaceholdersForTypes = typesAsSet.stream().map(_ -> "?").collect(joining(",")); final String sql = IDENTITY_ACTIVE_PROVIDERS_OF_TYPE_QUERY_TEMPLATE.formatted(sqlPlaceholdersForTypes); final ArrayList arrayList = new ArrayList<>(typesAsSet.size() + 2); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparator.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparator.java index 80b9ac128ee..ebc141bdf2e 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparator.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparator.java @@ -36,9 +36,9 @@ public boolean matches(CharSequence rawPassword, String encodedPassword) { throw new UnsupportedOperationException(); } - public static void main(String[] args) { + void main() { LdapSecurityConstants test = PasswordUtil.findAlgorithm("{sha}YaE1CJ6sVhov987e77A5db7QAPg=".getBytes()); - System.out.println(test); + IO.println(test); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/ExtendedLdapUserMapper.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/ExtendedLdapUserMapper.java index ad43e65d020..d6eda9ace10 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/ExtendedLdapUserMapper.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/ExtendedLdapUserMapper.java @@ -71,7 +71,7 @@ public UserDetails mapUserFromContext(DirContextOperations ctx, String username, } else { record.put(attributeName, values); } - } catch (ArrayStoreException x) { + } catch (ArrayStoreException _) { logger.debug("Attribute value is not a string for '{}'", attributeName); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/PasswordComparisonAuthenticator.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/PasswordComparisonAuthenticator.java index a4aceec575c..c16844f4403 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/PasswordComparisonAuthenticator.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/PasswordComparisonAuthenticator.java @@ -69,7 +69,7 @@ public DirContextOperations authenticate(Authentication authentication) { for (String userDn : getUserDns(username)) { try { user = ldapTemplate.retrieveEntry(userDn, getUserAttributes()); - } catch (NameNotFoundException ignore) { + } catch (NameNotFoundException _) { // ignore } if (user != null) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/extension/SpringSecurityLdapTemplate.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/extension/SpringSecurityLdapTemplate.java index 1141c83c21e..fadd96f3458 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/extension/SpringSecurityLdapTemplate.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/ldap/extension/SpringSecurityLdapTemplate.java @@ -260,7 +260,7 @@ public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, } results.add(dca); } - } catch (PartialResultException e) { + } catch (PartialResultException _) { LdapUtils.closeEnumeration(resultsEnum); logger.info("Ignoring PartialResultException"); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManager.java index 40589aa85a2..9ec2c1d1025 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManager.java @@ -191,7 +191,7 @@ public IdentityProvider resolveOriginProvider(String idToken) throws Authenticat // 1. Check if there is an IdP with the 'iss' claim value equal to the 'issuer' field in its configuration try { return retrieveRegisteredIdentityProviderByIssuer(issuer); - } catch (IncorrectResultSizeDataAccessException x) { + } catch (IncorrectResultSizeDataAccessException _) { logger.debug("No registered identity provider found for given issuer. Checking for uaa."); } @@ -206,7 +206,7 @@ public IdentityProvider resolveOriginProvider(String idToken) throws Authenticat } //All other cases: throw Exception throw new InsufficientAuthenticationException("Unable to map issuer, %s , to a single registered provider".formatted(issuer)); - } catch (IllegalArgumentException | JsonUtils.JsonUtilException x) { + } catch (IllegalArgumentException | JsonUtils.JsonUtilException _) { throw new InsufficientAuthenticationException("Unable to decode expected id_token"); } } @@ -251,7 +251,7 @@ protected AuthenticationData getExternalAuthenticationDetails(final Authenticati if (provider == null) { try { provider = getProviderProvisioning().retrieveByOrigin(origin, identityZoneManager.getCurrentIdentityZoneId()); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { logger.info("No provider found for given origin"); throw new InsufficientAuthenticationException("Could not resolve identity provider with given origin."); } @@ -353,19 +353,17 @@ protected void populateAuthenticationAttributes(UaaAuthentication authentication Object acr = claims.get(ClaimConstants.ACR); if (acr != null) { - if (acr instanceof Map acrMap) { - Object values = acrMap.get("values"); - if (values instanceof Collection collection) { - authentication.setAuthContextClassRef(new HashSet<>(collection)); - } else if (values instanceof String[] strings) { - authentication.setAuthContextClassRef(new HashSet<>(Arrays.asList(strings))); - } else { - log.debug("Unrecognized ACR claim[{}] for user_id: {}", values, authentication.getPrincipal().getId()); + switch (acr) { + case Map acrMap -> { + Object values = acrMap.get("values"); + switch (values) { + case Collection collection -> authentication.setAuthContextClassRef(new HashSet<>(collection)); + case String[] strings -> authentication.setAuthContextClassRef(new HashSet<>(Arrays.asList(strings))); + case null, default -> log.debug("Unrecognized ACR claim[{}] for user_id: {}", values, authentication.getPrincipal().getId()); + } } - } else if (acr instanceof String string) { - authentication.setAuthContextClassRef(new HashSet<>(singletonList(string))); - } else { - log.debug("Unrecognized ACR claim[{}] for user_id: {}", acr, authentication.getPrincipal().getId()); + case String string -> authentication.setAuthContextClassRef(new HashSet<>(singletonList(string))); + case null, default -> log.debug("Unrecognized ACR claim[{}] for user_id: {}", acr, authentication.getPrincipal().getId()); } } @@ -381,15 +379,15 @@ protected void populateAuthenticationAttributes(UaaAuthentication authentication Object values = claims.get(entry.getValue()); if (values != null) { log.debug("Mapped ExternalOAuth attribute {} to {}", key, values); - if (values instanceof List list) { - List strings = list.stream() - .map(object -> Objects.toString(object, null)) - .toList(); - userAttributes.put(key, strings); - } else if (values instanceof String string) { - userAttributes.put(key, singletonList(string)); - } else { - userAttributes.put(key, singletonList(values.toString())); + switch (values) { + case List list -> { + List strings = list.stream() + .map(object -> Objects.toString(object, null)) + .toList(); + userAttributes.put(key, strings); + } + case String string -> userAttributes.put(key, singletonList(string)); + case null, default -> userAttributes.put(key, singletonList(values.toString())); } } } @@ -574,7 +572,7 @@ private boolean isRegisteredIdpAuthentication(Authentication request) { // check if the UAA Identity Zone is registered as an external Idp of itself retrieveRegisteredIdentityProviderByIssuer(issuer); return true; - } catch (IncorrectResultSizeDataAccessException e) { + } catch (IncorrectResultSizeDataAccessException _) { return false; } } else { @@ -917,7 +915,7 @@ && providerSupportsTokenExchange(retrievedByOrigin) && (allowedProviders == null || allowedProviders.contains(useOrigin))) { return (IdentityProvider) retrievedByOrigin; } - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIDPWrapperFactoryBean.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIDPWrapperFactoryBean.java index a672df013b4..5e2575289ae 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIDPWrapperFactoryBean.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIDPWrapperFactoryBean.java @@ -128,7 +128,7 @@ public static IdentityProviderWrapper getIdentityProviderWrapper(String origin, provider.setActive(true); try { provider.setConfig(rawDef); - } catch (JsonUtils.JsonUtilException x) { + } catch (JsonUtils.JsonUtilException _) { throw new RuntimeException("Non serializable Oauth config"); } IdentityProviderWrapper wrapper = new IdentityProviderWrapper(provider); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderData.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderData.java index 639598ced18..6bf4138d368 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderData.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderData.java @@ -67,7 +67,7 @@ public static IdentityProvider parseSamlProvider provider.setActive(true); try { provider.setConfig(def); - } catch (JsonUtils.JsonUtilException x) { + } catch (JsonUtils.JsonUtilException _) { throw new RuntimeException("Non serializable SAML config"); } return provider; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProvider.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProvider.java index 945adc95a8e..48e7979c0c3 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProvider.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProvider.java @@ -301,7 +301,7 @@ public static Converter createDefa public static Converter createDefaultAssertionValidatorWithParameters( Consumer> validationContextParameters, boolean saml2bearer) { return createAssertionValidator(Saml2ErrorCodes.INVALID_ASSERTION, - assertionToken -> SAML20AssertionValidators.attributeValidator, + _ -> SAML20AssertionValidators.attributeValidator, assertionToken -> createValidationContext(assertionToken, validationContextParameters, saml2bearer)); } @@ -462,7 +462,7 @@ public static Converter createDefa RelyingPartyRegistration registration = assertionToken.getToken().getRelyingPartyRegistration(); SignatureTrustEngine engine = OpenSamlVerificationUtils.trustEngine(registration); return SAML20AssertionValidators.createSignatureValidator(engine); - }, assertionToken -> new ValidationContext( + }, _ -> new ValidationContext( Collections.singletonMap(SAML2AssertionValidationParameters.SIGNATURE_REQUIRED, false))); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlVerificationUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlVerificationUtils.java index 0a28068b90f..bd096fd64bf 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlVerificationUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlVerificationUtils.java @@ -103,7 +103,7 @@ Saml2ResponseValidatorResult post(Signature signature) { SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); try { profileValidator.validate(signature); - } catch (Exception ex) { + } catch (Exception _) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, INVALID_SIGNATURE_FOR_OBJECT_COLON.formatted(this.id))); } @@ -113,7 +113,7 @@ Saml2ResponseValidatorResult post(Signature signature) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, INVALID_SIGNATURE_FOR_OBJECT.formatted(this.id))); } - } catch (Exception ex) { + } catch (Exception _) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, INVALID_SIGNATURE_FOR_OBJECT_COLON.formatted(this.id))); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java index 86c7e33a28c..825a1c783fd 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java @@ -25,26 +25,28 @@ private OpenSamlXmlUtils() { public static String getStringValue(String key, SamlIdentityProviderDefinition definition, XMLObject xmlObject) { String value = null; - if (xmlObject instanceof XSString xsString) { - value = xsString.getValue(); - } else if (xmlObject instanceof XSAny xsAny) { - value = xsAny.getTextContent(); - } else if (xmlObject instanceof XSInteger xsInteger) { - Integer i = xsInteger.getValue(); - value = i != null ? i.toString() : null; - } else if (xmlObject instanceof XSBoolean xsBoolean) { - XSBooleanValue b = xsBoolean.getValue(); - value = b != null && b.getValue() != null ? b.getValue().toString() : null; - } else if (xmlObject instanceof XSDateTime xsDateTime) { - Instant d = xsDateTime.getValue(); - value = d != null ? d.toString() : null; - } else if (xmlObject instanceof XSQName xsQName) { - QName name = xsQName.getValue(); - value = name != null ? name.toString() : null; - } else if (xmlObject instanceof XSURI xsUri) { - value = xsUri.getURI(); - } else if (xmlObject instanceof XSBase64Binary xsBase64Binary) { - value = xsBase64Binary.getValue(); + switch (xmlObject) { + case XSString xsString -> value = xsString.getValue(); + case XSAny xsAny -> value = xsAny.getTextContent(); + case XSInteger xsInteger -> { + Integer i = xsInteger.getValue(); + value = i != null ? i.toString() : null; + } + case XSBoolean xsBoolean -> { + XSBooleanValue b = xsBoolean.getValue(); + value = b != null && b.getValue() != null ? b.getValue().toString() : null; + } + case XSDateTime xsDateTime -> { + Instant d = xsDateTime.getValue(); + value = d != null ? d.toString() : null; + } + case XSQName xsQName -> { + QName name = xsQName.getValue(); + value = name != null ? name.toString() : null; + } + case XSURI xsUri -> value = xsUri.getURI(); + case XSBase64Binary xsBase64Binary -> value = xsBase64Binary.getValue(); + case null, default -> {} } if (value != null) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/RelyingPartyRegistrationBuilder.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/RelyingPartyRegistrationBuilder.java index efabfb2742c..7c68081864d 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/RelyingPartyRegistrationBuilder.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/RelyingPartyRegistrationBuilder.java @@ -107,7 +107,7 @@ public static String createOwnMetadata(String entityId, List keyWit String certificate = keyWithCerts.stream().findFirst().map(e -> { try { return e.getEncodedCertificate(); - } catch (CertificateException ex) { + } catch (CertificateException _) { return UaaStringUtils.EMPTY_STRING; } }).orElse(UaaStringUtils.EMPTY_STRING); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlConfiguration.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlConfiguration.java index e7a278e6827..a717f341e55 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlConfiguration.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlConfiguration.java @@ -84,7 +84,7 @@ public static Boolean setupOpenSaml() { .forEach(SamlConfiguration::init); try { OpenSamlInitializationService.initialize(); - } catch (NoClassDefFoundError | NoSuchMethodError e) { + } catch (NoClassDefFoundError | NoSuchMethodError _) { // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfigurator.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfigurator.java index dcc8f07c25d..ac7350f2280 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfigurator.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfigurator.java @@ -44,7 +44,7 @@ public List getIdentityProviderDefinitions() { public AbstractIdentityProviderDefinition getIdentityProviderDefinitionsForOrigin(IdentityZone zone, String origin) { try { return providerProvisioning.retrieveByOrigin(origin, zone.getId()).getConfig(); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { return null; } } @@ -52,7 +52,7 @@ public AbstractIdentityProviderDefinition getIdentityProviderDefinitionsForOrigi public AbstractIdentityProviderDefinition getIdentityProviderDefinitionsForIssuer(IdentityZone zone, String issuer) { try { return providerProvisioning.retrieveByExternId(issuer, OriginKeys.SAML, zone.getId()).getConfig(); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { return null; } } @@ -116,7 +116,7 @@ public synchronized String validateSamlIdentityProviderDefinition(SamlIdentityPr private boolean entityIdExists(String entityId, String zoneId) { try { return providerProvisioning.retrieveByExternId(entityId, OriginKeys.SAML, zoneId) != null; - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { return false; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlKeyManagerFactory.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlKeyManagerFactory.java index 857c80349a6..c79e7e9f093 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlKeyManagerFactory.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlKeyManagerFactory.java @@ -57,7 +57,7 @@ protected List convertList(List samlKeys) { for (SamlKey k : samlKeys) { try { result.add(convertKey(k)); - } catch (CertificateRuntimeException e) { + } catch (CertificateRuntimeException _) { // already logged in convertKey } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlRedirectUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlRedirectUtils.java index ef3fba06d47..2b5e89d358f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlRedirectUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlRedirectUtils.java @@ -39,7 +39,7 @@ public static String getZonifiedEntityId(String entityID, IdentityZone identityZ return url; } } - } catch (Exception ignored) { + } catch (Exception _) { // ignore } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlUaaAuthenticationUserManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlUaaAuthenticationUserManager.java index 943163a3432..88bbfe85d86 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlUaaAuthenticationUserManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/SamlUaaAuthenticationUserManager.java @@ -211,7 +211,7 @@ protected UaaAuthentication getUaaAuthentication(String subjectName, Saml2Authen samlConfig = (SamlIdentityProviderDefinition) idpConfig.getConfig(); idp = (IdentityProvider) idpConfig; addNew = samlConfig.isAddShadowUserOnLogin(); - } catch (EmptyResultDataAccessException x) { + } catch (EmptyResultDataAccessException _) { throw new ProviderNotFoundException("No SAML identity provider found in zone for alias:" + alias); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterFactoriesSupplier.java b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterFactoriesSupplier.java index 0d8c2757b72..5002b17818e 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterFactoriesSupplier.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterFactoriesSupplier.java @@ -45,7 +45,7 @@ default int getLimiterMappings() { return 0; } - InternalLimiterFactoriesSupplier NOOP = info -> null; + InternalLimiterFactoriesSupplier NOOP = _ -> null; static InternalLimiterFactoriesSupplier deNull(InternalLimiterFactoriesSupplier supplier) { return supplier != null ? supplier : NOOP; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBuckets.java b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBuckets.java index c9ea25f8291..3c582077fb5 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBuckets.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBuckets.java @@ -69,7 +69,7 @@ public void run() { TimeUnit.NANOSECONDS.sleep(EXPIRATION_WAIT); processExpirations(); } - catch (InterruptedException e) { //NOSONAR + catch (InterruptedException _) { //NOSONAR // As it is a Daemon, ignore InterruptedException } catch (RuntimeException e) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtils.java index 6080a3a23f7..88769d21110 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtils.java @@ -11,7 +11,7 @@ public static Integer parseNoException(String source, Integer defaultOnEmpty) { try { return parse(source, defaultOnEmpty); } - catch (NumberFormatException e) { + catch (NumberFormatException _) { return defaultOnEmpty; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFile.java b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFile.java index 7363d3f44e9..92530dc12f7 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFile.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFile.java @@ -68,7 +68,7 @@ private static InputStream getFileInputStream(String dir, String name) { if (file.isFile()) { return new FileInputStream( file ); } - } catch (IOException ignore) { + } catch (IOException _) { // ignore! } return null; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/StringUtilities.java b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/StringUtilities.java index 395708ad158..92305d74946 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/StringUtilities.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/ratelimiting/util/StringUtilities.java @@ -24,14 +24,11 @@ public static String options(String labelSingularButPluralWithAnS, Object[] vali } public static String options(String labelSingular, String labelPlural, Object[] validOptions) { - switch (count(validOptions)) { - case 0: - return "no " + labelPlural; - case 1: - return "the " + labelSingular + " is: " + options(validOptions); - default: - return "the " + labelPlural + " are: " + options(validOptions); - } + return switch (count(validOptions)) { + case 0 -> "no " + labelPlural; + case 1 -> "the " + labelSingular + " is: " + options(validOptions); + default -> "the " + labelPlural + " are: " + options(validOptions); + }; } public static String options(Object[] validOptions) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/resources/SearchResultsFactory.java b/server/src/main/java/org/cloudfoundry/identity/uaa/resources/SearchResultsFactory.java index 7a4403a163d..6dee040366f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/resources/SearchResultsFactory.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/resources/SearchResultsFactory.java @@ -108,7 +108,7 @@ public static SearchResults> buildSearchResultFrom( try { Object value = attribute.getValue().read(serializedObject); map.put(attribute.getKey(), value); - } catch (PathNotFoundException e) { + } catch (PathNotFoundException _) { map.put(attribute.getKey(), null); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingList.java b/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingList.java index ec16ee78e33..271c4082b32 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingList.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingList.java @@ -185,7 +185,7 @@ public boolean hasNext() { next = iterator.next(); hasNext = true; return true; - } catch (NoSuchElementException e) { + } catch (NoSuchElementException _) { hasNext = false; return false; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/SimpleSearchQueryConverter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/SimpleSearchQueryConverter.java index dd9e36c63e0..2867b0532b4 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/SimpleSearchQueryConverter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/resources/jdbc/SimpleSearchQueryConverter.java @@ -248,29 +248,18 @@ private void extractValues(SCIMFilter filter, MultiValueMap valu } private String whereClauseFromFilter(SCIMFilter filter, Map values, AttributeNameMapper mapper, String paramPrefix) { - switch (filter.getFilterType()) { - case AND: - return "(" + whereClauseFromFilter(filter.getFilterComponents().getFirst(), values, mapper, paramPrefix) + " AND " + whereClauseFromFilter(filter.getFilterComponents().get(1), values, mapper, paramPrefix) + ")"; - case OR: - return "(" + whereClauseFromFilter(filter.getFilterComponents().getFirst(), values, mapper, paramPrefix) + " OR " + whereClauseFromFilter(filter.getFilterComponents().get(1), values, mapper, paramPrefix) + ")"; - case EQUALITY: - return comparisonClause(filter, "=", values, "", "", paramPrefix); - case CONTAINS: - return comparisonClause(filter, "LIKE", values, "%", "%", paramPrefix); - case STARTS_WITH: - return comparisonClause(filter, "LIKE", values, "", "%", paramPrefix); - case PRESENCE: - return getAttributeName(filter, mapper) + " IS NOT NULL"; - case GREATER_THAN: - return comparisonClause(filter, ">", values, "", "", paramPrefix); - case GREATER_OR_EQUAL: - return comparisonClause(filter, ">=", values, "", "", paramPrefix); - case LESS_THAN: - return comparisonClause(filter, "<", values, "", "", paramPrefix); - case LESS_OR_EQUAL: - return comparisonClause(filter, "<=", values, "", "", paramPrefix); - } - return null; + return switch (filter.getFilterType()) { + case AND -> "(" + whereClauseFromFilter(filter.getFilterComponents().getFirst(), values, mapper, paramPrefix) + " AND " + whereClauseFromFilter(filter.getFilterComponents().get(1), values, mapper, paramPrefix) + ")"; + case OR -> "(" + whereClauseFromFilter(filter.getFilterComponents().getFirst(), values, mapper, paramPrefix) + " OR " + whereClauseFromFilter(filter.getFilterComponents().get(1), values, mapper, paramPrefix) + ")"; + case EQUALITY -> comparisonClause(filter, "=", values, "", "", paramPrefix); + case CONTAINS -> comparisonClause(filter, "LIKE", values, "%", "%", paramPrefix); + case STARTS_WITH -> comparisonClause(filter, "LIKE", values, "", "%", paramPrefix); + case PRESENCE -> getAttributeName(filter, mapper) + " IS NOT NULL"; + case GREATER_THAN -> comparisonClause(filter, ">", values, "", "", paramPrefix); + case GREATER_OR_EQUAL -> comparisonClause(filter, ">=", values, "", "", paramPrefix); + case LESS_THAN -> comparisonClause(filter, "<", values, "", "", paramPrefix); + case LESS_OR_EQUAL -> comparisonClause(filter, "<=", values, "", "", paramPrefix); + }; } private String comparisonClause(SCIMFilter filter, @@ -309,7 +298,7 @@ private String comparisonClause(SCIMFilter filter, } else { try { values.put(pName, Double.parseDouble(filter.getFilterValue())); - } catch (NumberFormatException x) { + } catch (NumberFormatException _) { if ("true".equalsIgnoreCase(filter.getFilterValue())) { values.put(pName, Boolean.TRUE); } else if ("false".equalsIgnoreCase(filter.getFilterValue())) { @@ -341,7 +330,7 @@ private Object getStringOrDate(String s) { try { DateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); return timestampFormat.parse(s); - } catch (ParseException x) { + } catch (ParseException _) { return s; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandler.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandler.java index 9e6222e2593..70fc07c3657 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandler.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandler.java @@ -70,7 +70,7 @@ private Optional> retrieveIdpByOrigin(final String originKey final IdentityProvider idpInAliasZone; try { idpInAliasZone = identityProviderProvisioning.retrieveByOrigin(originKey, zoneId); - } catch (final EmptyResultDataAccessException e) { + } catch (final EmptyResultDataAccessException _) { return Optional.empty(); } return Optional.ofNullable(idpInAliasZone); @@ -129,7 +129,7 @@ protected Optional retrieveEntity(final String id, final String zoneId final ScimUser user; try { user = scimUserProvisioning.retrieve(id, zoneId); - } catch (final ScimResourceNotFoundException e) { + } catch (final ScimResourceNotFoundException _) { return Optional.empty(); } return Optional.ofNullable(user); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimExternalGroupBootstrap.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimExternalGroupBootstrap.java index 968ecd8803d..f40d44497d0 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimExternalGroupBootstrap.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimExternalGroupBootstrap.java @@ -72,7 +72,7 @@ protected ScimGroup addGroup(String groupName) { ScimGroup group = new ScimGroup(null, groupName, identityZoneManager.getCurrentIdentityZoneId()); try { return getScimGroupProvisioning().create(group, identityZoneManager.getCurrentIdentityZoneId()); - } catch (ScimResourceAlreadyExistsException x) { + } catch (ScimResourceAlreadyExistsException _) { List groups = getScimGroupProvisioning().query(GROUP_BY_NAME_AND_ZONE_FILTER.formatted(groupName, identityZoneManager.getCurrentIdentityZoneId()), identityZoneManager.getCurrentIdentityZoneId()); if (groups != null && !groups.isEmpty()) { return groups.getFirst(); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrap.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrap.java index 5082c32d958..4c85e827ccb 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrap.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrap.java @@ -97,7 +97,7 @@ public PropertySource getMessageSource() { String messagesFilename = "messages.properties"; try { messageSource = new ResourcePropertySource(messagesFilename); - } catch (IOException ex) { + } catch (IOException _) { messageSource = new PropertySource.StubPropertySource(messagesFilename); } } @@ -229,7 +229,7 @@ private void addMembers(ScimGroup group) { for (ScimGroupMember member : members) { try { membershipManager.addMember(group.getId(), member, identityZoneManager.getCurrentIdentityZoneId()); - } catch (MemberAlreadyExistsException ex) { + } catch (MemberAlreadyExistsException _) { logger.debug("{} already is member of group {}", member.getMemberId(), name); } } @@ -279,7 +279,7 @@ ScimGroup getGroup(String name) { ScimGroup gr = scimGroupProvisioning.getByName(name, identityZoneManager.getCurrentIdentityZoneId()); gr.setMembers(membershipManager.getMembers(gr.getId(), false, identityZoneManager.getCurrentIdentityZoneId())); return gr; - } catch (ScimResourceNotFoundException | IncorrectResultSizeDataAccessException e) { + } catch (ScimResourceNotFoundException | IncorrectResultSizeDataAccessException _) { logger.debug("could not find group with name"); return null; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrap.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrap.java index f83c16783dc..c638e170b36 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrap.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrap.java @@ -133,7 +133,7 @@ private ScimUser getScimUser(UaaUser user) { if (users.isEmpty() && StringUtils.hasText(user.getId())) { try { users = Collections.singletonList(scimUserProvisioning.retrieve(user.getId(), identityZoneManager.getCurrentIdentityZoneId())); - } catch (ScimResourceNotFoundException x) { + } catch (ScimResourceNotFoundException _) { logger.debug("Unable to find scim user based on ID:{}", user.getId()); } } @@ -266,7 +266,7 @@ public void onApplicationEvent(AuthEvent event) { for (ScimGroup group : groupsMap.values()) { try { membershipManager.removeMemberById(group.getId(), exEvent.getUser().getId(), group.getZoneId()); - } catch (MemberNotFoundException ex) { + } catch (MemberNotFoundException _) { // do nothing } } @@ -313,7 +313,7 @@ private void addToGroup(String scimUserId, String gName, String origin, boolean ScimGroupMember groupMember = new ScimGroupMember(scimUserId); groupMember.setOrigin(ofNullable(origin).orElse(OriginKeys.UAA)); membershipManager.addMember(group.getId(), groupMember, identityZoneManager.getCurrentIdentityZoneId()); - } catch (MemberAlreadyExistsException | DuplicateKeyException ex) { + } catch (MemberAlreadyExistsException | DuplicateKeyException _) { // do nothing } } @@ -332,7 +332,7 @@ private ScimGroup getOrCreateGroup(String gName, boolean addGroup) { try { group = scimGroupProvisioning.getByName(gName, identityZoneManager.getCurrentIdentityZoneId()); } - catch (IncorrectResultSizeDataAccessException e) { + catch (IncorrectResultSizeDataAccessException _) { if (!addGroup) { logger.debug("No group found with name:{}. Group membership will not be added.", gName); return null; @@ -359,14 +359,14 @@ private void removeFromGroup(String scimUserId, String gName) { ScimGroup group; try { group = scimGroupProvisioning.getByName(gName, identityZoneManager.getCurrentIdentityZoneId()); - } catch (IncorrectResultSizeDataAccessException ex) { + } catch (IncorrectResultSizeDataAccessException _) { // Group not found or multiple groups found - silently skip as per previous behavior logger.debug("Group '{}' not found or multiple groups found, skipping removal", gName); return; } try { membershipManager.removeMemberById(group.getId(), scimUserId, identityZoneManager.getCurrentIdentityZoneId()); - } catch (MemberNotFoundException ex) { + } catch (MemberNotFoundException _) { // do nothing } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpoints.java index b1e61d14bee..084d00e9e59 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpoints.java @@ -158,7 +158,7 @@ public SearchResults listGroups( sortBy, "ascending".equalsIgnoreCase(sortOrder), identityZoneManager.getCurrentIdentityZoneId()); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { throw new ScimException("Invalid filter expression: [" + HtmlUtils.htmlEscape(filter) + "]", HttpStatus.BAD_REQUEST); } @@ -178,7 +178,7 @@ public SearchResults listGroups( try { return SearchResultsFactory.buildSearchResultFrom(input, startIndex, count, result.size(), attributes, mapper, Arrays.asList(ScimCore.SCHEMAS)); - } catch (JsonPathException e) { + } catch (JsonPathException _) { throw new ScimException("Invalid attributes: [" + attributesCommaSeparated + "]", HttpStatus.BAD_REQUEST); } } @@ -349,7 +349,7 @@ private String getGroupId(String displayName) { try { return dao.getByName(displayName, identityZoneManager.getCurrentIdentityZoneId()).getId(); - } catch (IncorrectResultSizeDataAccessException e) { + } catch (IncorrectResultSizeDataAccessException _) { throw new ScimException("Group not found:" + displayName, HttpStatus.NOT_FOUND); } } @@ -617,7 +617,7 @@ private int getVersion(String groupId, String etag) { } try { return Integer.valueOf(value); - } catch (NumberFormatException e) { + } catch (NumberFormatException _) { throw new ScimException("Invalid version match header (should be a version number): " + etag, HttpStatus.BAD_REQUEST); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpoints.java index 7e652b0b452..5755c4f4a68 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpoints.java @@ -282,7 +282,7 @@ public ScimUser createUser(@RequestBody ScimUser user, HttpServletRequest reques private ScimUser createScimUserWithAliasHandling(final ScimUser user) { final ScimUser scimUser; try { - scimUser = transactionTemplate.execute(txStatus -> { + scimUser = transactionTemplate.execute(_ -> { final ScimUser originalScimUser = scimUserProvisioning.createUser( user, user.getPassword(), @@ -328,7 +328,7 @@ public ScimUser updateUser(@RequestBody ScimUser user, @PathVariable String user final ScimUser scimUser; try { scimUser = scimUserService.updateUser(userId, user); - } catch (final AliasPropertiesInvalidException e) { + } catch (final AliasPropertiesInvalidException _) { throw new ScimException("The fields 'aliasId' and/or 'aliasZid' are invalid.", HttpStatus.BAD_REQUEST); } catch (final OptimisticLockingFailureException e) { throw new ScimResourceConflictException(e.getMessage()); @@ -483,7 +483,7 @@ private int getVersion(String userId, String etag) { } try { return Integer.parseInt(value); - } catch (NumberFormatException e) { + } catch (NumberFormatException _) { throw new ScimException("Invalid version match header (should be a version number): " + etag, HttpStatus.BAD_REQUEST); } @@ -521,7 +521,7 @@ public SearchResults findUsers( } input.add(user); } - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException _) { String msg = "Invalid filter expression: [" + filter + "]"; if (hasText(sortBy)) { msg += " [" + sortBy + "]"; @@ -549,7 +549,7 @@ public SearchResults findUsers( mapper, Arrays.asList(ScimCore.SCHEMAS) ); - } catch (JsonPathException e) { + } catch (JsonPathException _) { throw new ScimException("Invalid attributes: [" + attributesCommaSeparated + "]", HttpStatus.BAD_REQUEST); } } @@ -664,7 +664,7 @@ private void incrementErrorCounts(ScimException e) { synchronized (errorCounts) { value = errorCounts.get(series); if (value == null) { - errorCounts.computeIfAbsent(series, k -> new AtomicInteger(1)); + errorCounts.computeIfAbsent(series, _ -> new AtomicInteger(1)); return; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManager.java index 45b64bbca67..72d821ab6ca 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManager.java @@ -122,7 +122,7 @@ public ScimGroupExternalMember mapExternalGroup(final String groupId, ps.setString(5, zoneId); }); - } catch (DuplicateKeyException e) { + } catch (DuplicateKeyException _) { // we should not throw, if the mapping exist, we should leave it // there. logger.info("The mapping between group {} and external group {} already exists", group.getDisplayName(), externalGroup); @@ -192,7 +192,7 @@ public List getExternalGroupMapsByGroupName( final ScimGroup group; try { group = scimGroupProvisioning.getByName(groupName, zoneId); - } catch (IncorrectResultSizeDataAccessException e) { + } catch (IncorrectResultSizeDataAccessException _) { return null; } @@ -238,7 +238,7 @@ private ScimGroupExternalMember getExternalGroupMap(final String groupId, try { return jdbcTemplate.queryForObject(getGroupsWithExternalGroupMappingsSql, rowMapper, zoneId, groupId, origin, externalGroup); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new ScimResourceNotFoundException("The mapping between groupId " + groupId + " and external group " + externalGroup + " does not exist"); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManager.java index 705eef30ed5..9e2d8fdbd40 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManager.java @@ -242,13 +242,13 @@ private void getGroupsWithMember(List results, final List mem while (!memberList.isEmpty()) { int size = maxSqlParameters > 1 ? Math.min(maxSqlParameters - 1, memberList.size()) : memberList.size(); StringBuilder builder = new StringBuilder(dynamicGetGroupsByMemberSqlBase); - builder.append(memberList.subList(0, size).stream().map(s -> "?").collect(Collectors.joining(", "))); + builder.append(memberList.subList(0, size).stream().map(_ -> "?").collect(Collectors.joining(", "))); builder.append(");"); Object[] parameterList = ArrayUtils.addAll(new Object[]{zoneId}, memberList.subList(0, size).toArray()); groups.addAll(jdbcTemplate.query(builder.toString(), new ScimGroupRowMapper(), parameterList)); memberList = memberList.subList(size, memberList.size()); } - } catch (EmptyResultDataAccessException ex) { + } catch (EmptyResultDataAccessException _) { groups = Collections.emptyList(); } @@ -277,7 +277,7 @@ public Set getGroupsWithExternalMember(final String memberId, final S ps.setString(2, memberId); ps.setString(3, origin); }, new ScimGroupRowMapper()); - } catch (EmptyResultDataAccessException ex) { + } catch (EmptyResultDataAccessException _) { results = Collections.emptyList(); } @@ -289,7 +289,7 @@ public ScimGroupMember getMemberById(String groupId, String memberId, String zon MemberNotFoundException { try { return jdbcTemplate.queryForObject(GET_MEMBER_SQL, rowMapper, memberId, groupId, zoneId); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new MemberNotFoundException("Member " + memberId + " does not exist in group " + groupId); } } @@ -405,7 +405,7 @@ private boolean isUser(String uuid) { try { userProvisioning.retrieve(uuid, identityZoneManager.getCurrentIdentityZoneId()); return true; - } catch (ScimResourceNotFoundException ex) { + } catch (ScimResourceNotFoundException _) { return false; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioning.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioning.java index 31888c1c40d..cbfd4ea3a84 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioning.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioning.java @@ -155,7 +155,7 @@ public void setJdbcIdentityZoneProvisioning(JdbcIdentityZoneProvisioning jdbcIde void createAndIgnoreDuplicate(final String name, final String zoneId) { try { create(new ScimGroup(null, name, zoneId), zoneId); - } catch (ScimResourceAlreadyExistsException ignore) { + } catch (ScimResourceAlreadyExistsException _) { // ignore } } @@ -164,7 +164,7 @@ void createAndIgnoreDuplicate(final String name, final String zoneId) { public ScimGroup createOrGet(ScimGroup group, String zoneId) { try { return getByName(group.getDisplayName(), zoneId); - } catch (IncorrectResultSizeDataAccessException e) { + } catch (IncorrectResultSizeDataAccessException _) { createAndIgnoreDuplicate(group.getDisplayName(), zoneId); return getByName(group.getDisplayName(), zoneId); } @@ -233,7 +233,7 @@ public List retrieveAll(final String zoneId) { public ScimGroup retrieve(String id, final String zoneId) throws ScimResourceNotFoundException { try { return jdbcTemplate.queryForObject(getGroupSql, rowMapper, id, zoneId); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new ScimResourceNotFoundException("Group " + id + " does not exist"); } } @@ -246,7 +246,7 @@ private Set getAllowedUserGroups(String zoneId) { zoneAllowedGroups = currentZone.getId().equals(zoneId) ? currentZone.getConfig().getUserConfig().resultingAllowedGroups() : jdbcIdentityZoneProvisioning.retrieve(zoneId).getConfig().getUserConfig().resultingAllowedGroups(); - } catch (ZoneDoesNotExistsException e) { + } catch (ZoneDoesNotExistsException _) { logger.debug("could not retrieve identity zone with id: {}", zoneId); } return zoneAllowedGroups; @@ -270,7 +270,7 @@ public ScimGroup create(final ScimGroup group, final String zoneId) throws Inval ps.setInt(pos++, group.getVersion()); ps.setString(pos, zoneId); }); - } catch (DuplicateKeyException ex) { + } catch (DuplicateKeyException _) { throw new ScimResourceAlreadyExistsException("A group with displayName: " + group.getDisplayName() + " already exists."); } @@ -299,7 +299,7 @@ public ScimGroup update(final String id, final ScimGroup group, final String zon throw new IncorrectResultSizeDataAccessException(1, updated); } return retrieve(id, zoneId); - } catch (DuplicateKeyException ex) { + } catch (DuplicateKeyException _) { throw new InvalidScimResourceException("A group with displayName: " + group.getDisplayName() + " already exists"); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioning.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioning.java index d82b31e9774..21adeebf110 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioning.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioning.java @@ -170,7 +170,7 @@ public JdbcScimUserProvisioning( public ScimUser retrieve(String id, String zoneId) { try { return jdbcTemplate.queryForObject(USER_BY_ID_QUERY, mapper, id, zoneId); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new ScimResourceNotFoundException(USER_DOES_NOT_EXIST_MESSAGE.formatted(id)); } } @@ -294,7 +294,7 @@ public ScimUser create(final ScimUser user, String zoneId) { ps.setNull(20, Types.BIGINT); // previous_logon_success_time ps.setString(21, user.getPassword()); }); - } catch (DuplicateKeyException e) { + } catch (DuplicateKeyException _) { String userOrigin = hasText(user.getOrigin()) ? user.getOrigin() : OriginKeys.UAA; Map userDetails = Collections.singletonMap("origin", userOrigin); throw new ScimResourceAlreadyExistsException("Username already in use: " + user.getUserName(), userDetails); @@ -411,7 +411,7 @@ public boolean checkPasswordMatches(String id, CharSequence password, String zon new int[]{VARCHAR, VARCHAR}, String.class ); - } catch (IncorrectResultSizeDataAccessException e) { + } catch (IncorrectResultSizeDataAccessException _) { throw new ScimResourceNotFoundException(USER_DOES_NOT_EXIST_MESSAGE.formatted(id)); } @@ -614,7 +614,7 @@ private UserConfig getUserConfig(String zoneId) throws InvalidScimResourceExcept return currentZone.getId().equals(zoneId) ? currentZone.getConfig().getUserConfig() : jdbcIdentityZoneProvisioning.retrieve(zoneId).getConfig().getUserConfig(); - } catch (ZoneDoesNotExistsException e) { + } catch (ZoneDoesNotExistsException _) { throw new InvalidScimResourceException("Invalid identity zone id: %s".formatted(zoneId)); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserService.java index d0e36fb16ac..f4647ef672a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserService.java @@ -58,7 +58,7 @@ private ScimUser updateUserWithAliasHandling( final ScimUser user, final ScimUser existingUser ) { - return transactionTemplate.execute(txStatus -> { + return transactionTemplate.execute(_ -> { final ScimUser updatedOriginalUser = scimUserProvisioning.update( userId, user, diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/security/IsSelfCheck.java b/server/src/main/java/org/cloudfoundry/identity/uaa/security/IsSelfCheck.java index 4aa5463db7b..077c3fdcb1d 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/security/IsSelfCheck.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/security/IsSelfCheck.java @@ -100,7 +100,7 @@ public boolean isTokenRevocationForSelf(HttpServletRequest request, int index) { if (hasText(userIdFromToken) && userIdFromToken.equals(userIdFromAuthentication)) { return true; } - } catch (EmptyResultDataAccessException x) { + } catch (EmptyResultDataAccessException _) { logger.debug("Token not found:{}", tokenId); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/security/ScimUserUpdateDiff.java b/server/src/main/java/org/cloudfoundry/identity/uaa/security/ScimUserUpdateDiff.java index 13cbb02ad2a..704e1d09f5c 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/security/ScimUserUpdateDiff.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/security/ScimUserUpdateDiff.java @@ -22,7 +22,7 @@ public boolean isAnythingOtherThanNameDifferent(String userId, ScimUser scimUser try { scimUserFromDb = scimUserProvisioning.retrieve(userId, zoneId); - } catch (ScimResourceNotFoundException e) { + } catch (ScimResourceNotFoundException _) { return true; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java index ff0943c3e69..64eb0b9b4d4 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java @@ -40,7 +40,7 @@ public X509ExpiryCheckingTrustManager() { } } delegate = x509Tm; - } catch (NoSuchAlgorithmException | KeyStoreException ignored) { + } catch (NoSuchAlgorithmException | KeyStoreException _) { } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/CorsFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/CorsFilter.java index db3965f1c3b..20d0a7246a4 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/CorsFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/CorsFilter.java @@ -165,7 +165,7 @@ protected boolean handleRequest(HttpServletRequest request, URI originURI; try { originURI = new URI(origin); - } catch (URISyntaxException e) { + } catch (URISyntaxException _) { log.debug("Request with invalid origin was rejected: %s".formatted(origin)); response.sendError(FORBIDDEN.value(), "Invalid origin"); return true; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessor.java b/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessor.java index eeb017c524d..ce1d97569fb 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessor.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessor.java @@ -355,12 +355,11 @@ public int getPosition(SecurityFilterChain chain) { } } } - switch (placement) { - case POSITION: return position; - case BEFORE: return index; - case AFTER: return Math.min(chain.getFilters().size(), index + 1); - } - return index; + return switch (placement) { + case POSITION -> position; + case BEFORE -> index; + case AFTER -> Math.min(chain.getFilters().size(), index + 1); + }; } public static FilterPosition position(int pos) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java b/server/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java index f901931fefe..ff8499934eb 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabase.java @@ -111,7 +111,7 @@ public UaaUser retrieveUserByName(String username, String origin) throws Usernam try { String sql = caseInsensitive ? DEFAULT_CASE_INSENSITIVE_USER_BY_USERNAME_QUERY : DEFAULT_CASE_SENSITIVE_USER_BY_USERNAME_QUERY; return jdbcTemplate.queryForObject(sql, mapper, username.toLowerCase(Locale.US), true, origin, identityZoneManager.getCurrentIdentityZoneId()); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new UsernameNotFoundException(username); } } @@ -121,7 +121,7 @@ public UaaUserPrototype retrieveUserPrototypeByName(String username, String orig try { String sql = caseInsensitive ? DEFAULT_CASE_INSENSITIVE_USER_BY_USERNAME_QUERY : DEFAULT_CASE_SENSITIVE_USER_BY_USERNAME_QUERY; return jdbcTemplate.queryForObject(sql, minimalMapper, username.toLowerCase(Locale.US), true, origin, identityZoneManager.getCurrentIdentityZoneId()); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new UsernameNotFoundException(username); } } @@ -130,7 +130,7 @@ public UaaUserPrototype retrieveUserPrototypeByName(String username, String orig public UaaUser retrieveUserById(String id) throws UsernameNotFoundException { try { return jdbcTemplate.queryForObject(DEFAULT_USER_BY_ID_QUERY, mapper, id, true, identityZoneManager.getCurrentIdentityZoneId()); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new UsernameNotFoundException(id); } } @@ -139,7 +139,7 @@ public UaaUser retrieveUserById(String id) throws UsernameNotFoundException { public UaaUserPrototype retrieveUserPrototypeById(String id) throws UsernameNotFoundException { try { return jdbcTemplate.queryForObject(DEFAULT_USER_BY_ID_QUERY, minimalMapper, id, true, identityZoneManager.getCurrentIdentityZoneId()); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { throw new UsernameNotFoundException(id); } } @@ -174,7 +174,7 @@ public UaaUserPrototype retrieveUserPrototypeByEmail(String email, String origin public UserInfo getUserInfo(String id) { try { return jdbcTemplate.queryForObject("select user_id, info from user_info where user_id = ?", userInfoMapper, id); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { logger.debug("No custom attributes stored for user:{}", id); return null; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/user/UaaUserApprovalHandler.java b/server/src/main/java/org/cloudfoundry/identity/uaa/user/UaaUserApprovalHandler.java index b43fe104066..f5ff2759db5 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/user/UaaUserApprovalHandler.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/user/UaaUserApprovalHandler.java @@ -98,7 +98,7 @@ public AuthorizationRequest checkForPreApproval(AuthorizationRequest authorizati authorizationRequest.setApproved(true); return authorizationRequest; } - } catch (ClientRegistrationException e) { + } catch (ClientRegistrationException _) { logger.warn("Client registration problem prevent autoapproval check for client={}", clientId); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAA.java b/server/src/main/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAA.java index df063e143b7..8d2c5301d94 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAA.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAA.java @@ -348,17 +348,17 @@ protected JwtTokenSignedByThisUAA checkAudience(Collection clients) { Object audClaim = claims.get(AUD); List audience; - if (audClaim instanceof String string) { - audience = Collections.singletonList(string); - } else if (audClaim == null) { - audience = Collections.emptyList(); - } else { - try { - audience = ((List) audClaim).stream() - .map(String.class::cast) - .toList(); - } catch (ClassCastException ex) { - throw new InvalidTokenException("The token's audience claim is invalid or unparseable.", ex); + switch (audClaim) { + case null -> audience = Collections.emptyList(); + case String string -> audience = Collections.singletonList(string); + default -> { + try { + audience = ((List) audClaim).stream() + .map(String.class::cast) + .toList(); + } catch (ClassCastException ex) { + throw new InvalidTokenException("The token's audience claim is invalid or unparseable.", ex); + } } } @@ -391,7 +391,7 @@ private static void checkRevocableToken(RevocableTokenProvisioning revocableToke RevocableToken revocableToken = null; try { revocableToken = revocableTokenProvisioning.retrieve(tokenId, IdentityZoneHolder.get().getId()); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { // ignore exception until null check below } if (revocableToken == null) { @@ -467,7 +467,7 @@ public ClientDetails getClientDetails(MultitenantClientServices clientDetailsSer } try { return clientDetailsService.loadClientByClientId(clientId, IdentityZoneHolder.get().getId()); - } catch (NoSuchClientException x) { + } catch (NoSuchClientException _) { //happens if the client is deleted and token exist throw new InvalidTokenException("Invalid client ID " + clientId); } @@ -478,7 +478,7 @@ public UaaUser getUserDetails(UaaUserDatabase userDatabase) { if (UaaTokenUtils.isUserToken(claims)) { try { return userDatabase.retrieveUserById(userId); - } catch (UsernameNotFoundException e) { + } catch (UsernameNotFoundException _) { throw new InvalidTokenException("Token bears a non-existent user ID: " + userId); } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java b/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java index 7618f46e188..f9f80532142 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java @@ -80,7 +80,7 @@ private boolean keysMatch(PublicKey publicKey, PrivateKey privateKey) { ver.update(data); return ver.verify(signature); - } catch (Exception e) { + } catch (Exception _) { return false; } } @@ -101,15 +101,18 @@ private static PrivateKey loadPrivateKey(String encodedPrivateKey, String passph Object object = pemParser.readObject(); - if (object instanceof PEMEncryptedKeyPair pemEncryptedKeyPair) { - PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray()); - KeyPair keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv)); - privateKey = keyPair.getPrivate(); - } else if (object instanceof PEMKeyPair pemKeyPair) { - KeyPair keyPair = converter.getKeyPair(pemKeyPair); - privateKey = keyPair.getPrivate(); - } else if (object instanceof PrivateKeyInfo privateKeyInfo) { - privateKey = converter.getPrivateKey(privateKeyInfo); + switch (object) { + case PEMEncryptedKeyPair pemEncryptedKeyPair -> { + PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passphrase.toCharArray()); + KeyPair keyPair = converter.getKeyPair(pemEncryptedKeyPair.decryptKeyPair(decProv)); + privateKey = keyPair.getPrivate(); + } + case PEMKeyPair pemKeyPair -> { + KeyPair keyPair = converter.getKeyPair(pemKeyPair); + privateKey = keyPair.getPrivate(); + } + case PrivateKeyInfo privateKeyInfo -> privateKey = converter.getPrivateKey(privateKeyInfo); + case null, default -> {} } } catch (IOException ex) { throw new CertificateException("Failed to read private key.", ex); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMap.java b/server/src/main/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMap.java index 8c6d99a568b..9782aebf768 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMap.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMap.java @@ -78,7 +78,7 @@ public LinkedMaskingMultiValueMap(K... maskedAttribute) { @Override public void add(K key, V value) { - List values = this.targetMap.computeIfAbsent(key, k -> new LinkedList<>()); + List values = this.targetMap.computeIfAbsent(key, _ -> new LinkedList<>()); values.add(value); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/util/MapCollector.java b/server/src/main/java/org/cloudfoundry/identity/uaa/util/MapCollector.java index 986f64a73e1..e83aa9ad5d1 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/util/MapCollector.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/util/MapCollector.java @@ -32,7 +32,7 @@ public BiConsumer, T> accumulator() { @Override public BinaryOperator> combiner() { - return (left, right) -> { + return (left, _) -> { throw new IllegalStateException("Duplicate key %s".formatted(left)); }; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtils.java index 84d80e839db..69cd67cb75f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtils.java @@ -134,7 +134,7 @@ static HttpClientBuilder getClientBuilder(boolean skipSslValidation, HttpClientC builder.setConnectionManager(cm); if (config.maxKeepAlive() <= 0) { - builder.setConnectionReuseStrategy((request, response, context) -> false); + builder.setConnectionReuseStrategy((_, _, _) -> false); } else { builder.setKeepAliveStrategy(new UaaConnectionKeepAliveStrategy(config.maxKeepAlive())); } @@ -177,7 +177,7 @@ public static boolean isAcceptedInvitationAuthentication() { return result; } } - } catch (IllegalStateException x) { + } catch (IllegalStateException _) { //nothing bound on thread. logger.debug("Unable to retrieve request attributes looking for invitation."); @@ -207,7 +207,7 @@ public TimeValue getKeepAliveDuration(HttpResponse httpResponse, HttpContext htt if (elementValue != null && elementName != null && elementName.equalsIgnoreCase(TIMEOUT)) { try { result = Math.min(TimeUnit.SECONDS.toMillis(Long.parseLong(elementValue)), connectionKeepAliveMax); - } catch (NumberFormatException e) { + } catch (NumberFormatException _) { //Ignore Exception and keep current elementValue of result } break; @@ -267,7 +267,7 @@ public static Map getCredentials(HttpServletRequest request, Lis new TypeReference<>() { }); credentials.putAll(jsonCredentials); - } catch (JsonUtils.JsonUtilException e) { + } catch (JsonUtils.JsonUtilException _) { logger.warn("Unknown format of value for request param: {}. Ignoring.", paramName); } } else { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtils.java index 77504426d4f..3672cad60b0 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtils.java @@ -106,7 +106,7 @@ private static boolean isZoneInRequestPath() { && contextPath.startsWith(originalContextPath + ZonePathContextRewritingFilter.ZONE_PATH_PREFIX); } } - } catch (IllegalStateException ignored) { + } catch (IllegalStateException _) { // No request bound } return false; @@ -186,7 +186,7 @@ static boolean matchHost(String uriPattern, String requestedUri, AntPathMatcher } hostnameFromRequestedUri = uri.getHost(); } - catch (URISyntaxException ex) { + catch (URISyntaxException _) { return false; } @@ -268,7 +268,7 @@ public static boolean isUrl(String url) { try { new URL(url).toURI(); return true; - } catch (MalformedURLException | URISyntaxException e) { + } catch (MalformedURLException | URISyntaxException _) { return false; } } @@ -302,7 +302,7 @@ public static String validateAndNormalizeSafeUrl(String url, String fallbackUrl) if ("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme)) { return trimmed; } - } catch (URISyntaxException e) { + } catch (URISyntaxException _) { // Invalid URI syntax, fall back to default } @@ -400,7 +400,7 @@ public static boolean uriHasMatchingHost(String uri, String hostname) { try { URL url = new URL(uri); return hostname.equals(url.getHost()); - } catch (MalformedURLException e) { + } catch (MalformedURLException _) { return false; } } @@ -477,7 +477,7 @@ public static String normalizeUrlForPortComparison(String url) { return new URI(scheme, uri.getUserInfo(), uri.getHost(), -1, uri.getPath(), uri.getQuery(), uri.getFragment()).toString(); } - } catch (Exception ignored) { + } catch (Exception _) { // ignore } return url; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java index 58c70b9c121..814e68e5209 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java @@ -115,7 +115,7 @@ public AnyOfAuthorizationManager isZoneAdmin() { */ public AnyOfAuthorizationManager hasScope(String... scope) { delegateAuthorizationManagers.add( - (auth, ctx) -> new ScopeTrackingAuthorizationDecision(OAuth2ExpressionUtils.hasAnyScope(auth.get(), scope), scope) + (auth, _) -> new ScopeTrackingAuthorizationDecision(OAuth2ExpressionUtils.hasAnyScope(auth.get(), scope), scope) ); return this; } @@ -126,7 +126,7 @@ public AnyOfAuthorizationManager hasScope(String... scope) { */ public AnyOfAuthorizationManager hasScopeWithZoneId(String scope) { delegateAuthorizationManagers.add( - (auth, ctx) -> { + (auth, _) -> { var securityMethods = new ContextSensitiveOAuth2SecurityExpressionMethods(auth.get()); return new ScopeTrackingAuthorizationDecision(securityMethods.hasScopeInAuthZone(scope), scope); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/web/SelfCheckAuthorizationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/web/SelfCheckAuthorizationManager.java index b65a21c5b1c..f321e13c15f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/web/SelfCheckAuthorizationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/web/SelfCheckAuthorizationManager.java @@ -18,7 +18,7 @@ private enum CheckType { TOKEN_REVOCATION_CLIENT, TOKEN_REVOCATION_SELF, TOKEN_REVOCATION_CLIENT_USER - }; + } private final IsSelfCheck selfCheck; private final int parameterIndex; private final int parameterIndex2; diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpoints.java b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpoints.java index f0a70ae3d7d..013390e0113 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpoints.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpoints.java @@ -112,7 +112,7 @@ protected IdentityZone removeKeys(IdentityZone identityZone) { if (identityZone.getConfig() != null && identityZone.getConfig().getSamlConfig() != null) { identityZone.getConfig().getSamlConfig().setPrivateKeyPassword(null); identityZone.getConfig().getSamlConfig().setPrivateKey(null); - identityZone.getConfig().getSamlConfig().getKeys().forEach((key, value) -> { + identityZone.getConfig().getSamlConfig().getKeys().forEach((_, value) -> { value.setPassphrase(null); value.setKey(null); }); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilter.java index 23ab052e59f..b4beb8b0300 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilter.java @@ -95,7 +95,7 @@ private IdentityZone resolveZoneBySubdomain(String subdomain, HttpServletRespons } try { return dao.retrieveBySubdomain(subdomain); - } catch (EmptyResultDataAccessException ex) { + } catch (EmptyResultDataAccessException _) { logger.debug("Cannot find identity zone for subdomain {}", subdomain); return null; } catch (Exception ex) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java index 565178076e0..eeb3460fe13 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java @@ -164,7 +164,7 @@ private IdentityZone validateIdentityZone(String identityZoneId, String identity } else { identityZone = dao.retrieve(identityZoneId); } - } catch (ZoneDoesNotExistsException | EmptyResultDataAccessException ignored) { + } catch (ZoneDoesNotExistsException | EmptyResultDataAccessException _) { } return identityZone; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidator.java b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidator.java index 7fb5f127ed4..ad4b6554ff8 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidator.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidator.java @@ -80,7 +80,7 @@ private static boolean isValidUrl(String urlString) { URL url = new URI(urlString).toURL(); String protocol = url.getProtocol(); return "http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol); - } catch (IllegalArgumentException | MalformedURLException | URISyntaxException e) { + } catch (IllegalArgumentException | MalformedURLException | URISyntaxException _) { return false; } } @@ -121,7 +121,7 @@ private static boolean isValidDuration(String duration) { "d".equalsIgnoreCase(unit) || "w".equalsIgnoreCase(unit) || "m".equalsIgnoreCase(unit); - } catch (NumberFormatException e) { + } catch (NumberFormatException _) { return false; } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsService.java index abf97a176dd..71b57484b8b 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsService.java @@ -135,7 +135,7 @@ public ClientDetails loadClientByClientId(String clientId, String zoneId) throws ClientDetails details; try { details = jdbcTemplate.queryForObject(selectClientDetailsSql, new ClientDetailsRowMapper(), clientId, zoneId); - } catch (EmptyResultDataAccessException | DataIntegrityViolationException e) { + } catch (EmptyResultDataAccessException | DataIntegrityViolationException _) { throw new NoSuchClientException("No client with requested id: " + clientId); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/ZonePathHttpSession.java b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/ZonePathHttpSession.java index 2a77cafb993..809de4ac7af 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/ZonePathHttpSession.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/ZonePathHttpSession.java @@ -175,7 +175,7 @@ public void invalidate() { for (String name : toRemove) { try { containerSession.removeAttribute(name); - } catch (IllegalStateException ignored) { + } catch (IllegalStateException _) { // Container session was invalidated } } diff --git a/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/MBeanMap.java b/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/MBeanMap.java index 7db4a8c9226..2f65c5372bc 100644 --- a/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/MBeanMap.java +++ b/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/MBeanMap.java @@ -67,7 +67,7 @@ public Set> entrySet() { try { Object value = server.getAttribute(name, key); verySafePut(map, key, value); - } catch (Exception e) { + } catch (Exception _) { logger.trace("Cannot extract attribute: {}", key); } } @@ -82,7 +82,7 @@ public Set> entrySet() { try { Object value = server.invoke(name, key, null, null); verySafePut(map, attribute, value); - } catch (Exception e) { + } catch (Exception _) { logger.trace("Cannot extract operation: {}", key); } } diff --git a/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/UaaMetricsEmitter.java b/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/UaaMetricsEmitter.java index 4bf9b92b90b..57d74e6fc49 100644 --- a/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/UaaMetricsEmitter.java +++ b/statsd-lib/src/main/java/org/cloudfoundry/identity/statsd/UaaMetricsEmitter.java @@ -217,7 +217,7 @@ public void enableNotification() { try { logger.debug("Trying to enable notification"); NotificationEmitter emitter = metricsUtils.getUaaMetricsSubscriber(server); - emitter.addNotificationListener((notification, handback) -> { + emitter.addNotificationListener((notification, _) -> { String key = notification.getType(); String prefix = key.startsWith("/") ? key.substring(1) : key; statsDClient.time("requests.%s.latency".formatted(prefix), (Long) notification.getSource()); diff --git a/uaa/src/main/java/org/cloudfoundry/identity/uaa/brave/WebMvcRuntime.java b/uaa/src/main/java/org/cloudfoundry/identity/uaa/brave/WebMvcRuntime.java index 3eb4617bffd..889038433a7 100644 --- a/uaa/src/main/java/org/cloudfoundry/identity/uaa/brave/WebMvcRuntime.java +++ b/uaa/src/main/java/org/cloudfoundry/identity/uaa/brave/WebMvcRuntime.java @@ -25,7 +25,7 @@ static WebMvcRuntime findWebMvcRuntime() { try { Class.forName("org.springframework.web.method.HandlerMethod"); return new WebMvc31(); // intentionally doesn't access the type prior to the above guard - } catch (ClassNotFoundException e) { + } catch (ClassNotFoundException _) { // pre spring-webmvc v3.1 } From 5547134992d6a0e27bd783170ff1f2236df15cdd Mon Sep 17 00:00:00 2001 From: Duane May Date: Wed, 3 Jun 2026 22:08:05 -0400 Subject: [PATCH 2/7] Fix broken logging test --- .../config/YamlServletProfileInitializerTest.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializerTest.java index 2e2a82be3c0..5303fa88d93 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/YamlServletProfileInitializerTest.java @@ -25,6 +25,7 @@ import org.springframework.web.context.support.StandardServletEnvironment; import jakarta.servlet.ServletContext; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PrintStream; @@ -38,9 +39,7 @@ import static org.cloudfoundry.identity.uaa.impl.config.YamlServletProfileInitializer.YML_ENV_VAR_NAME; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.contains; -import static org.mockito.Mockito.description; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(PollutionPreventionExtension.class) @@ -268,13 +267,13 @@ public String getEnvironmentVariable(String name) { class WithFakeStdOut { private PrintStream originalOut; - private PrintStream mockPrintStream; + private ByteArrayOutputStream outputStream; @BeforeEach void setUp() { originalOut = System.out; - mockPrintStream = mock(PrintStream.class); - System.setOut(mockPrintStream); + outputStream = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outputStream)); } @AfterEach @@ -311,8 +310,8 @@ public Object getProperty(String name) { initializer.initialize(context); assertThat(environment.getProperty("logging.config")).isEqualTo("-Djava.util.logging.config=/some/path/logging.properties"); - verify(mockPrintStream, description("Expected to find a log entry indicating that the LOGGING_CONFIG variable was found.")) - .println("Ignoring Log Config Location: -Djava.util.logging.config=/some/path/logging.properties. Location is suspect to be a Tomcat startup script environment variable"); + String output = outputStream.toString(); + assertThat(output).contains("Ignoring Log Config Location: -Djava.util.logging.config=/some/path/logging.properties. Location is suspect to be a Tomcat startup script environment variable"); } } From 72d3ed67e19cd5d4d2b1282f663126a3c748beb7 Mon Sep 17 00:00:00 2001 From: Duane May Date: Wed, 3 Jun 2026 22:55:02 -0400 Subject: [PATCH 3/7] Migrate test code to Java 25 Syntax Rewrite Rules applied --- .../oauth/client/OAuth2RestTemplateTests.java | 4 +- ...ccessTokenProviderWithConversionTests.java | 2 +- ...th2AccessTokenJackson2SerializerTests.java | 2 +- .../identity/uaa/scim/ScimUserTests.java | 2 +- .../account/EmailChangeEmailServiceTest.java | 2 +- .../ChainedAuthenticationManagerTest.java | 2 +- ...asswordGrantAuthenticationManagerTest.java | 2 +- .../uaa/cache/StaleUrlCacheTests.java | 2 +- .../ClientAdminEndpointsValidatorTests.java | 2 +- .../identity/uaa/client/UaaClientTest.java | 2 +- .../config/IdentityProviderBootstrapTest.java | 2 +- .../db/TableAndColumnNormalizationTest.java | 2 +- ..._7_3__StoreSubDomainAsLowerCase_Tests.java | 4 +- .../PollutionPreventionExtension.java | 2 +- .../profiles/ProfileSelectionExtension.java | 2 +- .../uaa/login/LoginInfoEndpointTests.java | 2 +- .../uaa/metrics/UaaMetricsFilterTests.java | 2 +- .../RestrictUaaScopesClientValidatorTest.java | 4 +- .../uaa/oauth/UaaTokenStoreTests.java | 8 +- .../OAuth2ClientContextFilterTests.java | 2 +- ...okenEndpointAuthenticationFilterTests.java | 2 +- .../AbstractDefaultTokenServicesTests.java | 2 +- ...ctPersistentDefaultTokenServicesTests.java | 4 +- .../uaa/oauth/token/KeyInfoServiceTests.java | 2 +- .../AbstractOAuth2AccessTokenMatchers.java | 10 +-- .../ldap/DynamicPasswordComparatorTests.java | 4 +- ...enSaml5AuthenticationProviderUaaTests.java | 2 +- .../saml/SamlMetadataEndpointTest.java | 2 +- .../provider/saml/TestOpenSamlObjects.java | 2 +- .../config/InitialConfigTest.java | 2 +- .../http/CredentialIdTypeAbstractTestJWT.java | 2 +- .../internal/common/InternalLimiterTest.java | 2 +- .../ExpirationBucketsTest.java | 2 +- .../LimiterManagerImplTest.java | 2 +- .../PathFragmentToLimiterMappingsTest.java | 2 +- .../bootstrap/ScimGroupBootstrapTests.java | 4 +- .../ScimUserEndpointsAliasTests.java | 2 +- .../jdbc/JdbcScimUserProvisioningTests.java | 2 +- .../uaa/scim/test/JsonObjectMatcherUtils.java | 4 +- .../X509ExpiryCheckingTrustManagerTest.java | 2 +- .../web/CorsFilterDefaultZoneTests.java | 2 +- .../web/CorsFilterNonDefaultZoneTests.java | 2 +- ...SecurityFilterChainPostProcessorTests.java | 2 +- .../identity/uaa/test/TestUtils.java | 10 +-- .../uaa/user/JdbcUaaUserDatabaseTests.java | 2 +- .../identity/uaa/user/UaaUserTests.java | 2 +- .../uaa/util/JwtTokenSignedByThisUAATest.java | 2 +- .../identity/uaa/util/PredicateMatcher.java | 2 +- .../uaa/util/UaaHttpRequestUtilsTest.java | 6 +- .../identity/uaa/util/UaaUrlUtilsTest.java | 2 +- .../uaa/zone/IdentityZoneEndpointsTests.java | 6 +- .../IdentityZoneResolvingFilterTests.java | 2 +- ...ntityZoneResolvingFilterZonePathTests.java | 2 +- .../JdbcIdentityZoneProvisioningTests.java | 4 +- ...titenantJdbcClientDetailsServiceTests.java | 4 +- .../uaa/zone/ZoneContextPathSessionTests.java | 8 +- .../ZonePathContextRewritingFilterTests.java | 84 +++++++++---------- .../integration/UaaMetricsEmitterIT.java | 2 +- .../uaa/OpenApiConfigurationTest.java | 6 +- ...micZoneAwareAuthenticationManagerTest.java | 6 +- ...uthorizationCodeGrantIntegrationTests.java | 2 +- .../CheckTokenEndpointIntegrationTests.java | 6 +- .../IntrospectEndpointIntegrationTests.java | 12 +-- .../uaa/integration/PrintSmtpToScreen.java | 4 +- .../SessionControllerIntegrationTests.java | 8 +- .../integration/feature/AppApprovalIT.java | 2 +- .../uaa/integration/feature/AutologinIT.java | 2 +- .../integration/feature/ChangeEmailIT.java | 2 +- .../integration/feature/ChangePasswordIT.java | 2 +- .../integration/feature/CreateAccountIT.java | 2 +- .../integration/feature/ErrorRoutingIT.java | 2 +- .../feature/ForcedPasswordChangeIT.java | 2 +- .../uaa/integration/feature/HealthzIT.java | 2 +- .../uaa/integration/feature/HomeIT.java | 4 +- .../integration/feature/ImplicitGrantIT.java | 4 +- .../integration/feature/InvitationsIT.java | 6 +- .../integration/feature/JWTBearerGrantIT.java | 4 +- .../uaa/integration/feature/LdapLoginIT.java | 2 +- .../uaa/integration/feature/LoginIT.java | 2 +- .../uaa/integration/feature/OIDCLoginIT.java | 2 +- .../feature/OpenIdTokenGrantsIT.java | 2 +- .../integration/feature/PasswordGrantIT.java | 2 +- .../integration/feature/RateLimitingIT.java | 4 +- .../integration/feature/ResetPasswordIT.java | 2 +- .../SamlLoginCustomUserAttributesIT.java | 2 +- .../integration/feature/SamlLoginEmailIT.java | 4 +- .../uaa/integration/feature/SamlLoginIT.java | 2 +- .../feature/SessionLossDuringOauthFlowIT.java | 2 +- .../uaa/integration/feature/TestClient.java | 2 +- .../integration/feature/UserTokenGrantIT.java | 2 +- .../integration/feature/XFrameOptionsIT.java | 2 +- .../feature/ZoneSessionPathsIT.java | 6 +- .../feature/ZoneValidationCookieHijackIT.java | 2 +- .../uaa/integration/pageObjects/Page.java | 2 +- .../util/IntegrationTestUtils.java | 2 +- .../util/ScreenshotOnFailExtension.java | 4 +- ...vitationsEndpointMockMvcZonePathTests.java | 4 +- ...nvitationsServiceMockMvcZonePathTests.java | 14 ++-- .../identity/uaa/login/LoginMockMvcTests.java | 2 +- .../uaa/login/LoginMockMvcZonePathTests.java | 4 +- .../mock/ldap/AbstractLdapMockMvcTest.java | 2 +- .../uaa/mock/ldap/LdapMockMvcTests.java | 2 +- ...ityProviderEndpointsAliasMockMvcTests.java | 2 +- .../mock/token/AbstractTokenMockMvcTests.java | 4 +- ...okenExchangeDefaultConfigMockMvcTests.java | 10 +-- .../mock/token/TokenExchangeMockMvcBase.java | 10 +-- ...changeOverrideAuthManagerMockMvcTests.java | 2 +- .../TokenRevocationEndpointMockMvcTest.java | 6 +- ...RevocationEndpointMockMvcZonePathTest.java | 6 +- .../identity/uaa/mock/util/JwtTokenUtils.java | 2 +- .../identity/uaa/mock/util/MockMvcUtils.java | 2 +- .../uaa/oauth/UaaTokenServicesTests.java | 4 +- .../LoginPagePerformanceMockMvcTest.java | 2 +- ...ginPagePerformanceMockMvcZonePathTest.java | 2 +- .../ScimGroupEndpointsMockMvcTests.java | 4 +- ...cimGroupEndpointsMockMvcZonePathTests.java | 4 +- .../endpoints/ScimGroupEndpointsTests.java | 6 +- .../identity/uaa/test/InMemoryLdapServer.java | 2 +- .../identity/uaa/test/UaaWebDriver.java | 6 +- .../identity/uaa/yml/YamlProcessorTest.java | 2 +- 120 files changed, 240 insertions(+), 242 deletions(-) diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java index 7adf608b425..85f412c5085 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java @@ -161,7 +161,7 @@ void doubleEncodingOfAccessTokenValue() { @Test void noRetryAccessDeniedExceptionForNoExistingToken() { restTemplate.setAccessTokenProvider(new StubAccessTokenProvider()); - restTemplate.setRequestFactory((uri, httpMethod) -> { + restTemplate.setRequestFactory((_, _) -> { throw new AccessTokenRequiredException(resource); }); assertThatExceptionOfType(AccessTokenRequiredException.class).isThrownBy(() -> @@ -300,7 +300,7 @@ public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails detail OAuth2AccessToken newToken = restTemplate.getAccessToken(); assertThat(newToken).isNotNull(); fail("Expected UserRedirectRequiredException"); - } catch (UserRedirectRequiredException e) { + } catch (UserRedirectRequiredException _) { // planned } // context token should be reset as it is invalid at this point diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java index 54c2f3c11fc..0a5b0c0e028 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java @@ -199,7 +199,7 @@ public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) { void getErrorFromForm() { final HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED); - requestFactory = (uri, httpMethod) -> new StubClientHttpRequest(HttpStatus.BAD_REQUEST, responseHeaders, + requestFactory = (_, _) -> new StubClientHttpRequest(HttpStatus.BAD_REQUEST, responseHeaders, "error=invalid_client&error_description=FOO"); AccessTokenRequest request = new DefaultAccessTokenRequest(); request.setAuthorizationCode("foo"); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java index 34f8f93fd50..2e16cb83b3a 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java @@ -59,7 +59,7 @@ void writeValueAsStringWithNullScope() { accessToken.getScope().clear(); try { accessToken.getScope().add(null); - } catch (NullPointerException e) { + } catch (NullPointerException _) { // short circuit NPE from Java 7 (which is correct but only relevant for this test) throw new IllegalArgumentException("Scopes cannot be null or empty. Got [null]"); } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java index a28643ec96c..572fedfe869 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java @@ -556,7 +556,7 @@ void patchUserChangeUserName() { try { user.patch(patch); fail("username is a required field, can't nullify it."); - } catch (IllegalArgumentException ignored) { + } catch (IllegalArgumentException _) { // ignore } assertThat(user.getUserName()).isNotNull(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java index b7ca3a4d68a..5341b4612a9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java @@ -279,7 +279,7 @@ void completeActivationWithInvalidClientId() { Map response = null; try { response = emailChangeEmailService.completeVerification("the_secret_code"); - } catch (NoSuchClientException e) { + } catch (NoSuchClientException _) { assertThat(response).doesNotContainKey("redirect_url"); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java index 62cd8b7b288..84df14b795b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java @@ -104,7 +104,7 @@ void uaaAuthThrowLdapAuthFalse() { try { authMgr.authenticate(failure); fail("Should have thrown exception"); - } catch (BadCredentialsException ignored) { + } catch (BadCredentialsException _) { } verify(authenticateThrow, times(1)).authenticate(any(Authentication.class)); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java index 3cb39543792..5ee66089c80 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java @@ -202,7 +202,7 @@ void oidcPasswordGrantInvalidLogin() { try { instance.authenticate(auth); fail("No Exception thrown."); - } catch (BadCredentialsException ignored) { + } catch (BadCredentialsException _) { } ArgumentCaptor eventArgumentCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java index 7202e5956b3..e3b549a79bf 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java @@ -124,7 +124,7 @@ void calling_twice_uses_cache() throws Exception { @Test void entry_refreshes_after_time() { - when(mockTimeService.getCurrentTimeMillis()).thenAnswer(e -> System.currentTimeMillis()); + when(mockTimeService.getCurrentTimeMillis()).thenAnswer(_ -> System.currentTimeMillis()); when(mockRestTemplate.getForObject(any(URI.class), any())).thenReturn(content1, content2, content3); // populate the cache diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java index 1972851a2f9..17d64a446e2 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java @@ -263,7 +263,7 @@ void validateValidURLs() { private void testValidatorForInvalidURL(String url) { try { testValidatorForURL(url); - } catch (InvalidClientDetailsException e) { + } catch (InvalidClientDetailsException _) { return; } fail("Url %s should not be allowed".formatted(url)); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java index 09571f214a0..1cf2d91c00a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java @@ -20,7 +20,7 @@ void getClientJwtConfiguration_includesTopLevelJwtCredsFromAdditionalInformation UaaClient c = new UaaClient("cid", "sec", List.of(new SimpleGrantedAuthority("uaa.none")), addl, null); ClientJwtConfiguration j = c.getClientJwtConfiguration(); assertThat(j.getClientJwtCredentials()).isNotNull().hasSize(1); - assertThat(j.getClientJwtCredentials().get(0).getIssuer()).isEqualTo("http://localhost/uaa/oauth/token"); + assertThat(j.getClientJwtCredentials().getFirst().getIssuer()).isEqualTo("http://localhost/uaa/oauth/token"); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java index cb33ee37c91..d9b41c29726 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java @@ -318,7 +318,7 @@ void oauthAndOidcProviderDeletion() throws Exception { try { provisioning.retrieveByOriginIgnoreActiveFlag(provider.getKey(), IdentityZone.getUaaZoneId()); fail("Provider '%s' should not exist.".formatted(provider.getKey())); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java index a0176a76d3b..7e3021439f8 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java @@ -45,7 +45,7 @@ class MySQLConfiguration { @Order(TestDatabaseNameCustomizer.ORDER + 1) @Profile("mysql") JdbcUrlCustomizer mysqlHardcodedJdbcUrlCustomizer() { - return url -> "jdbc:mysql://127.0.0.1:3306/uaa?useSSL=true&trustServerCertificate=true&permitMysqlScheme=true"; + return _ -> "jdbc:mysql://127.0.0.1:3306/uaa?useSSL=true&trustServerCertificate=true&permitMysqlScheme=true"; } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase_Tests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase_Tests.java index ab3bdb93f21..4dea31d9756 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase_Tests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/db/V2_7_3__StoreSubDomainAsLowerCase_Tests.java @@ -43,7 +43,7 @@ class V2_7_3__StoreSubDomainAsLowerCase_Tests { void closeConnection() { try { connection.close(); - } catch (Exception ignore) { + } catch (Exception _) { // ignore } } @@ -135,7 +135,7 @@ public void checkDbIsCaseSensitive() { IdentityZone identityZone = MultitenancyFixture.identityZone(subdomain + generator.generate(), subdomain); identityZone.setSubdomain(subdomain); createIdentityZoneThroughSQL(identityZone); - } catch (DuplicateKeyException x) { + } catch (DuplicateKeyException _) { assumeTrue(false, "DB is not case sensitive. No need for this test"); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java b/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java index 5091d6268a8..7085583eba4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java @@ -24,7 +24,7 @@ public void afterAll(ExtensionContext extensionContext) throws SQLException { private ApplicationContext getApplicationContextOrNull(ExtensionContext extensionContext) { try { return SpringExtension.getApplicationContext(extensionContext); - } catch (IllegalStateException ignore) { + } catch (IllegalStateException _) { } return null; } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/profiles/ProfileSelectionExtension.java b/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/profiles/ProfileSelectionExtension.java index 4f2da5ff7d8..b24644145ec 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/profiles/ProfileSelectionExtension.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/profiles/ProfileSelectionExtension.java @@ -63,7 +63,7 @@ private List getActiveProfilesOrNull(ExtensionContext context) { try { var applicationContext = SpringExtension.getApplicationContext(context); return Arrays.asList(applicationContext.getEnvironment().getActiveProfiles()); - } catch (IllegalStateException ignore) { + } catch (IllegalStateException _) { return null; } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java index 762404983de..1b3034eb419 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java @@ -1632,7 +1632,7 @@ void colorsMustBePublic() { (String str) -> { try { return Modifier.isPublic(LoginInfoEndpoint.SavedAccountOptionModel.class.getDeclaredField(str).getModifiers()); - } catch (NoSuchFieldException e) { + } catch (NoSuchFieldException _) { return false; } }; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/metrics/UaaMetricsFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/metrics/UaaMetricsFilterTests.java index ada830d9504..1ce3210eb92 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/metrics/UaaMetricsFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/metrics/UaaMetricsFilterTests.java @@ -238,7 +238,7 @@ void uri_groups_when_fails_to_load() { map.add("/identity-zones", "/identity-zones"); map.add("/identity-zones", "/identity-zones/some/value"); map.add("/saml/login", "/saml/login/value"); - map.forEach((key, value) -> { + map.forEach((_, value) -> { for (String s : value) { setRequestData(s); assertThat(filter.getUriGroup(request).getGroup()).as("Testing URL: " + s).isEqualTo(FALLBACK.getGroup()); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java index 3847368c8ce..8d9acdd1235 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java @@ -72,14 +72,14 @@ protected void validateClient(List restrictModes, L try { validator.validate(client, m); fail("Scope:" + s + " should not be valid during " + m + " mode."); - } catch (InvalidClientDetailsException x) { + } catch (InvalidClientDetailsException _) { //expected } } for (ClientDetailsValidator.Mode m : nonRestrictModes) { try { validator.validate(client, m); - } catch (InvalidClientDetailsException x) { + } catch (InvalidClientDetailsException _) { fail("Scope:" + s + " should be valid during " + m + " mode."); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java index 0eea1fff5a4..3d5a77b40e9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java @@ -291,7 +291,7 @@ void cleanUpUnusedOldTokensMySQLInAnotherTimezone( assertThat(template.queryForObject("SELECT count(*) FROM oauth_code", Integer.class)).isEqualTo(count); try { store.consumeAuthorizationCode(lastCode); - } catch (Exception ignore) { + } catch (Exception _) { // ignored } assertThat(template.queryForObject("SELECT count(*) FROM oauth_code", Integer.class)).isEqualTo(count - 1); @@ -315,7 +315,7 @@ void cleanUpExpiredTokensDeadlockLoser() throws Exception { String code = store.createAuthorizationCode(clientAuthentication); try { store.consumeAuthorizationCode(code); - } catch (InvalidGrantException ignored) { + } catch (InvalidGrantException _) { // ignored } } @@ -340,7 +340,7 @@ void countingTheExecutedSqlDeleteStatements() throws SQLException { for (int i = 0; i < 10; i++) { try { store.performExpirationCleanIfEnoughTimeHasElapsed(); - } catch (Exception sqlException) { + } catch (Exception _) { // ignore } } @@ -361,7 +361,7 @@ void countingTheExecutedSqlDeleteStatements() throws SQLException { private static void performExpirationClean(UaaTokenStore store) { try { store.performExpirationCleanIfEnoughTimeHasElapsed(); - } catch (Exception sqlException) { + } catch (Exception _) { // ignore } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java index 5349bff13e1..529b77a2d73 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java @@ -207,7 +207,7 @@ void currentUriWithInvalidQueryString() { request.setQueryString("foo=bar&code=XXXX&parm=%xx"); try { assertThat(filter.calculateCurrentUri(request)).isNull(); - } catch (IllegalStateException ex) { + } catch (IllegalStateException _) { // OAuth2ClientContextFilter.calculateCurrentUri() internally uses // ServletUriComponentsBuilder.fromRequest(), which behaves differently in Spring Framework 5 // and throws an IllegalStateException for a malformed URI. diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointAuthenticationFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointAuthenticationFilterTests.java index 8c56f2605c1..92732ec199f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointAuthenticationFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointAuthenticationFilterTests.java @@ -42,7 +42,7 @@ class TokenEndpointAuthenticationFilterTests { private final UaaClientDetails client = new UaaClientDetails("foo", "resource", "scope", "authorization_code", "ROLE_CLIENT"); - private final ClientDetailsService clientDetailsService = clientId -> client; + private final ClientDetailsService clientDetailsService = _ -> client; private final OAuth2RequestFactory oAuth2RequestFactory = new DefaultOAuth2RequestFactory(clientDetailsService); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java index 2f39560560e..06b1cfaf713 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java @@ -50,7 +50,7 @@ public void setUp() throws Exception { @Test public void clientSpecificRefreshTokenExpiry() { getTokenServices().setRefreshTokenValiditySeconds(1000); - getTokenServices().setClientDetailsService(clientId -> { + getTokenServices().setClientDetailsService(_ -> { UaaClientDetails client = new UaaClientDetails(); client.setRefreshTokenValiditySeconds(100); client.setAuthorizedGrantTypes(Arrays.asList("authorization_code", "refresh_token")); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractPersistentDefaultTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractPersistentDefaultTokenServicesTests.java index 0179693e1bb..8d6553f5e79 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractPersistentDefaultTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractPersistentDefaultTokenServicesTests.java @@ -25,7 +25,7 @@ public abstract class AbstractPersistentDefaultTokenServicesTests extends Abstra public void tokenEnhancerUpdatesStoredTokens() { final ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken("testToken", new Date( System.currentTimeMillis() + 100000)); - getTokenServices().setTokenEnhancer((accessToken, authentication) -> { + getTokenServices().setTokenEnhancer((accessToken, _) -> { DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken); result.setRefreshToken(refreshToken); return result; @@ -41,7 +41,7 @@ public void tokenEnhancerUpdatesStoredTokens() { @Test public void refreshedTokenIsEnhanced() { - getTokenServices().setTokenEnhancer((accessToken, authentication) -> { + getTokenServices().setTokenEnhancer((accessToken, _) -> { DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken); result.setValue("I'mEnhanced"); return result; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java index f74612ea196..87e9b1a80d0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java @@ -98,7 +98,7 @@ void signedProviderAsymmetricKeys() { keyInfoService.getKeys().values().forEach(keyInfo -> { try { jwkList.add(JWK.parse(keyInfo.getJwkMap())); - } catch (ParseException e) { + } catch (ParseException _) { // ignore } }); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/matchers/AbstractOAuth2AccessTokenMatchers.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/matchers/AbstractOAuth2AccessTokenMatchers.java index 00298a949d8..22302e38c91 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/matchers/AbstractOAuth2AccessTokenMatchers.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/matchers/AbstractOAuth2AccessTokenMatchers.java @@ -44,12 +44,10 @@ protected String getToken(String token) { protected Map getClaims(T token) { String tokenValue; - if (token instanceof OAuth2AccessToken accessToken) { - tokenValue = accessToken.getValue(); - } else if (token instanceof OAuth2RefreshToken refreshToken) { - tokenValue = refreshToken.getValue(); - } else { - throw new IllegalArgumentException("token must be instanceof OAuth2AccessToken or OAuth2RefreshToken"); + switch (token) { + case OAuth2AccessToken accessToken -> tokenValue = accessToken.getValue(); + case OAuth2RefreshToken refreshToken -> tokenValue = refreshToken.getValue(); + case null, default -> throw new IllegalArgumentException("token must be instanceof OAuth2AccessToken or OAuth2RefreshToken"); } Jwt tokenJwt = JwtHelper.decode(getToken(tokenValue)); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java index ac481cd6d0a..f069ca8cd35 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java @@ -59,7 +59,7 @@ void encodePassword() { try { comparator.encode("test"); fail("Method and test not implemented yet."); - } catch (UnsupportedOperationException ignored) { + } catch (UnsupportedOperationException _) { } } @@ -68,7 +68,7 @@ void isPasswordValid() { try { comparator.matches("test", "test"); fail("Method and test not implemented yet."); - } catch (UnsupportedOperationException ignored) { + } catch (UnsupportedOperationException _) { } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java index 7e0812a010e..6e3bc95bfce 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java @@ -548,7 +548,7 @@ void updateExistingUserWithDifferentAttributes() throws Exception { try { userDatabase.retrieveUserByName(TEST_USERNAME, OriginKeys.SAML); fail("user should not exist"); - } catch (UsernameNotFoundException ignored) { + } catch (UsernameNotFoundException _) { // expected } authenticate(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java index 37564dfc7cc..e3b67f6400f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java @@ -181,7 +181,7 @@ void sha256Signature() throws CertificateEncodingException { when(resolver.resolve(request, REGISTRATION_ID)).thenReturn(registration); ResponseEntity response = endpoint.metadataEndpoint(request); - System.out.println(response.getBody()); + IO.println(response.getBody()); XmlAssert xmlAssert = XmlAssert.assertThat(response.getBody()).withNamespaceContext(xmlNamespaces()); xmlAssert.valueByXPath("/md:EntityDescriptor/@ID").isEqualTo(ENTITY_ID); xmlAssert.valueByXPath("/md:EntityDescriptor/ds:Signature/ds:SignedInfo/ds:SignatureMethod/@Algorithm").isEqualTo(ALGO_ID_SIGNATURE_RSA_SHA256); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/TestOpenSamlObjects.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/TestOpenSamlObjects.java index 380a9d41d82..207b12dc55e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/TestOpenSamlObjects.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/TestOpenSamlObjects.java @@ -126,7 +126,7 @@ public static Response response(String destination, String issuerEntityId) { } static Response signedResponseWithOneAssertion() { - return signedResponseWithOneAssertion(response -> { + return signedResponseWithOneAssertion(_ -> { }); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/config/InitialConfigTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/config/InitialConfigTest.java index f92029b4ef8..857acac3815 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/config/InitialConfigTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/config/InitialConfigTest.java @@ -45,7 +45,7 @@ class InitialConfigTest { void create() { InitialConfig ic = InitialConfig.create(); assertThat(ic).isNotNull(); - System.out.println("InitialConfigTest.create, RateLimitingEnabled: " + ic.isRateLimitingEnabled()); + IO.println("InitialConfigTest.create, RateLimitingEnabled: " + ic.isRateLimitingEnabled()); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java index f117662fe01..16a60835356 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java @@ -111,7 +111,7 @@ public void checkEmailFromClaims() { when(requestInfo.getAuthorizationHeader()).thenReturn(AUTH_HEADER_VALUE_PREFIX_UC + jwt); id = factory.mapAuthorizationToCredentialsID(requestInfo); assertThat(id).isEqualTo("|" + email + "|"); - System.out.println(email + " -> " + jwt); + IO.println(email + " -> " + jwt); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterTest.java index ab37331bff7..f7a4e9bcb32 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/common/InternalLimiterTest.java @@ -234,7 +234,7 @@ public void run() { coordinator.waitForStart(); for (int i = 0; !checkList(toProcess); i++) { if ((i & 31) == 0) { - System.out.print(threadNumber); + IO.print(threadNumber); } } coordinator.done(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBucketsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBucketsTest.java index 6e3dd075eab..b46223ef5e2 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBucketsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/ExpirationBucketsTest.java @@ -66,7 +66,7 @@ private void assertBadBucketSecondRequest(long second) { try { bucket = buckets.getBucket(second); - } catch (BucketRingBoundsException expected) { + } catch (BucketRingBoundsException _) { // Ignore return; } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterManagerImplTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterManagerImplTest.java index 13b63907906..db59d12cb47 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterManagerImplTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterManagerImplTest.java @@ -139,7 +139,7 @@ private void recordCall(List iLimiters) { String callerID; String servletPath; - AuthorizationCredentialIdExtractor credentialIdExtractor = info -> callerID; + AuthorizationCredentialIdExtractor credentialIdExtractor = _ -> callerID; RequestInfo requestInfo = new RequestInfo() { @Override diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java index 751def8acab..4e64762e35f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java @@ -63,7 +63,7 @@ private int check(boolean expectedFound, String servletPath) { Instant start = Instant.now(); LimiterMapping found = mapper.get(servletPath); int calls = selector.calls; - System.out.println(Duration.between(start, Instant.now()).toNanos() + "ns: " + calls + " -> " + servletPath); + IO.println(Duration.between(start, Instant.now()).toNanos() + "ns: " + calls + " -> " + servletPath); if (expectedFound) { assertThat(found).isNotNull(); } else { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrapTests.java index 225eac612ec..acde4fab17f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimGroupBootstrapTests.java @@ -92,7 +92,7 @@ void initScimGroupBootstrapTests() throws SQLException { @Test void canAddGroups() { - bootstrap.setGroups(StringUtils.commaDelimitedListToSet("org1.dev,org1.qa,org1.engg,org1.mgr,org1.hr").stream().collect(new MapCollector<>(s -> s, s -> null))); + bootstrap.setGroups(StringUtils.commaDelimitedListToSet("org1.dev,org1.qa,org1.engg,org1.mgr,org1.hr").stream().collect(new MapCollector<>(s -> s, _ -> null))); bootstrap.afterPropertiesSet(); assertThat(gDB.retrieveAll(IdentityZone.getUaaZoneId())).hasSize(5); assertThat(bootstrap.getGroup("org1.dev")).isNotNull(); @@ -105,7 +105,7 @@ void canAddGroups() { @Test void allowsBootstrapFromOtherInstance() { //original bootstrap - bootstrap.setGroups(StringUtils.commaDelimitedListToSet("multiple_bootstrap_group").stream().collect(new MapCollector<>(s -> s, s -> null))); + bootstrap.setGroups(StringUtils.commaDelimitedListToSet("multiple_bootstrap_group").stream().collect(new MapCollector<>(s -> s, _ -> null))); bootstrap.afterPropertiesSet(); //mock external bootstrap in between getOrCreate and update calls diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java index 9462093d50d..4173fbaf05f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java @@ -274,7 +274,7 @@ void shouldThrow_IfAliasPropertiesAreInvalid() { void shouldThrow_IfAliasIsLocked() { when(scimUserAliasHandler.aliasPropertiesAreValid(originalUser, existingOriginalUser)) .thenReturn(true); - when(transactionTemplate.execute(any())).then(invocationOnMock -> { + when(transactionTemplate.execute(any())).then(_ -> { throw new OptimisticLockingFailureException("The alias is locked."); }); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java index 1d50be47526..916b4ad0b00 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java @@ -1437,7 +1437,7 @@ void canCreateUserWithValidOrigin() { idzManager.getCurrentIdentityZone().getConfig().getUserConfig().setCheckOriginEnabled(true); try { jdbcScimUserProvisioning.create(scimUser, currentIdentityZoneId); - } catch (InvalidScimResourceException e) { + } catch (InvalidScimResourceException _) { fail("Can't create user with valid origin when origin is checked"); } finally { idzManager.getCurrentIdentityZone().getConfig().getUserConfig().setCheckOriginEnabled(false); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/test/JsonObjectMatcherUtils.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/test/JsonObjectMatcherUtils.java index 3078a900575..98494026e9d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/test/JsonObjectMatcherUtils.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/test/JsonObjectMatcherUtils.java @@ -54,7 +54,7 @@ public boolean matches(Object item) { JSONObject actual = null; try { actual = new JSONObject(new JSONTokener(item.toString())); - } catch (JSONException e) { + } catch (JSONException _) { return false; } @@ -70,7 +70,7 @@ public boolean matches(Object item) { if (!Objects.equals(expected.get(name), actual.get(name))) { return false; } - } catch (JSONException e) { + } catch (JSONException _) { return false; } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManagerTest.java index f6079eeca37..e33e981a0e1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManagerTest.java @@ -41,7 +41,7 @@ void checkServerTrusted_throwsExceptionWhenCertIsExpired() throws Exception { try { manager.checkServerTrusted(x509Certificates, "string"); fail(""); - } catch (CertificateExpiredException e) { + } catch (CertificateExpiredException _) { verify(mockedDelegate).checkServerTrusted(x509Certificates, "string"); verify(certificate).checkValidity(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java index 9e25f734eaa..1ff19c7f130 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java @@ -469,7 +469,7 @@ private static void assertXhrCorsPreFlightResponse(final MockHttpServletResponse } private static FilterChain newMockFilterChain() { - return (request, response) -> { + return (_, _) -> { // Do nothing. }; } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java index 2967ec07654..d3af83c6541 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java @@ -456,7 +456,7 @@ private void setupBaselineCorsPolicyDefaultConfiguration() { } private static FilterChain newMockFilterChain() { - return (request, response) -> { + return (_, _) -> { // Do nothing. }; } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessorTests.java index 71ed3c8358a..0e8db1382cd 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/SecurityFilterChainPostProcessorTests.java @@ -157,7 +157,7 @@ void uaaLoggingFilter_invalidParameterException_returns400JsonAndDoesNotPropagat MockHttpServletRequest request = new MockHttpServletRequest("GET", "/oauth/token"); MockHttpServletResponse response = new MockHttpServletResponse(); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, _) -> { throw new InvalidParameterException("bad encoding"); }; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java b/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java index 5eb53fb2f22..d49500d6c0f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java @@ -78,7 +78,7 @@ private static void cleanAndSeedDb(ApplicationContext applicationContext) throws JdbcTemplate jdbcTemplate; try { jdbcTemplate = applicationContext.getBean(JdbcTemplate.class); - } catch (NoSuchBeanDefinitionException ignored) { + } catch (NoSuchBeanDefinitionException _) { return; } @@ -118,7 +118,7 @@ private static void bootstrapDb(ApplicationContext applicationContext) { try { ClientAdminBootstrap bootstrap = applicationContext.getBean(ClientAdminBootstrap.class); bootstrap.afterPropertiesSet(); - } catch (Exception ignored) { + } catch (Exception _) { } } @@ -127,7 +127,7 @@ private static void tryCallAfterPropertiesSet(Appli try { InitializingBean bootstrap = applicationContext.getBean(clazz); bootstrap.afterPropertiesSet(); - } catch (Exception ignored) { + } catch (Exception _) { } } @@ -144,10 +144,10 @@ public static void resetIdentityZoneHolder(ApplicationContext applicationContext try { IdentityZoneHolder.setProvisioning(applicationContext.getBean(JdbcIdentityZoneProvisioning.class)); IdentityZoneHolder.setSamlKeyManagerFactory(applicationContext.getBean(SamlKeyManagerFactory.class)); - } catch (NoSuchBeanDefinitionException ignored) { + } catch (NoSuchBeanDefinitionException _) { try { IdentityZoneHolder.setProvisioning(new JdbcIdentityZoneProvisioning(applicationContext.getBean(JdbcTemplate.class))); - } catch (NoSuchBeanDefinitionException ignoredAgain) { + } catch (NoSuchBeanDefinitionException _) { IdentityZoneHolder.setProvisioning(null); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java index 6013b8b900a..1f8934dc2df 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java @@ -391,7 +391,7 @@ void maxParameters() { validateBob(5, jdbcUaaUserDatabase.retrieveUserByName("bob", OriginKeys.UAA), l); for (int i = 5; i < 10; i++) { - System.out.println(i); + IO.println(i); addAuthority("testAuth" + l + i, jdbcTemplate, "zone-the-bob", BOB_ID); } validateBob(10, jdbcUaaUserDatabase.retrieveUserByName("bob", OriginKeys.UAA), l); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserTests.java index 01c232c97a0..7a4f05778a5 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserTests.java @@ -59,7 +59,7 @@ void defaultsUsernameToEmail() { @Test void defaultsUsernameToUnknownWhenNoEmailPresent() { - UaaUser user = UaaUser.createWithDefaults(u -> { + UaaUser user = UaaUser.createWithDefaults(_ -> { }); assertThat(user.getUsername()).isEqualTo(UaaUser.DEFAULT_USER_NAME); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java index 42b07695677..fe0028989a2 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java @@ -787,6 +787,6 @@ void readScopesFromClaim_rejects_non_string_scopes() { void nullUserIsCaught() { assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkUser(uid -> null)); + .checkUser(_ -> null)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/PredicateMatcher.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/PredicateMatcher.java index c8f72a2ce88..034ee163e07 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/PredicateMatcher.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/PredicateMatcher.java @@ -38,7 +38,7 @@ public static Matcher> has(Predicate predicate) { public boolean matches(Object item) { try { return predicate.test((T) item); - } catch (ClassCastException ex) { + } catch (ClassCastException _) { return false; } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java index 70ca1be1ea8..66f00a6310d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java @@ -141,7 +141,7 @@ public void testHttpProxy(String url, int expectedPort, String expectedHost, boo RestTemplate template = new RestTemplate(UaaHttpRequestUtils.createRequestFactory(builder, Integer.MAX_VALUE)); try { template.getForObject(url, String.class); - } catch (Exception ignored) { + } catch (Exception _) { // ignored } assertThat(routePlanner.routes).hasSize(1); @@ -167,7 +167,7 @@ void clientBuilderAppliesReadTimeout() throws Exception { try (var socket = ss.accept()) { // Sleep longer than the read timeout so the client times out first. Thread.sleep(readTimeoutMs * 10L); - } catch (Exception ignored) {} + } catch (Exception _) {} }); acceptThread.setDaemon(true); acceptThread.start(); @@ -204,7 +204,7 @@ void clientBuilderWithZeroTimeoutsDoesNotTimeOut() throws Exception { out.write(response.getBytes(StandardCharsets.US_ASCII)); out.flush(); clientSocket.close(); - } catch (Exception ignored) {} + } catch (Exception _) {} }); serverThread.setDaemon(true); serverThread.start(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java index 551cb4ea333..609ef8f1089 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java @@ -680,7 +680,7 @@ private static void validateRedirectUri(List urls, boolean result) { Map failed = getUnsuccessfulUrls(urls, result); if (!failed.isEmpty()) { StringBuilder builder = new StringBuilder("\n"); - failed.forEach((key, value) -> builder.append(value).append("\n")); + failed.forEach((_, value) -> builder.append(value).append("\n")); fail(builder.toString()); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java index c580bcd6f3a..41acfc223f3 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java @@ -117,7 +117,7 @@ void remove_keys_from_map() { assertThat(identityZone.getConfig().getSamlConfig().getPrivateKey()).isNull(); assertThat(identityZone.getConfig().getSamlConfig().getPrivateKeyPassword()).isNull(); - identityZone.getConfig().getSamlConfig().getKeys().forEach((key, value) -> { + identityZone.getConfig().getSamlConfig().getKeys().forEach((_, value) -> { assertThat(value.getKey()).isNull(); assertThat(value.getPassphrase()).isNull(); }); @@ -132,7 +132,7 @@ void restore_keys() { assertThat(identityZone.getConfig().getSamlConfig().getPrivateKey()).isNotNull(); assertThat(identityZone.getConfig().getSamlConfig().getPrivateKeyPassword()).isNotNull(); - identityZone.getConfig().getSamlConfig().getKeys().forEach((key, value) -> { + identityZone.getConfig().getSamlConfig().getKeys().forEach((_, value) -> { assertThat(value.getKey()).isNotNull(); assertThat(value.getPassphrase()).isNotNull(); }); @@ -225,7 +225,7 @@ private static IdentityZone createZone() { assertThat(zone.getConfig().getSamlConfig().getPrivateKey()).isNotNull(); assertThat(zone.getConfig().getSamlConfig().getPrivateKeyPassword()).isNotNull(); - zone.getConfig().getSamlConfig().getKeys().forEach((key, value) -> { + zone.getConfig().getSamlConfig().getKeys().forEach((_, value) -> { assertThat(value.getKey()).isNotNull(); assertThat(value.getPassphrase()).isNotNull(); }); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterTests.java index 6fcb95e6b0d..cea65005d7d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterTests.java @@ -134,7 +134,7 @@ private void assertFindsCorrectSubdomain(final String subDomainInput, final Stri identityZone.setSubdomain(subDomainInput); try { identityZone = dao.create(identityZone); - } catch (ZoneAlreadyExistsException x) { + } catch (ZoneAlreadyExistsException _) { identityZone = dao.retrieveBySubdomain(subDomainInput); } assertThat(identityZone.getSubdomain()).isEqualTo(expectedSubdomain); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterZonePathTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterZonePathTests.java index a8c464fd478..2787bf97145 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterZonePathTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneResolvingFilterZonePathTests.java @@ -65,7 +65,7 @@ void tearDown() { } private FilterChain chainThatCapturesHolder() { - return (req, res) -> { + return (_, _) -> { chainInvoked.set(true); zoneInHolderWhenChainInvoked.set(IdentityZoneHolder.get()); }; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java index 4d09b33de2e..0c9354fb686 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java @@ -189,7 +189,7 @@ void createDuplicateIdentityZone() { try { jdbcIdentityZoneProvisioning.create(identityZone); fail("Should have thrown exception"); - } catch (ZoneAlreadyExistsException e) { + } catch (ZoneAlreadyExistsException _) { // success } } @@ -203,7 +203,7 @@ void createDuplicateIdentityZoneSubdomain() { identityZone.setId(new RandomValueStringGenerator().generate()); jdbcIdentityZoneProvisioning.create(identityZone); fail("Should have thrown exception"); - } catch (ZoneAlreadyExistsException e) { + } catch (ZoneAlreadyExistsException _) { // success } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java index 75ee2f914b7..bc5e37a9750 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java @@ -113,7 +113,7 @@ void deleteByClientId() { when(mockIdentityZoneManager.getCurrentIdentityZoneId()).thenReturn(zoneId); try { service.removeClientDetails("some-client-id"); - } catch (Exception ignored) { + } catch (Exception _) { } verify(service, times(1)).deleteByClient(eq("some-client-id"), eq(zoneId)); reset(service); @@ -130,7 +130,7 @@ void deleteByClientRespectsZoneIdParam() { when(mockIdentityZoneManager.getCurrentIdentityZoneId()).thenReturn(zoneId); try { service.deleteByClient("some-client-id", "zone-id"); - } catch (Exception ignored) { + } catch (Exception _) { } verify(service, times(1)).deleteByClient(eq("some-client-id"), eq("zone-id")); verify(spyJdbcTemplate, times(1)).update(DEFAULT_DELETE_STATEMENT, "some-client-id", "zone-id"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java index 9fb4532918c..b9a1649fe01 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java @@ -951,7 +951,7 @@ void multipleZones_sameContainerSession() throws ServletException, IOException { request2.setContextPath("/uaa/z/zone2"); request2.setSession(containerSession); MockHttpServletResponse response2 = new MockHttpServletResponse(); - filter.doFilter(request2, response2, (req, resp) -> { + filter.doFilter(request2, response2, (req, _) -> { ((HttpServletRequest) req).getSession(true).setAttribute("user", "bob"); }); @@ -968,7 +968,7 @@ void containerSessionInvalidated_insideChain_handledGracefully() throws ServletE MockHttpSession containerSession = new MockHttpSession(); request.setSession(containerSession); - filter.doFilter(request, response, (req, resp) -> { + filter.doFilter(request, response, (req, _) -> { HttpServletRequest httpReq = (HttpServletRequest) req; httpReq.getSession(true).setAttribute("data", "val"); containerSession.invalidate(); @@ -992,7 +992,7 @@ void logoutFromOneZone_leavesOtherZonesIntact() throws ServletException, IOExcep MockHttpServletRequest zoneReq = new MockHttpServletRequest(); zoneReq.setContextPath("/uaa/z/zone1"); zoneReq.setSession(containerSession); - filter.doFilter(zoneReq, new MockHttpServletResponse(), (req, resp) -> { + filter.doFilter(zoneReq, new MockHttpServletResponse(), (req, _) -> { ((HttpServletRequest) req).getSession(true).setAttribute("user", "zone1-user"); }); @@ -1000,7 +1000,7 @@ void logoutFromOneZone_leavesOtherZonesIntact() throws ServletException, IOExcep MockHttpServletRequest logoutReq = new MockHttpServletRequest(); logoutReq.setContextPath("/uaa/z/zone1"); logoutReq.setSession(containerSession); - filter.doFilter(logoutReq, new MockHttpServletResponse(), (req, resp) -> { + filter.doFilter(logoutReq, new MockHttpServletResponse(), (req, _) -> { ((HttpServletRequest) req).getSession(false).invalidate(); }); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java index eea92c02d8d..7f5e05b91f4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java @@ -51,7 +51,7 @@ void pathWithoutZonePrefix_passesRequestUnchanged() throws ServletException, IOE request.setRequestURI("/uaa/login"); request.setServletPath("/login"); // container would set this; filter passes request as-is - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -67,7 +67,7 @@ void pathWithOnlyZ_noTrailingSlash_passesRequestUnchanged() throws ServletExcept request.setContextPath("/uaa"); request.setRequestURI("/uaa/z"); // does not start with /z/ so not treated as zone path - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_BAD_REQUEST); @@ -79,7 +79,7 @@ void pathWithOnlyZ_prefix_noSubdomain_rejectsWithBadRequest() throws ServletExce request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/"); // starts with /z/ but no subdomain segment - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); assertThat(requestPassedToChain.get()).isNull(); @@ -91,7 +91,7 @@ void pathWithZAndSubdomainButNoSlashAfter_rejectsWithBadRequest() throws Servlet request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); assertThat(requestPassedToChain.get()).isNull(); @@ -103,7 +103,7 @@ void pathWithEmptySubdomainSegment_rejectsWithBadRequest() throws ServletExcepti request.setContextPath("/uaa"); request.setRequestURI("/uaa/z//login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); assertThat(requestPassedToChain.get()).isNull(); @@ -118,7 +118,7 @@ void pathWithDefaultZonePrefix_withContextPath_rewritesToIncludeZonePathAndDoesN request.setServerPort(8080); request.setScheme("http"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -138,7 +138,7 @@ void pathWithDefaultZonePrefix_withoutContextPath_rewritesToIncludeZonePathAndDo request.setServerName("localhost"); request.setServerPort(8080); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -155,7 +155,7 @@ void pathWithDefaultZonePrefix_DEFAULT_caseInsensitive_rewritesSameAsLowercase() request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/" + DEFAULT_ZONE_SUBDOMAIN_PATH.toUpperCase() + "/profile"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -170,7 +170,7 @@ void pathWithDefaultZonePrefix_trailingSlash_rewritesWithServletPathEmptyAndPath request.setContextPath("/uaa"); request.setRequestURI("/uaa" + ZONE_PATH_PREFIX + DEFAULT_ZONE_SUBDOMAIN_PATH + "/"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -189,7 +189,7 @@ void pathWithZonePrefix_rewritesRequestAndSetsAttribute() throws ServletExceptio request.setServerPort(8080); request.setScheme("http"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -206,7 +206,7 @@ void pathWithZonePrefix_trailingSlashOnly_rewritesWithServletPathEmptyAndPathInf request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -225,7 +225,7 @@ void pathWithZonePrefix_multiplePathSegments_rewritesCorrectly() throws ServletE request.setServerPort(8443); request.setScheme("https"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -243,7 +243,7 @@ void emptyContextPath_rewritesCorrectly() throws ServletException, IOException { request.setServerName("localhost"); request.setServerPort(8080); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -260,7 +260,7 @@ void pathWithZonePrefix_Codes_rewritesServletPathToCodes() throws ServletExcepti request.setServerName("localhost"); request.setServerPort(8080); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -277,7 +277,7 @@ void pathWithZonePrefix_Codes_withContextPath_rewritesServletPathToCodes() throw request.setServerName("localhost"); request.setServerPort(8080); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -295,7 +295,7 @@ void getRequestURL_onWrappedRequest_returnsRewrittenPath() throws ServletExcepti request.setServerPort(443); request.setScheme("https"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -311,7 +311,7 @@ void getRequestURL_withNonStandardPort_includesPort() throws ServletException, I request.setServerPort(8080); request.setScheme("http"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -324,7 +324,7 @@ void contextPathSingleSlash_withZonePath_normalizesPathAndRewrites() throws Serv request.setRequestURI("/z/rootzone/oauth/token"); request.setServerName("localhost"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -339,7 +339,7 @@ void pathAfterContextEmpty_normalizedToSlash_noRewrite() throws ServletException request.setContextPath("/uaa"); request.setRequestURI("/uaa"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); assertThat(request.getAttribute(ZonePathContextRewritingFilter.ZONE_SUBDOMAIN_FROM_PATH)).isNull(); @@ -350,7 +350,7 @@ void subdomainWithHyphen_rewritesCorrectly() throws ServletException, IOExceptio request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/my-zone-name/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -366,7 +366,7 @@ void pathWithZonePrefix_setsZoneOriginalContextPathAttribute() throws ServletExc request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -378,7 +378,7 @@ void pathWithZonePrefix_emptyContextPath_setsZoneOriginalContextPathToEmpty() th request.setContextPath(""); request.setRequestURI("/z/testzone/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -390,7 +390,7 @@ void pathWithZonePrefix_contextPathSingleSlash_setsZoneOriginalContextPathToSlas request.setContextPath("/"); request.setRequestURI("/z/rootzone/oauth/token"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -402,7 +402,7 @@ void pathWithoutZonePrefix_setsZoneOriginalContextPathToActualContextPath() thro request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -416,7 +416,7 @@ void cookieWithPathSlash_whenZonePathRewritten_rewritesToOriginalContextPath() t request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, res) -> { Cookie c = new Cookie("TestCookie", "value"); c.setPath("/"); ((HttpServletResponse) res).addCookie(c); @@ -433,7 +433,7 @@ void cookieWithPathOtherThanSlash_whenZonePathRewritten_leavesPathUnchanged() th request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, res) -> { Cookie c = new Cookie("X", "v"); c.setPath("/uaa/other"); ((HttpServletResponse) res).addCookie(c); @@ -450,7 +450,7 @@ void cookieWithPathNull_whenZonePathRewritten_rewritesToOriginalContextPath() th request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, res) -> { Cookie c = new Cookie("S", "v"); ((HttpServletResponse) res).addCookie(c); }; @@ -466,7 +466,7 @@ void noZonePath_withContextPath_rewritesCookiePathToContextPath() throws Servlet request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, res) -> { Cookie c = new Cookie("A", "b"); c.setPath("/"); ((HttpServletResponse) res).addCookie(c); @@ -483,7 +483,7 @@ void emptyOriginalContextPath_cookiePathRemainsSlash() throws ServletException, request.setContextPath(""); request.setRequestURI("/z/myzone/login"); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, res) -> { Cookie c = new Cookie("C", "d"); c.setPath("/"); ((HttpServletResponse) res).addCookie(c); @@ -500,7 +500,7 @@ void originalContextPathSingleSlash_cookiePathRemainsSlash() throws ServletExcep request.setContextPath("/"); request.setRequestURI("/z/rootzone/login"); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, res) -> { Cookie c = new Cookie("K", "v"); c.setPath("/"); ((HttpServletResponse) res).addCookie(c); @@ -517,7 +517,7 @@ void multipleCookies_mixedPaths_rewritesOnlySlashPath() throws ServletException, request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> { + FilterChain chain = (_, res) -> { HttpServletResponse httpRes = (HttpServletResponse) res; Cookie c1 = new Cookie("One", "1"); c1.setPath("/"); @@ -541,7 +541,7 @@ void addHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOrigin request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "MyCookie=val; Path=/; HttpOnly"); + FilterChain chain = (_, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "MyCookie=val; Path=/; HttpOnly"); filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); @@ -554,7 +554,7 @@ void addHeaderSetCookie_withNoPath_whenZonePathRewritten_addsPathOriginalContext request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "Session=abc; HttpOnly"); + FilterChain chain = (_, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "Session=abc; HttpOnly"); filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); @@ -566,7 +566,7 @@ void addHeaderSetCookie_withPathOtherThanSlash_whenZonePathRewritten_leavesPathU request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "X=1; Path=/uaa/other"); + FilterChain chain = (_, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "X=1; Path=/uaa/other"); filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); @@ -578,7 +578,7 @@ void setHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOrigin request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> ((HttpServletResponse) res).setHeader("Set-Cookie", "Foo=bar; Path=/; Secure"); + FilterChain chain = (_, res) -> ((HttpServletResponse) res).setHeader("Set-Cookie", "Foo=bar; Path=/; Secure"); filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); @@ -591,7 +591,7 @@ void addHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws ServletEx request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "Current-User=encoded; Path=/; HttpOnly"); + FilterChain chain = (_, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "Current-User=encoded; Path=/; HttpOnly"); filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); @@ -604,7 +604,7 @@ void setHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws ServletEx request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); - FilterChain chain = (req, res) -> ((HttpServletResponse) res).setHeader("Set-Cookie", "Current-User=val; Path=/"); + FilterChain chain = (_, res) -> ((HttpServletResponse) res).setHeader("Set-Cookie", "Current-User=val; Path=/"); filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); @@ -616,7 +616,7 @@ void addHeaderSetCookie_withPathSlash_whenNoContextPath_leavesPathSlash() throws request.setContextPath(""); request.setRequestURI("/z/myzone/login"); - FilterChain chain = (req, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "A=B; Path=/"); + FilterChain chain = (_, res) -> ((HttpServletResponse) res).addHeader("Set-Cookie", "A=B; Path=/"); filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); @@ -631,7 +631,7 @@ void zonePathsDisabled_zonePathRequest_returns404() throws ServletException, IOE request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); disabledFilter.doFilter(request, response, chain); assertThat(requestPassedToChain.get()).isNull(); @@ -644,7 +644,7 @@ void zonePathsDisabled_nonZonePathRequest_passesThrough() throws ServletExceptio request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); disabledFilter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -658,7 +658,7 @@ void zonePathsEnabled_zonePathRequest_rewritesNormally() throws ServletException request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); enabledFilter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); @@ -672,7 +672,7 @@ void defaultConstructor_zonePathsEnabled() throws ServletException, IOException request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); - FilterChain chain = (req, res) -> requestPassedToChain.set((HttpServletRequest) req); + FilterChain chain = (req, _) -> requestPassedToChain.set((HttpServletRequest) req); filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); diff --git a/statsd-lib/src/test/java/org/cloudfoundry/identity/statsd/integration/UaaMetricsEmitterIT.java b/statsd-lib/src/test/java/org/cloudfoundry/identity/statsd/integration/UaaMetricsEmitterIT.java index 0e743a55ca1..563be83c861 100644 --- a/statsd-lib/src/test/java/org/cloudfoundry/identity/statsd/integration/UaaMetricsEmitterIT.java +++ b/statsd-lib/src/test/java/org/cloudfoundry/identity/statsd/integration/UaaMetricsEmitterIT.java @@ -128,7 +128,7 @@ private static Map getMessages(List fragments) throws IO results.put(fragment, message); } }); - } catch (SocketTimeoutException e) { + } catch (SocketTimeoutException _) { //expected so that we keep looping } } while (results.size() < fragments.size() && (System.nanoTime() < (startTime + UaaMetricsEmitterIT.WAIT_FOR_MESSAGE))); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/OpenApiConfigurationTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/OpenApiConfigurationTest.java index beb6f2bc32a..83258f3c8f3 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/OpenApiConfigurationTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/OpenApiConfigurationTest.java @@ -77,8 +77,8 @@ void openAPIServerUrlComesFromBuildInfo() { OpenAPI openAPI = openApiConfiguration.uaaOpenAPI(); assertThat(openAPI.getServers()).hasSize(1); - assertThat(openAPI.getServers().get(0).getUrl()).isEqualTo("https://uaa.example.com"); - assertThat(openAPI.getServers().get(0).getDescription()).isEqualTo("UAA Server"); + assertThat(openAPI.getServers().getFirst().getUrl()).isEqualTo("https://uaa.example.com"); + assertThat(openAPI.getServers().getFirst().getDescription()).isEqualTo("UAA Server"); } @Test @@ -86,7 +86,7 @@ void openAPIHasBearerAuthSecurityRequirement() { OpenAPI openAPI = openApiConfiguration.uaaOpenAPI(); assertThat(openAPI.getSecurity()).hasSize(1); - assertThat(openAPI.getSecurity().get(0).get("bearerAuth")).isNotNull(); + assertThat(openAPI.getSecurity().getFirst().get("bearerAuth")).isNotNull(); } @Test diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java index e2bc2556478..8297203a0d4 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java @@ -117,7 +117,7 @@ void nonUAAZoneUaaActiveAccountNotVerified() { try { manager.authenticate(success); fail("Expected AccountNotVerifiedException "); - } catch (AccountNotVerifiedException x) { + } catch (AccountNotVerifiedException _) { //expected } verify(mockManager, times(0)).authenticate(any(Authentication.class)); @@ -134,7 +134,7 @@ void nonUAAZoneUaaActiveAccountLocked() { try { manager.authenticate(success); fail("Expected AuthenticationPolicyRejectionException "); - } catch (AuthenticationPolicyRejectionException x) { + } catch (AuthenticationPolicyRejectionException _) { //expected } verify(mockManager, times(0)).authenticate(any(Authentication.class)); @@ -190,7 +190,7 @@ void authenticateInNoneUaaZoneWithInactiveProviders() { try { manager.authenticate(success); fail("Was expecting a " + ProviderNotFoundException.class); - } catch (ProviderNotFoundException x) { + } catch (ProviderNotFoundException _) { //expected } verifyNoInteractions(uaaAuthenticationMgr); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/AuthorizationCodeGrantIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/AuthorizationCodeGrantIntegrationTests.java index 286ab81235e..7915894b8e0 100755 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/AuthorizationCodeGrantIntegrationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/AuthorizationCodeGrantIntegrationTests.java @@ -209,7 +209,7 @@ void authorizationRequestWithoutRedirectUri() { IntegrationTestUtils.getAuthorizationCodeTokenMap(serverRunning, "app", "appclientsecret", testAccounts.getUserName(), testAccounts.getPassword(), null, null, null, null, false); - } catch (AssertionError error) { + } catch (AssertionError _) { // expected return; } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/CheckTokenEndpointIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/CheckTokenEndpointIntegrationTests.java index aa7b7f29288..65794457080 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/CheckTokenEndpointIntegrationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/CheckTokenEndpointIntegrationTests.java @@ -189,7 +189,7 @@ void invalidScope() { @SuppressWarnings("rawtypes") ResponseEntity response = serverRunning.postForMap("/check_token", requestBody, headers); - System.out.println(response.getBody()); + IO.println(response.getBody()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); @SuppressWarnings("unchecked") @@ -214,7 +214,7 @@ void validPasswordGrant() { ResponseEntity tokenResponse = serverRunning.postForMap("/check_token", formData, tokenHeaders); assertThat(tokenResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(tokenResponse.getBody()).isNotNull(); - System.out.println(tokenResponse.getBody()); + IO.println(tokenResponse.getBody()); @SuppressWarnings("unchecked") Map map = tokenResponse.getBody(); @@ -238,7 +238,7 @@ void addidionalAttributes() { ResponseEntity tokenResponse = serverRunning.postForMap("/check_token", formData, tokenHeaders); assertThat(tokenResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(tokenResponse.getBody()).isNotNull(); - System.out.println(tokenResponse.getBody()); + IO.println(tokenResponse.getBody()); @SuppressWarnings("unchecked") Map map = tokenResponse.getBody(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/IntrospectEndpointIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/IntrospectEndpointIntegrationTests.java index 81de4efc809..ce5df9a0c01 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/IntrospectEndpointIntegrationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/IntrospectEndpointIntegrationTests.java @@ -201,7 +201,7 @@ void validPasswordGrantClientSecretAuth() { ResponseEntity introspectResponse = serverRunning.postForMap("/introspect", formData, tokenHeaders); assertThat(introspectResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(introspectResponse.getBody()).isNotNull(); - System.out.println(introspectResponse.getBody()); + IO.println(introspectResponse.getBody()); @SuppressWarnings("unchecked") Map map = introspectResponse.getBody(); @@ -224,7 +224,7 @@ void validPasswordGrantClientSecretAuthWithSpecialCharacters() { ResponseEntity introspectResponse = serverRunning.postForMap("/introspect", formData, tokenHeaders); assertThat(introspectResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(introspectResponse.getBody()).isNotNull(); - System.out.println(introspectResponse.getBody()); + IO.println(introspectResponse.getBody()); @SuppressWarnings("unchecked") Map map = introspectResponse.getBody(); @@ -248,7 +248,7 @@ void validPasswordGrantClientTokenAuth() { ResponseEntity introspectResponse = serverRunning.postForMap("/introspect", formData, tokenHeaders); assertThat(introspectResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(introspectResponse.getBody()).isNotNull(); - System.out.println(introspectResponse.getBody()); + IO.println(introspectResponse.getBody()); @SuppressWarnings("unchecked") Map map = introspectResponse.getBody(); @@ -272,7 +272,7 @@ void validPasswordGrantClientTokenAuthWithSpecialCharacters() { ResponseEntity introspectResponse = serverRunning.postForMap("/introspect", formData, tokenHeaders); assertThat(introspectResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(introspectResponse.getBody()).isNotNull(); - System.out.println(introspectResponse.getBody()); + IO.println(introspectResponse.getBody()); @SuppressWarnings("unchecked") Map map = introspectResponse.getBody(); @@ -297,7 +297,7 @@ void validPasswordGrantValidClientTokenAndInvalidBasicAuth() { ResponseEntity introspectResponse = serverRunning.postForMap("/introspect", formData, tokenHeaders); assertThat(introspectResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(introspectResponse.getBody()).isNotNull(); - System.out.println(introspectResponse.getBody()); + IO.println(introspectResponse.getBody()); @SuppressWarnings("unchecked") Map map = introspectResponse.getBody(); @@ -401,7 +401,7 @@ void addidionalAttributes() { ResponseEntity introspectResponse = serverRunning.postForMap("/introspect", formData, tokenHeaders); assertThat(introspectResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(introspectResponse.getBody()).isNotNull(); - System.out.println(introspectResponse.getBody()); + IO.println(introspectResponse.getBody()); @SuppressWarnings("unchecked") Map map = introspectResponse.getBody(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PrintSmtpToScreen.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PrintSmtpToScreen.java index d9357cc8333..beb2ffb3330 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PrintSmtpToScreen.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PrintSmtpToScreen.java @@ -26,7 +26,7 @@ public static void main(String... args) throws Exception { GreenMail server = new GreenMail(new ServerSetup(2525, null, ServerSetup.PROTOCOL_SMTP)); server.start(); Runtime.getRuntime().addShutdownHook(new Thread(() -> { - System.out.println("Stopping SMTP server"); + IO.println("Stopping SMTP server"); server.stop(); })); @@ -34,7 +34,7 @@ public static void main(String... args) throws Exception { while (true) { MimeMessage[] messages = server.getReceivedMessages(); for (int i = lastCount; i < messages.length; i++) { - System.out.println(GreenMailUtil.getBody(messages[i])); + IO.println(GreenMailUtil.getBody(messages[i])); } lastCount = messages.length; Thread.sleep(250); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/SessionControllerIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/SessionControllerIntegrationTests.java index 708ee59cde1..60d5ed0fd3e 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/SessionControllerIntegrationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/SessionControllerIntegrationTests.java @@ -30,7 +30,7 @@ class SessionControllerIntegrationTests { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } @@ -43,7 +43,7 @@ void sessionPageHasTheFunction() { "/session?clientId=admin&messageOrigin=http://localhost:8080"); WebDriverWait wait = webDriver.createWebDriverWait(); - Object type = wait.until(driver -> { + Object type = wait.until(_ -> { Object t = webDriver.getJavascriptExecutor().executeScript( "return typeof(handleMessage);"); return "function".equals(String.valueOf(t)) ? t : null; @@ -60,13 +60,13 @@ void sessionManagementPageHasVariablesSet() { // Use WebDriverWait to wait for the variable to exist (prevents race conditions) // return null instead of crashing if undefined (better assertion handling) WebDriverWait wait = webDriver.createWebDriverWait(); - Object clientId = wait.until(driver -> webDriver.getJavascriptExecutor().executeScript( + Object clientId = wait.until(_ -> webDriver.getJavascriptExecutor().executeScript( "return (typeof clientId !== 'undefined') ? clientId : null;")); assertThat(clientId).as("Global variable 'clientId' should match URL param") .hasToString("admin"); - Object origin = wait.until(driver -> webDriver.getJavascriptExecutor().executeScript( + Object origin = wait.until(_ -> webDriver.getJavascriptExecutor().executeScript( "return (typeof messageOrigin !== 'undefined') ? messageOrigin : null;")); assertThat(origin).as("Global variable 'messageOrigin' should match URL param") diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AppApprovalIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AppApprovalIT.java index 76efc408b43..858852505e1 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AppApprovalIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AppApprovalIT.java @@ -74,7 +74,7 @@ void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AutologinIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AutologinIT.java index f2872dc1129..c72d12b8322 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AutologinIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/AutologinIT.java @@ -81,7 +81,7 @@ void logout_and_clear_cookies() { map.add("password", testAccounts.getPassword()); try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangeEmailIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangeEmailIT.java index a829c3ecd8e..e9c6ed855bc 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangeEmailIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangeEmailIT.java @@ -44,7 +44,7 @@ class ChangeEmailIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangePasswordIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangePasswordIT.java index 087cb33a6bc..31bc391b2a6 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangePasswordIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ChangePasswordIT.java @@ -63,7 +63,7 @@ public class ChangePasswordIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/CreateAccountIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/CreateAccountIT.java index 036b5ef861d..e0db98e33e7 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/CreateAccountIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/CreateAccountIT.java @@ -67,7 +67,7 @@ class CreateAccountIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java index d30b1568c68..cb67c823141 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java @@ -112,7 +112,7 @@ private String getResponseBody(HttpURLConnection connection) throws IOException while ((charsRead = reader.read(buffer, 0, bufferSize)) != -1) { sb.append(buffer, 0, charsRead); } - } catch (IOException ie) { + } catch (IOException _) { IOUtils.close(connection); } return sb.toString(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ForcedPasswordChangeIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ForcedPasswordChangeIT.java index 298d36e0875..9e3b5700967 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ForcedPasswordChangeIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ForcedPasswordChangeIT.java @@ -70,7 +70,7 @@ class ForcedPasswordChangeIT { void logoutAndClearCookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HealthzIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HealthzIT.java index f78195aa447..bc1976bbfb1 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HealthzIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HealthzIT.java @@ -43,7 +43,7 @@ class HealthzIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HomeIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HomeIT.java index f6a1a8615ef..1323e0ee091 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HomeIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/HomeIT.java @@ -58,7 +58,7 @@ class HomeIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } @@ -86,7 +86,7 @@ void profilePage() { try { homePage.goHome().assertThatPageSource().contains("Where to?"); webDriver.pressUaaNavigation("nav-dropdown-button", "nav-dropdown-content-profile"); - } catch (TimeoutException e) { + } catch (TimeoutException _) { webDriver.get(baseUrl + "/profile"); } WebDriverWait wait = webDriver.createWebDriverWait(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java index 073ed7853dd..2273e12e50f 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java @@ -74,7 +74,7 @@ public class ImplicitGrantIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } @@ -148,7 +148,7 @@ void invalidScopes() { assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.FOUND); - System.out.println("responseEntity.getHeaders().getLocation() = " + responseEntity.getHeaders().getLocation()); + IO.println("responseEntity.getHeaders().getLocation() = " + responseEntity.getHeaders().getLocation()); UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()).build(); assertThat(locationComponents.getHost()).isEqualTo("localhost"); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/InvitationsIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/InvitationsIT.java index b9f4d43d40f..a497084e162 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/InvitationsIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/InvitationsIT.java @@ -98,7 +98,7 @@ public static String createInvitation(String baseUrl, String username, String us try { userId = IntegrationTestUtils.getUserIdByField(scimToken, baseUrl, origin, "email", userEmail); scimUser = IntegrationTestUtils.getUser(scimToken, baseUrl, userId); - } catch (RuntimeException ignored) { + } catch (RuntimeException _) { // ignored } if (userId == null) { @@ -155,7 +155,7 @@ void setup() { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } @@ -201,7 +201,7 @@ public void performInviteUser(String email, boolean isVerified) { String currentUserId = null; try { currentUserId = IntegrationTestUtils.getUserId(scimToken, baseUrl, OriginKeys.UAA, email); - } catch (RuntimeException ignored) { + } catch (RuntimeException _) { // ignored } assertThat(currentUserId).isEqualTo(invitedUserId); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/JWTBearerGrantIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/JWTBearerGrantIT.java index 863d4890377..b80d45fe2dd 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/JWTBearerGrantIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/JWTBearerGrantIT.java @@ -67,7 +67,7 @@ class JWTBearerGrantIT { private static boolean doesSupportZoneDNS() { try { return Arrays.equals(Inet4Address.getByName("testzone3.localhost").getAddress(), new byte[]{127, 0, 0, 1}); - } catch (UnknownHostException e) { + } catch (UnknownHostException _) { return false; } } @@ -78,7 +78,7 @@ void logout_and_clear_cookies() { assertThat(doesSupportZoneDNS()).as("/etc/hosts should contain the host 'testzone3/4.localhost' for this test to work").isTrue(); try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java index 4295b461cfc..c236d1072c3 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java @@ -197,7 +197,7 @@ private void saveAlertErrorMessage() { try { WebElement element = webDriver.findElement(By.className("alert-error")); alertError = Optional.of(element.getText()); - } catch (NoSuchElementException e) { + } catch (NoSuchElementException _) { // do nothing } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LoginIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LoginIT.java index 214d1025dfd..8f5ec9f66be 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LoginIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LoginIT.java @@ -86,7 +86,7 @@ class LoginIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java index beff7c2da22..3ca0dcad58a 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java @@ -127,7 +127,7 @@ public class OIDCLoginIT { public static boolean doesSupportZoneDNS() { try { return Arrays.equals(Inet4Address.getByName("oidcloginit.localhost").getAddress(), new byte[]{127, 0, 0, 1}); - } catch (UnknownHostException e) { + } catch (UnknownHostException _) { return false; } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OpenIdTokenGrantsIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OpenIdTokenGrantsIT.java index b5da5812339..019d99d6e45 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OpenIdTokenGrantsIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OpenIdTokenGrantsIT.java @@ -106,7 +106,7 @@ void setUp() { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PasswordGrantIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PasswordGrantIT.java index 9ccab35903c..60d8d90bf34 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PasswordGrantIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PasswordGrantIT.java @@ -64,7 +64,7 @@ class PasswordGrantIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java index 86674e75fa2..51315e2ee3e 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java @@ -58,7 +58,7 @@ class RateLimitingIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } @@ -80,7 +80,7 @@ void infoEndpointRateLimited() throws InterruptedException { int tolerance = 5; List responses = new ArrayList<>(requestCount); - IntStream.range(0, requestCount).forEach(x -> responses.add(restTemplate.getForEntity(baseUrl + "/info", String.class))); + IntStream.range(0, requestCount).forEach(_ -> responses.add(restTemplate.getForEntity(baseUrl + "/info", String.class))); long limits = responses.stream().filter(s -> HttpStatus.TOO_MANY_REQUESTS.equals(s.getStatusCode())).count(); long oKs = responses.stream().filter(s -> HttpStatus.OK.equals(s.getStatusCode())).count(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ResetPasswordIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ResetPasswordIT.java index d5c80a27872..a59671fefb5 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ResetPasswordIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ResetPasswordIT.java @@ -71,7 +71,7 @@ class ResetPasswordIT { void logoutAndClearCookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { webDriver.get(baseUrl + "/logout.do"); } webDriver.manage().deleteAllCookies(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginCustomUserAttributesIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginCustomUserAttributesIT.java index 248664bb78d..1976d5a344a 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginCustomUserAttributesIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginCustomUserAttributesIT.java @@ -131,7 +131,7 @@ void afterEach() { try { IntegrationTestUtils.deleteZone(baseUrl, zoneId, token); IntegrationTestUtils.deleteProvider(token, baseUrl, "uaa", zoneId + ".cloudfoundry-saml-login"); - } catch (Exception ignored) { + } catch (Exception _) { // ignored } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginEmailIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginEmailIT.java index 22f6a5aa22c..f0d96aa23c0 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginEmailIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginEmailIT.java @@ -130,7 +130,7 @@ void afterEach() { try { IntegrationTestUtils.deleteZone(baseUrl, zoneId, token); IntegrationTestUtils.deleteProvider(token, baseUrl, "uaa", zoneId + ".cloudfoundry-saml-login"); - } catch (Exception ignored) { + } catch (Exception _) { // ignored } } @@ -214,7 +214,7 @@ void samlLoginEmailInIDTokenWhenUserIDIsNotEmail() { // do an auth code grant, passing the jsessionid Cookie cookie = webDriver.manage().getCookieNamed("JSESSIONID"); - System.out.println("cookie = " + "%s=%s".formatted(cookie.getName(), cookie.getValue())); + IO.println("cookie = " + "%s=%s".formatted(cookie.getName(), cookie.getValue())); serverRunning.setHostName(zoneId + ".localhost"); Map authCodeTokenResponse = IntegrationTestUtils.getAuthorizationCodeTokenMap(serverRunning, diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java index 205549ac4ab..aa2af94bc89 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java @@ -185,7 +185,7 @@ void afterEach() { try { IntegrationTestUtils.deleteZone(baseUrl, zoneId, token); IntegrationTestUtils.deleteProvider(token, baseUrl, "uaa", zoneId + ".cloudfoundry-saml-login"); - } catch (Exception ignored) { + } catch (Exception _) { // ignored } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SessionLossDuringOauthFlowIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SessionLossDuringOauthFlowIT.java index 740f629ab4f..49f7f49128b 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SessionLossDuringOauthFlowIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SessionLossDuringOauthFlowIT.java @@ -75,7 +75,7 @@ void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/TestClient.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/TestClient.java index 70f2fa4d3d5..4a17452a029 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/TestClient.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/TestClient.java @@ -111,7 +111,7 @@ public String createClientJwt(String clientId, String keyId, String jwks) { config.setJwtClientAuthentication(oidcKeyInfo); try { config.setTokenUrl(new URL(baseUrl + "/oauth/token")); - } catch (MalformedURLException e) { + } catch (MalformedURLException _) { return ""; } LegacyTokenKey.setLegacySigningKey(jwks, baseUrl); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java index 7efe832e992..0d79a8e09f7 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java @@ -55,7 +55,7 @@ class UserTokenGrantIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/XFrameOptionsIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/XFrameOptionsIT.java index c7f23e4a09c..35d5f5468b3 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/XFrameOptionsIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/XFrameOptionsIT.java @@ -49,7 +49,7 @@ class XFrameOptionsIT { void logout_and_clear_cookies() { try { webDriver.get(baseUrl + "/logout.do"); - } catch (org.openqa.selenium.TimeoutException x) { + } catch (org.openqa.selenium.TimeoutException _) { //try again - this should not be happening - 20 second timeouts webDriver.get(baseUrl + "/logout.do"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneSessionPathsIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneSessionPathsIT.java index 185cbab6830..65bfb9dca5f 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneSessionPathsIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneSessionPathsIT.java @@ -123,11 +123,11 @@ private static ScimUser scimUser(String username, String givenName, String famil void tearDown() { try { IntegrationTestUtils.deleteZone(baseUrl, ZONE1, adminToken); - } catch (Exception ignored) { + } catch (Exception _) { } try { IntegrationTestUtils.deleteZone(baseUrl, ZONE2, adminToken); - } catch (Exception ignored) { + } catch (Exception _) { } } @@ -305,7 +305,7 @@ void mainJSESSIONIDCookieDeletedAfterAllLogout() { webDriver.get(zonePathUrl(ZONE2) + "/logout.do"); Set cookiesList = webDriver.manage().getCookies(); - System.out.println("Cookies: " + cookiesList); + IO.println("Cookies: " + cookiesList); webDriver.get(zonePathUrl(ZONE1) + "/profile"); assertThat(webDriver.getCurrentUrl()) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneValidationCookieHijackIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneValidationCookieHijackIT.java index 31e6fc8cc45..4e1af9f3252 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneValidationCookieHijackIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ZoneValidationCookieHijackIT.java @@ -113,7 +113,7 @@ void afterEach() { try { IntegrationTestUtils.deleteZone(baseUrl, zoneId, token); IntegrationTestUtils.deleteProvider(token, baseUrl, "uaa", zoneId + ".cloudfoundry-saml-login"); - } catch (Exception ignored) { + } catch (Exception _) { // ignored } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/pageObjects/Page.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/pageObjects/Page.java index 154c037dc76..40313571582 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/pageObjects/Page.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/pageObjects/Page.java @@ -84,7 +84,7 @@ public LoggedOutPage assertThatLogout_goesToLoggedOutPage(final String baseUrl) private void clickLogout(String baseUrl) { try { ((UaaWebDriver) driver).pressUaaNavigation("nav-dropdown-button", "nav-dropdown-content-logout"); - } catch (WebDriverException e) { + } catch (WebDriverException _) { driver.get(baseUrl + "/logout.do"); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java index 51a7aad47fe..77d3de1cf8f 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java @@ -248,7 +248,7 @@ public static boolean doesSupportZoneDNS() { Arrays.equals(Inet4Address.getByName("testzone4.localhost").getAddress(), new byte[]{127, 0, 0, 1}) && Arrays.equals(Inet4Address.getByName("testzonedoesnotexist.localhost").getAddress(), new byte[]{127, 0, 0, 1}) && Arrays.equals(Inet4Address.getByName("testzoneinactive.localhost").getAddress(), new byte[]{127, 0, 0, 1}); - } catch (UnknownHostException e) { + } catch (UnknownHostException _) { return false; } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/ScreenshotOnFailExtension.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/ScreenshotOnFailExtension.java index 8b145b5fa5e..1d8788e40b8 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/ScreenshotOnFailExtension.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/ScreenshotOnFailExtension.java @@ -40,7 +40,7 @@ public void afterTestExecution(ExtensionContext context) { File screenshotFile = getDestinationFile(className, description, "png"); try { FileUtils.copyFile(sourceScreenshotFile, screenshotFile); - } catch (IOException ioe) { + } catch (IOException _) { log.error("ScreenshotOnFail could not write image: {}", screenshotFile); return; } @@ -51,7 +51,7 @@ public void afterTestExecution(ExtensionContext context) { try { FileUtils.write(pageSourceFile, pageSource, StandardCharsets.UTF_8); - } catch (IOException e) { + } catch (IOException _) { log.error("ScreenshotOnFail could not write source: {}", pageSourceFile); return; } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java index 08ed9eac4f0..ff780344b81 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java @@ -632,7 +632,7 @@ void acceptInvitationEmailWithDefaultCompanyNameWithinZone(ZoneResolutionMode mo MvcResult inviteResult = mockMvc.perform(postReq).andExpect(status().isOk()).andReturn(); InvitationsResponse inviteResponse = readValue(inviteResult.getResponse().getContentAsString(), InvitationsResponse.class); assertThat(inviteResponse.getNewInvites()).hasSize(1); - String acceptUrl = inviteResponse.getNewInvites().get(0).getInviteLink().toString(); + String acceptUrl = inviteResponse.getNewInvites().getFirst().getInviteLink().toString(); String code = acceptUrl.contains("code=") ? acceptUrl.substring(acceptUrl.indexOf("code=") + 5).split("&")[0] : null; assertThat(code).isNotNull(); @@ -702,7 +702,7 @@ void acceptInvitationEmailWithCompanyNameWithinZone(ZoneResolutionMode mode) thr MvcResult inviteResult = mockMvc.perform(postReq).andExpect(status().isOk()).andReturn(); InvitationsResponse inviteResponse = readValue(inviteResult.getResponse().getContentAsString(), InvitationsResponse.class); assertThat(inviteResponse.getNewInvites()).hasSize(1); - String acceptUrl = inviteResponse.getNewInvites().get(0).getInviteLink().toString(); + String acceptUrl = inviteResponse.getNewInvites().getFirst().getInviteLink().toString(); String code = acceptUrl.contains("code=") ? acceptUrl.substring(acceptUrl.indexOf("code=") + 5).split("&")[0] : null; assertThat(code).isNotNull(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/InvitationsServiceMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/InvitationsServiceMockMvcZonePathTests.java index d68937e0f40..1c3e7cd2a6c 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/InvitationsServiceMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/InvitationsServiceMockMvcZonePathTests.java @@ -238,7 +238,7 @@ void authorizeWithInvitationLoginWithinZone(ZoneResolutionMode mode) throws Exce MvcResult inviteResult = mockMvc.perform(postReq).andExpect(status().isOk()).andReturn(); InvitationsResponse response = JsonUtils.readValue(inviteResult.getResponse().getContentAsString(), InvitationsResponse.class); assertThat(response.getNewInvites()).hasSize(1); - String code = extractInvitationCode(response.getNewInvites().get(0).getInviteLink().toString()); + String code = extractInvitationCode(response.getNewInvites().getFirst().getInviteLink().toString()); MvcResult result = mockMvc.perform(mode.createRequestBuilder(subdomain, HttpMethod.GET, "/invitations/accept") .param("code", code) @@ -325,7 +325,7 @@ void acceptInvitationShouldNotLogYouInWithinZone(ZoneResolutionMode mode) throws .content(JsonUtils.writeValueAsString(invitations)); MvcResult inviteResult = mockMvc.perform(postReq).andExpect(status().isOk()).andReturn(); InvitationsResponse response = JsonUtils.readValue(inviteResult.getResponse().getContentAsString(), InvitationsResponse.class); - String code = extractInvitationCode(response.getNewInvites().get(0).getInviteLink().toString()); + String code = extractInvitationCode(response.getNewInvites().getFirst().getInviteLink().toString()); MvcResult result = mockMvc.perform(mode.createRequestBuilder(subdomain, HttpMethod.GET, "/invitations/accept") .param("code", code) @@ -386,7 +386,7 @@ void acceptInvitationForVerifiedUserSendsRedirectWithinZone(ZoneResolutionMode m .content(JsonUtils.writeValueAsString(invitations)); MvcResult inviteResult = mockMvc.perform(postReq).andExpect(status().isOk()).andReturn(); InvitationsResponse response = JsonUtils.readValue(inviteResult.getResponse().getContentAsString(), InvitationsResponse.class); - String code = extractInvitationCode(response.getNewInvites().get(0).getInviteLink().toString()); + String code = extractInvitationCode(response.getNewInvites().getFirst().getInviteLink().toString()); String zoneId = zoneResult.getIdentityZone().getId(); jdbcTemplate.update("UPDATE users SET verified=true WHERE email=? AND identity_zone_id=?", email, zoneId); @@ -427,7 +427,7 @@ void acceptInvitationPageWithinZone(ZoneResolutionMode mode) throws Exception { MvcResult inviteResult = mockMvc.perform(postReq).andExpect(status().isOk()).andReturn(); InvitationsResponse response = JsonUtils.readValue(inviteResult.getResponse().getContentAsString(), InvitationsResponse.class); assertThat(response.getNewInvites()).hasSize(1); - URL inviteLink = response.getNewInvites().get(0).getInviteLink(); + URL inviteLink = response.getNewInvites().getFirst().getInviteLink(); String code = extractInvitationCode(inviteLink.toString()); mockMvc.perform(mode.createRequestBuilder(subdomain, HttpMethod.GET, "/invitations/accept") @@ -482,7 +482,7 @@ void acceptInvitationForUaaUserShouldNotExpireInvitelinkWithinZone(ZoneResolutio .content(JsonUtils.writeValueAsString(invitations)); MvcResult inviteResult = mockMvc.perform(postReq).andExpect(status().isOk()).andReturn(); InvitationsResponse response = JsonUtils.readValue(inviteResult.getResponse().getContentAsString(), InvitationsResponse.class); - String code = extractInvitationCode(response.getNewInvites().get(0).getInviteLink().toString()); + String code = extractInvitationCode(response.getNewInvites().getFirst().getInviteLink().toString()); MockHttpServletRequestBuilder get = mode.createRequestBuilder(subdomain, HttpMethod.GET, "/invitations/accept") .param("code", code) @@ -572,8 +572,8 @@ void invalid_codeWithinZone(ZoneResolutionMode mode) throws Exception { .header("Authorization", "Bearer " + zonedToken) .contentType(APPLICATION_JSON) .content(JsonUtils.writeValueAsString(new InvitationsRequest(new String[]{email2})))).andReturn(); - String code1 = extractInvitationCode(JsonUtils.readValue(r1.getResponse().getContentAsString(), InvitationsResponse.class).getNewInvites().get(0).getInviteLink().toString()); - String invalidCode = extractInvitationCode(JsonUtils.readValue(r2.getResponse().getContentAsString(), InvitationsResponse.class).getNewInvites().get(0).getInviteLink().toString()); + String code1 = extractInvitationCode(JsonUtils.readValue(r1.getResponse().getContentAsString(), InvitationsResponse.class).getNewInvites().getFirst().getInviteLink().toString()); + String invalidCode = extractInvitationCode(JsonUtils.readValue(r2.getResponse().getContentAsString(), InvitationsResponse.class).getNewInvites().getFirst().getInviteLink().toString()); MvcResult result = mockMvc.perform(mode.createRequestBuilder(subdomain, HttpMethod.GET, "/invitations/accept") .param("code", code1) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcTests.java index 052b9ce2348..535efb049df 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcTests.java @@ -1848,7 +1848,7 @@ void changeEmailSubmitWithSpringSecurityForcedCsrf() throws Exception { .andExpect(status().isFound()) .andExpect(redirectedUrl("email_sent?code=email_change")) .andReturn().getRequest().getSession(false); - System.out.println("session = " + session); + IO.println("session = " + session); } @Test diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java index bd07e1a0ba3..9d2397ea3e4 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java @@ -752,7 +752,7 @@ void previous_login_time_upon_authentication(ZoneResolutionMode mode) throws Exc zonedUser.setPrimaryEmail("marissa@test.org"); zonedUser.setPassword("koala"); scimUserProvisioning.createUser(zonedUser, "koala", zone.getId()); - ScimUser user = scimUserProvisioning.retrieveByUsernameAndZone("marissa", zone.getId()).get(0); + ScimUser user = scimUserProvisioning.retrieveByUsernameAndZone("marissa", zone.getId()).getFirst(); String password = "koala"; MockHttpSession session = new MockHttpSession(); long beforeAuthTime = System.currentTimeMillis(); @@ -2254,7 +2254,7 @@ void changeEmailSubmitWithSpringSecurityForcedCsrf(ZoneResolutionMode mode) thro .andExpect(status().isFound()) .andExpect(redirectedUrl("email_sent?code=email_change")) .andReturn().getRequest().getSession(false); - System.out.println("session = " + session); + IO.println("session = " + session); } @ParameterizedTest diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java index 02abd502624..aafa746bc3b 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java @@ -1146,7 +1146,7 @@ void transferDefaultMappingsToZone(IdentityZone zone) { group.setZoneId(zone.getId()); try { group = gp.create(group, IdentityZoneHolder.get().getId()); - } catch (ScimResourceAlreadyExistsException e) { + } catch (ScimResourceAlreadyExistsException _) { String filter = "displayName eq \"" + internalName + "\""; group = gp.query(filter, IdentityZoneHolder.get().getId()).getFirst(); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/LdapMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/LdapMockMvcTests.java index bdf566e7519..8910a2315b5 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/LdapMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/LdapMockMvcTests.java @@ -301,7 +301,7 @@ void unableToConnectToLdapWithInvalidSsl() { .andDo(print()) .andExpect(status().isBadRequest()) .andExpect(content().string(containsString("Caused by:"))); - } catch (Exception ignored) { + } catch (Exception _) { fail("should not be able to connect to LDAP server"); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java index f17b231d983..a4f78a6bbd1 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java @@ -1360,7 +1360,7 @@ private Optional> readIdpViaDb(final String id, final String final IdentityProvider idp; try { idp = identityProviderProvisioning.retrieve(id, zoneId); - } catch (final Exception e) { + } catch (final Exception _) { return Optional.empty(); } return Optional.of(idp); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/AbstractTokenMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/AbstractTokenMockMvcTests.java index 8f33a8ce089..0c58e5a173f 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/AbstractTokenMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/AbstractTokenMockMvcTests.java @@ -382,7 +382,7 @@ private static void addMember( ScimGroupMember gm = new ScimGroupMember(user.getId()); try { groupMembershipManager.addMember(group.getId(), gm, zoneId); - } catch (MemberAlreadyExistsException ignored) { + } catch (MemberAlreadyExistsException _) { } } @@ -405,7 +405,7 @@ protected void waitForClient(String clientId, int max) throws InterruptedExcepti try { clientDetailsService.loadClientByClientId(clientId); break; - } catch (NoSuchClientException e) { + } catch (NoSuchClientException _) { Thread.sleep(500); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java index 85f470b51c8..87d9866fa96 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java @@ -67,7 +67,7 @@ void token_exchange_three_idps_using_id_token() throws Exception { Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().get(0).getValue()); + assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); Map act = (Map) claims.get("act"); @@ -123,7 +123,7 @@ void token_exchange_three_idps_using_access_token() throws Exception { Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().get(0).getValue()); + assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); } @@ -182,7 +182,7 @@ void token_exchange_three_idps_using_opaque_access_token() throws Exception { Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().get(0).getValue()); + assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); } @@ -250,7 +250,7 @@ void token_exchange_three_idps_using_client_assertion() throws Exception { Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().get(0).getValue()); + assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); Map subjectTokenClaims = JsonUtils.readValueAsMap(JwtHelper.decode(idToken).getClaims()); @@ -318,7 +318,7 @@ void token_exchange_impersonate_client() throws Exception { Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().get(0).getValue()); + assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); assertThat(claims.get("client_id")).isEqualTo(audience.getClientId()); assertThat(claims.get("cid")).isEqualTo(audience.getClientId()); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java index 7e679b9309b..49d1987d998 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java @@ -129,7 +129,7 @@ public Jwt getTokenClaims(String token, String tokenKey, String serverKey) { try { return JwtHelper.decode(token); - } catch (RuntimeException e) { + } catch (RuntimeException _) { Assertions.fail( String.format("Unable to decode token: %s for server: %s and key: %s", token, serverKey, tokenKey) ); @@ -142,7 +142,7 @@ ThreeWayUAASetup getThreeWayUaaSetUp() throws Exception { //simulate an outside IDP AuthorizationServer thirdParty = getAuthorizationServer( "3rd", - provider -> null, + _ -> null, (client) -> { client.setScope(List.of("openid")); client.setAuthorizedGrantTypes(List.of("password", "refresh_token")); @@ -169,7 +169,7 @@ ThreeWayUAASetup getThreeWayUaaSetUp() throws Exception { client.setAutoApproveScopes(List.of("openid")); return client; }, - user -> null + _ -> null ); //create foundation UAA @@ -195,7 +195,7 @@ ThreeWayUAASetup getThreeWayUaaSetUp() throws Exception { client.setAutoApproveScopes(List.of("openid")); return client; }, - user -> null + _ -> null ); //get an id_token from third party UAA @@ -413,7 +413,7 @@ String getClientAssertion(IdentityZone zone, String issuer, UaaClientDetails cli claims.setJti(UUID.randomUUID().toString().replace("-", "")); claims.setIat((int) Instant.now().minusSeconds(120).getEpochSecond()); claims.setExp(Instant.now().plusSeconds(300).getEpochSecond()); - JsonWebKey jsonWebKey = clientJwtConfiguration.getJwkSet().getKeys().get(0); + JsonWebKey jsonWebKey = clientJwtConfiguration.getJwkSet().getKeys().getFirst(); KeyInfo signingKeyInfo = getPrivateKey(issuer); return signingKeyInfo.verifierCertificate().isPresent() ? JwtHelper.encodePlusX5t(claims.getClaimMap(), signingKeyInfo, signingKeyInfo.verifierCertificate().orElseThrow()).getEncoded() : diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java index ea124da2a27..1d73e57a68e 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java @@ -140,7 +140,7 @@ void token_exchange_modify_origin_based_on_bean_override() throws Exception { Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().get(0).getValue()); + assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); assertThat(claims.get("origin")).isEqualTo("override-origin"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java index bdf3187fe58..bda6250eeee 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java @@ -87,7 +87,7 @@ void revokeOwnJWToken() throws Exception { assertThat(tokenRevocationEvent.getAuditEvent().getOrigin()).contains(client.getClientId()); revocableTokenProvisioning.retrieve(jti, IdentityZoneHolder.get().getId()); fail("Expected EmptyResultDataAccessException to be thrown for revoked token"); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { // expected } finally { defaultZone.getConfig().getTokenPolicy().setJwtRevocable(false); @@ -203,7 +203,7 @@ void revokeOtherClientTokenByClientId(String scope) throws Exception { try { revocableTokenProvisioning.retrieve(tokenToBeRevoked, IdentityZoneHolder.get().getId()); fail("Token should have been deleted"); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { // expected } } @@ -265,7 +265,7 @@ void revokeOpaqueTokenWithOpaqueToken() throws Exception { try { revocableTokenProvisioning.retrieve(opaqueUserToken, IdentityZoneHolder.get().getId()); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java index 2106693dbfe..8f589800902 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java @@ -96,7 +96,7 @@ void revokeOwnJWToken() throws Exception { assertThat(tokenRevocationEvent.getAuditEvent().getOrigin()).contains(client.getClientId()); revocableTokenProvisioning.retrieve(jti, IdentityZoneHolder.get().getId()); fail("Expected EmptyResultDataAccessException to be thrown for revoked token"); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { // expected } finally { defaultZone.getConfig().getTokenPolicy().setJwtRevocable(false); @@ -212,7 +212,7 @@ void revokeOtherClientTokenByClientId(String scope) throws Exception { try { revocableTokenProvisioning.retrieve(tokenToBeRevoked, IdentityZoneHolder.get().getId()); fail("Token should have been deleted"); - } catch (EmptyResultDataAccessException e) { + } catch (EmptyResultDataAccessException _) { // expected } } @@ -274,7 +274,7 @@ void revokeOpaqueTokenWithOpaqueToken() throws Exception { try { revocableTokenProvisioning.retrieve(opaqueUserToken, IdentityZoneHolder.get().getId()); - } catch (EmptyResultDataAccessException ignored) { + } catch (EmptyResultDataAccessException _) { } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/JwtTokenUtils.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/JwtTokenUtils.java index 1b358c2b077..29d97c2640a 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/JwtTokenUtils.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/JwtTokenUtils.java @@ -16,7 +16,7 @@ public static Map getClaimsForToken(String token) { Jwt tokenJwt; try { tokenJwt = JwtHelper.decode(token); - } catch (Throwable t) { + } catch (Throwable _) { throw new InvalidTokenException("Invalid token (could not decode): " + token); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/MockMvcUtils.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/MockMvcUtils.java index 1038b207c66..46277da706d 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/MockMvcUtils.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/util/MockMvcUtils.java @@ -625,7 +625,7 @@ public static IdentityProvider createIdpUsingWebRequest(MockMvc mockMvc, String if (hasText(result.getResponse().getContentAsString())) { try { return JsonUtils.readValue(result.getResponse().getContentAsString(), IdentityProvider.class); - } catch (JsonUtils.JsonUtilException e) { + } catch (JsonUtils.JsonUtilException _) { return null; } } else { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java index 3ab374a6bf1..edbac6ee642 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java @@ -860,10 +860,10 @@ private boolean waitForClient(String clientId, int max) { try { jdbcClientDetailsService.loadClientByClientId(clientId); return true; - } catch (NoSuchClientException e) { + } catch (NoSuchClientException _) { try { Thread.sleep(500); - } catch (InterruptedException interruptedException) { + } catch (InterruptedException _) { return false; } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcTest.java index 41b0b233bbc..fa7e30eddcc 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcTest.java @@ -133,7 +133,7 @@ void idpDiscoveryRedirectsToOIDCProvider( stopWatch.stop(); long totalTimeMillis = stopWatch.getTotalTimeMillis(); - System.out.println(totalTimeMillis + "ms"); + IO.println(totalTimeMillis + "ms"); } private static String createOIDCProvider(JdbcIdentityProviderProvisioning jdbcIdentityProviderProvisioning, AlphanumericRandomValueStringGenerator generator, IdentityZone zone, String responseType, String domain) throws Exception { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcZonePathTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcZonePathTest.java index 16971251256..dbf6056fbb0 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcZonePathTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/performance/LoginPagePerformanceMockMvcZonePathTest.java @@ -137,7 +137,7 @@ void idpDiscoveryRedirectsToOIDCProvider( stopWatch.stop(); long totalTimeMillis = stopWatch.getTotalTimeMillis(); - System.out.println(totalTimeMillis + "ms"); + IO.println(totalTimeMillis + "ms"); } private static String createOIDCProvider(JdbcIdentityProviderProvisioning jdbcIdentityProviderProvisioning, AlphanumericRandomValueStringGenerator generator, IdentityZone zone, String responseType, String domain) throws Exception { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java index d1686563ded..c09ac0e0ec7 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java @@ -1391,7 +1391,7 @@ private ScimUser createUserAndAddToGroups(IdentityZone zone, Set groupNa ScimGroupMember member = new ScimGroupMember(user.getId(), ScimGroupMember.Type.USER); try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); - } catch (MemberAlreadyExistsException ignored) { + } catch (MemberAlreadyExistsException _) { } } } finally { @@ -1432,7 +1432,7 @@ private ScimGroup createGroupWithinGroups(IdentityZone zone, Set groupNa ScimGroupMember member = new ScimGroupMember(newGroup.getId(), ScimGroupMember.Type.GROUP); try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); - } catch (MemberAlreadyExistsException ignored) { + } catch (MemberAlreadyExistsException _) { } } } finally { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java index 59ac379d774..efba385aee8 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java @@ -1393,7 +1393,7 @@ private ScimUser createUserAndAddToGroups(IdentityZone zone, Set groupNa ScimGroupMember member = new ScimGroupMember(user.getId(), ScimGroupMember.Type.USER); try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); - } catch (MemberAlreadyExistsException ignored) { + } catch (MemberAlreadyExistsException _) { } } } finally { @@ -1434,7 +1434,7 @@ private ScimGroup createGroupWithinGroups(IdentityZone zone, Set groupNa ScimGroupMember member = new ScimGroupMember(newGroup.getId(), ScimGroupMember.Type.GROUP); try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); - } catch (MemberAlreadyExistsException ignored) { + } catch (MemberAlreadyExistsException _) { } } } finally { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java index 3eb531fc8a9..8ac0a10f971 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java @@ -551,7 +551,7 @@ void updateWithInvalidMemberFails() { try { scimGroupEndpoints.updateGroup(g1, g1.getId(), "*", new MockHttpServletResponse()); fail("must have thrown exception"); - } catch (ScimException ex) { + } catch (ScimException _) { // ensure that displayName was not updated g1 = scimGroupEndpoints.getGroup(g1.getId(), new MockHttpServletResponse()); validateGroup(g1, "clients.read", 0); @@ -620,7 +620,7 @@ void updateWrongVersionFails() { try { scimGroupEndpoints.updateGroup(g1, g1.getId(), String.valueOf(g1.getVersion() + 23), new MockHttpServletResponse()); - } catch (ScimException ex) { + } catch (ScimException _) { validateSearchResults(scimGroupEndpoints.listGroups("id", "displayName eq \"clients.write\"", "id", "ASC", 1, 100), 0); validateSearchResults(scimGroupEndpoints.listGroups("id", "displayName eq \"clients.read\"", "id", "ASC", 1, 100), 1); } @@ -683,7 +683,7 @@ void deleteWrongVersionFails() { try { scimGroupEndpoints.deleteGroup(g.getId(), String.valueOf(g.getVersion() + 3), new MockHttpServletResponse()); - } catch (ScimException ex) { + } catch (ScimException _) { validateSearchResults(scimGroupEndpoints.listGroups("id", "displayName eq \"clients.read\"", "id", "ASC", 1, 100), 1); } deleteGroup("clients.read"); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/InMemoryLdapServer.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/InMemoryLdapServer.java index 9dad8b92d5a..f8f8580c26f 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/InMemoryLdapServer.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/InMemoryLdapServer.java @@ -116,7 +116,7 @@ public void stop() { public boolean isRunning() { try { return this.directoryServer.getConnection().isConnected(); - } catch (LDAPException e) { + } catch (LDAPException _) { return false; } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/UaaWebDriver.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/UaaWebDriver.java index 4c29f868b55..4f0e6c773be 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/UaaWebDriver.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/test/UaaWebDriver.java @@ -50,11 +50,11 @@ public void clickAndWait(By locator) { new FluentWait<>(this.delegate).withTimeout(WAIT_TIMEOUT) .pollingEvery(POLLING_TIME) .withMessage(() -> "Waiting for navigation after clicking on [%s]. Current URL [%s].".formatted(locator, delegate.getCurrentUrl())) - .until((d) -> { + .until(_ -> { try { clickableElement.isDisplayed(); return false; - } catch (StaleElementReferenceException e) { + } catch (StaleElementReferenceException _) { return true; } catch (WebDriverException e) { return e.getMessage().contains("-32000"); @@ -158,7 +158,7 @@ public SessionId getSessionId() { } try { return ((RemoteWebDriver) this.delegate).getSessionId(); - } catch (Exception e) { + } catch (Exception _) { // If the WebDriver has been quit or closed, getSessionId() may throw an exception // Return null to indicate the session is no longer available return null; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java index 93d46c37f59..c933a59858b 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java @@ -27,7 +27,7 @@ void loadAll_yamlIsFullOfLongComments_yamlLoadsInUnderASecond() { Iterable objects = yaml.loadAll(inputStream); for (Object o : objects) { - System.out.println(o); + IO.println(o); } }); } From a46b369f93699fc27496fda1d876e4a6f82081d3 Mon Sep 17 00:00:00 2001 From: Duane May Date: Wed, 3 Jun 2026 22:59:18 -0400 Subject: [PATCH 4/7] Sonar Fixes --- .../identity/uaa/account/EmailChangeEmailService.java | 1 + .../identity/uaa/account/UaaResetPasswordService.java | 1 + .../org/cloudfoundry/identity/uaa/authentication/Origin.java | 1 + .../manager/DynamicZoneAwareAuthenticationManager.java | 1 + .../org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java | 1 + .../oauth2/provider/endpoint/DefaultRedirectResolver.java | 1 + .../identity/uaa/provider/saml/OpenSamlXmlUtils.java | 4 +++- .../identity/uaa/security/X509ExpiryCheckingTrustManager.java | 1 + .../java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java | 4 +++- .../identity/uaa/web/AuthorizationManagersUtils.java | 3 +++ .../identity/uaa/zone/IdentityZoneSwitchingFilter.java | 1 + 11 files changed, 17 insertions(+), 2 deletions(-) diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java index da7257c6f14..d6967aa20e7 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailService.java @@ -129,6 +129,7 @@ public Map completeVerification(String code) { String changeEmailRedirectUrl = (String) clientDetails.getAdditionalInformation().get(CHANGE_EMAIL_REDIRECT_URL); redirectLocation = findMatchingRedirectUri(redirectUris, redirectUri, changeEmailRedirectUrl); } catch (NoSuchClientException _) { + // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java b/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java index 5ebf434a29e..b0256990e4f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/account/UaaResetPasswordService.java @@ -132,6 +132,7 @@ private ResetPasswordResponse changePasswordCodeAuthenticated(ExpiringCode expir redirectLocation = matchingRedirectUri; } } catch (NoSuchClientException _) { + // ignore } } return new ResetPasswordResponse(user, redirectLocation, clientId); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java index 0cf1a854487..cb1b6758407 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/Origin.java @@ -51,6 +51,7 @@ public static String getUserIdThroughReflection(Authentication authentication, S return id.toString(); } } catch (Exception _) { + // ignore } return null; } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java index d6279f395a8..9fa0d97c6eb 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManager.java @@ -138,6 +138,7 @@ protected IdentityProvider getProvider(String origin, IdentityZone zone) { return result; } } catch (EmptyResultDataAccessException _) { + // ignore } IdentityProvider provider = new IdentityProvider(); provider.setOriginKey(origin); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java index 14cb7a01779..776e86280b8 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStore.java @@ -155,6 +155,7 @@ public OAuth2Authentication consumeAuthorizationCode(String code) throws Invalid } } } catch (EmptyResultDataAccessException _) { + // ignore } throw new InvalidGrantException("Invalid authorization code: " + code); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java index a3e5f7d5cf0..5ed9dd66a7f 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/oauth/beans/org/springframework/security/oauth2/provider/endpoint/DefaultRedirectResolver.java @@ -130,6 +130,7 @@ protected boolean redirectMatches(String requestedRedirect, String redirectUri) } } catch (MalformedURLException _) { + // ignore } return requestedRedirect.equals(redirectUri); } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java index 825a1c783fd..6825d2ee0dc 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSamlXmlUtils.java @@ -46,7 +46,9 @@ public static String getStringValue(String key, SamlIdentityProviderDefinition d } case XSURI xsUri -> value = xsUri.getURI(); case XSBase64Binary xsBase64Binary -> value = xsBase64Binary.getValue(); - case null, default -> {} + case null, default -> { + // ignore + } } if (value != null) { diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java b/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java index 64eb0b9b4d4..6d5613ad0a7 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/security/X509ExpiryCheckingTrustManager.java @@ -41,6 +41,7 @@ public X509ExpiryCheckingTrustManager() { } delegate = x509Tm; } catch (NoSuchAlgorithmException | KeyStoreException _) { + // ignore } } diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java b/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java index f9f80532142..ee7381d1c62 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/util/KeyWithCert.java @@ -112,7 +112,9 @@ private static PrivateKey loadPrivateKey(String encodedPrivateKey, String passph privateKey = keyPair.getPrivate(); } case PrivateKeyInfo privateKeyInfo -> privateKey = converter.getPrivateKey(privateKeyInfo); - case null, default -> {} + case null, default -> { + // ignore + } } } catch (IOException ex) { throw new CertificateException("Failed to read private key.", ex); diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java b/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java index 814e68e5209..e0f528ee8d5 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/web/AuthorizationManagersUtils.java @@ -24,6 +24,9 @@ */ public class AuthorizationManagersUtils { + private AuthorizationManagersUtils() { + } + /** * Grants access if any of the registered authorization managers grants access. */ diff --git a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java index eeb3460fe13..8dded7c600a 100644 --- a/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java +++ b/server/src/main/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneSwitchingFilter.java @@ -165,6 +165,7 @@ private IdentityZone validateIdentityZone(String identityZoneId, String identity identityZone = dao.retrieve(identityZoneId); } } catch (ZoneDoesNotExistsException | EmptyResultDataAccessException _) { + // ignore } return identityZone; } From eb61e182129672a4040263c5edd16d90ff21902e Mon Sep 17 00:00:00 2001 From: Duane May Date: Wed, 3 Jun 2026 23:29:20 -0400 Subject: [PATCH 5/7] Assertj Rewrite --- .../identity/uaa/metrics/MetricsUtilTest.java | 12 +- .../uaa/metrics/StatusCodeGroupTest.java | 10 +- .../identity/uaa/metrics/UrlGroupTest.java | 11 +- .../identity/uaa/util/JsonUtilsTest.java | 73 +++----- .../uaa/account/OpenIdConfigurationTests.java | 3 +- .../InMemoryClientDetailsServiceTest.java | 2 +- .../uaa/impl/JsonDateDeserializerTest.java | 5 +- .../uaa/impl/JsonDateSerializerTest.java | 2 +- .../oauth/client/ClientJwtCredentialTest.java | 12 +- ...efaultOAuth2RequestAuthenticatorTests.java | 2 +- .../oauth/client/OAuth2RestTemplateTests.java | 11 +- .../client/http/OAuth2ErrorHandlerTests.java | 11 +- .../FormOAuth2ExceptionHttpMessageTest.java | 9 +- .../token/AccessTokenProviderChainTests.java | 2 +- ...orizationCodeAccessTokenProviderTests.java | 4 +- ...ccessTokenProviderWithConversionTests.java | 1 - .../ImplicitAccessTokenProviderTests.java | 5 +- ...OwnerPasswordAccessTokenProviderTests.java | 2 +- ...2AccessTokenJackson2DeserializerTests.java | 20 +- ...th2AccessTokenJackson2SerializerTests.java | 16 +- .../util/RandomValueStringGeneratorTests.java | 2 +- .../oauth/jwk/JsonWebKeyDeserializerTest.java | 6 +- .../uaa/oauth/jwk/JsonWebKeyTests.java | 2 +- .../oauth/token/IntrospectionClaimsTest.java | 2 +- .../token/OAuth2AccessTokenSupportTests.java | 2 +- .../uaa/oauth/token/UaaTokenTests.java | 10 +- .../token/VerificationKeyResponseTest.java | 2 +- .../OIDCIdentityProviderDefinitionTests.java | 13 +- .../SamlIdentityProviderDefinitionTests.java | 4 +- .../identity/uaa/scim/ScimGroupTests.java | 2 +- .../identity/uaa/scim/ScimUserTests.java | 23 +-- .../identity/uaa/test/JsonTranslation.java | 11 +- .../identity/uaa/util/ObjectUtilsTest.java | 3 +- .../identity/uaa/util/UaaStringUtilsTest.java | 9 +- .../identity/uaa/zone/IdentityZoneTest.java | 4 +- .../identity/uaa/zone/LoginConsentTest.java | 20 +- .../identity/uaa/zone/SamlConfigTest.java | 2 +- .../identity/uaa/zone/TokenPolicyTest.java | 8 +- .../identity/uaa/zone/UserConfigTest.java | 10 +- .../identity/uaa/UaaPropertiesTest.java | 30 +-- .../account/EmailChangeEmailServiceTest.java | 2 +- .../account/PasswordChangeEndpointTests.java | 4 +- ...ResetPasswordAuthenticationFilterTest.java | 4 +- ...tityAliasHandlerEnsureConsistencyTest.java | 33 ++-- .../EntityAliasHandlerValidationTest.java | 14 +- .../event/ApprovalModifiedEventTest.java | 2 +- .../ClientBasicAuthenticationFilterTests.java | 10 +- ...entParametersAuthenticationFilterTest.java | 11 +- .../CurrentUserCookieRequestFilterTest.java | 10 +- .../UaaAuthenticationSerializationTests.java | 5 +- .../UaaClientAuthenticationProviderTest.java | 4 +- ...areWhitelistLogoutSuccessHandlerTests.java | 6 +- .../AuthzAuthenticationManagerTests.java | 4 +- .../AutologinRequestConverterTest.java | 11 +- .../ChainedAuthenticationManagerTest.java | 8 +- ...ckIdpEnabledAuthenticationManagerTest.java | 2 +- ...xternalLoginAuthenticationManagerTest.java | 4 +- .../LdapLoginAuthenticationManagerTests.java | 1 - .../LoginAuthenticationManagerTests.java | 4 +- ...asswordGrantAuthenticationManagerTest.java | 13 +- .../ScopeAuthenticationManagerTests.java | 2 +- .../uaa/cache/StaleUrlCacheTests.java | 9 +- .../uaa/client/ClientAdminBootstrapTests.java | 10 +- .../uaa/client/ClientAdminEndpointsTests.java | 11 +- .../ClientAdminEndpointsValidatorTests.java | 8 +- .../client/ClientJwtConfigurationTest.java | 8 +- .../JdbcClientMetadataProvisioningTest.java | 4 +- ...aaClientDetailsUserDetailsServiceTest.java | 2 +- .../identity/uaa/client/UaaClientTest.java | 2 +- .../uaa/codestore/ExpiringCodeStoreTests.java | 4 +- .../codestore/JdbcExpiringCodeStoreTest.java | 2 +- .../config/IdentityProviderBootstrapTest.java | 16 +- ...entityZoneConfigurationBootstrapTests.java | 28 +-- .../IdentityZoneConfigurationTests.java | 24 +-- .../uaa/db/DatabaseParametersTests.java | 2 +- ...roupMembershipAuthoritiesNullableTest.java | 3 +- .../db/TableAndColumnNormalizationTest.java | 4 +- .../identity/uaa/error/UaaExceptionTests.java | 2 +- .../PollutionPreventionExtension.java | 1 + .../uaa/health/HealthzEndpointTests.java | 10 +- .../config/UaaConfigurationTokenKeyTest.java | 1 - ...avingAuthenticationSuccessHandlerTest.java | 8 +- .../AutologinAuthenticationManagerTest.java | 2 +- .../login/ChangePasswordControllerTest.java | 2 +- .../EmailAccountCreationServiceTests.java | 9 +- .../identity/uaa/login/EmailServiceTests.java | 2 +- .../uaa/login/LoginConsentHashUtilTest.java | 36 ++-- .../uaa/login/LoginInfoEndpointTests.java | 17 +- .../login/ResetPasswordControllerTest.java | 7 +- .../UaaAuthenticationFailureHandlerTests.java | 6 +- ...enticationFailureHandlerZonePathTests.java | 8 +- .../login/UaaChangePasswordServiceTest.java | 2 +- .../login/UaaResetPasswordServiceTests.java | 5 +- .../uaa/oauth/CheckTokenEndpointTests.java | 9 +- .../oauth/ClientAccessTokenValidityTest.java | 2 +- .../oauth/ClientRefreshTokenValidityTest.java | 2 +- .../DeprecatedUaaTokenServicesTests.java | 18 +- .../uaa/oauth/RemoteTokenServicesTests.java | 4 +- .../RestrictUaaScopesClientValidatorTest.java | 8 +- .../uaa/oauth/TokenEndpointBuilderTest.java | 4 +- .../oauth/UaaAuthorizationEndpointTest.java | 2 +- .../UaaAuthorizationRequestManagerTests.java | 26 ++- .../identity/uaa/oauth/UaaScopesTests.java | 2 +- .../uaa/oauth/UaaTokenStoreTests.java | 6 +- .../UserManagedAuthzApprovalHandlerTests.java | 8 +- ...eEndpointsClientDetailsValidatorTests.java | 12 +- .../ApprovalsAdminEndpointsTests.java | 6 +- .../approval/JdbcApprovalStoreTests.java | 2 +- .../beans/LegacyRedirectResolverTest.java | 4 +- .../uaa/oauth/beans/RedirectResolverTest.java | 2 +- .../client/ClientDetailsModificationTest.java | 2 +- .../uaa/oauth/jwk/JsonWebKeySetTests.java | 11 +- .../jwt/ChainedSignatureVerifierTests.java | 4 +- .../uaa/oauth/jwt/CommonSignerTest.java | 12 +- .../jwt/JwtClientAuthenticationTest.java | 52 +++--- .../uaa/oauth/jwt/JwtHeaderHelperTest.java | 4 +- .../identity/uaa/oauth/jwt/JwtHelperTest.java | 8 +- .../uaa/oauth/jwt/JwtHelperX5tTest.java | 2 +- .../uaa/oauth/jwt/SignatureVerifierTest.java | 2 +- .../uaa/oauth/openid/IdTokenCreatorTest.java | 26 +-- .../oauth/pkce/PkceValidationServiceTest.java | 4 +- .../provider/CompositeTokenGranterTests.java | 2 +- .../oauth/provider/OAuth2RequestTests.java | 10 +- .../OAuth2ClientContextFilterTests.java | 2 +- .../xml/ResourceBeanDefinitionParserTest.java | 2 +- .../DefaultRedirectResolverTests.java | 4 +- .../provider/endpoint/TokenEndpointTests.java | 6 +- .../OAuth2ExpressionParserTests.java | 2 +- ...2MethodSecurityExpressionHandlerTests.java | 2 +- .../OAuth2SecurityExpressionMethodsTests.java | 2 +- ...uth2WebSecurityExpressionHandlerTests.java | 2 +- .../implicit/ImplicitTokenGranterTests.java | 2 +- ...esourceOwnerPasswordTokenGranterTests.java | 6 +- .../refresh/RefreshTokenGranterTests.java | 2 +- .../DefaultOAuth2RequestFactoryTests.java | 2 +- .../AbstractDefaultTokenServicesTests.java | 2 +- .../token/DefaultTokenServicesTests.java | 2 +- ...DefaultTokenServicesWithInMemoryTests.java | 4 +- ...faultUserAuthenticationConverterTests.java | 2 +- .../oauth/provider/vote/ScopeVoterTests.java | 2 +- .../JdbcRevocableTokenProvisioningTest.java | 4 +- .../uaa/oauth/token/KeyInfoServiceTests.java | 7 +- ...ncedAuthorizationCodeTokenGranterTest.java | 9 +- .../oauth/token/TokenKeyEndpointTests.java | 2 +- .../oauth/token/UaaTokenEndpointTests.java | 5 +- .../uaa/oauth/token/UserTokenGranterTest.java | 2 +- .../uaa/openid/UserInfoEndpointTests.java | 2 +- .../uaa/passcode/PasscodeInformationTest.java | 4 +- .../IdentityProviderEndpointsTest.java | 11 +- ...JdbcIdentityProviderProvisioningTests.java | 4 +- .../ldap/DynamicPasswordComparatorTests.java | 2 + .../LdapIdentityProviderDefinitionTest.java | 12 +- .../ldap/ProcessLdapPropertiesTest.java | 2 +- ...ExternalOAuthAuthenticationFilterTest.java | 22 +-- .../ExternalOAuthAuthenticationManagerIT.java | 48 +++-- ...xternalOAuthAuthenticationManagerTest.java | 41 ++--- ...thIdentityProviderConfigValidatorTest.java | 2 +- ...ExternalOAuthLogoutSuccessHandlerTest.java | 6 +- ...xternalOAuthProviderConfiguratorTests.java | 20 +- ...tityProviderDefinitionFactoryBeanTest.java | 6 +- .../oauth/OidcMetadataFetcherTest.java | 26 +-- ...ootstrapSamlIdentityProviderDataTests.java | 6 +- ...elyingPartyRegistrationRepositoryTest.java | 2 +- ...enSaml5AuthenticationProviderUaaTests.java | 11 +- ...nSaml5AuthenticationProviderUnitTests.java | 16 +- ...earerGrantAuthenticationConverterTest.java | 3 +- ...SamlIdentityProviderConfiguratorTests.java | 4 +- ...LoginAuthenticationFailureHandlerTest.java | 14 +- ...henticationFailureHandlerZonePathTest.java | 14 +- .../saml/SamlMetadataEndpointTest.java | 3 +- ...UaaDelegatingLogoutSuccessHandlerTest.java | 20 +- ...RelyingPartyRegistrationResolverTests.java | 9 +- ...aaIdentityProviderConfigValidatorTest.java | 2 +- .../uaa/ratelimiting/RateLimiterImplTest.java | 2 +- .../ratelimiting/RateLimitingFilterTest.java | 11 +- .../http/CredentialIdTypeAbstractTestJWT.java | 2 +- .../LimiterByCompoundKeyTest.java | 3 +- .../PathFragmentToLimiterMappingsTest.java | 4 +- .../uaa/ratelimiting/util/IntUtilsTest.java | 2 +- .../util/LazyEnumerationToListTest.java | 4 +- .../ratelimiting/util/SourcedFileTest.java | 2 +- .../resources/jdbc/JdbcPagingListTests.java | 4 +- ...UserAliasHandlerEnsureConsistencyTest.java | 4 +- .../bootstrap/ScimUserBootstrapTests.java | 14 +- .../ScimUserEndpointsAliasTests.java | 10 +- .../UserIdConversionEndpointsTests.java | 28 +-- ...imGroupExternalMembershipManagerTests.java | 2 +- .../JdbcScimGroupMembershipManagerTests.java | 50 +++-- .../jdbc/JdbcScimGroupProvisioningTests.java | 5 +- .../jdbc/JdbcScimUserProvisioningTests.java | 15 +- .../jdbc/ScimSearchQueryConverterTests.java | 2 +- .../scim/services/ScimUserServiceTest.java | 7 +- .../identity/uaa/scim/util/ScimUtilsTest.java | 7 +- ...rfAwareEntryPointAndDeniedHandlerTest.java | 2 +- .../web/ContentSecurityPolicyFilterTest.java | 16 +- .../web/CorsFilterDefaultZoneTests.java | 34 ++-- .../web/CorsFilterNonDefaultZoneTests.java | 58 +++--- .../identity/uaa/test/TestUtils.java | 4 +- .../user/InMemoryUaaUserDatabaseTests.java | 2 +- .../uaa/user/JdbcUaaUserDatabaseTests.java | 20 +- .../identity/uaa/user/UaaUserEditorTests.java | 2 +- .../uaa/util/CachingPasswordEncoderTest.java | 3 +- .../identity/uaa/util/DomainFilterTest.java | 4 +- .../uaa/util/JwtTokenSignedByThisUAATest.java | 6 +- .../identity/uaa/util/KeyWithCertTest.java | 8 +- .../util/LinkedMaskingMultiValueMapTests.java | 16 +- .../identity/uaa/util/MediaTypeUtilsTest.java | 35 ++-- .../identity/uaa/util/SessionUtilsTest.java | 2 +- .../uaa/util/TestUaaUrlBuilderTest.java | 2 +- .../uaa/util/UaaHttpRequestUtilsTest.java | 14 +- .../identity/uaa/util/UaaMapUtilsTest.java | 2 +- .../uaa/util/UaaPagingUtilsTests.java | 12 +- .../uaa/util/UaaRandomStringUtilImplTest.java | 2 +- .../identity/uaa/util/UaaTokenUtilsTest.java | 2 +- .../identity/uaa/util/UaaUrlUtilsTest.java | 4 +- .../identity/uaa/util/beans/DbUtilsTest.java | 16 +- .../CookieBasedCsrfTokenRepositoryTests.java | 7 +- ...wareAuthenticationSuccessHandlerTests.java | 8 +- ...enticationSuccessHandlerZonePathTests.java | 9 +- .../uaa/web/UaaSavedRequestCacheTests.java | 7 +- .../tomcat/UaaStartupFailureListenerTest.java | 8 +- .../uaa/zone/BannerValidatorTest.java | 6 +- ...entityZoneConfigurationValidatorTests.java | 14 +- .../GeneralIdentityZoneValidatorTests.java | 4 +- .../uaa/zone/IdentityZoneEndpointsTests.java | 10 +- .../JdbcIdentityZoneProvisioningTests.java | 18 +- .../uaa/zone/LoginConsentValidatorTest.java | 174 +++++++++--------- ...titenantJdbcClientDetailsServiceTests.java | 13 +- .../uaa/zone/UserConfigValidatorTest.java | 8 +- ...AwareClientSecretPolicyValidatorTests.java | 2 +- .../uaa/zone/ZoneContextPathSessionTests.java | 37 ++-- .../ZonePathContextRewritingFilterTests.java | 105 +++++------ .../boot/UaaBootServerCustomizerTest.java | 10 +- .../cloudfoundry/identity/uaa/MBeanTests.java | 2 +- .../identity/uaa/UaaConfigurationTests.java | 2 +- .../uaa/UaaWebApplicationInitializerTest.java | 5 +- .../DynamicLdapAuthenticationManagerTest.java | 2 +- ...micZoneAwareAuthenticationManagerTest.java | 24 +-- .../ClientAdminEndpointsIntegrationTests.java | 4 +- .../PasswordGrantIntegrationTests.java | 2 +- .../ScimGroupEndpointsIntegrationTests.java | 8 +- .../integration/feature/ErrorRoutingIT.java | 8 +- .../integration/feature/ImplicitGrantIT.java | 4 +- .../uaa/integration/feature/LdapLoginIT.java | 6 +- .../uaa/integration/feature/OIDCLoginIT.java | 13 +- .../feature/PrivateKeyJwtClientAuthIT.java | 4 +- .../integration/feature/RateLimitingIT.java | 2 +- .../uaa/integration/feature/SamlLoginIT.java | 4 +- .../integration/feature/UserTokenGrantIT.java | 2 +- .../util/IntegrationTestUtils.java | 14 +- .../InvitationsEndpointMockMvcTests.java | 2 +- ...vitationsEndpointMockMvcZonePathTests.java | 2 +- .../uaa/login/LoginMockMvcZonePathTests.java | 39 ++-- .../ResetPasswordControllerMockMvcTests.java | 7 - ...asswordControllerMockMvcZonePathTests.java | 7 - .../LocalUaaRestTemplateMockMvcTests.java | 6 +- .../mock/audit/AuditCheckMockMvcTests.java | 2 +- ...entJwtCredentialsEndpointMockMvcTests.java | 10 +- .../mock/ldap/AbstractLdapMockMvcTest.java | 12 +- ...ityProviderEndpointsAliasMockMvcTests.java | 17 +- ...IdentityProviderEndpointsMockMvcTests.java | 8 +- ...ProviderEndpointsMockMvcZonePathTests.java | 8 +- ...okenExchangeDefaultConfigMockMvcTests.java | 89 ++++----- .../mock/token/TokenExchangeMockMvcBase.java | 5 +- ...changeOverrideAuthManagerMockMvcTests.java | 9 +- .../uaa/mock/token/TokenMvcMockTests.java | 91 +++++---- .../mock/token/TokenMvcMockZonePathTests.java | 94 +++++----- .../TokenRevocationEndpointMockMvcTest.java | 8 +- ...RevocationEndpointMockMvcZonePathTest.java | 8 +- .../mock/token/ZonePathTokenMockMvcTests.java | 6 +- .../IdentityZoneEndpointsMockMvcTests.java | 10 +- ...tityZoneEndpointsMockMvcZonePathTests.java | 8 +- .../uaa/oauth/UaaTokenServicesTests.java | 16 +- .../ratelimiting/RateLimiterMockMvcTest.java | 24 +-- ...RateLimitingFilterZonePathMockMvcTest.java | 2 +- .../PasswordResetEndpointMockMvcTests.java | 3 - .../ScimGroupEndpointsMockMvcTests.java | 3 +- ...cimGroupEndpointsMockMvcZonePathTests.java | 3 +- .../endpoints/ScimGroupEndpointsTests.java | 6 +- .../ScimUserEndpointsAliasMockMvcTests.java | 4 +- .../ScimUserEndpointsMockMvcTests.java | 3 +- ...ScimUserEndpointsMockMvcZonePathTests.java | 3 +- .../endpoints/ScimUserEndpointsTests.java | 6 +- .../endpoints/ScimUserLookupMockMvcTests.java | 2 +- .../UserInfoEndpointMockMvcTests.java | 6 +- 285 files changed, 1345 insertions(+), 1604 deletions(-) diff --git a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/MetricsUtilTest.java b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/MetricsUtilTest.java index cdea7b3e75a..83fe61d2112 100644 --- a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/MetricsUtilTest.java +++ b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/MetricsUtilTest.java @@ -47,23 +47,23 @@ void addAverages() { @Test void mutableLong() { MetricsUtil.MutableLong mlong = new MetricsUtil.MutableLong(1); - assertThat(mlong.get()).isEqualTo(1L); + assertThat(mlong.get()).isOne(); mlong.add(1L); assertThat(mlong.get()).isEqualTo(2L); mlong.set(1L); - assertThat(mlong.get()).isEqualTo(1L); - assertThat(mlong.toString()).isEqualTo("1"); + assertThat(mlong.get()).isOne(); + assertThat(mlong).hasToString("1"); } @Test void mutableDouble() { MetricsUtil.MutableDouble mlong = new MetricsUtil.MutableDouble(1.0); - assertThat(mlong.get()).isEqualTo(1.0d); + assertThat(mlong.get()).isOne(); mlong.add(1.5d); assertThat(mlong.get()).isEqualTo(2.5d); mlong.set(1.0d); - assertThat(mlong.get()).isEqualTo(1.0d); - assertThat(mlong.toString()).isEqualTo("1.0"); + assertThat(mlong.get()).isOne(); + assertThat(mlong).hasToString("1.0"); } @Test diff --git a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/StatusCodeGroupTest.java b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/StatusCodeGroupTest.java index 60880372acb..5b80d2216cd 100644 --- a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/StatusCodeGroupTest.java +++ b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/StatusCodeGroupTest.java @@ -4,7 +4,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class StatusCodeGroupTest { @@ -17,14 +17,10 @@ void getName() { @Test void throwsWhenInvalid() { - IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, - () -> StatusCodeGroup.valueOf("INVALID GROUP") - ); + IllegalArgumentException exception = assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> StatusCodeGroup.valueOf("INVALID GROUP")).actual(); assertThat(exception.getMessage()).startsWith("No enum constant org.cloudfoundry.identity.uaa.metrics.StatusCodeGroup.INVALID GROUP"); - exception = assertThrows(IllegalArgumentException.class, - () -> StatusCodeGroup.valueOf(606) - ); + exception = assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> StatusCodeGroup.valueOf(606)).actual(); assertThat(exception.getMessage()).startsWith("No matching constant for [" + 606 + "]"); } } \ No newline at end of file diff --git a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/UrlGroupTest.java b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/UrlGroupTest.java index 288fff609ef..77f617f01e9 100644 --- a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/UrlGroupTest.java +++ b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/metrics/UrlGroupTest.java @@ -25,10 +25,11 @@ void setup() { @Test void getMap() { - assertThat(map.get("group")).isEqualTo("group"); - assertThat(map.get("category")).isEqualTo("category"); - assertThat(map.get("limit")).isEqualTo(1L); - assertThat(map.get("pattern")).isEqualTo("/**"); + assertThat(map) + .containsEntry("group", "group") + .containsEntry("category", "category") + .containsEntry("limit", 1L) + .containsEntry("pattern", "/**"); } @Test @@ -36,7 +37,7 @@ void from() { group = UrlGroup.from(map); assertThat(group.getGroup()).isEqualTo("group"); assertThat(group.getCategory()).isEqualTo("category"); - assertThat(group.getLimit()).isEqualTo(1L); + assertThat(group.getLimit()).isOne(); assertThat(group.getPattern()).isEqualTo("/**"); } } \ No newline at end of file diff --git a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java index 8dccc30d4d0..a79d32edc0c 100644 --- a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java +++ b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java @@ -5,11 +5,11 @@ import tools.jackson.databind.DeserializationContext; import tools.jackson.databind.JsonNode; import tools.jackson.databind.annotation.JsonDeserialize; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.metrics.UrlGroup; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import tools.jackson.core.JacksonException; import tools.jackson.databind.ValueDeserializer; import java.lang.reflect.Constructor; @@ -17,10 +17,7 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.*; class JsonUtilsTest { private static final String JSON_TEST_OBJECT_STRING = "{\"pattern\":\"/pattern\",\"group\":\"group\",\"limit\":1000,\"category\":\"category\"}"; @@ -68,8 +65,8 @@ void readValueAsMap() { @ParameterizedTest @ValueSource(strings = {"{", "}", "{\"prop1\":\"abc\","}) void readValueAsMapInvalid(final String input) { - assertThatExceptionOfType(JsonUtils.JsonUtilException.class) - .isThrownBy(() -> JsonUtils.readValueAsMap(input)); + assertThatThrownBy(() -> JsonUtils.readValueAsMap(input)) + .asInstanceOf(InstanceOfAssertFactories.throwable(JsonUtils.JsonUtilException.class)); } @Test @@ -105,8 +102,8 @@ void serializeExcludingProperties() { void serializeExcludingPropertiesInnerCallFails() { Map groupProperties = JsonUtils.readValue(JSON_TEST_OBJECT_STRING, new TypeReference<>() { }); - assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> - JsonUtils.serializeExcludingProperties(groupProperties, "limit.unknown")); + assertThatThrownBy(() -> JsonUtils.serializeExcludingProperties(groupProperties, "limit.unknown")) + .asInstanceOf(InstanceOfAssertFactories.throwable(JsonUtils.JsonUtilException.class)); } @Test @@ -139,82 +136,64 @@ void cannotInstantiate() { } @Test - void throwsException_writeValueAsString() throws JacksonException { - JsonUtils.JsonUtilException exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.writeValueAsString(new Object()) - ); + void throwsException_writeValueAsString() throws Exception { + JsonUtils.JsonUtilException exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.writeValueAsString(new Object())).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.lang.Object"); } @Test - void throwsException_writeValueAsBytes() throws JacksonException { - JsonUtils.JsonUtilException exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.writeValueAsBytes(new Object()) - ); + void throwsException_writeValueAsBytes() throws Exception { + JsonUtils.JsonUtilException exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.writeValueAsBytes(new Object())).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.lang.Object"); } @Test - void throwsException_readValue() throws JacksonException { - JsonUtils.JsonUtilException exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.readValue("invalid json", String.class) - ); + void throwsException_readValue() throws Exception { + JsonUtils.JsonUtilException exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.readValue("invalid json", String.class)).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.core.exc.StreamReadException: Unrecognized token 'invalid'"); - exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.readValue("invalid json".getBytes(), String.class) - ); + exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.readValue("invalid json".getBytes(), String.class)).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.core.exc.StreamReadException: Unrecognized token 'invalid'"); - exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.readValue("invalid json", new TypeReference() {}) - ); + exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.readValue("invalid json", new TypeReference() { + })).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.core.exc.StreamReadException: Unrecognized token 'invalid'"); - exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.readValue("invalid json".getBytes(), new TypeReference() {}) - ); + exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.readValue("invalid json".getBytes(), new TypeReference() { + })).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.core.exc.StreamReadException: Unrecognized token 'invalid'"); } @Test - void throwsException_readValueAsMap() throws JacksonException { - JsonUtils.JsonUtilException exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.readValueAsMap("invalid json") - ); + void throwsException_readValueAsMap() throws Exception { + JsonUtils.JsonUtilException exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.readValueAsMap("invalid json")).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.core.exc.StreamReadException: Unrecognized token 'invalid'"); } @Test - void throwsException_convertValue() throws JacksonException { - JsonUtils.JsonUtilException exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.convertValue(Boolean.TRUE, Integer.class) - ); + void throwsException_convertValue() throws Exception { + JsonUtils.JsonUtilException exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.convertValue(Boolean.TRUE, Integer.class)).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.lang.Integer` from Boolean value"); } @Test - void throwsException_readTree() throws JacksonException { + void throwsException_readTree() throws Exception { assertThat(JsonUtils.readTree((String)null)).isNull(); - JsonUtils.JsonUtilException exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.readTree("invalid json") - ); + JsonUtils.JsonUtilException exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.readTree("invalid json")).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.core.exc.StreamReadException: Unrecognized token 'invalid'"); } @Test - void throwsException_readTreeWithParserArg() throws JacksonException { + void throwsException_readTreeWithParserArg() throws Exception { - JsonUtils.JsonUtilException exception = assertThrows(JsonUtils.JsonUtilException.class, - () -> JsonUtils.readValue("{'valid':'json'}", SerializerTestObject.class) - ); + JsonUtils.JsonUtilException exception = assertThatExceptionOfType(JsonUtils.JsonUtilException.class).isThrownBy(() -> JsonUtils.readValue("{'valid':'json'}", SerializerTestObject.class)).actual(); assertThat(exception.getMessage()).startsWith("tools.jackson.core.exc.StreamReadException: Unexpected character"); } @Test - void readNodes() throws JacksonException { + void readNodes() throws Exception { JsonUtils.readValue(""" { "date": "1320105600000", diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/account/OpenIdConfigurationTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/account/OpenIdConfigurationTests.java index 306909ac989..6530d0206ad 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/account/OpenIdConfigurationTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/account/OpenIdConfigurationTests.java @@ -5,7 +5,6 @@ import org.junit.jupiter.api.Test; import org.springframework.boot.test.json.BasicJsonTester; import org.springframework.test.util.ReflectionTestUtils; -import tools.jackson.core.JacksonException; import java.lang.reflect.Field; @@ -51,7 +50,7 @@ void defaultClaims() { } @Test - void allNulls() throws JacksonException { + void allNulls() throws Exception { OpenIdConfiguration openIdConfiguration = new OpenIdConfiguration(null, null); for (Field field : OpenIdConfiguration.class.getDeclaredFields()) { diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java index 0ef5a1b0e23..a344ec2aeec 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java @@ -9,7 +9,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Test for InMemoryClientDetailsService diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateDeserializerTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateDeserializerTest.java index 75a911a8642..cabeb8ccf2d 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateDeserializerTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateDeserializerTest.java @@ -18,7 +18,6 @@ import tools.jackson.core.JsonParser; import tools.jackson.databind.json.JsonMapper; -import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @@ -30,14 +29,14 @@ class JsonDateDeserializerTest { Exception exceptionOccured; @Test - void parsing() throws ParseException { + void parsing() throws Exception { JsonParser jp = JsonMapper.shared().createParser("\"" + testDateString + "\""); Date d = JsonDateDeserializer.getDate(testDateString, jp); assertThat((long) d.getTime()).isEqualTo(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(testDateString).getTime()); } @Test - void parsingParallel() throws InterruptedException { + void parsingParallel() throws Exception { Thread[] threadArray = new Thread[1000]; for (int i = 0; i < 1000; i++) { diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateSerializerTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateSerializerTest.java index 210be7f07fc..43b0a115a42 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateSerializerTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/impl/JsonDateSerializerTest.java @@ -25,7 +25,7 @@ void formatting() { } @Test - void formattingParallel() throws InterruptedException { + void formattingParallel() throws Exception { Thread[] threadArray = new Thread[1000]; for (int i = 0; i < 1000; i++) { diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientJwtCredentialTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientJwtCredentialTest.java index 6cb308ea43c..c373c12dd2a 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientJwtCredentialTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientJwtCredentialTest.java @@ -4,8 +4,8 @@ import java.util.List; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class ClientJwtCredentialTest { @@ -18,7 +18,7 @@ void parse() { } @Test - void testConstructor() { + void constructor() { ClientJwtCredential jwtCredential = new ClientJwtCredential("subject", "issuer", "audience"); assertThat(jwtCredential.getSubject()).isEqualTo("subject"); assertThat(jwtCredential.getIssuer()).isEqualTo("issuer"); @@ -26,7 +26,7 @@ void testConstructor() { } @Test - void testDeserializerConstructorException() { + void deserializerConstructorException() { assertThatThrownBy(() -> ClientJwtCredential.parse("[{\"iss\":\"http://localhost:8080/uaa\",\"sub\":\"client_with_jwks_trust\"},{\"iss\":\"http://localhost:8080/uaa\"}]")) .isInstanceOf(IllegalArgumentException.class).hasMessage("Client jwt configuration cannot be parsed"); assertThatThrownBy(() -> ClientJwtCredential.parse("[{\"sub\":\"client_with_jwks_trust\"}]")) @@ -36,7 +36,7 @@ void testDeserializerConstructorException() { } @Test - void testDeserializerParserException() { + void deserializerParserException() { assertThatThrownBy(() -> ClientJwtCredential.parse("[\"iss\":\"issuer\"]")) .isInstanceOf(IllegalArgumentException.class).hasMessage("Client jwt configuration cannot be parsed"); } @@ -48,7 +48,7 @@ void testHashCode() { } @Test - void testEquals() { + void equals() { assertThat(new ClientJwtCredential("subject", "issuer", "audience")).isEqualTo(new ClientJwtCredential("subject", "issuer", "audience")); assertThat(new ClientJwtCredential("subject", "issuer", "audience")).isNotEqualTo(new ClientJwtCredential("subject", "issuer", null)); } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java index 3d2ce0e2c79..c2dad87633c 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java @@ -8,7 +8,7 @@ import org.springframework.mock.http.client.MockClientHttpRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java index 85f412c5085..d1e2e6771ed 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java @@ -32,9 +32,7 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; /** * Moved test class of from spring-security-oauth2 into UAA @@ -296,13 +294,10 @@ public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails detail throw new UserRedirectRequiredException("https://www.foo.com/", Collections.emptyMap()); } }); - try { + assertThatThrownBy(() -> { OAuth2AccessToken newToken = restTemplate.getAccessToken(); assertThat(newToken).isNotNull(); - fail("Expected UserRedirectRequiredException"); - } catch (UserRedirectRequiredException _) { - // planned - } + }).isInstanceOf(UserRedirectRequiredException.class); // context token should be reset as it is invalid at this point assertThat(restTemplate.getOAuth2ClientContext().getAccessToken()).isNull(); } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java index 19db180a494..4f1555f32ad 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java @@ -27,14 +27,11 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.net.URI; import java.util.ArrayList; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.when; /** @@ -178,7 +175,7 @@ void handleGeneric403ErrorWithBody() { } @Test - void bodyCanBeUsedByCustomHandler() throws UnsupportedEncodingException { + void bodyCanBeUsedByCustomHandler() throws Exception { final String appSpecificBodyContent = "{\"some_status\":\"app error\"}"; OAuth2ErrorHandler handler = new OAuth2ErrorHandler(new ResponseErrorHandler() { public boolean hasError(ClientHttpResponse response) throws IOException { @@ -205,7 +202,7 @@ public void handleError(URI url, HttpMethod method, ClientHttpResponse response) } @Test - void handleErrorWithMissingHeader() throws IOException { + void handleErrorWithMissingHeader() throws Exception { final HttpHeaders headers = new HttpHeaders(); when(response.getHeaders()).thenReturn(headers); when(response.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); @@ -240,7 +237,7 @@ void handleErrorWhenAccessDeniedMessageAndStatus403ThenThrowsOAuth2AccessDeniedE } @Test - void handleMessageConversionExceptions() throws UnsupportedEncodingException { + void handleMessageConversionExceptions() throws Exception { HttpMessageConverter extractor = new HttpMessageConverter() { @Override public boolean canRead(Class clazz, MediaType mediaType) { diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java index bdb1ed19868..3ff92f8bbc3 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java @@ -10,11 +10,10 @@ import org.springframework.mock.http.MockHttpInputMessage; import org.springframework.mock.http.MockHttpOutputMessage; -import java.io.IOException; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class FormOAuth2ExceptionHttpMessageTest { @@ -41,11 +40,11 @@ void canWrite() { @Test void getSupportedMediaTypes() { - assertThat(converter.getSupportedMediaTypes()).isEqualTo(Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED)); + assertThat(converter.getSupportedMediaTypes()).containsExactlyElementsOf(Collections.singletonList(MediaType.APPLICATION_FORM_URLENCODED)); } @Test - void read() throws IOException { + void read() throws Exception { assertThat(converter.read(OAuth2Exception.class, new MockHttpInputMessage("".getBytes()))).isNotNull(); } @@ -56,7 +55,7 @@ void writeInternal() { } @Test - void write() throws IOException { + void write() throws Exception { HttpOutputMessage outputMessage = new MockHttpOutputMessage(); OAuth2Exception e = new BadClientCredentialsException(); e.addAdditionalInformation("key", "value"); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java index aa6c67ba424..d6d6153e4b9 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java @@ -34,7 +34,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java index 7a3abccd279..0fe2c11a73c 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java @@ -17,9 +17,7 @@ import java.util.Collections; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java index 0a5b0c0e028..39703c9ab0d 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderWithConversionTests.java @@ -1,6 +1,5 @@ package org.cloudfoundry.identity.uaa.oauth.client.token.grant; -import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; import org.cloudfoundry.identity.uaa.oauth.client.grant.AuthorizationCodeAccessTokenProvider; diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java index 1f95fe0875d..3325fc8ece9 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java @@ -14,13 +14,12 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA @@ -65,7 +64,7 @@ void refreshAccessToken() { } @Test - void implicitResponseExtractor() throws IOException { + void implicitResponseExtractor() throws Exception { assertThat(provider.getResponseExtractor().extractData(new MockClientHttpResponse(new byte[0], 200))).isNull(); } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java index 3b20153dd3d..5850ca42611 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java @@ -17,7 +17,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2DeserializerTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2DeserializerTests.java index ff9d766b6cb..c35bf49c56f 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2DeserializerTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2DeserializerTests.java @@ -2,11 +2,9 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; import java.util.Date; import java.util.HashSet; @@ -26,7 +24,7 @@ void createObjectMapper() { } @Test - void readValueNoRefresh() throws IOException { + void readValueNoRefresh() throws Exception { accessToken.setRefreshToken(null); accessToken.setScope(null); OAuth2AccessToken actual = mapper.readValue(ACCESS_TOKEN_NOREFRESH, OAuth2AccessToken.class); @@ -34,28 +32,28 @@ void readValueNoRefresh() throws IOException { } @Test - void readValueWithRefresh() throws IOException { + void readValueWithRefresh() throws Exception { accessToken.setScope(null); OAuth2AccessToken actual = mapper.readValue(ACCESS_TOKEN_NOSCOPE, OAuth2AccessToken.class); assertTokenEquals(accessToken, actual); } @Test - void readValueWithSingleScopes() throws IOException { + void readValueWithSingleScopes() throws Exception { accessToken.getScope().remove(accessToken.getScope().iterator().next()); OAuth2AccessToken actual = mapper.readValue(ACCESS_TOKEN_SINGLESCOPE, OAuth2AccessToken.class); assertTokenEquals(accessToken, actual); } @Test - void readValueWithEmptyStringScope() throws IOException { + void readValueWithEmptyStringScope() throws Exception { accessToken.setScope(new HashSet<>()); OAuth2AccessToken actual = mapper.readValue(ACCESS_TOKEN_EMPTYSCOPE, OAuth2AccessToken.class); assertTokenEquals(accessToken, actual); } @Test - void readValueWithBrokenExpiresIn() throws IOException { + void readValueWithBrokenExpiresIn() throws Exception { accessToken.setScope(new HashSet<>()); OAuth2AccessToken actual = mapper.readValue(ACCESS_TOKEN_BROKENEXPIRES, OAuth2AccessToken.class); assertTokenEquals(accessToken, actual); @@ -107,11 +105,15 @@ private static void assertTokenEquals(OAuth2AccessToken expected, OAuth2AccessTo } else { assertThat(actual.getRefreshToken().getValue()).isEqualTo(expectedRefreshToken.getValue()); } - assertThat(actual.getScope()).isEqualTo(expected.getScope()); + if (expected.getScope() == null) { + assertThat(actual.getScope()).isNull(); + } else { + assertThat(actual.getScope()).hasSameElementsAs(expected.getScope()); + } Date expectedExpiration = expected.getExpiration(); if (expectedExpiration == null) { assertThat(actual.getExpiration()).isNull(); } - assertThat(actual.getAdditionalInformation()).isEqualTo(expected.getAdditionalInformation()); + assertThat(actual.getAdditionalInformation()).containsExactlyInAnyOrderEntriesOf(expected.getAdditionalInformation()); } } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java index 2e16cb83b3a..26081e98ec5 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/OAuth2AccessTokenJackson2SerializerTests.java @@ -6,8 +6,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.IOException; - import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -25,7 +23,7 @@ void createObjectMapper() { } @Test - void writeValueAsStringNoRefresh() throws IOException { + void writeValueAsStringNoRefresh() throws Exception { accessToken.setRefreshToken(null); accessToken.setScope(null); String encodedAccessToken = mapper.writeValueAsString(accessToken); @@ -33,21 +31,21 @@ void writeValueAsStringNoRefresh() throws IOException { } @Test - void writeValueAsStringWithRefresh() throws IOException { + void writeValueAsStringWithRefresh() throws Exception { accessToken.setScope(null); String encodedAccessToken = mapper.writeValueAsString(accessToken); assertThat(encodedAccessToken).isNotEqualTo(BaseOAuth2AccessTokenJacksonTest.ACCESS_TOKEN_NOSCOPE); } @Test - void writeValueAsStringWithEmptyScope() throws IOException { + void writeValueAsStringWithEmptyScope() throws Exception { accessToken.getScope().clear(); String encodedAccessToken = mapper.writeValueAsString(accessToken); assertThat(encodedAccessToken).isNotEqualTo(BaseOAuth2AccessTokenJacksonTest.ACCESS_TOKEN_NOSCOPE); } @Test - void writeValueAsStringWithSingleScopes() throws IOException { + void writeValueAsStringWithSingleScopes() throws Exception { accessToken.getScope().remove(accessToken.getScope().iterator().next()); String encodedAccessToken = mapper.writeValueAsString(accessToken); assertThat(encodedAccessToken).isNotEqualTo(BaseOAuth2AccessTokenJacksonTest.ACCESS_TOKEN_SINGLESCOPE); @@ -79,14 +77,14 @@ void writeValueAsStringWithEmptyStringScope() { } @Test - void writeValueAsStringWithQuoteInScope() throws IOException { + void writeValueAsStringWithQuoteInScope() throws Exception { accessToken.getScope().add("\""); String encodedAccessToken = mapper.writeValueAsString(accessToken); assertThat(encodedAccessToken).isNotEqualTo("{\"access_token\":\"token-value\",\"token_type\":\"bearer\",\"refresh_token\":\"refresh-value\",\"expires_in\":10,\"scope\":\"\\\" read write\"}"); } @Test - void writeValueAsStringWithMultiScopes() throws IOException { + void writeValueAsStringWithMultiScopes() throws Exception { String encodedAccessToken = mapper.writeValueAsString(accessToken); assertThat(encodedAccessToken).isNotEqualTo(ACCESS_TOKEN_MULTISCOPE); } @@ -100,7 +98,7 @@ void writeValueAsStringWithMac() throws Exception { } @Test - void writeValueWithAdditionalInformation() throws IOException { + void writeValueWithAdditionalInformation() throws Exception { accessToken.setRefreshToken(null); accessToken.setScope(null); accessToken.setExpiration(null); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java index 00bbb32a7f3..922f5241d72 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java @@ -6,7 +6,7 @@ import java.security.SecureRandom; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyDeserializerTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyDeserializerTest.java index 6696d243a5e..3a784ab27c2 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyDeserializerTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyDeserializerTest.java @@ -41,7 +41,7 @@ void webKeysUaa() { JsonWebKeySet keys = JsonUtils.readValue(uaaLegacyJwkSet, new TypeReference>() { }); assertThat(keys).isNotNull(); - assertThat(keys.getKeys()).isNotNull() + assertThat(keys.getKeys()) .hasSize(1); for (JsonWebKey key : keys.getKeys()) { assertThat(key).isNotNull(); @@ -56,7 +56,7 @@ void webKeysKeycloak() { JsonWebKeySet keys = JsonUtils.readValue(keyCloakJwkSet, new TypeReference>() { }); assertThat(keys).isNotNull(); - assertThat(keys.getKeys()).isNotNull() + assertThat(keys.getKeys()) .hasSize(1); for (JsonWebKey key : keys.getKeys()) { assertThat(key).isNotNull(); @@ -72,7 +72,7 @@ void webKeysOcted() { JsonWebKeySet keys = JsonUtils.readValue(keyOctedJwkSet, new TypeReference>() { }); assertThat(keys).isNotNull(); - assertThat(keys.getKeys()).isNotNull() + assertThat(keys.getKeys()) .hasSize(1); for (JsonWebKey key : keys.getKeys()) { assertThat(key).isNotNull(); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java index 3ce29b1d881..ba717d155be 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java @@ -8,7 +8,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; class JsonWebKeyTests { diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/IntrospectionClaimsTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/IntrospectionClaimsTest.java index d5579734565..bbe3490faa1 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/IntrospectionClaimsTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/IntrospectionClaimsTest.java @@ -36,7 +36,7 @@ void isActive() { @Test void serialize() { assertThat(JsonUtils.writeValueAsString(introspectionPayload)).contains(TokenConstants.CLIENT_AUTH_NONE); - assertThat(introspectionPayload.getClaimMap()).isNotNull() + assertThat(introspectionPayload.getClaimMap()) .containsEntry("grant_type", "authorization_code") .containsEntry("client_id", "login") .containsEntry("aud", Arrays.asList("openid", "login")) diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java index 9ea3dceed04..66c36aa2c3b 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java @@ -31,7 +31,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java index 64e26b3309a..bcba1e41c9e 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java @@ -24,7 +24,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.common.OAuth2AccessToken.BEARER_TYPE; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -120,7 +120,7 @@ void defaultAccessTokenRequest() { accessTokenRequest.addAll(parameters); accessTokenRequest.clear(); accessTokenRequest.add("key", "value"); - assertThat(accessTokenRequest.keySet()).isEqualTo(Set.of("key")); + assertThat(accessTokenRequest.keySet()).hasSameElementsAs(Set.of("key")); assertThat(accessTokenRequest.values()).hasToString(List.of(List.of("value")).toString()); // parameters @@ -136,7 +136,7 @@ void defaultAccessTokenRequest() { accessTokenRequest.clear(); parameters = new LinkedMultiValueMap<>(); parameters.addAll("key", List.of("value")); - assertThat(new DefaultAccessTokenRequest(null)).isEqualTo(accessTokenRequest); + assertThat(new DefaultAccessTokenRequest(null)).containsExactlyInAnyOrderEntriesOf(accessTokenRequest); DefaultAccessTokenRequest newAccessTokenRequest = new DefaultAccessTokenRequest(Map.of("scope", new String[]{"x"}, "client_id", new String[]{"x"})); assertThat(newAccessTokenRequest).isNotEqualTo(accessTokenRequest); assertThat(newAccessTokenRequest.toString()).isNotEqualTo(accessTokenRequest.toString()); @@ -146,8 +146,8 @@ void defaultAccessTokenRequest() { } accessTokenRequest.remove("key"); assertThat(accessTokenRequest).doesNotContainKey("key") - .doesNotContainKey("key"); - assertThat(accessTokenRequest.containsValue("value")).isFalse(); + .doesNotContainKey("key") + .doesNotContainValue(List.of("value")); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java index dc06489af86..fa6b6d24981 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java @@ -9,7 +9,7 @@ import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class VerificationKeyResponseTest { diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/provider/OIDCIdentityProviderDefinitionTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/provider/OIDCIdentityProviderDefinitionTests.java index ad35f596f9f..6e64ea45f19 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/provider/OIDCIdentityProviderDefinitionTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/provider/OIDCIdentityProviderDefinitionTests.java @@ -19,7 +19,6 @@ import org.cloudfoundry.identity.uaa.util.JsonUtils; import org.junit.jupiter.api.Test; -import java.net.MalformedURLException; import java.net.URI; import java.util.Arrays; import java.util.HashMap; @@ -34,7 +33,7 @@ class OIDCIdentityProviderDefinitionTests { String url = "https://accounts.google.com/.well-known/openid-configuration"; @Test - void serialize_discovery_url() throws MalformedURLException { + void serialize_discovery_url() throws Exception { OIDCIdentityProviderDefinition def = JsonUtils.readValue(defaultJson, OIDCIdentityProviderDefinition.class); assertThat(def.getDiscoveryUrl()).isNull(); def.setDiscoveryUrl(URI.create(url).toURL()); @@ -46,7 +45,7 @@ void serialize_discovery_url() throws MalformedURLException { } @Test - void serializableObjectCalls() throws CloneNotSupportedException { + void serializableObjectCalls() throws Exception { OIDCIdentityProviderDefinition def = JsonUtils.readValue(defaultJson, OIDCIdentityProviderDefinition.class); OIDCIdentityProviderDefinition def2 = (OIDCIdentityProviderDefinition) def.clone(); assertThat(def2).isEqualTo(def) @@ -65,11 +64,11 @@ void serialize_prompts() { def.setPrompts(prompts); String json = JsonUtils.writeValueAsString(def); def = JsonUtils.readValue(json, OIDCIdentityProviderDefinition.class); - assertThat(def.getPrompts()).isEqualTo(prompts); + assertThat(def.getPrompts()).containsExactlyElementsOf(prompts); } @Test - void equalsTests() throws CloneNotSupportedException { + void equalsTests() throws Exception { OIDCIdentityProviderDefinition original = JsonUtils.readValue(defaultJson, OIDCIdentityProviderDefinition.class); OIDCIdentityProviderDefinition compare = (OIDCIdentityProviderDefinition) original.clone(); compare.setTokenExchangeEnabled(false); @@ -91,7 +90,7 @@ void serialize_jwtClientAuthentication() { } @Test - void testToString() throws MalformedURLException { + void testToString() throws Exception { OIDCIdentityProviderDefinition def = new OIDCIdentityProviderDefinition(); def.setDiscoveryUrl(URI.create(url).toURL()); def.setPasswordGrantEnabled(true); @@ -129,7 +128,7 @@ void testToString() throws MalformedURLException { } @Test - void testToStringWithNullValues() { + void toStringWithNullValues() { OIDCIdentityProviderDefinition def = new OIDCIdentityProviderDefinition(); String result = def.toString(); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderDefinitionTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderDefinitionTests.java index 6f42a869f4f..cfd79af801f 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderDefinitionTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderDefinitionTests.java @@ -192,7 +192,7 @@ void setIdpEntityId() { void setEmailDomain() { SamlIdentityProviderDefinition def = new SamlIdentityProviderDefinition(); def.setEmailDomain(Collections.singletonList("test.com")); - assertThat(def.getEmailDomain().getFirst()).isEqualTo("test.com"); + assertThat(def.getEmailDomain()).first().isEqualTo("test.com"); } @Test @@ -205,7 +205,7 @@ void defaultAuthnContext() { void setAuthnContext() { SamlIdentityProviderDefinition def = new SamlIdentityProviderDefinition(); def.setAuthnContext(Collections.singletonList("a-custom-context")); - assertThat(def.getAuthnContext().getFirst()).isEqualTo("a-custom-context"); + assertThat(def.getAuthnContext()).first().isEqualTo("a-custom-context"); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java index 83dd263fb17..142ecb93196 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java @@ -23,7 +23,7 @@ import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class ScimGroupTests { private static final String GROUP_BEFORE_DESCRIPTION = "{\"meta\":{\"version\":0,\"created\":\"2016-01-13T09:01:33.909Z\"},\"zoneId\":\"zoneId\",\"displayName\":\"name\",\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"id\":\"id\"}"; diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java index 572fedfe869..407dad85ad3 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserTests.java @@ -31,9 +31,7 @@ import java.util.Set; import java.util.UUID; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; /** * @author Luke Taylor @@ -331,7 +329,7 @@ void setPrimaryEmail() { assertThat(user.getPrimaryEmail()).isEqualTo("new@example.com"); - assertThat(user.getEmails()).isEqualTo(Arrays.asList(newEmail, email2, email3)); + assertThat(user.getEmails()).containsExactlyElementsOf(Arrays.asList(newEmail, email2, email3)); try { user.addEmail("email3@bar.com"); @@ -448,9 +446,9 @@ void phoneNumber() { // should reject adding duplicate phone number if the existing has a type set to null p1.setType(null); - assertThatIllegalArgumentException() - .isThrownBy(() -> user.addPhoneNumber(p1.getValue())) - .withMessageStartingWith("Already contains phoneNumber"); + assertThatThrownBy(() -> user.addPhoneNumber(p1.getValue())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("Already contains phoneNumber"); } @Test @@ -553,12 +551,7 @@ void patchUserChangeUserName() { //username is a required field patch.getMeta().setAttributes(new String[]{"username"}); patch.setUserName(null); - try { - user.patch(patch); - fail("username is a required field, can't nullify it."); - } catch (IllegalArgumentException _) { - // ignore - } + assertThatThrownBy(() -> user.patch(patch)).isInstanceOf(IllegalArgumentException.class); assertThat(user.getUserName()).isNotNull(); //we can drop and set the username again @@ -605,8 +598,8 @@ void patchUserDropNameSubAttributes() { @Test void patchUserRejectChangingOrigin() { patch.setOrigin("some-new-origin"); - assertThatIllegalArgumentException().isThrownBy(() -> user.patch(patch)) - .withMessage("Cannot change origin in patch of user."); + assertThatThrownBy(() -> user.patch(patch)).isInstanceOf(IllegalArgumentException.class) + .hasMessage("Cannot change origin in patch of user."); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/test/JsonTranslation.java b/model/src/test/java/org/cloudfoundry/identity/uaa/test/JsonTranslation.java index 2d99dcc0510..e655c5629fe 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/test/JsonTranslation.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/test/JsonTranslation.java @@ -4,9 +4,6 @@ import tools.jackson.databind.json.JsonMapper; import org.junit.jupiter.api.Test; -import tools.jackson.core.JacksonException; - -import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.HamcrestCondition.matching; @@ -62,7 +59,7 @@ private void validate() { } @Test - void toJson() throws JacksonException { + void toJson() throws Exception { validate(); assertThat(subjectClass.getResourceAsStream(jsonFileName)).as("file <%s/%s> must exist on classpath".formatted(subjectClass.getPackage().getName().replace(".", "/"), jsonFileName)).isNotNull(); @@ -72,7 +69,7 @@ void toJson() throws JacksonException { } @Test - void fromJson() throws IOException { + void fromJson() throws Exception { validate(); assertThat(subjectClass.getResourceAsStream(jsonFileName)).as("file <%s/%s> must exist on classpath".formatted(subjectClass.getPackage().getName().replace(".", "/"), jsonFileName)).isNotNull(); @@ -84,7 +81,7 @@ void fromJson() throws IOException { } @Test - void withNullFields_checkIsEmptyJson() throws IllegalAccessException, InstantiationException, JacksonException { + void withNullFields_checkIsEmptyJson() throws Exception { assumeTrue(EXPECT_EMPTY_JSON.equals(withAllNullFields), "To configure this test, use %s instead of %s".formatted(EXPECT_EMPTY_JSON, withAllNullFields)); validate(); @@ -94,7 +91,7 @@ void withNullFields_checkIsEmptyJson() throws IllegalAccessException, Instantiat } @Test - void withNullFields_compareToFile() throws JacksonException, IllegalAccessException, InstantiationException { + void withNullFields_compareToFile() throws Exception { assumeTrue(EXPECT_NULLS_IN_JSON.equals(withAllNullFields), "To configure this test, use %s instead of %s".formatted(EXPECT_NULLS_IN_JSON, withAllNullFields)); validate(); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/util/ObjectUtilsTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/util/ObjectUtilsTest.java index b23391d3f59..ac2b5be1be61 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/util/ObjectUtilsTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/util/ObjectUtilsTest.java @@ -3,7 +3,6 @@ import org.junit.jupiter.api.Test; import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.ParserConfigurationException; import java.util.ArrayList; import java.util.List; @@ -25,7 +24,7 @@ void countNonNull() { } @Test - void getDocumentBuilder() throws ParserConfigurationException { + void getDocumentBuilder() throws Exception { DocumentBuilder builder = ObjectUtils.getDocumentBuilder(); assertThat(builder).isNotNull(); assertThat(builder.getDOMImplementation()).isNotNull(); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/util/UaaStringUtilsTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/util/UaaStringUtilsTest.java index cee191b7869..140a0ee12d9 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/util/UaaStringUtilsTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/util/UaaStringUtilsTest.java @@ -343,7 +343,7 @@ void getAuthoritiesFromStrings() { assertThat(authorities).isEqualTo(Collections.emptyList()); assertThat(UaaStringUtils.getStringsFromAuthorities(null)).isEmpty(); authorities = UaaStringUtils.getAuthoritiesFromStrings(Collections.singletonList("uaa.user")); - assertThat(UaaStringUtils.getStringsFromAuthorities(authorities)).isEqualTo(Set.of("uaa.user")); + assertThat(UaaStringUtils.getStringsFromAuthorities(authorities)).hasSameElementsAs(Set.of("uaa.user")); } @Test @@ -401,10 +401,9 @@ void getSafeParameterValue() { @Test void getArrayDefaultValue() { - assertThat(UaaStringUtils.getValuesOrDefaultValue(Set.of("1", "2"), "1").stream().sorted().toList()) - .isEqualTo(Stream.of("1", "2").sorted().toList()); - assertThat(UaaStringUtils.getValuesOrDefaultValue(Set.of(), "1")).isEqualTo(List.of("1")); - assertThat(UaaStringUtils.getValuesOrDefaultValue(null, "1")).isEqualTo(List.of("1")); + assertThat(UaaStringUtils.getValuesOrDefaultValue(Set.of("1", "2"), "1").stream().sorted().toList()).containsExactlyElementsOf(Stream.of("1", "2").sorted().toList()); + assertThat(UaaStringUtils.getValuesOrDefaultValue(Set.of(), "1")).containsExactlyElementsOf(List.of("1")); + assertThat(UaaStringUtils.getValuesOrDefaultValue(null, "1")).containsExactlyElementsOf(List.of("1")); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneTest.java index 45d0ad76d69..1e1e467272b 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneTest.java @@ -137,9 +137,9 @@ void deserialize() { assertThat(sampleIdentityZone).isNotNull() .returns("f7758816-ab47-48d9-9d24-25b10b92d4cc", IdentityZone::getId) .returns("demo", IdentityZone::getSubdomain); - assertThat(sampleIdentityZone.getConfig().getUserConfig().getDefaultGroups()).isEqualTo(List.of("openid", "password.write", "uaa.user", "approvals.me", + assertThat(sampleIdentityZone.getConfig().getUserConfig().getDefaultGroups()).containsExactlyElementsOf(List.of("openid", "password.write", "uaa.user", "approvals.me", "profile", "roles", "user_attributes", "uaa.offline_token")); - assertThat(sampleIdentityZone.getConfig().getUserConfig().resultingAllowedGroups()).isEqualTo(Set.of("openid", "password.write", "uaa.user", "approvals.me", + assertThat(sampleIdentityZone.getConfig().getUserConfig().resultingAllowedGroups()).hasSameElementsAs(Set.of("openid", "password.write", "uaa.user", "approvals.me", "profile", "roles", "user_attributes", "uaa.offline_token", "scim.me", "cloud_controller.user")); assertThat(sampleIdentityZone.getConfig().getUserConfig().getMaxUsers()).isEqualTo(1000); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentTest.java index 016c469196e..308514c3977 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentTest.java @@ -12,7 +12,7 @@ class LoginConsentTest { private final ObjectMapper objectMapper = new JsonMapper(); @Test - void testDefaultConstructor() { + void defaultConstructor() { LoginConsent consent = new LoginConsent(); assertThat(consent.isEnabled()).isFalse(); assertThat(consent.getTitle()).isNotNull(); @@ -24,7 +24,7 @@ void testDefaultConstructor() { } @Test - void testFullConstructor() { + void fullConstructor() { LoginConsent consent = new LoginConsent( true, "Test Title", @@ -45,7 +45,7 @@ void testFullConstructor() { } @Test - void testSettersAndGetters() { + void settersAndGetters() { LoginConsent consent = new LoginConsent(); consent.setEnabled(true); @@ -66,7 +66,7 @@ void testSettersAndGetters() { } @Test - void testJsonSerialization() throws Exception { + void jsonSerialization() throws Exception { LoginConsent consent = new LoginConsent( true, "Test Title", @@ -78,14 +78,14 @@ void testJsonSerialization() throws Exception { ); String json = objectMapper.writeValueAsString(consent); - assertThat(json).isNotNull() + assertThat(json) .contains("\"enabled\":true") .contains("\"title\":\"Test Title\"") .contains("\"text\":\"Test Text\""); } @Test - void testJsonDeserialization() throws Exception { + void jsonDeserialization() throws Exception { String json = """ { "enabled": true, @@ -110,14 +110,14 @@ void testJsonDeserialization() throws Exception { } @Test - void testJsonSerializationWithNulls() throws Exception { + void jsonSerializationWithNulls() throws Exception { LoginConsent consent = new LoginConsent(); consent.setEnabled(true); consent.setTitle("Title"); consent.setText("Text"); String json = objectMapper.writeValueAsString(consent); - assertThat(json).isNotNull() + assertThat(json) // Non-null fields should be included .contains("\"enabled\":true") .contains("\"title\":\"Title\"") @@ -126,7 +126,7 @@ void testJsonSerializationWithNulls() throws Exception { } @Test - void testEquals() { + void equals() { LoginConsent consent1 = new LoginConsent(true, "Title", "Text", "Accept", "Decline", "https://example.com", "12h"); LoginConsent consent2 = new LoginConsent(true, "Title", "Text", "Accept", "Decline", "https://example.com", "12h"); LoginConsent consent3 = new LoginConsent(true, "Different", "Text", "Accept", "Decline", "https://example.com", "12h"); @@ -150,7 +150,7 @@ void testToString() { LoginConsent consent = new LoginConsent(true, "Title", "Test Text", "Accept", "Decline", "https://example.com", "12h"); String toString = consent.toString(); - assertThat(toString).isNotNull() + assertThat(toString) .contains("enabled=true") .contains("title=Title") .contains("acceptButtonText=Accept"); diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/SamlConfigTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/SamlConfigTest.java index 211eabd2adf..c8b0f384d57 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/SamlConfigTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/SamlConfigTest.java @@ -123,7 +123,7 @@ void addActiveKey() { .returns(passphrase, SamlKey::getPassphrase) .returns(certificate, SamlKey::getCertificate); assertThat(config.getActiveKey()).isSameAs(keys.get(keyId)); - assertThat(config.getKeyList()).hasSize(1).containsExactly(key); + assertThat(config.getKeyList()).containsExactly(key); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java index 4d98e4a2043..cd00c99e037 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java @@ -7,9 +7,7 @@ import java.util.Collections; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; class TokenPolicyTest { @@ -24,12 +22,12 @@ void json_has_expected_properties() { String json = JsonUtils.writeValueAsString(tokenPolicy); Map properties = JsonUtils.readValue(json, Map.class); - assertThat(properties).isNotNull() + assertThat(properties) .containsEntry("accessTokenValidity", 1234) .containsEntry("refreshTokenValidity", 9876) .containsKey("keys"); Map keys = (Map) properties.get("keys"); - assertThat(keys).isNotNull() + assertThat(keys) .hasSize(1); assertThat(((Map) keys.get("aKeyId"))).containsEntry("signingKey", "KeyKeyKey"); } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigTest.java index cbd7f12991b..7cc588be017 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigTest.java @@ -22,9 +22,9 @@ void resultingAllowedGroups() { UserConfig userConfig = new UserConfig(); userConfig.setDefaultGroups(List.of("openid")); userConfig.setAllowedGroups(List.of("uaa.user")); - assertThat(userConfig.getDefaultGroups()).isEqualTo(List.of("openid")); - assertThat(userConfig.getAllowedGroups()).isEqualTo(List.of("uaa.user")); - assertThat(userConfig.resultingAllowedGroups()).isEqualTo(Set.of("openid", "uaa.user")); + assertThat(userConfig.getDefaultGroups()).containsExactlyElementsOf(List.of("openid")); + assertThat(userConfig.getAllowedGroups()).containsExactlyElementsOf(List.of("uaa.user")); + assertThat(userConfig.resultingAllowedGroups()).hasSameElementsAs(Set.of("openid", "uaa.user")); } @Test @@ -33,8 +33,8 @@ void noDefaultGroups() { userConfig.setDefaultGroups(null); userConfig.setAllowedGroups(List.of("uaa.user")); assertThat(userConfig.getDefaultGroups()).isNull(); - assertThat(userConfig.getAllowedGroups()).isEqualTo(List.of("uaa.user")); - assertThat(userConfig.resultingAllowedGroups()).isEqualTo(Set.of("uaa.user")); + assertThat(userConfig.getAllowedGroups()).containsExactlyElementsOf(List.of("uaa.user")); + assertThat(userConfig.resultingAllowedGroups()).hasSameElementsAs(Set.of("uaa.user")); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/UaaPropertiesTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/UaaPropertiesTest.java index aba6ccf09ff..8f93d2d8f5f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/UaaPropertiesTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/UaaPropertiesTest.java @@ -162,13 +162,13 @@ void whenClientSecretPolicyPropertiesAreNotSet() { assertThat(properties).isNotNull(); assertThat(properties.global()).isNotNull(); - assertThat(properties.global().minLength()).isEqualTo(0); + assertThat(properties.global().minLength()).isZero(); assertThat(properties.global().maxLength()).isEqualTo(255); - assertThat(properties.global().requireUpperCaseCharacter()).isEqualTo(0); - assertThat(properties.global().requireLowerCaseCharacter()).isEqualTo(0); - assertThat(properties.global().requireDigit()).isEqualTo(0); - assertThat(properties.global().requireSpecialCharacter()).isEqualTo(0); - assertThat(properties.global().expireSecretInMonths()).isEqualTo(0); + assertThat(properties.global().requireUpperCaseCharacter()).isZero(); + assertThat(properties.global().requireLowerCaseCharacter()).isZero(); + assertThat(properties.global().requireDigit()).isZero(); + assertThat(properties.global().requireSpecialCharacter()).isZero(); + assertThat(properties.global().expireSecretInMonths()).isZero(); assertThat(properties.minLength()).isEqualTo(properties.global().minLength()); assertThat(properties.maxLength()).isEqualTo(properties.global().maxLength()); @@ -195,7 +195,7 @@ void whenGlobalClientSecretPolicyPropertiesAreSet() { assertThat(properties).isNotNull(); assertThat(properties.global()).isNotNull(); - assertThat(properties.global().minLength()).isEqualTo(1); + assertThat(properties.global().minLength()).isOne(); assertThat(properties.global().maxLength()).isEqualTo(2); assertThat(properties.global().requireUpperCaseCharacter()).isEqualTo(3); assertThat(properties.global().requireLowerCaseCharacter()).isEqualTo(4); @@ -230,15 +230,15 @@ void whenDefaultClientSecretPolicyPropertiesAreSet() { assertThat(properties).isNotNull(); assertThat(properties.global()).isNotNull(); - assertThat(properties.global().minLength()).isEqualTo(0); + assertThat(properties.global().minLength()).isZero(); assertThat(properties.global().maxLength()).isEqualTo(255); - assertThat(properties.global().requireUpperCaseCharacter()).isEqualTo(0); - assertThat(properties.global().requireLowerCaseCharacter()).isEqualTo(0); - assertThat(properties.global().requireDigit()).isEqualTo(0); - assertThat(properties.global().requireSpecialCharacter()).isEqualTo(0); - assertThat(properties.global().expireSecretInMonths()).isEqualTo(0); + assertThat(properties.global().requireUpperCaseCharacter()).isZero(); + assertThat(properties.global().requireLowerCaseCharacter()).isZero(); + assertThat(properties.global().requireDigit()).isZero(); + assertThat(properties.global().requireSpecialCharacter()).isZero(); + assertThat(properties.global().expireSecretInMonths()).isZero(); - assertThat(properties.minLength()).isEqualTo(1); + assertThat(properties.minLength()).isOne(); assertThat(properties.maxLength()).isEqualTo(2); assertThat(properties.requireUpperCaseCharacter()).isEqualTo(3); assertThat(properties.requireLowerCaseCharacter()).isEqualTo(4); @@ -279,7 +279,7 @@ void whenDefaultAndGlobalClientSecretPolicyPropertiesAreSet() { assertThat(properties.global().requireSpecialCharacter()).isEqualTo(13); assertThat(properties.global().expireSecretInMonths()).isEqualTo(14); - assertThat(properties.minLength()).isEqualTo(1); + assertThat(properties.minLength()).isOne(); assertThat(properties.maxLength()).isEqualTo(2); assertThat(properties.requireUpperCaseCharacter()).isEqualTo(3); assertThat(properties.requireLowerCaseCharacter()).isEqualTo(4); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java index 5341b4612a9..94f7e25af94 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java @@ -42,7 +42,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.account.EmailChangeEmailService.CHANGE_EMAIL_REDIRECT_URL; import static org.cloudfoundry.identity.uaa.codestore.ExpiringCodeType.EMAIL; import static org.mockito.Mockito.any; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java index 631781fd922..c6973b217c2 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java @@ -25,8 +25,8 @@ import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.crypto.password.PasswordEncoder; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/account/ResetPasswordAuthenticationFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/account/ResetPasswordAuthenticationFilterTest.java index a664702877a..c3c52c2d227 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/account/ResetPasswordAuthenticationFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/account/ResetPasswordAuthenticationFilterTest.java @@ -14,9 +14,7 @@ package org.cloudfoundry.identity.uaa.account; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; import java.sql.Timestamp; import static org.assertj.core.api.Assertions.assertThat; @@ -168,7 +166,7 @@ void invalid_code_password_reset() throws Exception { } @Test - void different_uri_skip_filter() throws ServletException, IOException { + void different_uri_skip_filter() throws Exception { var request = MockMvcRequestBuilders.post("/wrong_url") .buildRequest(new MockServletContext()); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java index 6ecf7f04025..06139c6c7c3 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.alias; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.EntityWithAlias; import org.cloudfoundry.identity.uaa.scim.ScimUser; import org.junit.jupiter.api.BeforeEach; @@ -11,8 +12,7 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.UAA; public abstract class EntityAliasHandlerEnsureConsistencyTest { @@ -90,9 +90,9 @@ final void shouldThrow_WhenAliasZidSetButZoneDoesNotExist() { arrangeZoneDoesNotExist(customZoneId); - assertThatExceptionOfType(EntityAliasFailedException.class).isThrownBy(() -> - aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity) - ); + assertThatThrownBy(() -> + aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) + .asInstanceOf(InstanceOfAssertFactories.throwable(EntityAliasFailedException.class)); } @Test @@ -126,9 +126,9 @@ final void shouldThrow_WhenAliasZidSet() { final T originalEntity = shallowCloneEntity(existingEntity); originalEntity.setAliasZid(customZoneId); - assertThatIllegalStateException().isThrownBy(() -> - aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity) - ).withMessage("Trying to create a new alias while alias feature is disabled."); + assertThatThrownBy(() -> aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Trying to create a new alias while alias feature is disabled."); } } @@ -149,9 +149,8 @@ final void shouldThrow_WhenReferencedAliasEntityAndAliasZoneDoNotExist() { arrangeEntityDoesNotExist(aliasId, customZoneId); arrangeZoneDoesNotExist(customZoneId); - assertThatExceptionOfType(EntityAliasFailedException.class).isThrownBy(() -> - aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity) - ); + assertThatThrownBy(() -> aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) + .asInstanceOf(InstanceOfAssertFactories.throwable(EntityAliasFailedException.class)); } } @@ -168,9 +167,9 @@ final void shouldThrow_EvenIfNoAliasPropertyIsChanged() { final T originalEntity = shallowCloneEntity(existingEntity); changeNonAliasProperties(originalEntity); - assertThatIllegalStateException().isThrownBy(() -> - aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity) - ).withMessage("Performing update on entity with alias while alias feature is disabled."); + assertThatThrownBy(() -> aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Performing update on entity with alias while alias feature is disabled."); } @Test @@ -182,9 +181,9 @@ final void shouldThrow_AliasPropertiesSetToNull() { originalEntity.setAliasId(null); originalEntity.setAliasZid(null); - assertThatIllegalStateException().isThrownBy(() -> - aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity) - ).withMessage("Performing update on entity with alias while alias feature is disabled."); + assertThatThrownBy(() -> aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Performing update on entity with alias while alias feature is disabled."); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerValidationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerValidationTest.java index b503c2130b0..6ffd12bf70f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerValidationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerValidationTest.java @@ -12,8 +12,7 @@ import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatIllegalStateException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.alias.EntityAliasHandlerValidationTest.NoExistingAliasBase.ExistingEntityArgument.ENTITY_WITH_EMPTY_ALIAS_PROPS; public abstract class EntityAliasHandlerValidationTest { @@ -77,9 +76,9 @@ final void shouldThrowIllegalArgumentException_ZoneIdEmptyInReqBody(final Existi setZoneId(requestBody, null); final T existingEntity = resolveExistingEntityArgument(existingEntityArg); - assertThatIllegalArgumentException().isThrownBy(() -> - aliasHandler.aliasPropertiesAreValid(requestBody, existingEntity) - ).withMessage("The zone ID of the request body must not be empty."); + assertThatThrownBy(() -> aliasHandler.aliasPropertiesAreValid(requestBody, existingEntity)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The zone ID of the request body must not be empty."); } protected final T resolveExistingEntityArgument(@NonNull final ExistingEntityArgument existingEntityArgument) { @@ -169,9 +168,8 @@ final void shouldThrow_AliasIdEmptyInExisting() { final T requestBody = buildEntityWithAliasProps(IdentityZone.getUaaZoneId(), null, CUSTOM_ZONE_ID); changeNonAliasProperties(requestBody); - assertThatIllegalStateException().isThrownBy(() -> - aliasHandler.aliasPropertiesAreValid(requestBody, existingEntity) - ); + assertThatThrownBy(() -> + aliasHandler.aliasPropertiesAreValid(requestBody, existingEntity)).isInstanceOf(IllegalStateException.class); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java index eeea999e67f..6c258f1c872 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class ApprovalModifiedEventTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilterTests.java index ec2aa525d16..1ac73176691 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientBasicAuthenticationFilterTests.java @@ -16,9 +16,7 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.AuthenticationEntryPoint; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; -import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Base64; @@ -60,7 +58,7 @@ void setUp() { } @Test - void urlDecodesClientIdAndClientSecret() throws IOException, ServletException { + void urlDecodesClientIdAndClientSecret() throws Exception { String clientId = "app|whatever"; String clientSecret = "sec|ret"; MockFilterChain chain = mock(MockFilterChain.class); @@ -77,7 +75,7 @@ void urlDecodesClientIdAndClientSecret() throws IOException, ServletException { } @Test - void urlFailsGracefullyWhenEncodedBadly() throws IOException, ServletException { + void urlFailsGracefullyWhenEncodedBadly() throws Exception { String clientId = "app|whatever"; String clientSecret = "sec%ret"; MockFilterChain chain = mock(MockFilterChain.class); @@ -100,7 +98,7 @@ void setUp() { } @Test - void doesNotDecodeClientIdAndClientSecretByDefault() throws IOException, ServletException { + void doesNotDecodeClientIdAndClientSecretByDefault() throws Exception { String clientId = "app%whatever"; String clientSecret = "sec%ret"; MockFilterChain chain = mock(MockFilterChain.class); @@ -117,7 +115,7 @@ void doesNotDecodeClientIdAndClientSecretByDefault() throws IOException, Servlet } @Test - void decodeClientIdAndClientSecretWhenHeaderProvided() throws IOException, ServletException { + void decodeClientIdAndClientSecretWhenHeaderProvided() throws Exception { String clientId = "app%whatever"; String clientSecret = "sec%ret"; MockFilterChain chain = mock(MockFilterChain.class); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientParametersAuthenticationFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientParametersAuthenticationFilterTest.java index 785718bcf00..63664c89c79 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientParametersAuthenticationFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ClientParametersAuthenticationFilterTest.java @@ -11,9 +11,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.web.AuthenticationEntryPoint; -import jakarta.servlet.ServletException; -import java.io.IOException; - import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.CLIENT_AUTH_NONE; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeast; @@ -26,7 +23,7 @@ class ClientParametersAuthenticationFilterTest { @Test - void doesNotContinueWithFilterChain_IfAuthenticationException() throws IOException, ServletException { + void doesNotContinueWithFilterChain_IfAuthenticationException() throws Exception { ClientParametersAuthenticationFilter filter = new ClientParametersAuthenticationFilter(); AuthenticationEntryPoint authenticationEntryPoint = mock(AuthenticationEntryPoint.class); @@ -50,7 +47,7 @@ void doesNotContinueWithFilterChain_IfAuthenticationException() throws IOExcepti } @Test - void storeClientAuthenticationMethod() throws IOException, ServletException { + void storeClientAuthenticationMethod() throws Exception { ClientParametersAuthenticationFilter filter = new ClientParametersAuthenticationFilter(); AuthenticationEntryPoint authenticationEntryPoint = mock(AuthenticationEntryPoint.class); @@ -78,7 +75,7 @@ void storeClientAuthenticationMethod() throws IOException, ServletException { } @Test - void storeClientAuthenticationMethodNoDetails() throws IOException, ServletException { + void storeClientAuthenticationMethodNoDetails() throws Exception { ClientParametersAuthenticationFilter filter = new ClientParametersAuthenticationFilter(); AuthenticationEntryPoint authenticationEntryPoint = mock(AuthenticationEntryPoint.class); @@ -103,7 +100,7 @@ void storeClientAuthenticationMethodNoDetails() throws IOException, ServletExcep } @Test - void storeClientAuthenticationMethodNoMethod() throws IOException, ServletException { + void storeClientAuthenticationMethodNoMethod() throws Exception { ClientParametersAuthenticationFilter filter = new ClientParametersAuthenticationFilter(); AuthenticationEntryPoint authenticationEntryPoint = mock(AuthenticationEntryPoint.class); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/CurrentUserCookieRequestFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/CurrentUserCookieRequestFilterTest.java index 8a3a7f2ba8e..5348f698b96 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/CurrentUserCookieRequestFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/CurrentUserCookieRequestFilterTest.java @@ -11,9 +11,7 @@ import org.springframework.security.core.context.SecurityContextHolder; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; -import java.io.IOException; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +44,7 @@ void cleanup() { } @Test - void whenUserIsAuthenticated_addsCurrentUserCookie() throws ServletException, IOException, CurrentUserCookieFactory.CurrentUserCookieEncodingException { + void whenUserIsAuthenticated_addsCurrentUserCookie() throws Exception { UaaAuthentication authentication = new UaaAuthentication(new UaaPrincipal("user-guid", "marissa", "marissa@test.org", "uaa", "", ""), Collections.emptyList(), null); SecurityContextHolder.getContext().setAuthentication(authentication); @@ -68,7 +66,7 @@ void whenUserIsAuthenticated_addsCurrentUserCookie() throws ServletException, IO } @Test - void whenUserIsAuthenticated_addsCurrentUserCookieWithStrictSameSiteAttribute() throws ServletException, IOException, CurrentUserCookieFactory.CurrentUserCookieEncodingException { + void whenUserIsAuthenticated_addsCurrentUserCookieWithStrictSameSiteAttribute() throws Exception { UaaAuthentication authentication = new UaaAuthentication(new UaaPrincipal("user-guid", "marissa", "marissa@test.org", "uaa", "", ""), Collections.emptyList(), null); SecurityContextHolder.getContext().setAuthentication(authentication); when(currentUserCookieFactory.getCookie(Mockito.any(UaaPrincipal.class))).thenReturn(new Cookie("Current-User", "current-user-cookie-value")); @@ -80,7 +78,7 @@ void whenUserIsAuthenticated_addsCurrentUserCookieWithStrictSameSiteAttribute() } @Test - void whenUserIsNotAuthenticated_clearsCurrentUserCookie() throws IOException, ServletException { + void whenUserIsNotAuthenticated_clearsCurrentUserCookie() throws Exception { when(currentUserCookieFactory.getNullCookie()).thenReturn(new Cookie("Current-User", null)); filter.doFilterInternal(req, res, filterChain); @@ -90,7 +88,7 @@ void whenUserIsNotAuthenticated_clearsCurrentUserCookie() throws IOException, Se } @Test - void whenCurrentUserExceptionOccurs_respondWithInternalServerError() throws CurrentUserCookieFactory.CurrentUserCookieEncodingException, ServletException, IOException { + void whenCurrentUserExceptionOccurs_respondWithInternalServerError() throws Exception { UaaAuthentication authentication = new UaaAuthentication(new UaaPrincipal("user-guid", "marissa", "marissa@test.org", "uaa", "", ""), Collections.emptyList(), null); SecurityContextHolder.getContext().setAuthentication(authentication); when(currentUserCookieFactory.getCookie(Mockito.any(UaaPrincipal.class))).thenThrow(currentUserCookieFactory.new CurrentUserCookieEncodingException(null)); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaAuthenticationSerializationTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaAuthenticationSerializationTests.java index 3bfaa51359f..b095eb3507e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaAuthenticationSerializationTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaAuthenticationSerializationTests.java @@ -14,7 +14,6 @@ */ package org.cloudfoundry.identity.uaa.authentication; - import org.cloudfoundry.identity.uaa.util.JsonUtils; import org.junit.jupiter.api.Test; import org.springframework.security.core.GrantedAuthority; @@ -166,8 +165,8 @@ void deserialization_with_user_attributes() { UaaAuthentication authWithUserData = JsonUtils.readValue(dataWithUserAttributes, UaaAuthentication.class); assertThat(authWithUserData.getUserAttributes()).isNotNull(); - assertThat(authWithUserData.getUserAttributes().entrySet()).containsExactlyInAnyOrderElementsOf(userAttributes.entrySet()); - assertThat(userAttributes.entrySet()).containsExactlyInAnyOrderElementsOf(authWithUserData.getUserAttributes().entrySet()); + assertThat(authWithUserData.getUserAttributes().entrySet()).hasSameElementsAs(userAttributes.entrySet()); + assertThat(userAttributes.entrySet()).hasSameElementsAs(authWithUserData.getUserAttributes().entrySet()); assertThat(authentication.getExternalGroups()) .hasSize(3) diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java index 4176da5540d..e5ce8618315 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java @@ -31,9 +31,7 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification.SECRET; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ZoneAwareWhitelistLogoutSuccessHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ZoneAwareWhitelistLogoutSuccessHandlerTests.java index e5b4d15481c..57af1df7827 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ZoneAwareWhitelistLogoutSuccessHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/ZoneAwareWhitelistLogoutSuccessHandlerTests.java @@ -33,8 +33,6 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import jakarta.servlet.ServletException; -import java.io.IOException; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; @@ -179,7 +177,7 @@ void external_client_redirect() { "'',true,1", "'',false,0", ",true,0"}) - void external_logout(String url, boolean rpInitiated, int onSuccessCalls) throws ServletException, IOException { + void external_logout(String url, boolean rpInitiated, int onSuccessCalls) throws Exception { when(oAuthLogoutHandler.getLogoutUrl(null)).thenReturn(url); when(oAuthLogoutHandler.getPerformRpInitiatedLogout(null)).thenReturn(rpInitiated); handler.onLogoutSuccess(request, response, null); @@ -187,7 +185,7 @@ void external_logout(String url, boolean rpInitiated, int onSuccessCalls) throws } @Test - void logout() throws ServletException, IOException { + void logout() throws Exception { handler.onLogoutSuccess(request, response, null); verify(oAuthLogoutHandler, times(0)).onLogoutSuccess(request, response, null); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java index 270b2849f3b..d22b03c0158 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java @@ -46,7 +46,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -117,7 +117,7 @@ void successfulAuthentication() { assertThat(((UaaAuthentication) result).getAuthenticationMethods()).containsExactlyInAnyOrder("pwd"); List events = eventCaptor.getAllValues(); - assertThat(events.getFirst()).isInstanceOf(IdentityProviderAuthenticationSuccessEvent.class); + assertThat(events).first().isInstanceOf(IdentityProviderAuthenticationSuccessEvent.class); assertThat(((IdentityProviderAuthenticationSuccessEvent) events.getFirst()).getUser().getUsername()).isEqualTo("auser"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinRequestConverterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinRequestConverterTest.java index c0666c8d12a..c25b441ca9c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinRequestConverterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AutologinRequestConverterTest.java @@ -9,7 +9,6 @@ import org.springframework.http.MediaType; import java.io.ByteArrayInputStream; -import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.StandardCharsets; @@ -57,13 +56,13 @@ void isJsonContent() { } @Test - void readInternalNoJson() throws IOException { + void readInternalNoJson() throws Exception { AutologinRequest autologin = autologinRequestConverter.readInternal(autologinRequest.getClass(), inputMessage); assertThat(autologin).isNotNull(); } @Test - void readInternalFromJson() throws IOException { + void readInternalFromJson() throws Exception { InputStream inputStream = new ByteArrayInputStream("{ \"username\": \"user\",\"password\": \"pwd\" }".getBytes(StandardCharsets.UTF_8)); when(httpHeaders.get(HttpHeaders.CONTENT_TYPE)).thenReturn(jsonMediaType); when(inputMessage.getBody()).thenReturn(inputStream); @@ -74,7 +73,7 @@ void readInternalFromJson() throws IOException { } @Test - void readInternalFromJsonButNull() throws IOException { + void readInternalFromJsonButNull() throws Exception { when(httpHeaders.get(HttpHeaders.CONTENT_TYPE)).thenReturn(jsonMediaType); when(inputMessage.getBody()).thenReturn(null); AutologinRequest autologin = autologinRequestConverter.readInternal(autologinRequest.getClass(), inputMessage); @@ -84,7 +83,7 @@ void readInternalFromJsonButNull() throws IOException { } @Test - void writeInternal() throws IOException { + void writeInternal() throws Exception { OutputStream outputStream = mock(OutputStream.class); HttpOutputMessage outputMessage = mock(HttpOutputMessage.class); when(outputMessage.getHeaders()).thenReturn(httpHeaders); @@ -97,7 +96,7 @@ void writeInternal() throws IOException { } @Test - void writeInternalNoValuesInAutoLoginRequest() throws IOException { + void writeInternalNoValuesInAutoLoginRequest() throws Exception { OutputStream outputStream = mock(OutputStream.class); HttpOutputMessage outputMessage = mock(HttpOutputMessage.class); when(outputMessage.getHeaders()).thenReturn(httpHeaders); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java index 84df14b795b..e730bace8de 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ChainedAuthenticationManagerTest.java @@ -9,6 +9,7 @@ import org.springframework.security.core.AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -101,11 +102,8 @@ void uaaAuthFalseLdapFalse() { void uaaAuthThrowLdapAuthFalse() { managers[0].setAuthenticationManager(authenticateThrow); managers[1].setAuthenticationManager(authenticateFalse); - try { - authMgr.authenticate(failure); - fail("Should have thrown exception"); - } catch (BadCredentialsException _) { - } + assertThatThrownBy(() -> authMgr.authenticate(failure)) + .isInstanceOf(BadCredentialsException.class); verify(authenticateThrow, times(1)).authenticate(any(Authentication.class)); verify(authenticateFalse, times(1)).authenticate(any(Authentication.class)); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java index b9f5140eb8d..a7b5fd94810 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java @@ -20,7 +20,7 @@ import java.sql.SQLException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java index 8d758848790..682ea96f51a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java @@ -39,9 +39,7 @@ import java.util.LinkedList; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LdapLoginAuthenticationManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LdapLoginAuthenticationManagerTests.java index 8cf69a9ef9a..8a6f51a78ea 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LdapLoginAuthenticationManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LdapLoginAuthenticationManagerTests.java @@ -325,7 +325,6 @@ void test_authentication_attributes(boolean storeUserInfo) { assertThat(authentication.getUserAttributes()).as("Expected manager attribute").containsKey(MANAGERS); assertThat(authentication.getUserAttributes().get(MANAGERS)).as("Expected 2 manager attribute values") - .hasSize(2) .containsExactlyInAnyOrder(JOHN_THE_SLOTH, KARI_THE_ANT_EATER); assertThat(authentication.getAuthenticationMethods()).containsExactlyInAnyOrder("ext", "pwd"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java index 3c023c62bd0..4cc3c48219b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java @@ -32,9 +32,7 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.HamcrestCondition.matching; import static org.cloudfoundry.identity.uaa.user.UaaUserMatcher.aUaaUser; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java index 5ee66089c80..f3ca0d908b6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java @@ -36,7 +36,6 @@ import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; -import java.net.MalformedURLException; import java.net.URI; import java.util.Arrays; import java.util.Collections; @@ -44,9 +43,7 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_PASSWORD; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; @@ -199,11 +196,7 @@ void oidcPasswordGrantInvalidLogin() { when(rt.exchange(anyString(), any(HttpMethod.class), any(HttpEntity.class), any(ParameterizedTypeReference.class))).thenThrow(exception); when(externalOAuthAuthenticationManager.oauthTokenRequest(eq(null), eq(idp), eq(GRANT_TYPE_PASSWORD), any(MultiValueMap.class))).thenThrow(exception); - try { - instance.authenticate(auth); - fail("No Exception thrown."); - } catch (BadCredentialsException _) { - } + assertThatThrownBy(() -> instance.authenticate(auth)).isInstanceOf(BadCredentialsException.class); ArgumentCaptor eventArgumentCaptor = ArgumentCaptor.forClass(AbstractUaaEvent.class); verify(eventPublisher, times(1)).publishEvent(eventArgumentCaptor.capture()); @@ -295,7 +288,7 @@ void oidcPasswordGrantProviderDoesNotSupportPassword() { } @Test - void oidcPasswordGrantNoUserCredentials() throws MalformedURLException { + void oidcPasswordGrantNoUserCredentials() throws Exception { UaaLoginHint loginHint = mock(UaaLoginHint.class); when(loginHint.getOrigin()).thenReturn("oidcprovider"); Authentication auth = mock(Authentication.class); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java index c6ab9cc11c0..76987b28aa7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java @@ -21,7 +21,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java index e3b549a79bf..d990ffaf585 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/cache/StaleUrlCacheTests.java @@ -25,7 +25,6 @@ import org.springframework.web.client.RestTemplate; import java.net.URI; -import java.net.URISyntaxException; import java.time.Duration; import java.util.Arrays; import java.util.concurrent.TimeUnit; @@ -95,7 +94,7 @@ void setup() { } @Test - void correct_method_invoked_on_rest_template() throws URISyntaxException { + void correct_method_invoked_on_rest_template() throws Exception { cache.getUrlContent(URL, mockRestTemplate); verify(mockRestTemplate, times(1)).getForObject(eq(new URI(URL)), same(byte[].class)); } @@ -135,7 +134,7 @@ void entry_refreshes_after_time() { // This call is necessary to trigger the cache refresh operation after the timeout period. cache.getUrlContent(URL, mockRestTemplate); await().atMost(5, TimeUnit.SECONDS).untilAsserted( - () -> assertThat(listener.removalCount).isGreaterThan(0) + () -> assertThat(listener.removalCount).isPositive() ); byte[] c2 = cache.getUrlContent(URL, mockRestTemplate); assertThat(c2).isSameAs(content2); @@ -159,7 +158,7 @@ void cache_should_start_empty() { } @Test - void max_entries_is_respected() throws URISyntaxException { + void max_entries_is_respected() throws Exception { String uri1 = "https://test1.com"; String uri2 = "https://test2.com"; String uri3 = "https://test3.com"; @@ -207,7 +206,7 @@ void stale_entry_returned_on_failure() { } @Test - void extended_method_invoked_on_rest_template() throws URISyntaxException { + void extended_method_invoked_on_rest_template() throws Exception { when(mockRestTemplate.exchange(any(URI.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class))).thenReturn(responseEntity); when(responseEntity.getStatusCode()).thenReturn(HttpStatus.OK); when(responseEntity.getBody()).thenReturn(new byte[1]); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java index 77695a52a8f..e188b744264 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java @@ -35,9 +35,7 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_IMPLICIT; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_JWT_BEARER; @@ -444,7 +442,7 @@ void overrideClient() { ArgumentCaptor captor = ArgumentCaptor.forClass(ClientDetails.class); verify(multitenantJdbcClientDetailsService, times(1)).updateClientDetails(captor.capture(), anyString()); verify(multitenantJdbcClientDetailsService, times(1)).updateClientSecret(clientId, "bar", "uaa"); - assertThat(captor.getValue().getAuthorizedGrantTypes()).isEqualTo(new HashSet<>(Collections.singletonList("client_credentials"))); + assertThat(captor.getValue().getAuthorizedGrantTypes()).hasSameElementsAs(new HashSet<>(Collections.singletonList("client_credentials"))); } @Nested @@ -508,7 +506,7 @@ void overrideClientWithEmptySecret() { ArgumentCaptor captor = ArgumentCaptor.forClass(ClientDetails.class); verify(multitenantJdbcClientDetailsService, times(1)).updateClientDetails(captor.capture(), anyString()); verify(multitenantJdbcClientDetailsService, times(1)).updateClientSecret(clientId, "", "uaa"); - assertThat(captor.getValue().getAuthorizedGrantTypes()).isEqualTo(new HashSet<>(Collections.singletonList("client_credentials"))); + assertThat(captor.getValue().getAuthorizedGrantTypes()).hasSameElementsAs(new HashSet<>(Collections.singletonList("client_credentials"))); } @Test @@ -533,7 +531,7 @@ void doNotOverrideClientWithNullSecret() { ArgumentCaptor captor = ArgumentCaptor.forClass(ClientDetails.class); verify(multitenantJdbcClientDetailsService, times(1)).updateClientDetails(captor.capture(), anyString()); verify(multitenantJdbcClientDetailsService, times(1)).updateClientSecret(clientId, null, "uaa"); - assertThat(captor.getValue().getAuthorizedGrantTypes()).isEqualTo(new HashSet<>(Collections.singletonList("client_credentials"))); + assertThat(captor.getValue().getAuthorizedGrantTypes()).hasSameElementsAs(new HashSet<>(Collections.singletonList("client_credentials"))); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java index 8e34fe67951..f0ef13359fa 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java @@ -53,10 +53,7 @@ import java.util.Map; import java.util.Set; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.client.SecretChangeRequest.ChangeMode.ADD; import static org.cloudfoundry.identity.uaa.oauth.client.SecretChangeRequest.ChangeMode.DELETE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; @@ -316,7 +313,7 @@ void createClientDetailsWithSecondarySecretNotMeetingSecretPolicy() { @Test void get_restricted_scopes_list() { - assertThat(endpoints.getRestrictedClientScopes()).isEqualTo(new UaaScopes().getUaaScopes()); + assertThat(endpoints.getRestrictedClientScopes()).containsExactlyElementsOf(new UaaScopes().getUaaScopes()); } @Test @@ -550,7 +547,7 @@ void getClientDetails() { input.setAdditionalInformation(Collections.singletonMap("foo", "bar")); ClientDetails result = endpoints.getClientDetails(input.getClientId()); assertThat(result.getClientSecret()).isNull(); - assertThat(result.getAdditionalInformation()).isEqualTo(input.getAdditionalInformation()); + assertThat(result.getAdditionalInformation()).containsExactlyInAnyOrderEntriesOf(input.getAdditionalInformation()); } @Test @@ -1025,7 +1022,7 @@ void getClientWithFederatedJwt() { // When assertThat(result.getClientSecret()).isNull(); ClientDetailsModification modification = (ClientDetailsModification) result; - assertThat(modification.getClientJwtCredentials()).size().isEqualTo(1); + assertThat(modification.getClientJwtCredentials()).hasSize(1); assertThat(modification.getJwkSet()).isNull(); assertThat(modification.getJwksUri()).isEqualTo("http://localhost:8080/uaa/token_keys"); ClientJwtCredential clientJwtCredential = modification.getClientJwtCredentials().getFirst(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java index 17d64a446e2..82a56d2e5f8 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java @@ -35,11 +35,7 @@ import java.util.Map; import java.util.Set; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_IMPLICIT; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_JWT_BEARER; @@ -142,7 +138,7 @@ void token_exchange_cannot_contain_other_grant_types() { } @Test - public void validate_rejectsMalformedUrls() { + void validate_rejectsMalformedUrls() { client.setAuthorizedGrantTypes(Collections.singletonList(GRANT_TYPE_AUTHORIZATION_CODE)); client.setRegisteredRedirectUri(Collections.singleton("httasdfasp://anything.comadfsfdasfdsa")); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java index 2e2183b8d04..effbbaf1fc0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java @@ -10,9 +10,7 @@ import java.util.Collections; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -274,14 +272,14 @@ void testHashCode() { } @Test - void equals() throws CloneNotSupportedException { + void equals() throws Exception { ClientJwtConfiguration key1 = ClientJwtConfiguration.parse("http://localhost:8080/uaa"); ClientJwtConfiguration key2 = (ClientJwtConfiguration) key1.clone(); assertThat(key2).isEqualTo(key1); } @Test - void serializableObjectCalls() throws CloneNotSupportedException { + void serializableObjectCalls() throws Exception { ClientJwtConfiguration key1 = JsonUtils.readValue(defaultJsonUri, ClientJwtConfiguration.class); ClientJwtConfiguration key2 = (ClientJwtConfiguration) key1.clone(); assertThat(key2).isEqualTo(key1); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java index a72a1f51b8f..7b997d93238 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java @@ -16,9 +16,7 @@ import java.net.URL; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; @WithDatabaseContext diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java index 1993c27587a..42f834b0391 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java @@ -11,7 +11,7 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class UaaClientDetailsUserDetailsServiceTest { @SuppressWarnings("unchecked") diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java index 1cf2d91c00a..dd95014fd74 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientTest.java @@ -19,7 +19,7 @@ void getClientJwtConfiguration_includesTopLevelJwtCredsFromAdditionalInformation "[{\"iss\":\"http://localhost/uaa/oauth/token\",\"sub\":\"c1\",\"aud\":\"c1\"}]", List.class)); UaaClient c = new UaaClient("cid", "sec", List.of(new SimpleGrantedAuthority("uaa.none")), addl, null); ClientJwtConfiguration j = c.getClientJwtConfiguration(); - assertThat(j.getClientJwtCredentials()).isNotNull().hasSize(1); + assertThat(j.getClientJwtCredentials()).hasSize(1); assertThat(j.getClientJwtCredentials().getFirst().getIssuer()).isEqualTo("http://localhost/uaa/oauth/token"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java index 49f5c0bbf85..20b25f3f094 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java @@ -15,7 +15,7 @@ import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -41,7 +41,7 @@ void generateCode() { ExpiringCode expiringCode = expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId()); assertThat(expiringCode).isNotNull(); - assertThat(expiringCode.getCode()).isNotNull().isNotBlank(); + assertThat(expiringCode.getCode()).isNotBlank(); assertThat(expiringCode.getExpiresAt()).isEqualTo(expiresAt); assertThat(expiringCode.getData()).isEqualTo(data); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java index 8eeb1a4c1ae..0dc96d84976 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java @@ -13,7 +13,7 @@ import java.sql.SQLException; import java.sql.Timestamp; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java index d9b41c29726..7f0dd1eba17 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.config; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.constants.OriginKeys; @@ -43,9 +44,8 @@ import java.util.List; import java.util.Map; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.fail; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.KEYSTONE; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.OAUTH20; @@ -156,7 +156,7 @@ private static void validateGenericLdapProvider( assertThat(ldapProvider.getLastModified()).isNotNull(); assertThat(ldapProvider.getType()).isEqualTo(LDAP); assertThat(ldapProvider.getConfig().getEmailDomain()).contains("test.domain"); - assertThat(ldapProvider.getConfig().getExternalGroupsWhitelist()).isEqualTo(Collections.singletonList("value")); + assertThat(ldapProvider.getConfig().getExternalGroupsWhitelist()).containsExactlyElementsOf(Collections.singletonList("value")); assertThat(ldapProvider.getConfig().getAttributeMappings()).containsEntry("given_name", "first_name"); assertThat(ldapProvider.getConfig().getProviderDescription()).isEqualTo("Test LDAP Provider Description"); assertThat(ldapProvider.getConfig().isStoreCustomAttributes()).isFalse(); @@ -315,12 +315,7 @@ void oauthAndOidcProviderDeletion() throws Exception { bootstrap.setOriginsToDelete(new LinkedList<>(oauthProviderConfig.keySet())); bootstrap.afterPropertiesSet(); for (Map.Entry provider : oauthProviderConfig.entrySet()) { - try { - provisioning.retrieveByOriginIgnoreActiveFlag(provider.getKey(), IdentityZone.getUaaZoneId()); - fail("Provider '%s' should not exist.".formatted(provider.getKey())); - } catch (EmptyResultDataAccessException _) { - } - + assertThatThrownBy(() -> provisioning.retrieveByOriginIgnoreActiveFlag(provider.getKey(), IdentityZone.getUaaZoneId())).isInstanceOf(EmptyResultDataAccessException.class); } } @@ -405,7 +400,8 @@ void bootstrapFailsIfSamlAndOauthHaveTheSameAlias() throws Exception { setOauthIDPWrappers(); bootstrap.setSamlProviders(configurator); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> bootstrap.afterPropertiesSet()); + assertThatThrownBy(() -> bootstrap.afterPropertiesSet()) + .asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } private AbstractExternalOAuthIdentityProviderDefinition setCommonProperties(AbstractExternalOAuthIdentityProviderDefinition definition) throws MalformedURLException { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java index 7bda55d7c7a..f45b403ad4a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.config; +import org.assertj.core.api.InstanceOfAssertFactories; import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.impl.config.IdentityZoneConfigurationBootstrap; @@ -30,7 +31,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.TokenFormat.JWT; import static org.cloudfoundry.identity.uaa.provider.saml.TestCredentialObjects.certificate1; import static org.cloudfoundry.identity.uaa.provider.saml.TestCredentialObjects.key1; @@ -91,7 +92,7 @@ void clientSecretPolicy() throws Exception { } @Test - void multipleKeys() throws InvalidIdentityZoneDetailsException { + void multipleKeys() throws Exception { bootstrap.setSamlSpPrivateKey(key1()); bootstrap.setSamlSpCertificate(certificate1()); bootstrap.setSamlSpPrivateKeyPassphrase(passphrase1()); @@ -131,7 +132,8 @@ void keyIdNullException() { keys.put(null, key1); bootstrap.setActiveKeyId(null); bootstrap.setSamlKeys(keys); - assertThatExceptionOfType(InvalidIdentityZoneDetailsException.class).isThrownBy(() -> bootstrap.afterPropertiesSet()); + assertThatThrownBy(() -> bootstrap.afterPropertiesSet()) + .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidIdentityZoneDetailsException.class)); } @Test @@ -145,9 +147,9 @@ void passphraseOnlyException() { keys.put("key1", key1); bootstrap.setActiveKeyId(null); bootstrap.setSamlKeys(keys); - assertThatExceptionOfType(InvalidIdentityZoneDetailsException.class) - .isThrownBy(() -> bootstrap.afterPropertiesSet()) - .withMessage("The zone configuration is invalid. Identity zone cannot be updated with partial Saml CertKey config."); + assertThatThrownBy(() -> bootstrap.afterPropertiesSet()) + .isInstanceOf(InvalidIdentityZoneDetailsException.class) + .hasMessage("The zone configuration is invalid. Identity zone cannot be updated with partial Saml CertKey config."); } @Test @@ -277,7 +279,7 @@ void logoutRedirect() throws Exception { IdentityZoneConfiguration config = provisioning.retrieve(IdentityZone.getUaaZoneId()).getConfig(); assertThat(config.getLinks().getLogout().getRedirectUrl()).isEqualTo("/configured_login"); assertThat(config.getLinks().getLogout().getRedirectParameterName()).isEqualTo("test"); - assertThat(config.getLinks().getLogout().getWhitelist()).isEqualTo(Collections.singletonList("http://single-url")); + assertThat(config.getLinks().getLogout().getWhitelist()).containsExactlyElementsOf(Collections.singletonList("http://single-url")); assertThat(config.getLinks().getLogout().isDisableRedirectParameter()).isFalse(); } @@ -290,7 +292,7 @@ void prompts() throws Exception { bootstrap.setPrompts(prompts); bootstrap.afterPropertiesSet(); IdentityZoneConfiguration config = provisioning.retrieve(IdentityZone.getUaaZoneId()).getConfig(); - assertThat(config.getPrompts()).isEqualTo(prompts); + assertThat(config.getPrompts()).containsExactlyElementsOf(prompts); } @Test @@ -304,7 +306,7 @@ void idpDiscoveryEnabled() throws Exception { @Test void issuerConfiguration() throws Exception { String testIssuer = "http://test.example.com/uaa"; - + // Set up token policy with keys to satisfy validation TokenPolicy tokenPolicy = new TokenPolicy(3600, 7200); Map keys = new HashMap<>(); @@ -312,7 +314,7 @@ void issuerConfiguration() throws Exception { tokenPolicy.setKeys(keys); tokenPolicy.setActiveKeyId("testkey"); bootstrap.setTokenPolicy(tokenPolicy); - + bootstrap.setIssuer(testIssuer); bootstrap.afterPropertiesSet(); IdentityZoneConfiguration config = provisioning.retrieve(IdentityZone.getUaaZoneId()).getConfig(); @@ -339,7 +341,7 @@ void issuerConfiguration_emptyValue() throws Exception { void issuerConfiguration_defaultZoneWithTokenPolicy() throws Exception { // This test verifies that the default zone can have an issuer set with a proper token policy String testIssuer = "http://localhost:8080/uaa"; - + // Set up token policy with keys to satisfy validation TokenPolicy tokenPolicy = new TokenPolicy(3600, 7200); Map keys = new HashMap<>(); @@ -347,10 +349,10 @@ void issuerConfiguration_defaultZoneWithTokenPolicy() throws Exception { tokenPolicy.setKeys(keys); tokenPolicy.setActiveKeyId("defaultkey"); bootstrap.setTokenPolicy(tokenPolicy); - + bootstrap.setIssuer(testIssuer); bootstrap.afterPropertiesSet(); - + IdentityZone defaultZone = provisioning.retrieve(IdentityZone.getUaaZoneId()); assertThat(defaultZone.isUaa()).isTrue(); assertThat(defaultZone.getConfig().getIssuer()).isEqualTo(testIssuer); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationTests.java index 13710f028db..20359ccf78f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationTests.java @@ -209,12 +209,12 @@ void deserializeWithSamlConfig() { @Test void defaultCorsConfiguration() { - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedHeaders()).isEqualTo(Arrays.asList(new String[]{ACCEPT, AUTHORIZATION, CONTENT_TYPE})); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedMethods()).isEqualTo(Collections.singletonList(GET.toString())); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUris()).isEqualTo(Collections.singletonList(".*")); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUriPatterns()).isEqualTo(Collections.emptyList()); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOrigins()).isEqualTo(Collections.singletonList(".*")); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOriginPatterns()).isEqualTo(Collections.emptyList()); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedHeaders()).containsExactlyElementsOf(Arrays.asList(new String[]{ACCEPT, AUTHORIZATION, CONTENT_TYPE})); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedMethods()).containsExactlyElementsOf(Collections.singletonList(GET.toString())); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUris()).containsExactlyElementsOf(Collections.singletonList(".*")); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUriPatterns()).containsExactlyElementsOf(Collections.emptyList()); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOrigins()).containsExactlyElementsOf(Collections.singletonList(".*")); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOriginPatterns()).containsExactlyElementsOf(Collections.emptyList()); assertThat(definition.getCorsPolicy().getDefaultConfiguration().getMaxAge()).isEqualTo(1728000); } @@ -227,12 +227,12 @@ void deserializeDefaultCorsConfiguration() { s = s.replace("\"allowedUris\":[\".*\"]", "\"allowedUris\":[\"^/uaa/userinfo$\",\"^/uaa/logout\\\\.do$\"]"); definition = JsonUtils.readValue(s, IdentityZoneConfiguration.class); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedHeaders()).isEqualTo(Arrays.asList(new String[]{ACCEPT})); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedMethods()).isEqualTo(Arrays.asList(new String[]{GET.toString(), POST.toString()})); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUris()).isEqualTo(Arrays.asList(new String[]{"^/uaa/userinfo$", "^/uaa/logout\\.do$"})); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUriPatterns()).isEqualTo(Collections.emptyList()); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOrigins()).isEqualTo(Arrays.asList(new String[]{"^localhost$", "^.*\\.localhost$"})); - assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOriginPatterns()).isEqualTo(Collections.emptyList()); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedHeaders()).containsExactlyElementsOf(Arrays.asList(new String[]{ACCEPT})); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedMethods()).containsExactlyElementsOf(Arrays.asList(new String[]{GET.toString(), POST.toString()})); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUris()).containsExactlyElementsOf(Arrays.asList(new String[]{"^/uaa/userinfo$", "^/uaa/logout\\.do$"})); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedUriPatterns()).containsExactlyElementsOf(Collections.emptyList()); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOrigins()).containsExactlyElementsOf(Arrays.asList(new String[]{"^localhost$", "^.*\\.localhost$"})); + assertThat(definition.getCorsPolicy().getDefaultConfiguration().getAllowedOriginPatterns()).containsExactlyElementsOf(Collections.emptyList()); assertThat(definition.getCorsPolicy().getDefaultConfiguration().getMaxAge()).isEqualTo(1728000); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/db/DatabaseParametersTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/db/DatabaseParametersTests.java index 41c68c83007..182e0b6694b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/db/DatabaseParametersTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/db/DatabaseParametersTests.java @@ -41,7 +41,7 @@ void validation_query_timeout() { } @Test - void testWhileIdle() { + void whileIdle() { assertThat(dataSource.isTestWhileIdle()).isTrue(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/db/GroupMembershipAuthoritiesNullableTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/db/GroupMembershipAuthoritiesNullableTest.java index 859487200fa..ceeafe99b33 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/db/GroupMembershipAuthoritiesNullableTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/db/GroupMembershipAuthoritiesNullableTest.java @@ -8,7 +8,6 @@ import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; -import java.sql.SQLException; import static org.assertj.core.api.Assertions.assertThat; @@ -16,7 +15,7 @@ class GroupMembershipAuthoritiesNullableTest { @Test - void authoritiesNullable(@Autowired DataSource dataSource) throws SQLException { + void authoritiesNullable(@Autowired DataSource dataSource) throws Exception { try (Connection connection = dataSource.getConnection()) { DatabaseMetaData meta = connection.getMetaData(); ResultSet rs; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java index 7e3021439f8..201624a8012 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/db/TableAndColumnNormalizationTest.java @@ -67,7 +67,7 @@ class TableAndColumnNormalizationTest { @Test @EnabledIfProfile({"postgresql", "mysql"}) - void tableNamesAreLowercase() throws SQLException { + void tableNamesAreLowercase() throws Exception { try (Connection connection = dataSource.getConnection()) { DatabaseMetaData metaData = connection.getMetaData(); ResultSet rs = metaData.getTables(null, null, null, new String[]{"TABLE"}); @@ -101,7 +101,7 @@ void tableNamesAreLowercase() throws SQLException { */ @Test @EnabledIfProfile({"postgresql"}) - void columnNamesAreLowercase() throws SQLException { + void columnNamesAreLowercase() throws Exception { try (Connection connection = dataSource.getConnection()) { DatabaseMetaData metaData = connection.getMetaData(); ResultSet rs = metaData.getColumns(null, null, null, null); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/error/UaaExceptionTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/error/UaaExceptionTests.java index 001b9f2cb19..586a2bc256f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/error/UaaExceptionTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/error/UaaExceptionTests.java @@ -66,7 +66,7 @@ void valueOf() { .containsEntry("additional2", "additional2") .containsEntry("additional3", "additional3"); - assertThat(x.getSummary()).isNotNull() + assertThat(x.getSummary()) .contains("error=\"error\"") .contains("additional3=\"additional3\""); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java b/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java index 7085583eba4..4b83610a492 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/extensions/PollutionPreventionExtension.java @@ -25,6 +25,7 @@ private ApplicationContext getApplicationContextOrNull(ExtensionContext extensio try { return SpringExtension.getApplicationContext(extensionContext); } catch (IllegalStateException _) { + // ignore } return null; } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/health/HealthzEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/health/HealthzEndpointTests.java index 1f973baf133..3afe3377c5d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/health/HealthzEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/health/HealthzEndpointTests.java @@ -40,20 +40,20 @@ void setUp() throws SQLException { } @Test - void getHealthz() throws SQLException { + void getHealthz() throws Exception { when(dataSource.getConnection()).thenThrow(new SQLException("DB is Down")); assertThat(endpoint.getHealthz(response)).isEqualTo("UAA running. Database failed to start.\n"); } @Test - void getHealthz_connectionSuccess() throws SQLException { + void getHealthz_connectionSuccess() throws Exception { endpoint.isDataSourceConnectionAvailable(); assertThat(endpoint.getHealthz(response)).isEqualTo("ok\n"); verify(dataSource).getConnection(); } @Test - void getHealthz_connectionFailed() throws SQLException { + void getHealthz_connectionFailed() throws Exception { when(dataSource.getConnection()).thenThrow(new SQLException()); endpoint.isDataSourceConnectionAvailable(); assertThat(endpoint.getHealthz(response)).isEqualTo("Database Connection failed.\n"); @@ -61,7 +61,7 @@ void getHealthz_connectionFailed() throws SQLException { } @Test - void shutdownSendsStopping() throws InterruptedException { + void shutdownSendsStopping() throws Exception { long now = System.currentTimeMillis(); shutdownHook.start(); shutdownHook.join(); @@ -86,7 +86,7 @@ void setUp() { } @Test - void shutdownWithoutSleep() throws InterruptedException { + void shutdownWithoutSleep() throws Exception { long now = System.currentTimeMillis(); shutdownHook.start(); shutdownHook.join(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfigurationTokenKeyTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfigurationTokenKeyTest.java index 0927a3e7b83..fdf979a51fd 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfigurationTokenKeyTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/impl/config/UaaConfigurationTokenKeyTest.java @@ -37,7 +37,6 @@ void tokenKeyStructure() { assertThat(keys).isNotNull(); Map keyId1 = (Map) keys.get("key-id-1"); assertThat(keyId1) - .isNotNull() .containsEntry("signingCert", "cert") .containsEntry("signingKey", "key") .containsEntry("signingAlg", "PS256"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/AccountSavingAuthenticationSuccessHandlerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/AccountSavingAuthenticationSuccessHandlerTest.java index 1ef6b354063..2730418581c 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/AccountSavingAuthenticationSuccessHandlerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/AccountSavingAuthenticationSuccessHandlerTest.java @@ -15,9 +15,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler; -import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; -import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Collections; @@ -68,7 +66,7 @@ void invalid_principal_throws(boolean secure) { @MethodSource("parameters") @SuppressWarnings("deprecation") @ParameterizedTest - void whenSuccessfullyAuthenticated_accountGetsSavedViaCookie(boolean secure) throws IOException, ServletException, CurrentUserCookieFactory.CurrentUserCookieEncodingException { + void whenSuccessfullyAuthenticated_accountGetsSavedViaCookie(boolean secure) throws Exception { IdentityZoneHolder.get().getConfig().setAccountChooserEnabled(true); Date yesterday = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)); UaaUser user = new UaaUser( @@ -127,12 +125,12 @@ void whenSuccessfullyAuthenticated_accountGetsSavedViaCookie(boolean secure) thr Optional actualCurrentUserCookieHeaderValue = response.getHeaders("Set-Cookie").stream() .filter(headerValue -> headerValue.startsWith("Current-User")) .findAny(); - assertThat(actualCurrentUserCookieHeaderValue).contains("Current-User=%7B%22userId%22%3A%22user-id%22%7D; SameSite=Strict"); + assertThat(actualCurrentUserCookieHeaderValue).hasValue("Current-User=%7B%22userId%22%3A%22user-id%22%7D; SameSite=Strict"); } @MethodSource("parameters") @ParameterizedTest - void empty_Account_Cookie(boolean secure) throws IOException, ServletException { + void empty_Account_Cookie(boolean secure) throws Exception { IdentityZoneHolder.get().getConfig().setAccountChooserEnabled(false); Date yesterday = new Date(System.currentTimeMillis() - (1000 * 60 * 60 * 24)); UaaUser user = new UaaUser( diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java index 415e3154e3c..21f5ea204c6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java @@ -31,7 +31,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/ChangePasswordControllerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/ChangePasswordControllerTest.java index cc1686599dd..d8caddcb753 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/ChangePasswordControllerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/ChangePasswordControllerTest.java @@ -90,7 +90,7 @@ void changePassword_Returns302Found_SuccessfullyChangedPassword() throws Excepti verify(changePasswordService).changePassword("bob", "secret", "new secret"); Authentication afterAuth = SecurityContextHolder.getContext().getAuthentication(); - assertThat(((UaaAuthentication) afterAuth).getAuthenticationMethods()).containsExactlyInAnyOrderElementsOf(authMethods); + assertThat(((UaaAuthentication) afterAuth).getAuthenticationMethods()).hasSameElementsAs(authMethods); assertThat(afterAuth).isSameAs(authentication); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java index a2c5725c49b..007024462d9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java @@ -45,9 +45,7 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.codestore.ExpiringCodeType.REGISTRATION; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.anyInt; @@ -420,8 +418,9 @@ private void beginActivationWithCompanyNameConfigured(String companyName) { String emailBody = captorEmailBody("Activate your " + companyName + " account"); - assertThat(emailBody).contains(companyName + " account"); - assertThat(emailBody).contains("Activate your account"); + assertThat(emailBody) + .contains(companyName + " account") + .contains("Activate your account"); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailServiceTests.java index f93329ff4ef..2306fefc238 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailServiceTests.java @@ -59,7 +59,7 @@ void sendOssMimeMessage() throws Exception { assertThat(fromAddress.getAddress()).isEqualTo("admin@login.example.com"); assertThat(fromAddress.getPersonal()).isEqualTo("Cloud Foundry"); assertThat(mimeMessageWrapper.getRecipients(Message.RecipientType.TO)).hasSize(1); - assertThat(mimeMessageWrapper.getRecipients(Message.RecipientType.TO).getFirst()).isEqualTo(new InternetAddress("user@example.com")); + assertThat(mimeMessageWrapper.getRecipients(Message.RecipientType.TO)).first().isEqualTo(new InternetAddress("user@example.com")); assertThat(mimeMessageWrapper.getContentString()).isEqualTo("hi"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtilTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtilTest.java index 3d10e847d43..18a173673c3 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtilTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginConsentHashUtilTest.java @@ -8,7 +8,7 @@ class LoginConsentHashUtilTest { @Test - void testCalculateConsentHash() { + void calculateConsentHash() { LoginConsent consent = new LoginConsent(true, "Title", "Text", "Accept", "Decline", null, "12h"); String hash = LoginConsentHashUtil.calculateConsentHash(consent); @@ -16,7 +16,7 @@ void testCalculateConsentHash() { } @Test - void testCalculateConsentHashConsistency() { + void calculateConsentHashConsistency() { LoginConsent consent1 = new LoginConsent(true, "Title", "Text", "Accept", "Decline", null, "12h"); LoginConsent consent2 = new LoginConsent(true, "Title", "Text", "Accept", "Decline", null, "24h"); @@ -28,7 +28,7 @@ void testCalculateConsentHashConsistency() { } @Test - void testCalculateConsentHashChangesWithTitle() { + void calculateConsentHashChangesWithTitle() { LoginConsent consent1 = new LoginConsent(true, "Title1", "Text", "Accept", "Decline", null, "12h"); LoginConsent consent2 = new LoginConsent(true, "Title2", "Text", "Accept", "Decline", null, "12h"); @@ -40,7 +40,7 @@ void testCalculateConsentHashChangesWithTitle() { } @Test - void testCalculateConsentHashChangesWithText() { + void calculateConsentHashChangesWithText() { LoginConsent consent1 = new LoginConsent(true, "Title", "Text1", "Accept", "Decline", null, "12h"); LoginConsent consent2 = new LoginConsent(true, "Title", "Text2", "Accept", "Decline", null, "12h"); @@ -52,20 +52,20 @@ void testCalculateConsentHashChangesWithText() { } @Test - void testCalculateConsentHashWithNullConsent() { + void calculateConsentHashWithNullConsent() { String hash = LoginConsentHashUtil.calculateConsentHash(null); assertThat(hash).isNull(); } @Test - void testCalculateConsentHashWithDisabledConsent() { + void calculateConsentHashWithDisabledConsent() { LoginConsent consent = new LoginConsent(false, "Title", "Text", "Accept", "Decline", null, "12h"); String hash = LoginConsentHashUtil.calculateConsentHash(consent); assertThat(hash).isNull(); } @Test - void testCalculateConsentHashWithEmptyFields() { + void calculateConsentHashWithEmptyFields() { LoginConsent consent = new LoginConsent(true, "", "", "Accept", "Decline", null, "12h"); String hash = LoginConsentHashUtil.calculateConsentHash(consent); @@ -74,57 +74,57 @@ void testCalculateConsentHashWithEmptyFields() { } @Test - void testParseDurationToSeconds_Minutes() { + void parseDurationToSecondsMinutes() { assertThat(LoginConsentHashUtil.parseDurationToSeconds("1m")).isEqualTo(60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("3m")).isEqualTo(3 * 60); } @Test - void testParseDurationToSeconds_Hours() { + void parseDurationToSecondsHours() { assertThat(LoginConsentHashUtil.parseDurationToSeconds("12h")).isEqualTo(12 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("1h")).isEqualTo(60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("24h")).isEqualTo(24 * 60 * 60); } @Test - void testParseDurationToSeconds_Days() { + void parseDurationToSecondsDays() { assertThat(LoginConsentHashUtil.parseDurationToSeconds("7d")).isEqualTo(7 * 24 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("1d")).isEqualTo(24 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("30d")).isEqualTo(30 * 24 * 60 * 60); } @Test - void testParseDurationToSeconds_Weeks() { + void parseDurationToSecondsWeeks() { assertThat(LoginConsentHashUtil.parseDurationToSeconds("1w")).isEqualTo(7 * 24 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("2w")).isEqualTo(2 * 7 * 24 * 60 * 60); } @Test - void testParseDurationToSeconds_Years() { + void parseDurationToSecondsYears() { assertThat(LoginConsentHashUtil.parseDurationToSeconds("1y")).isEqualTo(365 * 24 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("2y")).isEqualTo(2 * 365 * 24 * 60 * 60); } @Test - void testParseDurationToSeconds_Zero() { + void parseDurationToSecondsZero() { assertThat(LoginConsentHashUtil.parseDurationToSeconds("0")).isZero(); } @Test - void testParseDurationToSeconds_Null() { + void parseDurationToSecondsNull() { // Should return default: 24 hours assertThat(LoginConsentHashUtil.parseDurationToSeconds(null)).isEqualTo(24 * 60 * 60); } @Test - void testParseDurationToSeconds_Empty() { + void parseDurationToSecondsEmpty() { // Should return default: 24 hours assertThat(LoginConsentHashUtil.parseDurationToSeconds("")).isEqualTo(24 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds(" ")).isEqualTo(24 * 60 * 60); } @Test - void testParseDurationToSeconds_Invalid() { + void parseDurationToSecondsInvalid() { // Invalid formats should return default: 24 hours assertThat(LoginConsentHashUtil.parseDurationToSeconds("invalid")).isEqualTo(24 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("12x")).isEqualTo(24 * 60 * 60); @@ -133,7 +133,7 @@ void testParseDurationToSeconds_Invalid() { } @Test - void testParseDurationToSeconds_CaseInsensitive() { + void parseDurationToSecondsCaseInsensitive() { assertThat(LoginConsentHashUtil.parseDurationToSeconds("1M")).isEqualTo(60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("12H")).isEqualTo(12 * 60 * 60); assertThat(LoginConsentHashUtil.parseDurationToSeconds("7D")).isEqualTo(7 * 24 * 60 * 60); @@ -142,7 +142,7 @@ void testParseDurationToSeconds_CaseInsensitive() { } @Test - void testHashCollision() { + void hashCollision() { // Case 1: title contains pipe, short text LoginConsent consent1 = new LoginConsent(true, "abc|def", "ghi", "Accept", "Decline", null, "12h"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java index 1b3034eb419..487ac48af06 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java @@ -1,5 +1,5 @@ package org.cloudfoundry.identity.uaa.login; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.codestore.InMemoryExpiringCodeStore; @@ -71,7 +71,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.util.UaaUrlUtils.addSubdomainToUrl; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; @@ -386,7 +386,7 @@ void discoverIdentityProvider_carriesAllParametersOnRedirect() { } @Test - void discoverIdentityProvider_propagatesUsernameToExternalOidcProvider() throws MalformedURLException { + void discoverIdentityProvider_propagatesUsernameToExternalOidcProvider() throws Exception { LoginInfoEndpoint endpoint = getEndpoint(IdentityZoneHolder.get()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("username", "testuser@fake.com"); @@ -532,7 +532,7 @@ void saml_links_for_html() throws Exception { LoginInfoEndpoint endpoint = getEndpoint(IdentityZoneHolder.get()); endpoint.loginForHtml(extendedModelMap, null, new MockHttpServletRequest("GET", "http://someurl"), null); Map links = (Map) extendedModelMap.asMap().get("links"); - assertThat(links).isNotNull() + assertThat(links) .containsEntry("login", "http://someurl"); assertThat(extendedModelMap.get("idpDefinitions")).isInstanceOf(Collection.class); } @@ -947,7 +947,8 @@ void externalOAuthCallback_redirectsToSavedRequestIfPresent() { @Test void loginWithInvalidMediaType() { LoginInfoEndpoint endpoint = getEndpoint(IdentityZoneHolder.get()); - assertThatExceptionOfType(HttpMediaTypeNotAcceptableException.class).isThrownBy(() -> endpoint.loginForHtml(extendedModelMap, null, new MockHttpServletRequest(), singletonList(MediaType.TEXT_XML))); + assertThatThrownBy(() -> endpoint.loginForHtml(extendedModelMap, null, new MockHttpServletRequest(), singletonList(MediaType.TEXT_XML))) + .asInstanceOf(InstanceOfAssertFactories.throwable(HttpMediaTypeNotAcceptableException.class)); } @Test @@ -1817,7 +1818,7 @@ private IdentityProvider mockOa } @Test - void testLoginConsentAddedToModelWhenEnabled() throws Exception { + void loginConsentAddedToModelWhenEnabled() throws Exception { // Set up login consent configuration BrandingInformation branding = new BrandingInformation(); LoginConsent loginConsent = new LoginConsent(); @@ -1850,7 +1851,7 @@ void testLoginConsentAddedToModelWhenEnabled() throws Exception { } @Test - void testLoginConsentNotAddedWhenDisabled() throws Exception { + void loginConsentNotAddedWhenDisabled() throws Exception { // Set up login consent configuration (disabled) BrandingInformation branding = new BrandingInformation(); LoginConsent loginConsent = new LoginConsent(); @@ -1874,7 +1875,7 @@ void testLoginConsentNotAddedWhenDisabled() throws Exception { } @Test - void testLoginConsentNotAddedWhenNull() throws Exception { + void loginConsentNotAddedWhenNull() throws Exception { // No branding configuration IdentityZoneConfiguration config = IdentityZoneHolder.get().getConfig(); config.setBranding(null); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerTest.java index a4a0cf3472f..646adf76e80 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerTest.java @@ -181,9 +181,10 @@ private void forgotPasswordWithConflict(String zoneDomain, String companyName) t ); String emailContent = captor.getValue(); - assertThat(emailContent).contains("A request has been made to reset your %s account password for %s".formatted(companyName, "user@example.com")); - assertThat(emailContent).contains("Your account credentials for " + domain + " are managed by an external service. Please contact your administrator for password recovery requests."); - assertThat(emailContent).containsIgnoringWhitespaces("Thank you,
" + companyName); + assertThat(emailContent) + .contains("A request has been made to reset your %s account password for %s".formatted(companyName, "user@example.com")) + .contains("Your account credentials for " + domain + " are managed by an external service. Please contact your administrator for password recovery requests.") + .containsIgnoringWhitespaces("Thank you,
" + companyName); } finally { IdentityZoneHolder.get().setConfig(defaultConfig); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerTests.java index 0d67a1bd58c..def1d41afcc 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerTests.java @@ -15,9 +15,7 @@ package org.cloudfoundry.identity.uaa.login; -import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; -import java.io.IOException; import java.util.HashMap; import java.util.Map; @@ -87,7 +85,7 @@ void logout() { } @Test - void onAuthenticationFailure_ForcePasswordChange() throws IOException, ServletException { + void onAuthenticationFailure_ForcePasswordChange() throws Exception { UaaAuthentication uaaAuthentication = mock(UaaAuthentication.class); PasswordChangeRequiredException exception = new PasswordChangeRequiredException(uaaAuthentication, "mock"); uaaAuthenticationFailureHandler.onAuthenticationFailure(request, response, exception); @@ -100,7 +98,7 @@ void onAuthenticationFailure_ForcePasswordChange() throws IOException, ServletEx } @Test - void redirectUrls() throws ServletException, IOException { + void redirectUrls() throws Exception { var handler = new UaaAuthenticationFailureHandler(cookieFactory); var response = new MockHttpServletResponse(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerZonePathTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerZonePathTests.java index 5965c107688..f4e13813077 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerZonePathTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaAuthenticationFailureHandlerZonePathTests.java @@ -15,9 +15,7 @@ package org.cloudfoundry.identity.uaa.login; -import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; -import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.cloudfoundry.identity.uaa.extensions.EnabledIfZonePathsEnabled; @@ -98,7 +96,7 @@ void logout(ZoneRequestPathMode mode) { @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void onAuthenticationFailure_ForcePasswordChange(ZoneRequestPathMode mode) throws IOException, ServletException { + void onAuthenticationFailure_ForcePasswordChange(ZoneRequestPathMode mode) throws Exception { mode.applyRequestPath(request, "/login.do"); UaaAuthentication uaaAuthentication = mock(UaaAuthentication.class); PasswordChangeRequiredException exception = new PasswordChangeRequiredException(uaaAuthentication, "mock"); @@ -113,7 +111,7 @@ void onAuthenticationFailure_ForcePasswordChange(ZoneRequestPathMode mode) throw @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void redirectUrls(ZoneRequestPathMode mode) throws ServletException, IOException { + void redirectUrls(ZoneRequestPathMode mode) throws Exception { var handler = new UaaAuthenticationFailureHandler(cookieFactory); String redirectPrefix = mode.redirectPrefix(); @@ -147,7 +145,7 @@ void redirectUrls(ZoneRequestPathMode mode) throws ServletException, IOException @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void redirectUrlsWithContextPath(ZoneRequestPathMode mode) throws ServletException, IOException { + void redirectUrlsWithContextPath(ZoneRequestPathMode mode) throws Exception { var handler = new UaaAuthenticationFailureHandler(cookieFactory); request.setContextPath("/uaa"); String redirectPrefix = "/uaa" + mode.redirectPrefix(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java index 6734d1cc634..9d5b1091d4f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java @@ -31,8 +31,8 @@ import java.util.List; import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java index 85589336ac3..8706ca043e1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java @@ -34,10 +34,7 @@ import java.util.Collections; import java.util.Date; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.doThrow; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java index adbe5da7c1a..b7b8adae10c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java @@ -73,10 +73,7 @@ import java.util.Set; import java.util.stream.Stream; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.TokenFormat.OPAQUE; import static org.junit.jupiter.params.provider.Arguments.arguments; import static org.mockito.AdditionalMatchers.not; @@ -677,7 +674,7 @@ void extAttrInResult(String signerKey, boolean useOpaque) throws Exception { tokenServices.setUaaTokenEnhancer(new TestTokenEnhancer()); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); Claims result = endpoint.checkToken(accessToken.getValue(), List.of(), request); - assertThat(result.getExtAttr()).as("external attributes not present").isNotNull() + assertThat(result.getExtAttr()).as("external attributes not present") .containsEntry("purpose", "test"); } @@ -1102,7 +1099,7 @@ void validAuthorities(String signerKey, boolean useOpaque) throws Exception { UaaAuthenticationTestFactory.getAuthentication(userId, userName, "olds@vmware.com")); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); Claims result = endpoint.checkToken(accessToken.getValue(), List.of(), request); - assertThat(azAttributes).isEqualTo(result.getAzAttr()); + assertThat(azAttributes).containsExactlyInAnyOrderEntriesOf(result.getAzAttr()); } @MethodSource("data") diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java index 00b7987b42a..27b59e01c79 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java @@ -20,7 +20,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java index ba6370e8f1d..b52ccde9ce4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java @@ -20,7 +20,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java index a382a7162ab..968279ebb7a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java @@ -82,10 +82,7 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.assertj.core.api.HamcrestCondition.matching; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.CLIENT_AUTHORITIES; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.CLIENT_ID; @@ -216,7 +213,7 @@ void opaque_tokens_are_persisted(TestTokenEnhancer enhancer) { verify(tokenProvisioning, times(1)).upsert(anyString(), rt.capture(), anyString()); verify(tokenProvisioning, times(1)).createIfNotExists(rt.capture(), anyString()); assertThat(rt.getAllValues()).hasSize(2); - assertThat(rt.getAllValues().getFirst()).isNotNull(); + assertThat(rt.getAllValues()).first().isNotNull(); assertThat(rt.getAllValues().getFirst().getResponseType()).isEqualTo(RevocableToken.TokenType.ACCESS_TOKEN); assertThat(rt.getAllValues().getFirst().getFormat()).isEqualTo(OPAQUE.getStringValue()); assertThat(result.getValue()).isEqualTo("id"); @@ -352,9 +349,9 @@ void refreshAccessToken_buildsIdToken_withRolesAndAttributesAndACR(TestTokenEnha verify(idTokenCreator).create(eq(clientDetails), any(), userAuthenticationDataArgumentCaptor.capture(), any()); UserAuthenticationData userData = userAuthenticationDataArgumentCaptor.getValue(); Set expectedRoles = Sets.newHashSet("custom_role"); - assertThat(userData.roles).isEqualTo(expectedRoles); - assertThat(userData.userAttributes).isEqualTo(userAttributes); - assertThat(userData.contextClassRef).isEqualTo(acrValue); + assertThat(userData.roles).hasSameElementsAs(expectedRoles); + assertThat(userData.userAttributes).containsExactlyInAnyOrderEntriesOf(userAttributes); + assertThat(userData.contextClassRef).hasSameElementsAs(acrValue); } @MethodSource("data") @@ -626,8 +623,9 @@ public Map enhance(Map claims, OAuth2Authenticat Jwt parsedToken = JwtHelper.decode(jwt); Map claims = JsonUtils.readValue(parsedToken.getClaims(), new TypeReference>() {}); - assertThat(claims).containsEntry("claim1", "value1"); - assertThat(claims).containsEntry("claim2", "value1_modified"); + assertThat(claims) + .containsEntry("claim1", "value1") + .containsEntry("claim2", "value1_modified"); } @MethodSource("data") diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java index 55715e30711..20864a6c06e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java @@ -30,7 +30,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -86,7 +86,7 @@ void tokenRetrievalWithClaims() { assertThat(result.getOAuth2Request().getClientId()).isEqualTo("remote"); assertThat(result.getUserAuthentication().getName()).isEqualTo("olds"); assertThat(((RemoteUserAuthentication) result.getUserAuthentication()).getId()).isEqualTo("HDGFJSHGDF"); - assertThat(result.getOAuth2Request().getRequestParameters()).isNotNull() + assertThat(result.getOAuth2Request().getRequestParameters()) .containsKey(ClaimConstants.ISS); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java index 8d9acdd1235..1d40adabf93 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RestrictUaaScopesClientValidatorTest.java @@ -27,6 +27,7 @@ import java.util.LinkedList; import java.util.List; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.cloudfoundry.identity.uaa.client.ClientDetailsValidator.Mode.CREATE; import static org.cloudfoundry.identity.uaa.client.ClientDetailsValidator.Mode.DELETE; @@ -69,12 +70,7 @@ void validate() { protected void validateClient(List restrictModes, List nonRestrictModes, UaaClientDetails client, String s) { for (ClientDetailsValidator.Mode m : restrictModes) { - try { - validator.validate(client, m); - fail("Scope:" + s + " should not be valid during " + m + " mode."); - } catch (InvalidClientDetailsException _) { - //expected - } + assertThatThrownBy(() -> validator.validate(client, m)).isInstanceOf(InvalidClientDetailsException.class); } for (ClientDetailsValidator.Mode m : nonRestrictModes) { try { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java index d9210f0e192..c11a6662731 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java @@ -4,8 +4,8 @@ import java.net.MalformedURLException; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatNoException; class TokenEndpointBuilderTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java index 48b04b7ec1e..2df9229e3a2 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java @@ -36,7 +36,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_IMPLICIT; import static org.mockito.ArgumentMatchers.any; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java index 14e1bfc764d..28c20efc4c9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java @@ -40,9 +40,7 @@ import java.util.Set; import java.util.TreeSet; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.CLIENT_ID; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -135,8 +133,8 @@ void tokenRequestIncludesResourceIds() { IdentityZoneHolder.get().getConfig().getUserConfig().setDefaultGroups(Collections.singletonList("aud1.test")); client.setScope(StringUtils.commaDelimitedListToSet("aud1.test,aud2.test")); OAuth2Request request = factory.createTokenRequest(parameters, client).createOAuth2Request(client); - assertThat(new TreeSet<>(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("aud1.test,aud2.test")); - assertThat(new TreeSet<>(request.getResourceIds())).isEqualTo(StringUtils.commaDelimitedListToSet("aud1,aud2")); + assertThat(new TreeSet<>(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("aud1.test,aud2.test")); + assertThat(new TreeSet<>(request.getResourceIds())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("aud1,aud2")); } @Test @@ -175,8 +173,8 @@ void user_token_request() { assertThat(request.getClientId()).isEqualTo(recipient.getClientId()); assertThat(request.getRequestParameters()).containsEntry(CLIENT_ID, recipient.getClientId()) .containsEntry(TokenConstants.USER_TOKEN_REQUESTING_CLIENT_ID, client.getClientId()); - assertThat(new TreeSet<>(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("requested.scope")); - assertThat(new TreeSet<>(request.getResourceIds())).isEqualTo(StringUtils.commaDelimitedListToSet(recipient.getClientId() + ",requested")); + assertThat(new TreeSet<>(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("requested.scope")); + assertThat(new TreeSet<>(request.getResourceIds())).hasSameElementsAs(StringUtils.commaDelimitedListToSet(recipient.getClientId() + ",requested")); assertThat(request.getRequestParameters()).containsEntry("expires_in", "44000"); } @@ -189,7 +187,7 @@ void factoryProducesSomething() { void scopeIncludesAuthoritiesForUser() { client.setScope(StringUtils.commaDelimitedListToSet("one,two,foo.bar")); AuthorizationRequest request = factory.createAuthorizationRequest(parameters); - assertThat(new TreeSet(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("foo.bar")); + assertThat(new TreeSet(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("foo.bar")); factory.validateParameters(request.getRequestParameters(), client); } @@ -200,7 +198,7 @@ void scopesIncludesAllowedAuthoritiesForUser() { IdentityZoneHolder.get().getConfig().getUserConfig().setAllowedGroups(Arrays.asList("openid", "foo.bar")); client.setScope(StringUtils.commaDelimitedListToSet("foo.bar,spam.baz,space.1.developer")); AuthorizationRequest request = factory.createAuthorizationRequest(parameters); - assertThat(new TreeSet(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("foo.bar")); + assertThat(new TreeSet(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("foo.bar")); factory.validateParameters(request.getRequestParameters(), client); } @@ -210,7 +208,7 @@ void wildcardScopesIncludesAuthoritiesForUser() { when(mockSecurityContextAccessor.getAuthorities()).thenReturn((Collection) AuthorityUtils.commaSeparatedStringToAuthorityList("space.1.developer,space.2.developer,space.1.admin")); client.setScope(StringUtils.commaDelimitedListToSet("space.*.developer")); AuthorizationRequest request = factory.createAuthorizationRequest(parameters); - assertThat(new TreeSet(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("space.1.developer,space.2.developer")); + assertThat(new TreeSet(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("space.1.developer,space.2.developer")); factory.validateParameters(request.getRequestParameters(), client); } @@ -221,7 +219,7 @@ void wildcardScopesIncludesAllowedAuthoritiesForUser() { IdentityZoneHolder.get().getConfig().getUserConfig().setAllowedGroups(Arrays.asList("openid", "space.1.developer")); client.setScope(StringUtils.commaDelimitedListToSet("space.*.developer")); AuthorizationRequest request = factory.createAuthorizationRequest(parameters); - assertThat(new TreeSet(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("space.1.developer")); + assertThat(new TreeSet(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("space.1.developer")); factory.validateParameters(request.getRequestParameters(), client); } @@ -232,15 +230,15 @@ void openidScopeIncludeIsAResourceId() { IdentityZoneHolder.get().getConfig().getUserConfig().setAllowedGroups(Arrays.asList("openid", "foo.bar")); client.setScope(StringUtils.commaDelimitedListToSet("openid,foo.bar")); AuthorizationRequest request = factory.createAuthorizationRequest(parameters); - assertThat(new TreeSet(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("openid,foo.bar")); - assertThat(new TreeSet(request.getResourceIds())).isEqualTo(StringUtils.commaDelimitedListToSet("openid,foo")); + assertThat(new TreeSet(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("openid,foo.bar")); + assertThat(new TreeSet(request.getResourceIds())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("openid,foo")); } @Test void emptyScopeOkForClientWithNoScopes() { client.setScope(StringUtils.commaDelimitedListToSet("")); // empty AuthorizationRequest request = factory.createAuthorizationRequest(parameters); - assertThat(new TreeSet(request.getScope())).isEqualTo(StringUtils.commaDelimitedListToSet("")); + assertThat(new TreeSet(request.getScope())).hasSameElementsAs(StringUtils.commaDelimitedListToSet("")); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaScopesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaScopesTests.java index ec0f8257ea6..0d7bea38080 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaScopesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaScopesTests.java @@ -38,7 +38,7 @@ void getUaaScopes() { void getUaaAuthorities() { List authorities = uaaScopes.getUaaAuthorities(); List expected = getGrantedAuthorities(); - assertThat(authorities).isEqualTo(expected); + assertThat(authorities).containsExactlyElementsOf(expected); } protected List getGrantedAuthorities() { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java index 3d5a77b40e9..0d7f710b851 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java @@ -36,7 +36,6 @@ import java.lang.reflect.Proxy; import java.sql.Connection; import java.sql.PreparedStatement; -import java.sql.SQLException; import java.time.Duration; import java.time.Instant; import java.util.Arrays; @@ -50,7 +49,7 @@ import java.util.logging.Logger; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -128,7 +127,6 @@ void deserializationOfUaaAuthentication() { assertThat(userAuthentication.getUserAttributes().get("btest")).containsExactlyInAnyOrder("test1", "test2", "test3"); assertThat(userAuthentication.getExternalGroups()) - .hasSize(3) .containsExactlyInAnyOrder("group1", "group2", "group3"); } @@ -331,7 +329,7 @@ void beOAuth2StandardCompliant() { } @Test - void countingTheExecutedSqlDeleteStatements() throws SQLException { + void countingTheExecutedSqlDeleteStatements() throws Exception { // Given, mocked data source to count how often it is used, call performExpirationClean 10 times. DataSource mockedDataSource = mock(DataSource.class); Instant before = Instant.now(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UserManagedAuthzApprovalHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UserManagedAuthzApprovalHandlerTests.java index 05a476db085..caf8016459a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UserManagedAuthzApprovalHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UserManagedAuthzApprovalHandlerTests.java @@ -245,7 +245,7 @@ void onlySomeRequestedScopeMatchesDeniedApprovalButScopeAutoApproved() { currentIdentityZoneId); assertThat(handler.isApproved(request, mockAuthentication)).isTrue(); - assertThat(request.getScope()).isEqualTo(new HashSet<>(Arrays.asList("cloud_controller.read", "openid"))); + assertThat(request.getScope()).hasSameElementsAs(new HashSet<>(Arrays.asList("cloud_controller.read", "openid"))); } @Test @@ -321,7 +321,7 @@ void allRequestedScopesMatchApproval() { // The request is approved because the user has approved all the scopes // requested assertThat(handler.isApproved(request, mockAuthentication)).isTrue(); - assertThat(request.getScope()).isEqualTo(new HashSet<>(Arrays.asList("openid", "cloud_controller.read", "cloud_controller.write"))); + assertThat(request.getScope()).hasSameElementsAs(new HashSet<>(Arrays.asList("openid", "cloud_controller.read", "cloud_controller.write"))); } @Test @@ -363,7 +363,7 @@ void requestedScopesMatchApprovalButSomeDenied() { // The request is approved because the user has acted on all requested // scopes assertThat(handler.isApproved(request, mockAuthentication)).isTrue(); - assertThat(request.getScope()).isEqualTo(new HashSet<>(Arrays.asList("openid", "cloud_controller.read"))); + assertThat(request.getScope()).hasSameElementsAs(new HashSet<>(Arrays.asList("openid", "cloud_controller.read"))); } @Test @@ -555,7 +555,7 @@ void someRequestedScopesMatchApproval() { // The request is approved because the user has approved all the scopes // requested assertThat(handler.isApproved(request, mockAuthentication)).isTrue(); - assertThat(request.getScope()).isEqualTo(new HashSet<>(Collections.singletonList("openid"))); + assertThat(request.getScope()).hasSameElementsAs(new HashSet<>(Collections.singletonList("openid"))); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java index 26b869a90b1..de9947135dc 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java @@ -18,9 +18,7 @@ import java.util.Collections; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.ALLOWED_PROVIDERS; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_JWT_BEARER; @@ -46,10 +44,10 @@ void createLimitedClient() { clientDetails.addAdditionalInformation(ALLOWED_PROVIDERS, Collections.singletonList(OriginKeys.UAA)); ClientDetails validatedClientDetails = zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE); assertThat(validatedClientDetails.getClientId()).isEqualTo(clientDetails.getClientId()); - assertThat(validatedClientDetails.getScope()).isEqualTo(clientDetails.getScope()); - assertThat(validatedClientDetails.getAuthorizedGrantTypes()).isEqualTo(clientDetails.getAuthorizedGrantTypes()); + assertThat(validatedClientDetails.getScope()).hasSameElementsAs(clientDetails.getScope()); + assertThat(validatedClientDetails.getAuthorizedGrantTypes()).hasSameElementsAs(clientDetails.getAuthorizedGrantTypes()); assertThat(validatedClientDetails.getAuthorities()).isEqualTo(clientDetails.getAuthorities()); - assertThat(validatedClientDetails.getResourceIds()).isEqualTo(Collections.singleton("none")); + assertThat(validatedClientDetails.getResourceIds()).hasSameElementsAs(Collections.singleton("none")); assertThat(validatedClientDetails.getAdditionalInformation()).containsEntry(ALLOWED_PROVIDERS, Collections.singletonList(OriginKeys.UAA)); } @@ -85,7 +83,7 @@ void createClientNoSecretForImplicitIsValid() { UaaClientDetails clientDetails = new UaaClientDetails("client", null, "openid", "implicit", "uaa.resource"); clientDetails.addAdditionalInformation(ALLOWED_PROVIDERS, Collections.singletonList(OriginKeys.UAA)); ClientDetails validatedClientDetails = zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE); - assertThat(validatedClientDetails.getAuthorizedGrantTypes()).isEqualTo(clientDetails.getAuthorizedGrantTypes()); + assertThat(validatedClientDetails.getAuthorizedGrantTypes()).hasSameElementsAs(clientDetails.getAuthorizedGrantTypes()); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java index b2ae9d9f857..a41343c53b9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java @@ -40,9 +40,7 @@ import java.util.Set; import java.util.UUID; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus.APPROVED; import static org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus.DENIED; import static org.mockito.Mockito.mock; @@ -160,7 +158,7 @@ void approvalsDeserializationIsCaseInsensitive() { .setStatus(ApprovalStatus.APPROVED)); Set deserializedApprovals = JsonUtils.readValue("[{\"userid\":\"test-user-id\",\"clientid\":\"testclientid\",\"scope\":\"scope\",\"status\":\"APPROVED\",\"expiresat\":\"2015-08-25T14:35:42.512Z\",\"lastupdatedat\":\"2015-08-25T14:35:42.512Z\"}]", new TypeReference>() { }); - assertThat(deserializedApprovals).isEqualTo(approvals); + assertThat(deserializedApprovals).hasSameElementsAs(approvals); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/JdbcApprovalStoreTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/JdbcApprovalStoreTests.java index 5fe342e7583..a52e45da585 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/JdbcApprovalStoreTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/JdbcApprovalStoreTests.java @@ -285,7 +285,7 @@ void canRefreshApproval() { } @Test - void canPurgeExpiredApprovals() throws InterruptedException { + void canPurgeExpiredApprovals() throws Exception { assertThat(jdbcApprovalStore.getApprovalsForClient("c3", defaultZoneId)).isEmpty(); assertThat(jdbcApprovalStore.getApprovalsForUser("u3", defaultZoneId)).isEmpty(); assertThat(jdbcApprovalStore.getApprovalsForClient("c1", defaultZoneId)).hasSize(2); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java index dd19a9fc72e..9f1077fb3b9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java @@ -23,9 +23,7 @@ import java.util.List; import static org.apache.logging.log4j.Level.WARN; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java index 11bb3300056..ca9ebfbba48 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java @@ -13,7 +13,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.HamcrestCondition.matching; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.hamcrest.Matchers.is; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientDetailsModificationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientDetailsModificationTest.java index e8c56f0bc41..1c929ebfd16 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientDetailsModificationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/ClientDetailsModificationTest.java @@ -23,7 +23,7 @@ void constructor_exposesMergedJwtCredsAndOmitsRawAdditionalKeys() { "[{\"iss\":\"http://u\",\"sub\":\"s\"}]", List.class)); ClientDetailsModification m = new ClientDetailsModification(d); - assertThat(m.getClientJwtCredentials()).isNotNull().hasSize(1); + assertThat(m.getClientJwtCredentials()).hasSize(1); assertThat(m.getAdditionalInformation()).doesNotContainKey(ClientJwtConfiguration.JWT_CREDS); assertThat(m.getAdditionalInformation()).doesNotContainKey("client_jwt_config"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java index e3d1c7e68a7..876ab9f5651 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java @@ -18,13 +18,12 @@ import com.nimbusds.jose.jwk.JWKSet; import org.junit.jupiter.api.Test; -import java.text.ParseException; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey.KeyUse.sig; class JsonWebKeySetTests { @@ -132,7 +131,7 @@ void multi_key() { assertThat(key.getKeyProperties()).containsEntry("k", "test-mac-key"); assertThat(key.getUse()).isNull(); - assertThat(key.getKeyOps()).isEqualTo(new LinkedHashSet<>(Arrays.asList(JsonWebKey.KeyOperation.sign, JsonWebKey.KeyOperation.verify))); + assertThat(key.getKeyOps()).hasSameElementsAs(new LinkedHashSet<>(Arrays.asList(JsonWebKey.KeyOperation.sign, JsonWebKey.KeyOperation.verify))); } @Test @@ -147,7 +146,7 @@ void multi_key_rfc7518() { assertThat(key.getKeyProperties()).containsEntry("k", "test-oct-key"); assertThat(key.getUse()).isNull(); - assertThat(key.getKeyOps()).isEqualTo(new LinkedHashSet<>(List.of(JsonWebKey.KeyOperation.verify))); + assertThat(key.getKeyOps()).hasSameElementsAs(new LinkedHashSet<>(List.of(JsonWebKey.KeyOperation.verify))); } @Test @@ -179,7 +178,7 @@ void ignoreUnknownKeyTypes() { } @Test - void jsonKeySetParseJson() throws ParseException { + void jsonKeySetParseJson() throws Exception { String jsonConfig = "{\"keys\":[{\"kty\":\"RSA\",\"e\":\"AQAB\",\"use\":\"sig\",\"kid\":\"key-1\",\"alg\":\"RS256\",\"n\":\"xMi4Z4FBfQEOdNYLmzxkYJvP02TSeapZMKMQo90JQRL07ttIKcDMP6pGcirOGSQWWBBpvdo5EnVOiNzViu9JCJP2IWbHJ4sRe0S1dySYdBRVV_ZkgWOrj7Cr2yT0ZVvCCzH7NAWmlA6LUV19Mnp-ugeGoxK-fsk8SRLS_Z9JdyxgOb3tPxdDas3MZweMZ6HqujoAAG9NASBGjFNXbhMckrEfecwm3OJzsjGFxhqXRqkTsGEHvzETMxfvSkTkldOzmErnjpwyoOPLrXcWIs1wvdXHakfVHSvyb3T4gm3ZfOOoUf6lrd2w1pF_PkA88NkjN2-W9fQmbUzNgVjEQiXo4w\"}]}"; JsonWebKeySet keys = JsonWebKeyHelper.parseConfiguration(jsonConfig); assertThat(keys.getKeys()).hasSize(1); @@ -190,7 +189,7 @@ void jsonKeySetParseJson() throws ParseException { } @Test - void jsonKeySetParsePublicKey() throws ParseException { + void jsonKeySetParsePublicKey() throws Exception { String publicKey = "-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxMi4Z4FBfQEOdNYLmzxkYJvP02TSeapZMKMQo90JQRL07ttIKcDMP6pGcirOGSQWWBBpvdo5EnVOiNzViu9JCJP2IWbHJ4sRe0S1dySYdBRVV/ZkgWOrj7Cr2yT0ZVvCCzH7NAWmlA6LUV19Mnp+ugeGoxK+fsk8SRLS/Z9JdyxgOb3tPxdDas3MZweMZ6HqujoAAG9NASBGjFNXbhMckrEfecwm3OJzsjGFxhqXRqkTsGEHvzETMxfvSkTkldOzmErnjpwyoOPLrXcWIs1wvdXHakfVHSvyb3T4gm3ZfOOoUf6lrd2w1pF/PkA88NkjN2+W9fQmbUzNgVjEQiXo4wIDAQAB-----END PUBLIC KEY-----"; JsonWebKeySet keys = JsonWebKeyHelper.parseConfiguration(publicKey); assertThat(keys.getKeys()).hasSize(1); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java index dd9ee227633..9026cc3f168 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java @@ -36,7 +36,7 @@ import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey.KeyType.MAC; import static org.mockito.Mockito.mock; @@ -193,7 +193,7 @@ void single_eckey_valid() { verifier = new ChainedSignatureVerifier(keySet); List delegates = new ArrayList<>((List) ReflectionTestUtils.getField(verifier, verifier.getClass(), "delegates")); assertThat(delegates).hasSize(1); - assertThat(delegates.getFirst()).isNotNull(); + assertThat(delegates).first().isNotNull(); assertThat(delegates.getFirst().algorithm()).isEqualTo("ES256"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java index cf320d4de66..7b62f7dc431 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java @@ -15,7 +15,6 @@ package org.cloudfoundry.identity.uaa.oauth.jwt; -import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JOSEObjectType; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; @@ -29,12 +28,11 @@ import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; -import java.text.ParseException; import java.util.List; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.util.UaaStringUtils.DEFAULT_UAA_URL; class CommonSignerTest { @@ -93,7 +91,7 @@ void null_key_is_rejected() { } @Test - void mac_signing() throws JOSEException, ParseException { + void mac_signing() throws Exception { final String jwtFromIo = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiSm9obiBEb2UiLCJzdWIiOiIxMjM0NTY3ODkwIn0.hUTNPTwAP4RQFr_d_GOwXrVOJsX1-PWAvHSsg-CSQPk"; CommonSigner signer = new CommonSigner(null, macSigningKey, DEFAULT_UAA_URL); assertThat(signer.algorithm()).isEqualTo("HS256"); @@ -112,12 +110,12 @@ void mac_signing() throws JOSEException, ParseException { @Test void mac_signing_options() { CommonSigner signer = new CommonSigner(null, macSigningKey, "http://localhost/uaa"); - assertThat(signer.supportedJWSAlgorithms()).isEqualTo(UaaMacSigner.SUPPORTED_ALGORITHMS); + assertThat(signer.supportedJWSAlgorithms()).hasSameElementsAs(UaaMacSigner.SUPPORTED_ALGORITHMS); assertThat(signer.getJCAContext()).isNotNull(); } @Test - void nimbus_singing_with_single_aud_value() throws JOSEException, ParseException { + void nimbus_singing_with_single_aud_value() throws Exception { // given Map objectMap = Map.of("sub", "1234567890", "name", "John Doe", "aud", List.of("single")); // when @@ -134,7 +132,7 @@ void nimbus_singing_with_single_aud_value() throws JOSEException, ParseException } @Test - void uaa_singing_with_single_aud_value() throws ParseException { + void uaa_singing_with_single_aud_value() throws Exception { // given Map objectMap = Map.of("sub", "1234567890", "name", "John Doe", "aud", List.of("single")); // when diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java index 1aee742cb53..17763affc7f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java @@ -11,6 +11,7 @@ import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.ClientJwtConfiguration; import org.cloudfoundry.identity.uaa.oauth.KeyInfo; import org.cloudfoundry.identity.uaa.oauth.KeyInfoBuilder; @@ -51,7 +52,6 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -85,7 +85,7 @@ void cleanup() { } @Test - void getClientAssertion() throws ParseException { + void getClientAssertion() throws Exception { // When String clientAssertion = jwtClientAuthentication.getClientAssertion(config); // Then @@ -93,7 +93,7 @@ void getClientAssertion() throws ParseException { } @Test - void getClientAssertionUsingTrueBooleanConfig() throws ParseException { + void getClientAssertionUsingTrueBooleanConfig() throws Exception { // Given config.setJwtClientAuthentication(true); MultiValueMap params = new LinkedMultiValueMap<>(); @@ -121,7 +121,7 @@ void getClientAssertionUsingFalseBooleanConfig() { } @Test - void getClientAssertionUsingCustomConfig() throws ParseException { + void getClientAssertionUsingCustomConfig() throws Exception { // Given Map customClaims = Map.of("iss", "identity"); config.setJwtClientAuthentication(customClaims); @@ -132,7 +132,7 @@ void getClientAssertionUsingCustomConfig() throws ParseException { } @Test - void getClientAssertionRfc7523Compliant() throws ParseException { + void getClientAssertionRfc7523Compliant() throws Exception { // Given Map customClaims = new HashMap<>(); customClaims.put("iss", "anotherIssuer"); @@ -145,7 +145,7 @@ void getClientAssertionRfc7523Compliant() throws ParseException { } @Test - void getClientAuthenticationParameters() throws ParseException { + void getClientAuthenticationParameters() throws Exception { // Given MultiValueMap params = new LinkedMultiValueMap<>(); // When @@ -154,7 +154,7 @@ void getClientAuthenticationParameters() throws ParseException { assertThat(params).containsKey("client_assertion") .containsKey("client_assertion_type") .containsEntry("client_assertion_type", Collections.singletonList(JwtClientAuthentication.GRANT_TYPE)); - assertThat(params.get("client_assertion").getFirst()).isNotNull(); + assertThat(params.get("client_assertion")).first().isNotNull(); validateClientAssertionOidcCompliant(params.get("client_assertion").getFirst()); } @@ -170,7 +170,7 @@ void getClientAuthenticationParametersNullJwtClientConfiguration() { MultiValueMap params = new LinkedMultiValueMap<>(); config.setJwtClientAuthentication(null); // When - assertThat(jwtClientAuthentication.getClientAuthenticationParameters(params, config)).isEqualTo(params); + assertThat(jwtClientAuthentication.getClientAuthenticationParameters(params, config)).containsExactlyInAnyOrderEntriesOf(params); } @Test @@ -185,7 +185,7 @@ void getClientAssertionUnknownSingingKey() { } @Test - void getClientAssertionUsingCustomSingingKeyFromEnvironment() throws ParseException, JOSEException { + void getClientAssertionUsingCustomSingingKeyFromEnvironment() throws Exception { // Given: register 2 keys mockKeyInfoService("key-id-321", JwtHelperX5tTest.CERTIFICATE_1); Map customClaims = new HashMap<>(); @@ -208,7 +208,7 @@ void getClientAssertionUsingCustomSingingKeyFromEnvironment() throws ParseExcept } @Test - void getClientAssertionUsingCustomSingingKeyFromEnvironmentNoDefault() throws ParseException, JOSEException { + void getClientAssertionUsingCustomSingingKeyFromEnvironmentNoDefault() throws Exception { // Given: register 2 keys mockKeyInfoService("key-id-321", JwtHelperX5tTest.CERTIFICATE_1); Map customClaims = new HashMap<>(); @@ -229,7 +229,7 @@ void getClientAssertionUsingCustomSingingKeyFromEnvironmentNoDefault() throws Pa } @Test - void getClientAssertionUsingCustomSingingKeyFromEnvironmentButEntryIsMissing() throws JOSEException { + void getClientAssertionUsingCustomSingingKeyFromEnvironmentButEntryIsMissing() throws Exception { // Given: register 2 keys mockKeyInfoService("key-id-321", JwtHelperX5tTest.CERTIFICATE_1); Map customClaims = new HashMap<>(); @@ -246,7 +246,7 @@ void getClientAssertionUsingCustomSingingKeyFromEnvironmentButEntryIsMissing() t } @Test - void getClientAssertionUsingCustomSingingKeyFromEnvironmentButNotInDefaultZone() throws JOSEException { + void getClientAssertionUsingCustomSingingKeyFromEnvironmentButNotInDefaultZone() throws Exception { // Given: register 2 keys mockKeyInfoService("key-id-321", JwtHelperX5tTest.CERTIFICATE_1); Map customClaims = new HashMap<>(); @@ -267,7 +267,7 @@ void getClientAssertionUsingCustomSingingKeyFromEnvironmentButNotInDefaultZone() } @Test - void getClientAssertionCustomSingingKeyButNoCertificate() throws ParseException, JOSEException { + void getClientAssertionCustomSingingKeyButNoCertificate() throws Exception { // Given mockKeyInfoService("myKey", null); Map customClaims = new HashMap<>(); @@ -287,7 +287,7 @@ void getClientAssertionCustomSingingKeyButNoCertificate() throws ParseException, } @Test - void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironment() throws ParseException, JOSEException { + void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironment() throws Exception { // Given: register 2 keys mockKeyInfoService("key-id-321", JwtHelperX5tTest.CERTIFICATE_1); // add reference in jwtClientAuthentication to customer one key-id-321 @@ -314,7 +314,7 @@ void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironment() throws Pars } @Test - void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironmentDisabledForCustomZone() throws JOSEException { + void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironmentDisabledForCustomZone() throws Exception { arrangeCustomIdz(); // Given: register 2 keys @@ -335,13 +335,12 @@ void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironmentDisabledForCus ); mockApplicationContext(keyMap); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> - jwtClientAuthentication.getClientAuthenticationParameters(params, config, false) - ).withMessage("Missing requested signing key"); + assertThatThrownBy(() -> + jwtClientAuthentication.getClientAuthenticationParameters(params, config, false)).isInstanceOf(BadCredentialsException.class).hasMessage("Missing requested signing key"); } @Test - void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironmentEnabledForCustomZone() throws ParseException, JOSEException { + void getClientAssertionUsingCustomSingingPrivateKeyFromEnvironmentEnabledForCustomZone() throws Exception { arrangeCustomIdz(); // Given: register 2 keys @@ -479,11 +478,12 @@ void signatureInvalidateClientAssertion() throws Exception { void getClientIdOfInvalidClientAssertionOidcCompliance() { // Then assertThat(JwtClientAuthentication.getClientIdOidcAssertion(INVALID_CLIENT_JWT)).isNull(); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> JwtClientAuthentication.getClientIdOidcAssertion("eyXXX")); + assertThatThrownBy(() -> JwtClientAuthentication.getClientIdOidcAssertion("eyXXX")) + .asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test - void clientJwtFederatedCreateAndValidateOwnAssertion() throws MalformedURLException, JOSEException { + void clientJwtFederatedCreateAndValidateOwnAssertion() throws Exception { // Given jwtClientAuthentication = new JwtClientAuthentication(keyInfoService, oidcMetadataFetcher, externalOAuthAuthenticationManager); mockKeyInfoService(KEY_ID, JwtHelperX5tTest.CERTIFICATE_1, JwtHelperX5tTest.SIGNING_KEY_1); @@ -497,7 +497,7 @@ void clientJwtFederatedCreateAndValidateOwnAssertion() throws MalformedURLExcept } @Test - void clientJwtFederatedCreateAndValidateTrustedIssuer() throws MalformedURLException, JOSEException, ParseException { + void clientJwtFederatedCreateAndValidateTrustedIssuer() throws Exception { // Given jwtClientAuthentication = new JwtClientAuthentication(keyInfoService, oidcMetadataFetcher, externalOAuthAuthenticationManager); mockKeyInfoService(KEY_ID, JwtHelperX5tTest.CERTIFICATE_1, JwtHelperX5tTest.SIGNING_KEY_1); @@ -513,7 +513,7 @@ void clientJwtFederatedCreateAndValidateTrustedIssuer() throws MalformedURLExcep } @Test - void clientJwtFederatedCreateAndValidateTrustedIdP() throws MalformedURLException, JOSEException, ParseException { + void clientJwtFederatedCreateAndValidateTrustedIdP() throws Exception { // Given IdentityProvider idp = new IdentityProvider(); OIDCIdentityProviderDefinition idpConfig = new OIDCIdentityProviderDefinition(); @@ -532,7 +532,7 @@ void clientJwtFederatedCreateAndValidateTrustedIdP() throws MalformedURLExceptio } @Test - void clientJwtFederatedCreateAndValidateWrongIdPAndWrongIssuer() throws MalformedURLException, JOSEException, ParseException { + void clientJwtFederatedCreateAndValidateWrongIdPAndWrongIssuer() throws Exception { // Given IdentityProvider idp = new IdentityProvider(); SamlIdentityProviderDefinition idpConfig = new SamlIdentityProviderDefinition(); @@ -684,7 +684,7 @@ private static JWSHeader getJwtHeader(String jwtString) throws ParseException { private static void validateClientAssertionOidcCompliant(String clientAssertion) throws ParseException { JWTClaimsSet jwtClaimsSet = JWTParser.parse(clientAssertion).getJWTClaimsSet(); - assertThat(jwtClaimsSet.getAudience()).isEqualTo(Collections.singletonList("http://localhost:8080/uaa/oauth/token")); + assertThat(jwtClaimsSet.getAudience()).containsExactlyElementsOf(Collections.singletonList("http://localhost:8080/uaa/oauth/token")); assertThat(jwtClaimsSet.getSubject()).isEqualTo("identity"); assertThat(jwtClaimsSet.getIssuer()).isEqualTo("identity"); assertThat(Instant.now()) @@ -696,7 +696,7 @@ private static void validateClientAssertionOidcCompliant(String clientAssertion) private static void validateClientAssertionRfc7523Compliant(String clientAssertion, String iss, String aud) throws ParseException { JWTClaimsSet jwtClaimsSet = JWTParser.parse(clientAssertion).getJWTClaimsSet(); - assertThat(jwtClaimsSet.getAudience()).isEqualTo(Collections.singletonList(aud)); + assertThat(jwtClaimsSet.getAudience()).containsExactlyElementsOf(Collections.singletonList(aud)); assertThat(jwtClaimsSet.getIssuer()).isEqualTo(iss); assertThat(jwtClaimsSet.getSubject()).isEqualTo("identity"); assertThat(Instant.now()) diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java index 48973734fd0..cd6db2be1ed 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java @@ -17,9 +17,7 @@ import java.util.Base64; import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; @Tag("https://tools.ietf.org/html/rfc7519#section-5") @DisplayName("JOSE Header") diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java index 4164dd3aaf1..877718a020d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java @@ -17,7 +17,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; import static org.cloudfoundry.identity.uaa.util.UaaStringUtils.DEFAULT_UAA_URL; @@ -63,15 +63,15 @@ void audClaimTypes() { Claims claimSingle = UaaTokenUtils.getClaimsFromTokenString(audSingle.getEncoded()); assertThat(claimSingle).isNotNull(); - assertThat(claimSingle.getAud()).isEqualTo(Arrays.asList("single")); + assertThat(claimSingle.getAud()).containsExactlyElementsOf(Arrays.asList("single")); Claims claimArray = UaaTokenUtils.getClaimsFromTokenString(audArray.getEncoded()); assertThat(claimArray).isNotNull(); - assertThat(claimArray.getAud()).isEqualTo(Arrays.asList("one")); + assertThat(claimArray.getAud()).containsExactlyElementsOf(Arrays.asList("one")); Claims claimArrayThree = UaaTokenUtils.getClaimsFromTokenString(audArrayThree.getEncoded()); assertThat(claimArrayThree).isNotNull(); - assertThat(claimArrayThree.getAud()).isEqualTo(Arrays.asList("one", "two", "three")); + assertThat(claimArrayThree.getAud()).containsExactlyElementsOf(Arrays.asList("one", "two", "three")); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java index e2b0eee1908..320baab49a7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java @@ -8,7 +8,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; public class JwtHelperX5tTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java index 146ed10ea6d..ab6e96bd4c1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java @@ -24,7 +24,7 @@ import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class SignatureVerifierTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenCreatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenCreatorTest.java index d1961216ae9..efdc3553f89 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenCreatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/openid/IdTokenCreatorTest.java @@ -182,7 +182,7 @@ void setup() throws Exception { } @Test - void create_includesStandardClaims() throws IdTokenCreationException { + void create_includesStandardClaims() throws Exception { IdToken idToken = tokenCreator.create(clientDetails, user, userAuthenticationData, tokenActor); assertThat(idToken).isNotNull(); @@ -198,7 +198,7 @@ void create_includesStandardClaims() throws IdTokenCreationException { } @Test - void create_includesAdditionalClaims() throws IdTokenCreationException { + void create_includesAdditionalClaims() throws Exception { IdToken idToken = tokenCreator.create(clientDetails, user, userAuthenticationData, tokenActor); assertThat(idToken).isNotNull(); @@ -206,8 +206,8 @@ void create_includesAdditionalClaims() throws IdTokenCreationException { assertThat(idToken.familyName).isEqualTo(familyName); assertThat(idToken.previousLogonTime).isEqualTo(previousLogonTime); assertThat(idToken.phoneNumber).isEqualTo(phoneNumber); - assertThat(idToken.roles).isEqualTo(roles); - assertThat(idToken.userAttributes).isEqualTo(userAttributes); + assertThat(idToken.roles).hasSameElementsAs(roles); + assertThat(idToken.userAttributes).containsExactlyInAnyOrderEntriesOf(userAttributes); assertThat(idToken.scope).contains("openid"); assertThat(idToken.emailVerified).isTrue(); assertThat(idToken.nonce).isEqualTo(nonce); @@ -219,18 +219,18 @@ void create_includesAdditionalClaims() throws IdTokenCreationException { assertThat(idToken.origin).isEqualTo(origin); assertThat(idToken.jti).isEqualTo("accessTokenId"); assertThat(idToken.revSig).isEqualTo("a039bd5"); - assertThat(idToken.getTokenActor().get(ClaimConstants.ISS)).isEqualTo(tokenActor.getIssuer()); + assertThat(idToken.getTokenActor()).containsEntry(ClaimConstants.ISS, tokenActor.getIssuer()); } @Test - void create_includesEmailVerified() throws IdTokenCreationException { + void create_includesEmailVerified() throws Exception { user.setVerified(false); IdToken idToken = tokenCreator.create(clientDetails, user, userAuthenticationData, tokenActor); assertThat(idToken.emailVerified).isFalse(); } @Test - void create_doesntPopulateRolesWhenScopeDoesntContainRoles() throws IdTokenCreationException { + void create_doesntPopulateRolesWhenScopeDoesntContainRoles() throws Exception { scopes.clear(); scopes.add("openid"); @@ -240,7 +240,7 @@ void create_doesntPopulateRolesWhenScopeDoesntContainRoles() throws IdTokenCreat } @Test - void create_setsRolesToNullIfThereAreNoRoles() throws IdTokenCreationException { + void create_setsRolesToNullIfThereAreNoRoles() throws Exception { roles.clear(); IdToken idToken = tokenCreator.create(clientDetails, user, userAuthenticationData, tokenActor); @@ -249,7 +249,7 @@ void create_setsRolesToNullIfThereAreNoRoles() throws IdTokenCreationException { } @Test - void create_setsRolesToNullIfRolesAreNull() throws IdTokenCreationException { + void create_setsRolesToNullIfRolesAreNull() throws Exception { userAuthenticationData = new UserAuthenticationData( authTime, amr, @@ -268,7 +268,7 @@ void create_setsRolesToNullIfRolesAreNull() throws IdTokenCreationException { } @Test - void create_doesntPopulateUserAttributesWhenScopeDoesntContainUserAttributes() throws IdTokenCreationException { + void create_doesntPopulateUserAttributesWhenScopeDoesntContainUserAttributes() throws Exception { scopes.clear(); scopes.add("openid"); @@ -278,7 +278,7 @@ void create_doesntPopulateUserAttributesWhenScopeDoesntContainUserAttributes() t } @Test - void create_doesntSetUserAttributesIfTheyAreNull() throws IdTokenCreationException { + void create_doesntSetUserAttributesIfTheyAreNull() throws Exception { userAuthenticationData = new UserAuthenticationData( authTime, amr, @@ -297,7 +297,7 @@ void create_doesntSetUserAttributesIfTheyAreNull() throws IdTokenCreationExcepti } @Test - void create_doesntPopulateNamesAndPhone_whenNoProfileScopeGiven() throws IdTokenCreationException { + void create_doesntPopulateNamesAndPhone_whenNoProfileScopeGiven() throws Exception { scopes.remove("profile"); IdToken idToken = tokenCreator.create(clientDetails, user, userAuthenticationData, tokenActor); @@ -308,7 +308,7 @@ void create_doesntPopulateNamesAndPhone_whenNoProfileScopeGiven() throws IdToken } @Test - void create_doesntIncludesExcludedClaims() throws IdTokenCreationException { + void create_doesntIncludesExcludedClaims() throws Exception { excludedClaims.add(ClaimConstants.USER_ID); excludedClaims.add(ClaimConstants.AUD); excludedClaims.add(ClaimConstants.ISS); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java index e1ad8ca256d..3e3c7972bf6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java @@ -15,7 +15,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -117,7 +117,7 @@ void noCodeChallengeMethodForEvaluation() throws Exception { @Test void pkceValidationServiceConstructorWithCodeChallengeMethodsMap() { Set testHashSet = new HashSet<>(Arrays.asList("S256", "plain")); - assertThat(pkceValidationService.getSupportedCodeChallengeMethods()).isEqualTo(testHashSet); + assertThat(pkceValidationService.getSupportedCodeChallengeMethods()).hasSameElementsAs(testHashSet); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java index 8cee358fded..8134b9a9323 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java @@ -16,7 +16,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/OAuth2RequestTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/OAuth2RequestTests.java index 56ae2de7c64..e22cf10be1a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/OAuth2RequestTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/OAuth2RequestTests.java @@ -34,7 +34,7 @@ void getRedirectUri() { @Test void getResponseTypes() { - assertThat(oAuth2Request.getResponseTypes()).isEqualTo(Set.of()); + assertThat(oAuth2Request.getResponseTypes()).hasSameElementsAs(Set.of()); } @Test @@ -49,12 +49,12 @@ void isApproved() { @Test void getResourceIds() { - assertThat(oAuth2Request.getResourceIds()).isEqualTo(Set.of()); + assertThat(oAuth2Request.getResourceIds()).hasSameElementsAs(Set.of()); } @Test void getExtensions() { - assertThat(oAuth2Request.getExtensions()).isEqualTo(Map.of("extra", "param")); + assertThat(oAuth2Request.getExtensions()).containsExactlyInAnyOrderEntriesOf(Map.of("extra", "param")); } @Test @@ -71,13 +71,13 @@ void createOAuth2Request() { @Test void narrowScope() { OAuth2Request narrow = oAuth2Request.narrowScope(Set.of("scope1", "scope2")); - assertThat(narrow.getScope()).isEqualTo(Set.of("scope1", "scope2")); + assertThat(narrow.getScope()).hasSameElementsAs(Set.of("scope1", "scope2")); } @Test void refresh() { OAuth2Request request = oAuth2Request.refresh(new ImplicitTokenRequest(mock(TokenRequest.class), mock(OAuth2Request.class))); - assertThat(request.getScope()).isEqualTo(Set.of("client")); + assertThat(request.getScope()).hasSameElementsAs(Set.of("client")); assertThat(request).isEqualTo(oAuth2Request); assertThat(request.getRefreshTokenRequest()).isNotNull(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java index 529b77a2d73..efb3c5cce8a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java @@ -16,7 +16,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/config/xml/ResourceBeanDefinitionParserTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/config/xml/ResourceBeanDefinitionParserTest.java index 6e4509cabd5..60f04b632f4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/config/xml/ResourceBeanDefinitionParserTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/config/xml/ResourceBeanDefinitionParserTest.java @@ -129,7 +129,7 @@ void doParsePassword() { void doStatic() throws Exception { ResourceBeanDefinitionParser.StringListFactoryBean stringListFactoryBean = new ResourceBeanDefinitionParser.StringListFactoryBean("one,two"); assertThat(stringListFactoryBean.getObject()).hasSize(2); - assertThat(stringListFactoryBean.getObject().getFirst()).isEqualTo("one"); + assertThat(stringListFactoryBean.getObject()).first().isEqualTo("one"); assertThat(stringListFactoryBean.getObject().get(1)).isEqualTo("two"); assertThat(stringListFactoryBean.getObjectType()).isEqualTo(List.class); assertThat(stringListFactoryBean.isSingleton()).isTrue(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java index 21db1cf5bbf..6d68d14ae9c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java @@ -12,9 +12,7 @@ import java.util.List; import java.util.Set; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java index 813bd43cd2d..19cc591ba03 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java @@ -38,7 +38,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -154,7 +154,7 @@ void getAccessTokenWithUnsupportedRequestParameters() { } @Test - void getAccessTokenWithSupportedRequestParametersNotPost() throws HttpRequestMethodNotSupportedException { + void getAccessTokenWithSupportedRequestParametersNotPost() throws Exception { endpoint.setAllowedRequestMethods(new HashSet<>(List.of(HttpMethod.GET))); HashMap parameters = new HashMap<>(); parameters.put("client_id", CLIENT_ID); @@ -215,7 +215,7 @@ void getAccessTokenReturnsHeaderContentTypeJson() { assertThat(response).isNotNull(); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getHeaders().get("Content-Type").getFirst()).isEqualTo("application/json"); + assertThat(response.getHeaders().get("Content-Type")).first().isEqualTo("application/json"); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java index 117e89bba0d..aaa58fb8c99 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java @@ -8,7 +8,7 @@ import org.springframework.expression.ExpressionParser; import org.springframework.expression.ParserContext; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.verify; /** diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java index a72b886fdab..0afa642ee97 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java @@ -19,7 +19,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java index 149f5a2962a..1e64524a2cb 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java @@ -14,7 +14,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java index f86db8607b9..70aac2b1f61 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java @@ -17,7 +17,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java index fce8d8b61d3..b29e16d41e0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java @@ -13,7 +13,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java index 6e28b190e40..b4cd3ccdad1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java @@ -31,7 +31,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA @@ -78,7 +78,7 @@ public ResourceOwnerPasswordTokenGranterTests() { @Test @Disabled("since 2024-05-08") - void testSunnyDay() { + void sunnyDay() { ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(authenticationManager, providerTokenServices, clientDetailsService, requestFactory); OAuth2AccessToken token = granter.grant("password", tokenRequest); @@ -88,7 +88,7 @@ void testSunnyDay() { @Test @Disabled("since 2024-05-08") - void testPasswordRemoved() { + void passwordRemoved() { ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(authenticationManager, providerTokenServices, clientDetailsService, requestFactory); OAuth2AccessToken token = granter.grant("password", tokenRequest); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java index eecb1b89acc..723276533de 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java @@ -31,7 +31,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java index d3e9c334fae..33b6c114a33 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java @@ -15,7 +15,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java index 06b1cfaf713..c070f5166da 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java @@ -28,7 +28,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java index 6e9f5827650..986dde1c3d0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java @@ -27,7 +27,7 @@ import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java index f4a2c5c81d9..c63a58129a1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java @@ -24,9 +24,7 @@ import java.util.Collections; import java.util.Date; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java index 7161040ab2d..774daf4fac6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java @@ -14,7 +14,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java index 60387466955..bf8c4152685 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java @@ -15,7 +15,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Moved test class of from spring-security-oauth2 into UAA diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java index fe9527bc28b..e9a00712604 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java @@ -32,9 +32,7 @@ import java.util.Random; import java.util.stream.Stream; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.token.RevocableToken.TokenType.ACCESS_TOKEN; import static org.cloudfoundry.identity.uaa.oauth.token.RevocableToken.TokenType.REFRESH_TOKEN; import static org.mockito.Mockito.eq; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java index 87e9b1a80d0..7c61dda4334 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/KeyInfoServiceTests.java @@ -17,7 +17,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; @@ -104,7 +103,7 @@ void signedProviderAsymmetricKeys() { }); jwkSet = new JWKSet(jwkList); assertThat(jwkSet).isNotNull(); - assertThat(jwkSet.size()).isEqualTo(1); + assertThat(jwkSet.size()).isOne(); } @Test @@ -152,14 +151,14 @@ void activeKeyFallsBackToLegacyKey() { } @Test - void tokenEndpointUrl_whenIssuerIsNull() throws URISyntaxException { + void tokenEndpointUrl_whenIssuerIsNull() throws Exception { configureDefaultZoneKeys(Collections.emptyMap()); assertThat(keyInfoService.getTokenEndpointUrl()).isEqualTo("https://localhost/uaa/oauth/token"); } @Test - void tokenEndpointUrl_whenIssuerSet() throws URISyntaxException { + void tokenEndpointUrl_whenIssuerSet() throws Exception { configureDefaultZoneKeys(Collections.emptyMap()); IdentityZoneHolder.get().getConfig().setIssuer("https://issuer.set/uaa"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java index a0b36ee780a..bca51c0ff1c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java @@ -2,7 +2,6 @@ import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidGrantException; -import org.cloudfoundry.identity.uaa.oauth.pkce.PkceValidationException; import org.cloudfoundry.identity.uaa.oauth.pkce.PkceValidationService; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Authentication; @@ -20,7 +19,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.CLIENT_AUTH_NONE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; @@ -86,13 +85,13 @@ void setup() { } @Test - void getOAuth2Authentication() throws PkceValidationException { + void getOAuth2Authentication() throws Exception { when(pkceValidationService.checkAndValidate(any(), any(), any())).thenReturn(false); assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> granter.getOAuth2Authentication((ClientDetails) requestingClient, tokenRequest)); } @Test - void getOAuth2AuthenticationMethod() throws PkceValidationException { + void getOAuth2AuthenticationMethod() throws Exception { HashMap authMap = new HashMap(); authMap.put(ClaimConstants.CLIENT_AUTH_METHOD, CLIENT_AUTH_NONE); when(pkceValidationService.checkAndValidate(any(), any(), any())).thenReturn(true); @@ -103,7 +102,7 @@ void getOAuth2AuthenticationMethod() throws PkceValidationException { } @Test - void getOAuth2AuthenticationNoMethod() throws PkceValidationException { + void getOAuth2AuthenticationNoMethod() throws Exception { HashMap authMap = new HashMap(); authMap.put(ClaimConstants.CLIENT_AUTH_METHOD, null); when(pkceValidationService.checkAndValidate(any(), any(), any())).thenReturn(true); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java index 3110ab45cfd..d8dc8983676 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java @@ -39,7 +39,7 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.jwt.JwtHelperX5tTest.CERTIFICATE_1; import static org.cloudfoundry.identity.uaa.oauth.jwt.JwtHelperX5tTest.SIGNING_KEY_1; import static org.cloudfoundry.identity.uaa.util.UaaStringUtils.DEFAULT_UAA_URL; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java index c21d78061bb..5f4dff4c901 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java @@ -16,9 +16,7 @@ import java.util.Set; import static java.util.Collections.emptyMap; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -66,7 +64,6 @@ void postAllowsQueryStringByDefault() throws Exception { void setAllowedRequestMethods() { Set methods = (Set) ReflectionTestUtils.getField(endpoint, "allowedRequestMethods"); assertThat(methods) - .hasSize(2) .containsExactlyInAnyOrder(POST, GET); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java index 7c028a606bc..c3b6eacb62c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java @@ -39,7 +39,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.CLIENT_ID; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.JTI; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java index 0507590eb3c..f2abbb437bc 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java @@ -28,7 +28,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.ROLES; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.USER_ATTRIBUTES; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.USER_ID; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java index 09926a4fdc3..a93ba6d4533 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java @@ -16,7 +16,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -44,7 +44,7 @@ void buildPasscodeInformationForUserAttributes() { assertThat(passcodeInformation.getUsername()).isEqualTo(uaaPrincipal.getName()); assertThat(passcodeInformation.getOrigin()).isEqualTo(uaaPrincipal.getOrigin()); assertThat(passcodeInformation.getUserId()).isEqualTo(uaaPrincipal.getId()); - assertThat(passcodeInformation.getSamlAuthorities()).isEqualTo(Collections.emptyList()); + assertThat(passcodeInformation.getSamlAuthorities()).containsExactlyElementsOf(Collections.emptyList()); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java index f3328d5081c..4c2acbb67fc 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java @@ -840,8 +840,7 @@ private static IdentityProvider result = jdbcIdentityProviderProvisioning.retrieveActiveByTypes(otherZoneId1, types); final Set idsInResult = result.stream().map(IdentityProvider::getId).collect(toSet()); - assertThat(idsInResult).hasSize(expectedIdpIds.size()); + assertThat(idsInResult).hasSameSizeAs(expectedIdpIds); for (final String id : expectedIdpIds) { assertThat(idsInResult).contains(id); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java index f069ca8cd35..3df2cbc6a68 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/DynamicPasswordComparatorTests.java @@ -60,6 +60,7 @@ void encodePassword() { comparator.encode("test"); fail("Method and test not implemented yet."); } catch (UnsupportedOperationException _) { + // ignore } } @@ -69,6 +70,7 @@ void isPasswordValid() { comparator.matches("test", "test"); fail("Method and test not implemented yet."); } catch (UnsupportedOperationException _) { + // ignore } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java index c85ba5495b3..ac22d7839df 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java @@ -31,9 +31,7 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_PROPERTY_TYPES; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_SSL_TLS; @@ -431,9 +429,9 @@ void search_and_compare_with_groups_1_config_and_custom_attributes() { void setEmailDomain() { LdapIdentityProviderDefinition def = new LdapIdentityProviderDefinition(); def.setEmailDomain(Collections.singletonList("test.com")); - assertThat(def.getEmailDomain().getFirst()).isEqualTo("test.com"); + assertThat(def.getEmailDomain()).first().isEqualTo("test.com"); def = JsonUtils.readValue(JsonUtils.writeValueAsString(def), LdapIdentityProviderDefinition.class); - assertThat(def.getEmailDomain().getFirst()).isEqualTo("test.com"); + assertThat(def.getEmailDomain()).first().isEqualTo("test.com"); } @Test @@ -442,9 +440,9 @@ void set_external_groups_whitelist() { List externalGroupsWhitelist = new ArrayList<>(); externalGroupsWhitelist.add("value"); def.setExternalGroupsWhitelist(externalGroupsWhitelist); - assertThat(def.getExternalGroupsWhitelist()).isEqualTo(Collections.singletonList("value")); + assertThat(def.getExternalGroupsWhitelist()).containsExactlyElementsOf(Collections.singletonList("value")); def = JsonUtils.readValue(JsonUtils.writeValueAsString(def), LdapIdentityProviderDefinition.class); - assertThat(def.getExternalGroupsWhitelist()).isEqualTo(Collections.singletonList("value")); + assertThat(def.getExternalGroupsWhitelist()).containsExactlyElementsOf(Collections.singletonList("value")); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java index 08e261f2d34..ac0cab56f13 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java @@ -28,7 +28,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_TLS_EXTERNAL; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_TLS_NONE; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_TLS_SIMPLE; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java index 5287cfb396f..9ec6fb59ec6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java @@ -14,14 +14,12 @@ import jakarta.servlet.FilterChain; import jakarta.servlet.RequestDispatcher; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; -import java.io.IOException; import java.util.function.Consumer; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -46,7 +44,7 @@ void setUp() { class WhenAuthenticationSucceeds { @Test - void itShouldCallTheNextFilter() throws IOException, ServletException { + void itShouldCallTheNextFilter() throws Exception { externalOAuthAuthenticationFilter = new ExternalOAuthAuthenticationFilter(externalOAuthAuthenticationManager, null); HttpServletRequest mockRequest = mockRedirectRequest(ORIGIN_KEY, request -> { mockAuthenticationInRequest(request); @@ -60,7 +58,7 @@ void itShouldCallTheNextFilter() throws IOException, ServletException { } @Test - void itCallsTheSuccessHandler() throws IOException, ServletException { + void itCallsTheSuccessHandler() throws Exception { AccountSavingAuthenticationSuccessHandler successHandler = mock(AccountSavingAuthenticationSuccessHandler.class); Authentication mockAuthentication = mock(Authentication.class); when(externalOAuthAuthenticationManager.authenticate(any())).thenReturn(mockAuthentication); @@ -89,7 +87,7 @@ void setUp() { } @Test - void itShouldNotCallTheNextFilter() throws IOException, ServletException { + void itShouldNotCallTheNextFilter() throws Exception { HttpServletRequest mockRequest = mockRedirectRequest(ORIGIN_KEY, request -> { mockAuthenticationInRequest(request); mockStateParamInRequest(request, OAUTH_STATE); @@ -111,7 +109,7 @@ void setUp() { } @Test - void itThrowsIfNoSession() throws IOException, ServletException { + void itThrowsIfNoSession() throws Exception { HttpServletRequest mockRequest = mockRedirectRequest(false, ORIGIN_KEY, request -> { mockAuthenticationInRequest(request); mockStateParamInRequest(request, OAUTH_STATE); @@ -124,7 +122,7 @@ void itThrowsIfNoSession() throws IOException, ServletException { } @Test - void itThrowsIfNoStateInSession() throws IOException, ServletException { + void itThrowsIfNoStateInSession() throws Exception { HttpServletRequest mockRequest = mockRedirectRequest(ORIGIN_KEY, request -> { mockAuthenticationInRequest(request); mockStateParamInRequest(request, OAUTH_STATE); @@ -137,7 +135,7 @@ void itThrowsIfNoStateInSession() throws IOException, ServletException { } @Test - void itThrowsIfNoStateInRequest() throws IOException, ServletException { + void itThrowsIfNoStateInRequest() throws Exception { HttpServletRequest mockRequest = mockRedirectRequest(ORIGIN_KEY, request -> { mockAuthenticationInRequest(request); mockStateParamInSession(request.getSession(), ORIGIN_KEY, OAUTH_STATE); @@ -150,7 +148,7 @@ void itThrowsIfNoStateInRequest() throws IOException, ServletException { } @Test - void itThrowsIfStateIsMismatched() throws IOException, ServletException { + void itThrowsIfStateIsMismatched() throws Exception { HttpServletRequest mockRequest = mockRedirectRequest(ORIGIN_KEY, request -> { mockAuthenticationInRequest(request); mockStateParamInRequest(request, "surprise"); @@ -173,7 +171,7 @@ void setUp() { } @Test - void itRedirects() throws IOException, ServletException { + void itRedirects() throws Exception { RequestDispatcher mockRequestDispatcher = mock(RequestDispatcher.class); HttpServletRequest mockRequest = mockRedirectRequest(ORIGIN_KEY, request -> { @@ -190,7 +188,7 @@ void itRedirects() throws IOException, ServletException { @Test void itRedirects_EvenWhenTheStateHasNotYetBeenPulledFromTheHashFragmentYet() - throws IOException, ServletException { + throws Exception { RequestDispatcher mockRequestDispatcher = mock(RequestDispatcher.class); HttpServletRequest mockRequest = mockRedirectRequest(ORIGIN_KEY, request -> diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java index 6dd31a442e1..546a9b25a4c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java @@ -5,6 +5,7 @@ import com.nimbusds.jose.JWSSigner; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.RandomStringUtils; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.AccountNotPreCreatedException; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal; @@ -94,7 +95,6 @@ import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.OAUTH20; @@ -341,8 +341,7 @@ void unable_to_resolve_to_single_provider() { String zoneId = IdentityZoneHolder.get().getId(); when(provisioning.retrieveAll(eq(true), eq(zoneId))).thenReturn(emptyList()); assertThatThrownBy(() -> externalOAuthAuthenticationManager.getExternalAuthenticationDetails(xCodeToken)) - .isInstanceOf(InsufficientAuthenticationException.class) - .hasMessage("Unable to map issuer, %s , to a single registered provider".formatted(claims.get(ISS))); + .isInstanceOf(InsufficientAuthenticationException.class).hasMessage("Unable to map issuer, %s , to a single registered provider", claims.get(ISS)); } @Test @@ -377,7 +376,8 @@ void when_unable_to_find_an_idp_that_matches_the_id_token_issuer() { claims.put("iss", issuerURL); CompositeToken token = getCompositeAccessToken(); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> externalOAuthAuthenticationManager.resolveOriginProvider(token.getIdTokenValue())); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.resolveOriginProvider(token.getIdTokenValue())) + .asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test @@ -423,7 +423,8 @@ void when_exchanging_an_id_token_issuedby_the_uaa_idp_but_not_uaa_origin(String xCodeToken.setIdToken(idToken); xCodeToken.setOrigin(null); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> externalOAuthAuthenticationManager.getExternalAuthenticationDetails(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.getExternalAuthenticationDetails(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test @@ -499,7 +500,7 @@ void when_exchanging_an_id_token_retrieved_by_an_external_oidc_idp_for_an_access } @Test - void discoveryURL_is_used() throws MalformedURLException { + void discoveryURL_is_used() throws Exception { URL authUrl = config.getAuthUrl(); URL tokenUrl = config.getTokenUrl(); @@ -801,7 +802,8 @@ void doesNotCreateShadowUserAndFailsAuthentication_IfAddShadowUserOnLoginIsFalse config.setAddShadowUserOnLogin(false); mockToken(); - assertThatExceptionOfType(AccountNotPreCreatedException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(AccountNotPreCreatedException.class)); } @Test @@ -810,14 +812,16 @@ void rejectTokenWithInvalidSignature() { config.setTokenKey("WRONG_KEY"); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void rejectTokenWithInvalidSignatureAccordingToTokenKeyEndpoint() throws Exception { configureTokenKeyResponse("http://localhost/token_key", INVALID_RSA_SIGNING_KEY, "wrongKey"); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -825,7 +829,8 @@ void rejectTokenWithInvalidIssuer() { claims.put("iss", "http://wrong.issuer/"); mockToken(); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -833,7 +838,8 @@ void rejectExpiredToken() { claims.put("exp", Instant.now().getEpochSecond() - 1); mockToken(); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -841,7 +847,8 @@ void rejectWrongAudience() { claims.put("aud", Arrays.asList("another_client", "a_complete_stranger")); mockToken(); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -928,7 +935,7 @@ void invitedUser_becomesVerifiedOnAccept() { ArgumentCaptor userArgumentCaptor = ArgumentCaptor.forClass(ApplicationEvent.class); verify(publisher, times(3)).publishEvent(userArgumentCaptor.capture()); assertThat(userArgumentCaptor.getAllValues()).hasSize(3); - assertThat(userArgumentCaptor.getAllValues().getFirst()).isInstanceOf(InvitedUserAuthenticatedEvent.class); + assertThat(userArgumentCaptor.getAllValues()).first().isInstanceOf(InvitedUserAuthenticatedEvent.class); RequestContextHolder.resetRequestAttributes(); } @@ -1055,10 +1062,11 @@ void getUserIssuerOverrideUsedNoMatch() { config.setIssuer(ISSUER); mockToken(); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> externalOAuthAuthenticationManager.getUser( + assertThatThrownBy(() -> externalOAuthAuthenticationManager.getUser( xCodeToken, externalOAuthAuthenticationManager.getExternalAuthenticationDetails(xCodeToken) - )); + )) + .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -1111,7 +1119,8 @@ void tokenCannotBeFetchedFromCodeBecauseOfServerError() { when(provisioning.retrieveByOrigin(eq(ORIGIN), anyString())).thenReturn(identityProvider); mockUaaServer.expect(requestTo("http://localhost/oauth/token")).andRespond(withServerError()); - assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(HttpServerErrorException.class)); } @Test @@ -1121,7 +1130,8 @@ void tokenCannotBeFetchedFromInvalidCode() { when(provisioning.retrieveByOrigin(eq(ORIGIN), anyString())).thenReturn(identityProvider); mockUaaServer.expect(requestTo("http://localhost/oauth/token")).andRespond(withBadRequest()); - assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) + .asInstanceOf(InstanceOfAssertFactories.throwable(HttpClientErrorException.class)); } @Test @@ -1227,13 +1237,13 @@ void custom_user_attributes_are_stored() { UaaAuthentication authentication = (UaaAuthentication) externalOAuthAuthenticationManager.authenticate(xCodeToken); - assertThat(authentication.getUserAttributes()).isEqualTo(map); + assertThat(authentication.getUserAttributes()).containsExactlyInAnyOrderEntriesOf(map); assertThat(authentication.getExternalGroups()).containsAll(scopes); UserInfo info = new UserInfo() .setUserAttributes(map) .setRoles(scopes); UserInfo actualUserInfo = externalOAuthAuthenticationManager.getUserDatabase().getUserInfo(authentication.getPrincipal().getId()); - assertThat(info.getUserAttributes()).isEqualTo(actualUserInfo.getUserAttributes()); + assertThat(info.getUserAttributes()).containsExactlyInAnyOrderEntriesOf(actualUserInfo.getUserAttributes()); assertThat(actualUserInfo.getRoles()).containsAll(info.getRoles()); UaaUser actualUser = externalOAuthAuthenticationManager.getUserDatabase().retrieveUserByName("12345", "the_origin"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerTest.java index 3aba7797f69..117ee43d5c7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerTest.java @@ -69,7 +69,6 @@ import java.net.MalformedURLException; import java.net.URI; -import java.text.ParseException; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -705,7 +704,7 @@ protected > String } @Test - void fetchOidcMetadata() throws OidcMetadataFetchingException { + void fetchOidcMetadata() throws Exception { OIDCIdentityProviderDefinition mockedProviderDefinition = mock(OIDCIdentityProviderDefinition.class); OidcMetadataFetcher mockedOidcMetadataFetcher = mock(OidcMetadataFetcher.class); authManager = new ExternalOAuthAuthenticationManager(identityProviderProvisioning, new IdentityZoneManagerImpl(), new RestTemplate(), new RestTemplate(), tokenEndpointBuilder, new KeyInfoService(UAA_ISSUER_BASE_URL), mockedOidcMetadataFetcher, false); @@ -753,7 +752,7 @@ void oidcPasswordGrantProviderNoRelyingPartyCredentials() { @Test - void getOidcProxyIdpForTokenExchangeSuccess() throws MalformedURLException { + void getOidcProxyIdpForTokenExchangeSuccess() throws Exception { IdentityProvider idp = mockOidcIdentityProvider(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("login_hint", new UaaLoginHint("idp").toString()); @@ -770,7 +769,7 @@ void getOidcProxyIdpForTokenExchangeSuccess() throws MalformedURLException { } @Test - void getOidcProxyIdpForTokenExchangeNotEnabled() throws MalformedURLException { + void getOidcProxyIdpForTokenExchangeNotEnabled() throws Exception { IdentityProvider idp = mockOidcIdentityProvider(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("login_hint", new UaaLoginHint("idp").toString()); @@ -788,7 +787,7 @@ void getOidcProxyIdpForTokenExchangeNotEnabled() throws MalformedURLException { } @Test - void getOidcProxyIdpForTokenExchangeDbException() throws MalformedURLException { + void getOidcProxyIdpForTokenExchangeDbException() throws Exception { IdentityProvider idp = mockOidcIdentityProvider(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("login_hint", new UaaLoginHint("idp").toString()); @@ -802,7 +801,7 @@ void getOidcProxyIdpForTokenExchangeDbException() throws MalformedURLException { } @Test - void getOidcProxyIdpForTokenExchangeNoResult() throws MalformedURLException { + void getOidcProxyIdpForTokenExchangeNoResult() throws Exception { IdentityProvider idp = mockOidcIdentityProvider(); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("login_hint", new UaaLoginHint("idp").toString()); @@ -854,7 +853,7 @@ void oidcPasswordGrant_requireAuthenticationStatement() { } @Test - void oidcPasswordGrantProviderJwtClientCredentials() throws ParseException, JOSEException, MalformedURLException { + void oidcPasswordGrantProviderJwtClientCredentials() throws Exception { // Given KeyInfoService keyInfoService = mockKeyInfoService(); ResponseEntity responseEntity = mock(ResponseEntity.class); @@ -882,15 +881,15 @@ void oidcPasswordGrantProviderJwtClientCredentials() throws ParseException, JOSE /* verify client assertion according OIDC private_key_jwt */ assertThat(httpEntityBody).isNotNull(); final List clientAssertion = httpEntityBody.get("client_assertion"); - assertThat(clientAssertion).isNotNull().isNotEmpty(); + assertThat(clientAssertion).isNotEmpty(); JWTClaimsSet jwtClaimsSet = JWTParser.parse((String) clientAssertion.getFirst()).getJWTClaimsSet(); - assertThat(jwtClaimsSet.getAudience()).isEqualTo(Collections.singletonList("http://localhost:8080/uaa/oauth/token")); + assertThat(jwtClaimsSet.getAudience()).containsExactlyElementsOf(Collections.singletonList("http://localhost:8080/uaa/oauth/token")); assertThat(jwtClaimsSet.getSubject()).isEqualTo("identity"); assertThat(jwtClaimsSet.getIssuer()).isEqualTo("identity"); } @Test - void oidcJwtBearerProviderJwtClientCredentials() throws ParseException, JOSEException, MalformedURLException { + void oidcJwtBearerProviderJwtClientCredentials() throws Exception { // Given KeyInfoService keyInfoService = mockKeyInfoService(); ResponseEntity responseEntity = mock(ResponseEntity.class); @@ -921,15 +920,15 @@ void oidcJwtBearerProviderJwtClientCredentials() throws ParseException, JOSEExce /* verify client assertion according OIDC private_key_jwt */ assertThat(httpEntityBody).isNotNull(); final List clientAssertion = httpEntityBody.get("client_assertion"); - assertThat(clientAssertion).isNotNull().isNotEmpty(); + assertThat(clientAssertion).isNotEmpty(); JWTClaimsSet jwtClaimsSet = JWTParser.parse((String) clientAssertion.getFirst()).getJWTClaimsSet(); - assertThat(jwtClaimsSet.getAudience()).isEqualTo(Collections.singletonList("http://localhost:8080/uaa/oauth/token")); + assertThat(jwtClaimsSet.getAudience()).containsExactlyElementsOf(Collections.singletonList("http://localhost:8080/uaa/oauth/token")); assertThat(jwtClaimsSet.getSubject()).isEqualTo("identity"); assertThat(jwtClaimsSet.getIssuer()).isEqualTo("identity"); } @Test - void oidcJwtBearerProviderProxyThrowException() throws JOSEException, MalformedURLException { + void oidcJwtBearerProviderProxyThrowException() throws Exception { // Given KeyInfoService keyInfoService = mockKeyInfoService(); UaaAuthenticationDetails uaaAuthenticationDetails = mock(UaaAuthenticationDetails.class); @@ -953,13 +952,13 @@ void oidcJwtBearerProviderProxyThrowException() throws JOSEException, MalformedU HttpEntity httpEntity = httpEntityArgumentCaptor.getValue(); HttpHeaders httpHeaders = httpEntity.getHeaders(); assertThat(httpHeaders.containsHeader("Authorization")).isTrue(); - assertThat(httpHeaders.get("Authorization")).isEqualTo(Collections.singletonList("Basic aWRlbnRpdHk6c2VjcmV0")); + assertThat(httpHeaders.get("Authorization")).containsExactlyElementsOf(Collections.singletonList("Basic aWRlbnRpdHk6c2VjcmV0")); assertThat(httpHeaders.containsHeader("Accept")).isTrue(); - assertThat(httpHeaders.get("Content-Type")).isEqualTo(Collections.singletonList("application/x-www-form-urlencoded")); + assertThat(httpHeaders.get("Content-Type")).containsExactlyElementsOf(Collections.singletonList("application/x-www-form-urlencoded")); } @Test - void oidcPasswordGrantWithForwardHeader() throws JOSEException, MalformedURLException { + void oidcPasswordGrantWithForwardHeader() throws Exception { IdentityProvider identityProvider = mockOidcIdentityProvider(); OIDCIdentityProviderDefinition config = identityProvider.getConfig(); KeyInfoService keyInfoService = mockKeyInfoService(); @@ -1009,17 +1008,17 @@ void oidcPasswordGrantWithForwardHeader() throws JOSEException, MalformedURLExce .containsEntry("password", Collections.singletonList("koala")); HttpHeaders headers = httpEntity.getHeaders(); - assertThat(headers.getAccept()).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); + assertThat(headers.getAccept()).containsExactlyElementsOf(Collections.singletonList(MediaType.APPLICATION_JSON)); assertThat(headers.getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED); assertAuthorizationHeaderIsSetAndStartsWithBasic(headers); assertThat(headers.containsHeader("X-Forwarded-For")).isTrue(); final List xForwardedForHeaders = headers.get("X-Forwarded-For"); assertThat(xForwardedForHeaders).hasSize(1); - assertThat(xForwardedForHeaders.getFirst()).isEqualTo("203.0.113.1"); + assertThat(xForwardedForHeaders).first().isEqualTo("203.0.113.1"); } @Test - void oidcPasswordGrant_credentialsMustBeStringButNoSecretNeeded() throws MalformedURLException, JOSEException { + void oidcPasswordGrant_credentialsMustBeStringButNoSecretNeeded() throws Exception { RestTemplate restTemplate = mock(RestTemplate.class); ResponseEntity responseEntity = mock(ResponseEntity.class); @@ -1042,7 +1041,7 @@ void oidcPasswordGrant_credentialsMustBeStringButNoSecretNeeded() throws Malform } @Test - void oidcPasswordGrantWithPrompts() throws MalformedURLException, JOSEException { + void oidcPasswordGrantWithPrompts() throws Exception { KeyInfoService keyInfoService = mockKeyInfoService(); IdentityProvider identityProvider = mockOidcIdentityProvider(); OIDCIdentityProviderDefinition config = identityProvider.getConfig(); @@ -1114,7 +1113,7 @@ void oidcPasswordGrantWithPrompts() throws MalformedURLException, JOSEException .doesNotContainKey("missingvalue"); HttpHeaders headers = httpEntity.getHeaders(); - assertThat(headers.getAccept()).isEqualTo(Collections.singletonList(MediaType.APPLICATION_JSON)); + assertThat(headers.getAccept()).containsExactlyElementsOf(Collections.singletonList(MediaType.APPLICATION_JSON)); assertThat(headers.getContentType()).isEqualTo(MediaType.APPLICATION_FORM_URLENCODED); assertAuthorizationHeaderIsSetAndStartsWithBasic(headers); assertThat(headers.containsHeader("X-Forwarded-For")).isFalse(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java index 0fdc515a3d9..7c430381a90 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java @@ -12,7 +12,7 @@ import java.util.Collections; import java.util.Map; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class ExternalOAuthIdentityProviderConfigValidatorTest { private AbstractExternalOAuthIdentityProviderDefinition definition; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthLogoutSuccessHandlerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthLogoutSuccessHandlerTest.java index c98c3dd0b22..322498473b9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthLogoutSuccessHandlerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthLogoutSuccessHandlerTest.java @@ -133,20 +133,20 @@ void constructOAuthProviderLogoutUrl() { } @Test - void getLogoutUrl() throws OidcMetadataFetchingException { + void getLogoutUrl() throws Exception { assertThat(oAuthLogoutHandler.getLogoutUrl(oAuthIdentityProviderDefinition)).isEqualTo(UAA_ENDSESSION_URL); verify(oidcMetadataFetcher, times(0)).fetchMetadataAndUpdateDefinition(oAuthIdentityProviderDefinition); } @Test - void getNewFetchedLogoutUrl() throws OidcMetadataFetchingException { + void getNewFetchedLogoutUrl() throws Exception { oAuthIdentityProviderDefinition.setLogoutUrl(null); assertThat(oAuthLogoutHandler.getLogoutUrl(oAuthIdentityProviderDefinition)).isNull(); verify(oidcMetadataFetcher, times(1)).fetchMetadataAndUpdateDefinition(oAuthIdentityProviderDefinition); } @Test - void getNewInvalidFetchedLogoutUrl() throws OidcMetadataFetchingException { + void getNewInvalidFetchedLogoutUrl() throws Exception { oAuthIdentityProviderDefinition.setLogoutUrl(null); doThrow(new OidcMetadataFetchingException("")).when(oidcMetadataFetcher).fetchMetadataAndUpdateDefinition(oAuthIdentityProviderDefinition); assertThat(oAuthLogoutHandler.getLogoutUrl(oAuthIdentityProviderDefinition)).isNull(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthProviderConfiguratorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthProviderConfiguratorTests.java index b1f76990223..983997c7d28 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthProviderConfiguratorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthProviderConfiguratorTests.java @@ -191,7 +191,7 @@ void retrieveActiveByNullType() { @ParameterizedTest @MethodSource - void retrieveActiveByTypes(final String[] types) throws OidcMetadataFetchingException { + void retrieveActiveByTypes(final String[] types) throws Exception { final String zoneId = RandomStringUtils.randomAlphanumeric(8); // eliminate duplicates @@ -357,8 +357,7 @@ void issuer_not_found() { when(identityZoneManager.getCurrentIdentityZoneId()).thenReturn(IdentityZone.getUaaZoneId()); when(identityZoneManager.getCurrentIdentityZone()).thenReturn(IdentityZone.getUaa()); assertThatThrownBy(() -> configurator.retrieveByIssuer(issuer, IdentityZone.getUaaZoneId())) - .isInstanceOf(IncorrectResultSizeDataAccessException.class) - .hasMessage("Active provider with issuer[%s] not found".formatted(issuer)); + .isInstanceOf(IncorrectResultSizeDataAccessException.class).hasMessage("Active provider with issuer[%s] not found", issuer); } @Test @@ -375,8 +374,7 @@ void duplicate_issuer_found() throws Exception { .fetchMetadataAndUpdateDefinition(any(OIDCIdentityProviderDefinition.class)); assertThatThrownBy(() -> configurator.retrieveByIssuer(issuer, IdentityZone.getUaaZoneId())) - .isInstanceOf(IncorrectResultSizeDataAccessException.class) - .hasMessage("Duplicate providers with issuer[%s] not found".formatted(issuer)); + .isInstanceOf(IncorrectResultSizeDataAccessException.class).hasMessage("Duplicate providers with issuer[%s] not found", issuer); } @Test @@ -458,27 +456,27 @@ void getIdpAuthenticationUrl_includesPkce() { } @Test - void oidcIdPPkceEqual() throws CloneNotSupportedException { + void oidcIdPPkceEqual() throws Exception { OIDCIdentityProviderDefinition oidc1 = (OIDCIdentityProviderDefinition) oidc.clone(); assertThat(oidc1).isEqualTo(oidc); } @Test - void oidcIdPPkceNotEqual() throws CloneNotSupportedException { + void oidcIdPPkceNotEqual() throws Exception { OIDCIdentityProviderDefinition oidc1 = (OIDCIdentityProviderDefinition) oidc.clone(); oidc.setPkce(false); assertThat(oidc1).isNotEqualTo(oidc); } @Test - void oidcIdPPkceHashCodeNotEqual() throws CloneNotSupportedException { + void oidcIdPPkceHashCodeNotEqual() throws Exception { OIDCIdentityProviderDefinition oidc1 = (OIDCIdentityProviderDefinition) oidc.clone(); oidc.setPkce(false); assertThat(oidc1).doesNotHaveSameHashCodeAs(oidc); } @Test - void oidcIdPPkceHashCodeEqual() throws CloneNotSupportedException { + void oidcIdPPkceHashCodeEqual() throws Exception { OIDCIdentityProviderDefinition oidc1 = (OIDCIdentityProviderDefinition) oidc.clone(); assertThat(oidc1).hasSameHashCodeAs(oidc); } @@ -496,7 +494,7 @@ void getIdpAuthenticationUrl_deactivatesPkce() { } @Test - void getIdpAuthenticationUrl_withOnlyDiscoveryUrlForOIDCProvider() throws MalformedURLException, OidcMetadataFetchingException { + void getIdpAuthenticationUrl_withOnlyDiscoveryUrlForOIDCProvider() throws Exception { String discoveryUrl = "https://accounts.google.com/.well-known/openid-configuration"; oidc.setDiscoveryUrl(URI.create(discoveryUrl).toURL()); oidc.setAuthUrl(null); @@ -556,7 +554,7 @@ void getIdpAuthenticationUrl_hasAllRequiredQueryParametersForOauth() { } @Test - void excludeUnreachableOidcProvider() throws OidcMetadataFetchingException { + void excludeUnreachableOidcProvider() throws Exception { when(mockIdentityProviderProvisioning.retrieveAll(eq(true), anyString())).thenReturn(Arrays.asList(oidcProvider, oauthProvider, new IdentityProvider<>().setType(LDAP))); doThrow(new NullPointerException("")).when(mockOidcMetadataFetcher) diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java index 22915e36054..f3302f1f2a4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java @@ -28,7 +28,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.GROUP_ATTRIBUTE_NAME; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.STORE_CUSTOM_ATTRIBUTES_NAME; import static org.cloudfoundry.identity.uaa.util.UaaMapUtils.entry; @@ -103,7 +103,7 @@ void external_group_mapping_in_body() { idpDefinitionMap.put("groupMappingMode", "AS_SCOPES"); idpDefinitionMap.put("attributeMappings", externalGroupMapping); factoryBean.setCommonProperties(idpDefinitionMap, providerDefinition); - assertThat(providerDefinition.getAttributeMappings()).isEqualTo(externalGroupMapping); + assertThat(providerDefinition.getAttributeMappings()).containsExactlyInAnyOrderEntriesOf(externalGroupMapping); assertThat(providerDefinition.getGroupMappingMode()).hasToString("AS_SCOPES"); } @@ -114,7 +114,7 @@ void external_group_mapping_default_in_body() { ); idpDefinitionMap.put("attributeMappings", externalGroupMapping); factoryBean.setCommonProperties(idpDefinitionMap, providerDefinition); - assertThat(providerDefinition.getAttributeMappings()).isEqualTo(externalGroupMapping); + assertThat(providerDefinition.getAttributeMappings()).containsExactlyInAnyOrderEntriesOf(externalGroupMapping); assertThat(providerDefinition.getGroupMappingMode()).isNull(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java index bf952013103..f36adfc7e3e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java @@ -21,7 +21,7 @@ import java.net.URI; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; @@ -65,7 +65,7 @@ void setup() throws MalformedURLException { } @Test - void shouldFavorUsingConfiguredIdentityProviderProperties() throws OidcMetadataFetchingException, MalformedURLException { + void shouldFavorUsingConfiguredIdentityProviderProperties() throws Exception { definition.setAuthUrl(URI.create("http://authz.should.not.have.been.updated").toURL()); definition.setTokenUrl(URI.create("http://token.should.not.have.been.updated").toURL()); definition.setUserInfoUrl(URI.create("http://userinfo.should.not.have.been.updated").toURL()); @@ -85,7 +85,7 @@ void shouldFavorUsingConfiguredIdentityProviderProperties() throws OidcMetadataF } @Test - void givenConfiguredIdentityProviderPropertiesAreNotSet_shouldUseOidcMetadata() throws OidcMetadataFetchingException { + void givenConfiguredIdentityProviderPropertiesAreNotSet_shouldUseOidcMetadata() throws Exception { when(urlContentCache.getUrlContent(anyString(), any(RestTemplate.class))) .thenReturn(JsonUtils.writeValueAsBytes(oidcMetadata)); @@ -100,7 +100,7 @@ void givenConfiguredIdentityProviderPropertiesAreNotSet_shouldUseOidcMetadata() } @Test - void shouldPerformDiscoveryUsingCache() throws OidcMetadataFetchingException, MalformedURLException { + void shouldPerformDiscoveryUsingCache() throws Exception { definition.setAuthUrl(URI.create("http://should.be.updated").toURL()); definition.setTokenUrl(URI.create("http://should.be.updated").toURL()); definition.setSkipSslValidation(false); @@ -118,7 +118,7 @@ void shouldPerformDiscoveryUsingCache() throws OidcMetadataFetchingException, Ma } @Test - void shouldPerformTokenKeyUrlUsingCache() throws OidcMetadataFetchingException, MalformedURLException { + void shouldPerformTokenKeyUrlUsingCache() throws Exception { definition.setTokenKeyUrl(URI.create("http://should.be.updated").toURL()); definition.setSkipSslValidation(false); @@ -135,7 +135,7 @@ void shouldPerformTokenKeyUrlUsingCache() throws OidcMetadataFetchingException, } @Test - void shouldPerformTokenKeyUrlNoCacheUsed() throws OidcMetadataFetchingException, MalformedURLException { + void shouldPerformTokenKeyUrlNoCacheUsed() throws Exception { definition.setTokenKeyUrl(URI.create("http://should.be.updated").toURL()); definition.setSkipSslValidation(false); definition.setCacheJwks(false); @@ -158,7 +158,7 @@ void shouldPerformTokenKeyUrlNoCacheUsed() throws OidcMetadataFetchingException, } @Test - void shouldPerformTokenKeyUrlNoCacheUsedError() throws MalformedURLException { + void shouldPerformTokenKeyUrlNoCacheUsedError() throws Exception { definition.setTokenKeyUrl(URI.create("http://should.be.updated").toURL()); definition.setSkipSslValidation(false); definition.setCacheJwks(false); @@ -187,7 +187,7 @@ void setup() { @Test @DisplayName("when the idp is configured without a discovery URL then it should retain the configured OAuth/OIDC endpoints") - void shouldNotPerformDiscovery() throws OidcMetadataFetchingException, MalformedURLException { + void shouldNotPerformDiscovery() throws Exception { definition.setAuthUrl(URI.create("http://authz.not.updated").toURL()); definition.setTokenUrl(URI.create("http://token.not.updated").toURL()); definition.setTokenKeyUrl(URI.create("http://jwk.not.updated").toURL()); @@ -220,7 +220,7 @@ void setup() throws MalformedURLException { } @Test - void failWithEmptyContent() throws OidcMetadataFetchingException, MalformedURLException { + void failWithEmptyContent() throws Exception { when(urlContentCache.getUrlContent(anyString(), any(RestTemplate.class), any(HttpMethod.class), any(HttpEntity.class))) .thenReturn("".getBytes()); @@ -229,7 +229,7 @@ void failWithEmptyContent() throws OidcMetadataFetchingException, MalformedURLEx } @Test - void failWithInvalidContent() throws OidcMetadataFetchingException, MalformedURLException { + void failWithInvalidContent() throws Exception { when(urlContentCache.getUrlContent(anyString(), any(RestTemplate.class), any(HttpMethod.class), any(HttpEntity.class))) .thenReturn("{x}".getBytes()); @@ -251,7 +251,7 @@ void setup() throws MalformedURLException { } @Test - void getConfigFromJwksUri() throws OidcMetadataFetchingException, MalformedURLException { + void getConfigFromJwksUri() throws Exception { JsonWebKeySet keys = metadataDiscoverer.fetchWebKeySet(new ClientJwtConfiguration("http://token_keys", null)); assertThat(keys).isNotNull(); @@ -260,7 +260,7 @@ void getConfigFromJwksUri() throws OidcMetadataFetchingException, MalformedURLEx } @Test - void getConfigFromJwks() throws OidcMetadataFetchingException, MalformedURLException { + void getConfigFromJwks() throws Exception { JsonWebKeySet keys = metadataDiscoverer.fetchWebKeySet(ClientJwtConfiguration.parse("{\"keys\":[{\"alg\":\"RS256\",\"e\":\"e\",\"kid\":\"a\",\"kty\":\"RSA\",\"n\":\"n\"}]}")); assertThat(keys).isNotNull(); @@ -269,7 +269,7 @@ void getConfigFromJwks() throws OidcMetadataFetchingException, MalformedURLExcep } @Test - void failWithInvalidConfig() throws OidcMetadataFetchingException, MalformedURLException { + void failWithInvalidConfig() throws Exception { assertThatExceptionOfType(OidcMetadataFetchingException.class).isThrownBy(() -> metadataDiscoverer.fetchWebKeySet(new ClientJwtConfiguration(null, null))); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderDataTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderDataTests.java index 27327ccbc75..d7edeebcb4d 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderDataTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/BootstrapSamlIdentityProviderDataTests.java @@ -240,8 +240,8 @@ private void testGetIdentityProviderDefinitions(int count, boolean addData) { Map attributeMappings = new HashMap<>(); attributeMappings.put("given_name", "first_name"); attributeMappings.put("external_groups", Collections.singletonList("roles")); - assertThat(idp.getAttributeMappings()).isEqualTo(attributeMappings); - assertThat(idp.getExternalGroupsWhitelist()).isEqualTo(asList("admin", "user")); + assertThat(idp.getAttributeMappings()).containsExactlyInAnyOrderEntriesOf(attributeMappings); + assertThat(idp.getExternalGroupsWhitelist()).containsExactlyElementsOf(asList("admin", "user")); assertThat(idp.isShowSamlLink()).isTrue(); assertThat(idp.isMetadataTrustCheck()).isTrue(); assertThat(idp.getEmailDomain()).contains("test.com", "test.org"); @@ -282,7 +282,7 @@ private void testGetIdentityProviderDefinitions(int count, boolean addData) { } case "custom-authncontext": { assertThat(idp.getAuthnContext()).hasSize(2); - assertThat(idp.getAuthnContext().getFirst()).isEqualTo("custom-context"); + assertThat(idp.getAuthnContext()).first().isEqualTo("custom-context"); assertThat(idp.getAuthnContext().get(1)).isEqualTo("another-context"); break; } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/DelegatingRelyingPartyRegistrationRepositoryTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/DelegatingRelyingPartyRegistrationRepositoryTest.java index 8f6e3fa3b68..8a3ea2403f7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/DelegatingRelyingPartyRegistrationRepositoryTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/DelegatingRelyingPartyRegistrationRepositoryTest.java @@ -12,7 +12,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java index 6e3bc95bfce..721e99b4ed7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUaaTests.java @@ -1,5 +1,4 @@ package org.cloudfoundry.identity.uaa.provider.saml; - import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal; @@ -83,7 +82,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.EMAIL_ATTRIBUTE_NAME; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.FAMILY_NAME_ATTRIBUTE_NAME; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.GIVEN_NAME_ATTRIBUTE_NAME; @@ -463,7 +461,7 @@ void addExternalGroupsToAuthenticationWithWhitelist() { providerProvisioning.update(provider, identityZoneManager.getCurrentIdentityZone().getId()); UaaAuthentication authentication = authenticate(); - assertThat(authentication.getExternalGroups()).isEqualTo(Collections.singleton(SAML_ADMIN)); + assertThat(authentication.getExternalGroups()).hasSameElementsAs(Collections.singleton(SAML_ADMIN)); } @Test @@ -545,12 +543,7 @@ private Map getUserAttributes(String firstName, @Test void updateExistingUserWithDifferentAttributes() throws Exception { - try { - userDatabase.retrieveUserByName(TEST_USERNAME, OriginKeys.SAML); - fail("user should not exist"); - } catch (UsernameNotFoundException _) { - // expected - } + assertThatThrownBy(() -> userDatabase.retrieveUserByName(TEST_USERNAME, OriginKeys.SAML)).isInstanceOf(UsernameNotFoundException.class); authenticate(); UaaUser user = userDatabase.retrieveUserByName(TEST_USERNAME, OriginKeys.SAML); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUnitTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUnitTests.java index 951f2989d33..b56aa342da6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUnitTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/OpenSaml5AuthenticationProviderUnitTests.java @@ -50,7 +50,6 @@ import javax.xml.namespace.QName; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -59,10 +58,7 @@ import java.util.function.Consumer; import static java.util.Map.entry; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; -import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; @@ -674,7 +670,7 @@ void authenticateWhenAuthenticationHasDetailsThenSucceeds() { } @Test - void writeObjectWhenTypeIsSaml2AuthenticationThenNoException() throws IOException { + void writeObjectWhenTypeIsSaml2AuthenticationThenNoException() throws Exception { Response response = response(); Assertion assertion = TestOpenSamlObjects.signed(assertion(), TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); @@ -736,8 +732,7 @@ void authenticateWhenResponseAuthenticationConverterConfiguredThenUses() { @Test void setResponseAuthenticationConverterWhenNullThenIllegalArgument() { // @formatter:off - assertThatIllegalArgumentException() - .isThrownBy(() -> this.provider.setResponseAuthenticationConverter(null)); + assertThatThrownBy(() -> this.provider.setResponseAuthenticationConverter(null)).isInstanceOf(IllegalArgumentException.class); // @formatter:on } @@ -762,7 +757,7 @@ void authenticateWhenResponseStatusIsSuccessThenSucceeds() { @Test void setResponseValidatorWhenNullThenIllegalArgument() { - assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setResponseValidator(null)); + assertThatThrownBy(() -> this.provider.setResponseValidator(null)).isInstanceOf(IllegalArgumentException.class); } @Test @@ -791,8 +786,7 @@ void authenticateWhenAssertionIssuerNotValidThenFailsWithInvalidIssuer() { assertion.setIssuer(TestOpenSamlObjects.issuer("https://invalid.idp.test/saml2/idp")); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); - assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> provider.authenticate(token)) - .withMessageContaining("did not match any valid issuers"); + assertThatThrownBy(() -> provider.authenticate(token)).isInstanceOf(Saml2AuthenticationException.class).hasMessageContaining("did not match any valid issuers"); } // gh-14931 diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/Saml2BearerGrantAuthenticationConverterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/Saml2BearerGrantAuthenticationConverterTest.java index 85a7cb18c99..31d1074f82d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/Saml2BearerGrantAuthenticationConverterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/Saml2BearerGrantAuthenticationConverterTest.java @@ -49,7 +49,6 @@ import javax.xml.namespace.QName; import java.security.Security; import java.io.ByteArrayOutputStream; -import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.charset.StandardCharsets; import java.time.Duration; @@ -380,7 +379,7 @@ void authenticateWhenAuthenticationHasDetailsThenSucceeds() { } @Test - void writeObjectWhenTypeIsSaml2AuthenticationThenNoException() throws IOException { + void writeObjectWhenTypeIsSaml2AuthenticationThenNoException() throws Exception { Assertion assertion = TestOpenSamlObjects.signed(assertion(), TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); Saml2AuthenticationToken token = token(signed(assertion), decrypting(verifying(registration()))); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfiguratorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfiguratorTests.java index ed887219734..29e40b861c7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfiguratorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlIdentityProviderConfiguratorTests.java @@ -233,7 +233,7 @@ FixedHttpMetaDataProvider createNonMockFixedHttpMetaDataProvider(SamlConfigurati } @Test - void shouldTimeoutOnReadWhenFetchingMetadataURL() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + void shouldTimeoutOnReadWhenFetchingMetadataURL() throws Exception { slowHttpServer.run(); // set read timeout to value that will cause read timeout before 1s samlConfiguration.setSocketReadTimeout(100); @@ -250,7 +250,7 @@ void shouldTimeoutOnReadWhenFetchingMetadataURL() throws NoSuchAlgorithmExceptio } @Test - void shouldTimeoutOnConnectingWhenFetchingMetadataURL() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { + void shouldTimeoutOnConnectingWhenFetchingMetadataURL() throws Exception { slowHttpServer.run(); // Set connection timeout to very low value to cause connect timeout samlConfiguration.setSocketConnectionTimeout(1); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerTest.java index d7ff035ec65..47dead63cdf 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerTest.java @@ -9,8 +9,6 @@ import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.savedrequest.DefaultSavedRequest; -import jakarta.servlet.ServletException; -import java.io.IOException; import java.io.Serial; import java.util.HashMap; import java.util.Map; @@ -22,7 +20,7 @@ class SamlLoginAuthenticationFailureHandlerTest { @Test - void errorRedirect() throws IOException, ServletException { + void errorRedirect() throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -46,7 +44,7 @@ void errorRedirect() throws IOException, ServletException { } @Test - void errorRedirectWithExistingQueryParameters() throws IOException, ServletException { + void errorRedirectWithExistingQueryParameters() throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -70,7 +68,7 @@ void errorRedirectWithExistingQueryParameters() throws IOException, ServletExcep } @Test - void someOtherErrorCondition() throws IOException, ServletException { + void someOtherErrorCondition() throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -99,7 +97,7 @@ void someOtherErrorCondition() throws IOException, ServletException { } @Test - void noSession() throws IOException, ServletException { + void noSession() throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); MockHttpServletRequest request = new MockHttpServletRequest(); @@ -115,7 +113,7 @@ void noSession() throws IOException, ServletException { } @Test - void noSavedRequest() throws IOException, ServletException { + void noSavedRequest() throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -138,7 +136,7 @@ void noSavedRequest() throws IOException, ServletException { } @Test - void noRedirectURI() throws IOException, ServletException { + void noRedirectURI() throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerZonePathTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerZonePathTest.java index d5c44997262..1efd3be879f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerZonePathTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlLoginAuthenticationFailureHandlerZonePathTest.java @@ -12,8 +12,6 @@ import org.springframework.security.web.savedrequest.DefaultSavedRequest; import org.cloudfoundry.identity.uaa.extensions.EnabledIfZonePathsEnabled; -import jakarta.servlet.ServletException; -import java.io.IOException; import java.io.Serial; import java.util.HashMap; import java.util.Map; @@ -27,7 +25,7 @@ class SamlLoginAuthenticationFailureHandlerZonePathTest { @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void errorRedirect(ZoneRequestPathMode mode) throws IOException, ServletException { + void errorRedirect(ZoneRequestPathMode mode) throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -52,7 +50,7 @@ void errorRedirect(ZoneRequestPathMode mode) throws IOException, ServletExceptio @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void errorRedirectWithExistingQueryParameters(ZoneRequestPathMode mode) throws IOException, ServletException { + void errorRedirectWithExistingQueryParameters(ZoneRequestPathMode mode) throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -77,7 +75,7 @@ void errorRedirectWithExistingQueryParameters(ZoneRequestPathMode mode) throws I @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void someOtherErrorCondition(ZoneRequestPathMode mode) throws IOException, ServletException { + void someOtherErrorCondition(ZoneRequestPathMode mode) throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -107,7 +105,7 @@ void someOtherErrorCondition(ZoneRequestPathMode mode) throws IOException, Servl @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void noSession(ZoneRequestPathMode mode) throws IOException, ServletException { + void noSession(ZoneRequestPathMode mode) throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); MockHttpServletRequest request = new MockHttpServletRequest(); @@ -124,7 +122,7 @@ void noSession(ZoneRequestPathMode mode) throws IOException, ServletException { @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void noSavedRequest(ZoneRequestPathMode mode) throws IOException, ServletException { + void noSavedRequest(ZoneRequestPathMode mode) throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); @@ -148,7 +146,7 @@ void noSavedRequest(ZoneRequestPathMode mode) throws IOException, ServletExcepti @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void noRedirectURI(ZoneRequestPathMode mode) throws IOException, ServletException { + void noRedirectURI(ZoneRequestPathMode mode) throws Exception { SamlLoginAuthenticationFailureHandler handler = new SamlLoginAuthenticationFailureHandler(); DefaultSavedRequest savedRequest = mock(DefaultSavedRequest.class); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java index e3b67f6400f..6ea08b85409 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/SamlMetadataEndpointTest.java @@ -24,7 +24,6 @@ import org.xmlunit.assertj.XmlAssert; import java.security.Security; -import java.security.cert.CertificateEncodingException; import java.util.List; import java.util.stream.Stream; @@ -177,7 +176,7 @@ void unsignedIfNoAlgorithm() { } @Test - void sha256Signature() throws CertificateEncodingException { + void sha256Signature() throws Exception { when(resolver.resolve(request, REGISTRATION_ID)).thenReturn(registration); ResponseEntity response = endpoint.metadataEndpoint(request); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaDelegatingLogoutSuccessHandlerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaDelegatingLogoutSuccessHandlerTest.java index e847f2a8490..f5898d7b5bf 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaDelegatingLogoutSuccessHandlerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaDelegatingLogoutSuccessHandlerTest.java @@ -60,13 +60,13 @@ void setup() { } @Test - void fallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void fallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { logoutSuccessHandler.onLogoutSuccess(request, response, authentication); verifyCorrectOnLogoutSuccessCalled(false, false, true); } @Test - void shouldPerformOAuthRpInitiatedLogout() throws ServletException, IOException { + void shouldPerformOAuthRpInitiatedLogout() throws Exception { var oauthConfig = mock(AbstractExternalOAuthIdentityProviderDefinition.class); when(externalOAuthLogoutHandler.getOAuthProviderForAuthentication(authentication)).thenReturn(oauthConfig); when(externalOAuthLogoutHandler.getLogoutUrl(oauthConfig)).thenReturn(URL); @@ -77,7 +77,7 @@ void shouldPerformOAuthRpInitiatedLogout() throws ServletException, IOException } @Test - void shouldPerformSamlRelyingPartyLogout() throws ServletException, IOException { + void shouldPerformSamlRelyingPartyLogout() throws Exception { var mockPrincipal = mock(UaaSamlPrincipal.class); when(authentication.getPrincipal()).thenReturn(mockPrincipal); when(mockPrincipal.getRelyingPartyRegistrationId()).thenReturn(REG_ID); @@ -96,7 +96,7 @@ void shouldPerformSamlRelyingPartyLogout() throws ServletException, IOException */ @Test - void nullAuthFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void nullAuthFallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { logoutSuccessHandler.onLogoutSuccess(request, response, null); verify(zoneAwareWhitelistLogoutHandler).onLogoutSuccess(request, response, null); verify(externalOAuthLogoutHandler, never()).onLogoutSuccess(any(), any(), any()); @@ -104,7 +104,7 @@ void nullAuthFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletExceptio } @Test - void nullRegIdFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void nullRegIdFallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { var mockPrincipal = mock(UaaSamlPrincipal.class); when(authentication.getPrincipal()).thenReturn(mockPrincipal); @@ -113,7 +113,7 @@ void nullRegIdFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletExcepti } @Test - void nullRegistrationFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void nullRegistrationFallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { var mockPrincipal = mock(UaaSamlPrincipal.class); when(authentication.getPrincipal()).thenReturn(mockPrincipal); when(mockPrincipal.getRelyingPartyRegistrationId()).thenReturn(REG_ID); @@ -123,7 +123,7 @@ void nullRegistrationFallsThruToZoneAwareWhitelistLogoutHandler() throws Servlet } @Test - void nullAssertingPartyDetailsFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void nullAssertingPartyDetailsFallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { var mockPrincipal = mock(UaaSamlPrincipal.class); when(authentication.getPrincipal()).thenReturn(mockPrincipal); when(mockPrincipal.getRelyingPartyRegistrationId()).thenReturn(REG_ID); @@ -135,7 +135,7 @@ void nullAssertingPartyDetailsFallsThruToZoneAwareWhitelistLogoutHandler() throw } @Test - void nullSingleLogoutServiceLocationFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void nullSingleLogoutServiceLocationFallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { var mockPrincipal = mock(UaaSamlPrincipal.class); when(authentication.getPrincipal()).thenReturn(mockPrincipal); when(mockPrincipal.getRelyingPartyRegistrationId()).thenReturn(REG_ID); @@ -153,7 +153,7 @@ void nullSingleLogoutServiceLocationFallsThruToZoneAwareWhitelistLogoutHandler() */ @Test - void nullLogoutUrlFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void nullLogoutUrlFallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { var oauthConfig = mock(AbstractExternalOAuthIdentityProviderDefinition.class); when(externalOAuthLogoutHandler.getOAuthProviderForAuthentication(authentication)).thenReturn(oauthConfig); when(externalOAuthLogoutHandler.getLogoutUrl(oauthConfig)).thenReturn(null); @@ -164,7 +164,7 @@ void nullLogoutUrlFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletExc } @Test - void falsePerformRpInitiatedLogoutFallsThruToZoneAwareWhitelistLogoutHandler() throws ServletException, IOException { + void falsePerformRpInitiatedLogoutFallsThruToZoneAwareWhitelistLogoutHandler() throws Exception { var oauthConfig = mock(AbstractExternalOAuthIdentityProviderDefinition.class); when(externalOAuthLogoutHandler.getOAuthProviderForAuthentication(authentication)).thenReturn(oauthConfig); when(externalOAuthLogoutHandler.getLogoutUrl(oauthConfig)).thenReturn(URL); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java index 73b5924071c..b420ce10e75 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java @@ -15,6 +15,7 @@ */ package org.cloudfoundry.identity.uaa.provider.saml; +import org.assertj.core.api.InstanceOfAssertFactories; import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider; import org.cloudfoundry.identity.uaa.zone.IdentityZone; import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder; @@ -37,8 +38,7 @@ import java.security.Security; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -99,7 +99,8 @@ void resolveWhenRequestIsWithInvalidSamlResponse() { request.setRequestURI("/some/path/cloudfoundry-saml-login"); request.setMethod("POST"); request.setParameter("SAMLResponse", "PGJhc2U2ND4="); - assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> resolver.resolve(request, null)); + assertThatThrownBy(() -> resolver.resolve(request, null)) + .asInstanceOf(InstanceOfAssertFactories.throwable(Saml2AuthenticationException.class)); } @Test @@ -143,7 +144,7 @@ void resolveWhenRequestIsWithValiddSamlResponseFromSimplySaml() { @Test void constructorWhenNullRelyingPartyRegistrationThenIllegalArgument() { - assertThatIllegalArgumentException().isThrownBy(() -> new UaaRelyingPartyRegistrationResolver(null, null, null)); + assertThatThrownBy(() -> new UaaRelyingPartyRegistrationResolver(null, null, null)).isInstanceOf(IllegalArgumentException.class); } @ParameterizedTest diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java index 7b7b0c137c8..1549dce9201 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class UaaIdentityProviderConfigValidatorTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java index 4211918add1..d1dfeaf8c9a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; class RateLimiterImplTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterTest.java index 1b788584ad2..318c2b8a0f1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterTest.java @@ -15,7 +15,6 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import java.io.IOException; import java.io.PrintWriter; import org.cloudfoundry.identity.uaa.ratelimiting.core.CompoundKey; @@ -38,14 +37,14 @@ void setUp() throws ServletException { } @Test - void inactiveByDefault() throws ServletException, IOException { + void inactiveByDefault() throws Exception { instanceNoConfig.doFilter(mock(HttpServletRequest.class), mock(HttpServletResponse.class), mock(FilterChain.class)); verify(limiter, times(0)).checkRequest(any()); } @Test - void withConfigActive() throws ServletException, IOException { + void withConfigActive() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); @@ -60,7 +59,7 @@ void withConfigActive() throws ServletException, IOException { } @Test - void withConfigLimitsWith429() throws ServletException, IOException { + void withConfigLimitsWith429() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); @@ -79,7 +78,7 @@ void withConfigLimitsWith429() throws ServletException, IOException { } @Test - void statusReturnsWithoutFurtherProcessing() throws ServletException, IOException { + void statusReturnsWithoutFurtherProcessing() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletPath()).thenReturn("/RateLimitingStatus"); HttpServletResponse response = mock(HttpServletResponse.class); @@ -93,7 +92,7 @@ void statusReturnsWithoutFurtherProcessing() throws ServletException, IOExceptio } @Test - void statusReturnsWithoutFurtherProcessingNoConfig() throws ServletException, IOException { + void statusReturnsWithoutFurtherProcessingNoConfig() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getServletPath()).thenReturn("/RateLimitingStatus"); HttpServletResponse response = mock(HttpServletResponse.class); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java index 16a60835356..6848ca55c90 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/core/http/CredentialIdTypeAbstractTestJWT.java @@ -83,7 +83,7 @@ private void checkJwtParts(String authHeaderValuePrefix) { assertThat(parts.token).as(authHeaderValuePrefix + "JWTparts.token").isEqualTo(JWT); String[] sections = parts.parts; assertThat(sections).as("JWTparts.parts.sections") - .as(authHeaderValuePrefix + "JWTparts.sections").hasSize(3) + .as(authHeaderValuePrefix + "JWTparts.sections") .containsExactly(B64_SECTION_HEADER, B64_SECTION_CLAIMS, B64_SECTION_SIGNATURE); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterByCompoundKeyTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterByCompoundKeyTest.java index 68c74782abf..218a3b8fbd7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterByCompoundKeyTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/LimiterByCompoundKeyTest.java @@ -54,8 +54,7 @@ int callsCount(String callerID) { private InternalLimiter getLimiter(String callerId) { CompoundKey compoundKey = CompoundKey.from(LIMITER_NAME, WINDOW_TYPE, callerId); InternalLimiter limiter = limiterByCompoundKey.get(compoundKey, factory, limiterCreationTracker); - assertThat(limiter).isNotNull(); - return limiter; + return assertThat(limiter).isNotNull().actual(); } private Params addLimiterAndAdvanceClockBy1Sec(String callerId) { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java index 4e64762e35f..ae3f15caa0f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/internal/limitertracking/PathFragmentToLimiterMappingsTest.java @@ -22,7 +22,7 @@ void noLimiterMappings() { assertThat(mapper.isEmpty()).isTrue(); assertThat(mapper.count()).isZero(); - assertThat(streamToPathFragments()).isEqualTo(List.of()); + assertThat(streamToPathFragments()).containsExactlyElementsOf(List.of()); assertThat(mapper.get("significantOther/Wilma/of/Fred")).isNull(); } @@ -37,7 +37,7 @@ void fewLimiterMappings() { assertThat(mapper.isEmpty()).isFalse(); assertThat(mapper.count()).isEqualTo(3); - assertThat(streamToPathFragments()).isEqualTo(List.of(pebbles, wilma, fred)); + assertThat(streamToPathFragments()).containsExactlyElementsOf(List.of(pebbles, wilma, fred)); assertThat(mapper.get("significantOther/Wilma/of/Fred")).isEqualTo(wilma.getLimiterMapping()); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java index da15ab84784..762a8bb546f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java @@ -3,7 +3,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class IntUtilsTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/LazyEnumerationToListTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/LazyEnumerationToListTest.java index 116e6083ee3..bdca002db6f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/LazyEnumerationToListTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/LazyEnumerationToListTest.java @@ -27,13 +27,13 @@ void getEnumeration() { private void checkNull(LazyEnumerationToList el) { assertThat(el).isNotNull(); - assertThat(el.get()).isEqualTo(Collections.emptyList()); + assertThat(el.get()).containsExactlyElementsOf(Collections.emptyList()); assertThat(el.hasValue()).isFalse(); } private void checkNonNull(LazyEnumerationToList el) { assertThat(el).isNotNull(); - assertThat(el.get()).isEqualTo(SOURCE); + assertThat(el.get()).containsExactlyElementsOf(SOURCE); assertThat(el.hasValue()).isTrue(); } } \ No newline at end of file diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java index 32bd420f7be..5eadb91a324 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java @@ -7,7 +7,7 @@ import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; class SourcedFileTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java index 7db9d4666c4..f038fb14015 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java @@ -20,9 +20,7 @@ import java.util.Map; import java.util.Set; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; @WithDatabaseContext class JdbcPagingListTests { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandlerEnsureConsistencyTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandlerEnsureConsistencyTest.java index 9425b71c823..4e28f799aa3 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandlerEnsureConsistencyTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimUserAliasHandlerEnsureConsistencyTest.java @@ -280,9 +280,7 @@ void shouldThrow_WhenUsernameAlreadyOccupiedInAliasZone() { mockCreateEntityThrows_UsernameAlreadyOccupied(originalEntity.getUserName(), customZoneId); assertThatThrownBy(() -> aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) - .isInstanceOf(EntityAliasFailedException.class) - .hasMessage("Could not create ScimUser[id=null,zid='%s',aliasId='%s',aliasZid='uaa']. A user with the same username already exists in the alias zone." - .formatted(customZoneId, existingEntity.getId())) + .isInstanceOf(EntityAliasFailedException.class).hasMessage("Could not create ScimUser[id=null,zid='%s',aliasId='%s',aliasZid='uaa']. A user with the same username already exists in the alias zone.", customZoneId, existingEntity.getId()) .satisfies(e -> assertThat(((EntityAliasFailedException) e).getHttpStatus()).isEqualTo(HttpStatus.CONFLICT.value())); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java index 6aa8c8b0798..0d15b4ae97b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java @@ -76,9 +76,7 @@ import static java.util.Collections.emptyList; import static java.util.Optional.ofNullable; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; @@ -199,7 +197,6 @@ void canDeleteUsersButOnlyInDefaultZone() { verify(publisher, times(2)).publishEvent(captor.capture()); List> deleted = new LinkedList(ofNullable(captor.getAllValues()).orElse(emptyList())); assertThat(deleted) - .isNotNull() .hasSize(2); deleted.forEach(event -> assertThat(event.getDeleted().getOrigin()).isEqualTo(OriginKeys.UAA)); assertThat(jdbcScimUserProvisioning.retrieveAll(IdentityZone.getUaaZoneId())).hasSize(2); @@ -485,7 +482,12 @@ void shouldOnlyUpdateOriginalUser_WhenUserHasAliasButAliasEntitiesDisabled() { assertThat(aliasUserAfterEvent.getAliasId()).isEqualTo(originalUserId); assertThat(aliasUserAfterEvent.getAliasZid()).isEqualTo(IdentityZone.getUaaZoneId()); assertThat(aliasUserAfterEvent.getExternalId()).isEqualTo(originalUser.getExternalId()); // should be left unchanged - assertThat(aliasUserAfterEvent.getPhoneNumbers()).isEqualTo(originalUser.getPhoneNumbers()); // should be left unchanged + // Handle null phone numbers case for AssertJ compatibility + if (originalUser.getPhoneNumbers() != null) { + assertThat(aliasUserAfterEvent.getPhoneNumbers()).containsExactlyElementsOf(originalUser.getPhoneNumbers()); // should be left unchanged + } else { + assertThat(aliasUserAfterEvent.getPhoneNumbers()).isNull(); // should be left unchanged + } } private void createCustomZone(final String customZoneId) { @@ -1191,7 +1193,7 @@ void bootstrapDoesNotCreateDuplicateMembershipForDefaultGroups() { int customGroupRows = jdbcTemplate.queryForObject( "select count(*) from group_membership where member_id=? and group_id=? and identity_zone_id=?", Integer.class, user.getId(), customGroup.getId(), IdentityZone.getUaaZoneId()); - assertThat(customGroupRows).isEqualTo(1); + assertThat(customGroupRows).isOne(); // Deletion should succeed without 422 assertThatCode(() -> jdbcScimGroupMembershipManager.removeMembersByMemberId(user.getId(), IdentityZone.getUaaZoneId())) diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java index 4173fbaf05f..7d8d48cb8ed 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasTests.java @@ -431,10 +431,10 @@ private void assertOriginalAndAliasUserAreRemovedFromGroups( zoneIdArgument.capture() ); final List capturedMemberIds = memberIdArgument.getAllValues(); - assertThat(capturedMemberIds.getFirst()).isEqualTo(userId); + assertThat(capturedMemberIds).first().isEqualTo(userId); assertThat(capturedMemberIds.get(1)).isEqualTo(aliasId); final List capturedZoneIds = zoneIdArgument.getAllValues(); - assertThat(capturedZoneIds.getFirst()).isEqualTo(zoneId); + assertThat(capturedZoneIds).first().isEqualTo(zoneId); assertThat(capturedZoneIds.get(1)).isEqualTo(aliasZid); } @@ -471,14 +471,14 @@ private void assertOriginalAndAliasUsersAreDeleted( zoneIdArgument.capture() ); final List capturedUserIds = userIdArgument.getAllValues(); - assertThat(capturedUserIds.getFirst()).isEqualTo(userId); + assertThat(capturedUserIds).first().isEqualTo(userId); assertThat(capturedUserIds.get(1)).isEqualTo(aliasId); final List capturedVersions = versionArgument.getAllValues(); - assertThat(capturedVersions.getFirst()) + assertThat(capturedVersions).first() .isEqualTo(-1); // etag in scimUserEndpoints.deleteUser call is null assertThat(capturedVersions.get(1)).isEqualTo(aliasUserVersion); final List capturedZoneIds2 = zoneIdArgument.getAllValues(); - assertThat(capturedZoneIds2.getFirst()).isEqualTo(zoneId); + assertThat(capturedZoneIds2).first().isEqualTo(zoneId); assertThat(capturedZoneIds2.get(1)).isEqualTo(aliasZid); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserIdConversionEndpointsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserIdConversionEndpointsTests.java index ee301c9c652..2e6ee50e70b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserIdConversionEndpointsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserIdConversionEndpointsTests.java @@ -39,9 +39,7 @@ import static java.util.Collections.singletonList; import static java.util.UUID.randomUUID; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; @@ -84,9 +82,7 @@ void happyDay() { @Test void sanitizeExceptionInFilter() { - assertThatExceptionOfType(ScimException.class) - .isThrownBy(() -> endpoints.findUsers("", "ascending", 0, 100, false)) - .withMessage("Invalid filter '<svg onload=alert(document.domain)>'"); + assertThatThrownBy(() -> endpoints.findUsers("", "ascending", 0, 100, false)).isInstanceOf(ScimException.class).hasMessage("Invalid filter '<svg onload=alert(document.domain)>'"); } @Test @@ -164,9 +160,7 @@ void goodFilter(final String filter) { "id eq \"foo\" or origin co \"uaa\"" }) void badFilterWildcardsNotAllowed(final String filter) { - assertThatExceptionOfType(ScimException.class) - .isThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)) - .withMessage("Wildcards are not allowed in filter."); + assertThatThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)).isInstanceOf(ScimException.class).hasMessage("Wildcards are not allowed in filter."); } @ParameterizedTest @@ -176,9 +170,7 @@ void badFilterWildcardsNotAllowed(final String filter) { "id lt \"foo\"" }) void badFilterUnsupportedOperator(final String filter) { - assertThatExceptionOfType(ScimException.class) - .isThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)) - .withMessage("Invalid operator."); + assertThatThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)).isInstanceOf(ScimException.class).hasMessage("Invalid operator."); } @ParameterizedTest @@ -186,9 +178,7 @@ void badFilterUnsupportedOperator(final String filter) { "id sq \"foo\"" }) void badFilterUnrecognizedOperator(final String filter) { - assertThatExceptionOfType(ScimException.class) - .isThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)) - .withMessageStartingWith("Invalid filter '"); + assertThatThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)).isInstanceOf(ScimException.class).hasMessageStartingWith("Invalid filter '"); } @ParameterizedTest @@ -199,9 +189,7 @@ void badFilterUnrecognizedOperator(final String filter) { "groups.display eq \"foo\"" }) void badFilterDoesNotContainClauseWithIdOrUserName(final String filter) { - assertThatExceptionOfType(ScimException.class) - .isThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)) - .withMessage("Invalid filter attribute."); + assertThatThrownBy(() -> endpoints.findUsers(filter, "ascending", 0, 100, false)).isInstanceOf(ScimException.class).hasMessage("Invalid filter attribute."); } @Test @@ -252,7 +240,7 @@ private void assertEndpointReturnsCorrectResult( filter, "ascending", startIndex, resultsPerPage, includeInactive ); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); - assertThat(response.getBody()).isNotNull().isInstanceOf(SearchResults.class); + assertThat(response.getBody()).isInstanceOf(SearchResults.class); return (SearchResults>) response.getBody(); }; @@ -280,7 +268,7 @@ private void assertEndpointReturnsCorrectResult( // check next page -> should be empty final SearchResults> responseBody = fetchNextPage.apply(currentStartIndex); assertThat(responseBody.getTotalResults()).isEqualTo(expectedUsers.size()); - assertThat(responseBody.getResources()).isNotNull().isEmpty(); + assertThat(responseBody.getResources()).isEmpty(); final List> expectedResponse = expectedUsers.stream().map(scimUser -> Map.of( "id", (Object) scimUser.getId(), diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java index a9cda6d077e..50b43259367 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java @@ -28,7 +28,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @WithDatabaseContext class JdbcScimGroupExternalMembershipManagerTests { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java index a3be93390b2..5082daf51cb 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java @@ -42,9 +42,7 @@ import java.util.Set; import static java.util.Collections.emptyList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LOGIN_SERVER; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.UAA; @@ -164,7 +162,7 @@ void defaultGroupsAreCached() { } @Test - void deleteByMember() throws SQLException { + void deleteByMember() throws Exception { addMember("g1", "m3", "USER", LDAP, jdbcTemplate, uaaIdentityZone.getId()); addMember("g1", "g2", "GROUP", LDAP, jdbcTemplate, uaaIdentityZone.getId()); addMember("g3", "m2", "USER", UAA, jdbcTemplate, uaaIdentityZone.getId()); @@ -175,7 +173,7 @@ void deleteByMember() throws SQLException { } @Test - void deleteByMemberAndOrigin() throws SQLException { + void deleteByMemberAndOrigin() throws Exception { addMember("g1", "m3", "USER", LDAP, jdbcTemplate, uaaIdentityZone.getId()); addMember("g1", "g2", "GROUP", LDAP, jdbcTemplate, uaaIdentityZone.getId()); addMember("g3", "m2", "USER", UAA, jdbcTemplate, uaaIdentityZone.getId()); @@ -188,7 +186,7 @@ void deleteByMemberAndOrigin() throws SQLException { } @Test - void canDeleteWithOrigin() throws SQLException { + void canDeleteWithOrigin() throws Exception { addMembers(jdbcTemplate, uaaIdentityZone.getId()); validateCount(4, jdbcTemplate, uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.deleteMembersByOrigin(OriginKeys.UAA, uaaIdentityZone.getId()); @@ -196,7 +194,7 @@ void canDeleteWithOrigin() throws SQLException { } @Test - void canDeleteWithOrigin2() throws SQLException { + void canDeleteWithOrigin2() throws Exception { addMembers(jdbcTemplate, uaaIdentityZone.getId()); validateCount(4, jdbcTemplate, uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.deleteMembersByOrigin(OriginKeys.ORIGIN, uaaIdentityZone.getId()); @@ -204,7 +202,7 @@ void canDeleteWithOrigin2() throws SQLException { } @Test - void canDeleteWithOrigin3() throws SQLException { + void canDeleteWithOrigin3() throws Exception { addMembers(jdbcTemplate, uaaIdentityZone.getId()); validateCount(4, jdbcTemplate, uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.removeMembersByMemberId("m3", uaaIdentityZone.getId()); @@ -212,7 +210,7 @@ void canDeleteWithOrigin3() throws SQLException { } @Test - void cannotDeleteWithFilterOutsideZone() throws SQLException { + void cannotDeleteWithFilterOutsideZone() throws Exception { addMembers(jdbcTemplate, uaaIdentityZone.getId()); validateCount(4, jdbcTemplate, uaaIdentityZone.getId()); IdentityZoneHolder.set(otherIdentityZone); @@ -232,7 +230,7 @@ void canGetGroupsForMember() { } @Test - void userDeleteClearsMemberships_InUaaZone() throws SQLException { + void userDeleteClearsMemberships_InUaaZone() throws Exception { UaaUserPrototype prototype = new UaaUserPrototype() .withUsername("username") .withEmail("test@test.com"); @@ -247,7 +245,7 @@ void userDeleteClearsMemberships_InUaaZone() throws SQLException { } @Test - void userDeleteClearsMemberships_InOtherZone() throws SQLException { + void userDeleteClearsMemberships_InOtherZone() throws Exception { UaaUserPrototype prototype = new UaaUserPrototype() .withUsername("username") .withEmail("test@test.com"); @@ -262,7 +260,7 @@ void userDeleteClearsMemberships_InOtherZone() throws SQLException { } @Test - void zoneDeleteClearsMemberships_InUaaZone() throws SQLException { + void zoneDeleteClearsMemberships_InUaaZone() throws Exception { addMembers(OriginKeys.LDAP, jdbcTemplate, uaaIdentityZone.getId()); validateCount(4, jdbcTemplate, uaaIdentityZone.getId()); @@ -272,7 +270,7 @@ void zoneDeleteClearsMemberships_InUaaZone() throws SQLException { } @Test - void zoneDeleteClearsMemberships_InOtherZone() throws SQLException { + void zoneDeleteClearsMemberships_InOtherZone() throws Exception { addMembers(OriginKeys.LDAP, jdbcTemplate, otherIdentityZone.getId()); validateCount(4, jdbcTemplate, otherIdentityZone.getId()); @@ -282,7 +280,7 @@ void zoneDeleteClearsMemberships_InOtherZone() throws SQLException { } @Test - void providerDeleteClearsMemberships_InUaaZone() throws SQLException { + void providerDeleteClearsMemberships_InUaaZone() throws Exception { addMembers(OriginKeys.LDAP, jdbcTemplate, uaaIdentityZone.getId()); validateCount(4, "ZoneID: " + uaaIdentityZone.getId(), jdbcTemplate, uaaIdentityZone.getId()); IdentityProvider provider = new IdentityProvider() @@ -296,7 +294,7 @@ void providerDeleteClearsMemberships_InUaaZone() throws SQLException { } @Test - void providerDeleteClearsMemberships_InOtherZone() throws SQLException { + void providerDeleteClearsMemberships_InOtherZone() throws Exception { addMembers(OriginKeys.LDAP, jdbcTemplate, otherIdentityZone.getId()); validateCount(4, "ZoneID: " + otherIdentityZone.getId(), jdbcTemplate, otherIdentityZone.getId()); IdentityProvider provider = new IdentityProvider() @@ -310,7 +308,7 @@ void providerDeleteClearsMemberships_InOtherZone() throws SQLException { } @Test - void zoneDeleted() throws SQLException { + void zoneDeleted() throws Exception { String zoneAdminId = generator.generate(); addGroup(zoneAdminId, "zones." + otherIdentityZone.getId() + ".admin", uaaIdentityZone.getId(), jdbcTemplate); addMember(zoneAdminId, "m1", "USER", OriginKeys.UAA, jdbcTemplate, uaaIdentityZone.getId()); @@ -343,7 +341,7 @@ void zoneDeleted() throws SQLException { } @Test - void providerDeleted() throws SQLException { + void providerDeleted() throws Exception { String groups = dbUtils.getQuotedIdentifier("groups", jdbcTemplate); addMembers(LOGIN_SERVER, jdbcTemplate, otherIdentityZone.getId()); @@ -368,7 +366,7 @@ void providerDeleted() throws SQLException { } @Test - void cannotDeleteUaaZone() throws SQLException { + void cannotDeleteUaaZone() throws Exception { String groups = dbUtils.getQuotedIdentifier("groups", jdbcTemplate); addMembers(jdbcTemplate, uaaIdentityZone.getId()); @@ -382,7 +380,7 @@ void cannotDeleteUaaZone() throws SQLException { } @Test - void cannotDeleteUaaProvider() throws SQLException { + void cannotDeleteUaaProvider() throws Exception { String groups = dbUtils.getQuotedIdentifier("groups", jdbcTemplate); addMembers(LOGIN_SERVER, jdbcTemplate, otherIdentityZone.getId()); @@ -415,7 +413,7 @@ void canGetGroupsForMemberEvenWhenCycleExistsInGroupHierarchy() { } @Test - void canAddMember() throws SQLException { + void canAddMember() throws Exception { validateCount(0, jdbcTemplate, uaaIdentityZone.getId()); ScimGroupMember m1 = new ScimGroupMember("m1", ScimGroupMember.Type.USER); ScimGroupMember m2 = jdbcScimGroupMembershipManager.addMember("g2", m1, uaaIdentityZone.getId()); @@ -435,7 +433,7 @@ void addMemberInDifferentZoneCausesIssues() { } @Test - void canAddMemberValidateOriginAndZoneId() throws SQLException { + void canAddMemberValidateOriginAndZoneId() throws Exception { otherIdentityZone.getConfig().getUserConfig().setDefaultGroups(emptyList()); IdentityZoneHolder.set(otherIdentityZone); validateCount(0, jdbcTemplate, otherIdentityZone.getId()); @@ -520,7 +518,7 @@ void canGetMemberById() { } @Test - void canUpdateOrAddMembers() throws SQLException { + void canUpdateOrAddMembers() throws Exception { jdbcScimGroupMembershipManager.addMember("g1", new ScimGroupMember("m1", ScimGroupMember.Type.USER), uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.addMember("g1", new ScimGroupMember("m4", ScimGroupMember.Type.USER), uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.addMember("g1", new ScimGroupMember("g2", ScimGroupMember.Type.GROUP), uaaIdentityZone.getId()); @@ -554,7 +552,7 @@ void canUpdateOrAddMembers() throws SQLException { } @Test - void canRemoveMemberById() throws SQLException { + void canRemoveMemberById() throws Exception { addMember("g1", "m1", "USER", "READER", jdbcTemplate, uaaIdentityZone.getId()); validateCount(1, jdbcTemplate, uaaIdentityZone.getId()); @@ -564,7 +562,7 @@ void canRemoveMemberById() throws SQLException { } @Test - void canRemoveNestedGroupMember() throws SQLException { + void canRemoveNestedGroupMember() throws Exception { jdbcScimGroupMembershipManager.addMember("g1", new ScimGroupMember("m1", ScimGroupMember.Type.USER), uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.addMember("g1", new ScimGroupMember("g2", ScimGroupMember.Type.GROUP), uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.addMember("g2", new ScimGroupMember("m2", ScimGroupMember.Type.USER), uaaIdentityZone.getId()); @@ -581,7 +579,7 @@ void canRemoveNestedGroupMember() throws SQLException { } @Test - void canRemoveAllMembers() throws SQLException { + void canRemoveAllMembers() throws Exception { jdbcScimGroupMembershipManager.addMember("g1", new ScimGroupMember("m1", ScimGroupMember.Type.USER), uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.addMember("g1", new ScimGroupMember("g2", ScimGroupMember.Type.GROUP), uaaIdentityZone.getId()); jdbcScimGroupMembershipManager.addMember("g2", new ScimGroupMember("m2", ScimGroupMember.Type.USER), uaaIdentityZone.getId()); @@ -621,7 +619,7 @@ void canAddMultipleMembers() { } @Test - void groupsWithMemberAndMaxSqlParameter() throws SQLException { + void groupsWithMemberAndMaxSqlParameter() throws Exception { int oldValue = jdbcScimGroupMembershipManager.getMaxSqlParameters(); for (int l : List.of(-1, 10)) { jdbcScimGroupMembershipManager.setMaxSqlParameters(l); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java index 2b0190ed9c9..c9af937019c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java @@ -38,10 +38,7 @@ import java.util.List; import java.util.UUID; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.scim.jdbc.JdbcScimGroupMembershipManager.MEMBERSHIP_FIELDS; import static org.cloudfoundry.identity.uaa.scim.jdbc.JdbcScimGroupMembershipManager.MEMBERSHIP_TABLE; import static org.mockito.Mockito.anyString; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java index 916b4ad0b00..42f897a751b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java @@ -58,11 +58,7 @@ import java.util.stream.Stream; import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LOGIN_SERVER; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.UAA; import static org.mockito.ArgumentMatchers.any; @@ -297,7 +293,7 @@ void retrieveByScimFilterOnlyActive() { ); assertThat(result).isNotNull(); final List usernames = result.stream().map(ScimUser::getUserName).toList(); - assertThat(usernames).isSorted(); + assertThat(usernames).isSorted().actual(); return usernames; }; @@ -1073,7 +1069,7 @@ void createUserWithDuplicateUsername() { .isInstanceOf(ScimResourceAlreadyExistsException.class) .hasMessage("Username already in use: user@example.com") .satisfies(e -> assertThat(((ScimResourceAlreadyExistsException) e).getStatus()).isEqualTo(HttpStatus.CONFLICT)) - .satisfies(e -> assertThat(((ScimResourceAlreadyExistsException) e).getExtraInfo()).isEqualTo(userDetails)); + .satisfies(e -> assertThat(((ScimResourceAlreadyExistsException) e).getExtraInfo()).containsExactlyInAnyOrderEntriesOf(userDetails)); } @Test @@ -1489,9 +1485,8 @@ void cannotUpdateUserWithWrongIdentityZone() { scimUser.setEmails(singletonList(email)); scimUser.setPassword(randomString()); scimUser.setZoneId("wrongZone-" + randomString()); - assertThatNoException().isThrownBy(() -> { - jdbcScimUserProvisioning.create(scimUser, currentIdentityZoneId); - }); + assertThatNoException().isThrownBy(() -> + jdbcScimUserProvisioning.create(scimUser, currentIdentityZoneId)); assertThatThrownBy(() -> jdbcScimUserProvisioning.update(userId, scimUser, currentIdentityZoneId)) .isInstanceOf(ScimResourceNotFoundException.class) .hasMessageContaining("does not exist"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java index 90c88e485b0..ce359186120 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java @@ -11,7 +11,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class ScimSearchQueryConverterTests { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java index cc9f9c72920..7aeee58fd93 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java @@ -2,6 +2,7 @@ import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.alias.AliasPropertiesInvalidException; import org.cloudfoundry.identity.uaa.scim.ScimUser; import org.cloudfoundry.identity.uaa.scim.ScimUserAliasHandler; @@ -22,7 +23,7 @@ import java.util.List; import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; @@ -75,8 +76,8 @@ final void updateShouldThrowWhenAliasPropertiesAreInvalid() { final ScimUser user = mock(ScimUser.class); when(scimUserAliasHandler.aliasPropertiesAreValid(user, existingUser)).thenReturn(false); - assertThatExceptionOfType(AliasPropertiesInvalidException.class) - .isThrownBy(() -> scimUserService.updateUser(userId, user)); + assertThatThrownBy(() -> scimUserService.updateUser(userId, user)) +.asInstanceOf(InstanceOfAssertFactories.throwable(AliasPropertiesInvalidException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java index 3830ead8c43..5439fee0cac 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java @@ -18,7 +18,6 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.sql.Timestamp; @@ -26,7 +25,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -102,7 +101,7 @@ void tearDown() { class WhenZoneIsUaa { @Test - void getVerificationURL() throws MalformedURLException { + void getVerificationURL() throws Exception { URL actual = ScimUtils.getVerificationURL(mockExpiringCode, IdentityZone.getUaa()); URL expected = URI.create("http://localhost:8080/uaa/verify_user?code=code").toURL(); assertThat(actual).hasToString(expected.toString()); @@ -112,7 +111,7 @@ void getVerificationURL() throws MalformedURLException { @Nested class WhenZoneIsNotUaa { @Test - void getVerificationURL() throws MalformedURLException { + void getVerificationURL() throws Exception { IdentityZone mockIdentityZone = mock(IdentityZone.class); when(mockIdentityZone.isUaa()).thenReturn(false); when(mockIdentityZone.getSubdomain()).thenReturn("subdomain"); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java index beea633b157..8ec8de47cd0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java @@ -28,7 +28,7 @@ import jakarta.servlet.http.HttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class CsrfAwareEntryPointAndDeniedHandlerTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/ContentSecurityPolicyFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/ContentSecurityPolicyFilterTest.java index 217a9065e16..fa4792f9da5 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/ContentSecurityPolicyFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/ContentSecurityPolicyFilterTest.java @@ -7,8 +7,6 @@ import org.springframework.mock.web.MockHttpServletResponse; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import java.io.IOException; import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; @@ -30,14 +28,14 @@ void setUp() { } @Test - void verifyRequestHasHeader() throws ServletException, IOException { + void verifyRequestHasHeader() throws Exception { filter.doFilter(request, response, chain); assertThat(response.getHeader("Content-Security-Policy")).isEqualTo("script-src 'self'"); } @Test - void shouldNotAddHeader_WhenRespondingTo_SamlAuthRequests() throws ServletException, IOException { + void shouldNotAddHeader_WhenRespondingTo_SamlAuthRequests() throws Exception { request.setServletPath("/saml/some-path"); filter.doFilter(request, response, chain); @@ -45,7 +43,7 @@ void shouldNotAddHeader_WhenRespondingTo_SamlAuthRequests() throws ServletExcept } @Test - void shouldAddHeader_ForSamlSomeOtherThing() throws ServletException, IOException { + void shouldAddHeader_ForSamlSomeOtherThing() throws Exception { request.setServletPath("/samlSomeOtherThing"); filter.doFilter(request, response, chain); @@ -53,7 +51,7 @@ void shouldAddHeader_ForSamlSomeOtherThing() throws ServletException, IOExceptio } @Test - void shouldAddHeader_ForSamlInMiddleOfPath() throws ServletException, IOException { + void shouldAddHeader_ForSamlInMiddleOfPath() throws Exception { request.setServletPath("/other/saml/"); filter.doFilter(request, response, chain); @@ -61,7 +59,7 @@ void shouldAddHeader_ForSamlInMiddleOfPath() throws ServletException, IOExceptio } @Test - void shouldNotAddHeader_WhenRespondingTo_LoginImplicitPageRequests() throws ServletException, IOException { + void shouldNotAddHeader_WhenRespondingTo_LoginImplicitPageRequests() throws Exception { request.setServletPath("/login_implicit"); filter.doFilter(request, response, chain); @@ -69,14 +67,14 @@ void shouldNotAddHeader_WhenRespondingTo_LoginImplicitPageRequests() throws Serv } @Test - void verifyChainRequest() throws ServletException, IOException { + void verifyChainRequest() throws Exception { filter.doFilter(request, response, chain); Mockito.verify(chain).doFilter(request, response); } @Test - void customScriptSrc() throws ServletException, IOException { + void customScriptSrc() throws Exception { filter = new ContentSecurityPolicyFilter(Arrays.asList("'self'", "custom")); filter.doFilter(request, response, chain); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java index 1ff19c7f130..bc895d30881 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterDefaultZoneTests.java @@ -26,8 +26,6 @@ import org.springframework.mock.web.MockHttpServletResponse; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -107,7 +105,7 @@ void non_xhr_default_allowed_credentials() { } @Test - void requestExpectStandardCorsResponse() throws ServletException, IOException { + void requestExpectStandardCorsResponse() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); @@ -123,7 +121,7 @@ void requestExpectStandardCorsResponse() throws ServletException, IOException { } @Test - void requestWithMaliciousOrigin() throws ServletException, IOException { + void requestWithMaliciousOrigin() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); @@ -140,7 +138,7 @@ void requestWithMaliciousOrigin() throws ServletException, IOException { } @Test - void requestExpectXhrCorsResponse() throws ServletException, IOException { + void requestExpectXhrCorsResponse() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); @@ -157,7 +155,7 @@ void requestExpectXhrCorsResponse() throws ServletException, IOException { } @Test - void sameOriginRequest() throws ServletException, IOException { + void sameOriginRequest() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); @@ -173,7 +171,7 @@ void sameOriginRequest() throws ServletException, IOException { } @Test - void requestWithForbiddenOrigin() throws ServletException, IOException { + void requestWithForbiddenOrigin() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); @@ -190,7 +188,7 @@ void requestWithForbiddenOrigin() throws ServletException, IOException { } @Test - void requestWithForbiddenUri() throws ServletException, IOException { + void requestWithForbiddenUri() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/login"); @@ -207,7 +205,7 @@ void requestWithForbiddenUri() throws ServletException, IOException { } @Test - void requestWithMethodNotAllowed() throws ServletException, IOException { + void requestWithMethodNotAllowed() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/uaa/userinfo"); @@ -224,7 +222,7 @@ void requestWithMethodNotAllowed() throws ServletException, IOException { } @Test - void preFlightExpectStandardCorsResponse() throws ServletException, IOException { + void preFlightExpectStandardCorsResponse() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); corsFilter.getDefaultConfiguration().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); @@ -243,7 +241,7 @@ void preFlightExpectStandardCorsResponse() throws ServletException, IOException } @Test - void preFlightExpectXhrCorsResponse() throws ServletException, IOException { + void preFlightExpectXhrCorsResponse() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); corsFilter.getXhrConfiguration().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); @@ -261,7 +259,7 @@ void preFlightExpectXhrCorsResponse() throws ServletException, IOException { } @Test - void preFlightWrongOriginSpecified() throws ServletException, IOException { + void preFlightWrongOriginSpecified() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); @@ -279,7 +277,7 @@ void preFlightWrongOriginSpecified() throws ServletException, IOException { } @Test - void preFlightRequestNoRequestMethod() throws ServletException, IOException { + void preFlightRequestNoRequestMethod() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); @@ -296,7 +294,7 @@ void preFlightRequestNoRequestMethod() throws ServletException, IOException { } @Test - void preFlightRequestMethodNotAllowed() throws ServletException, IOException { + void preFlightRequestMethodNotAllowed() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); @@ -314,7 +312,7 @@ void preFlightRequestMethodNotAllowed() throws ServletException, IOException { } @Test - void preFlightRequestHeaderNotAllowed() throws ServletException, IOException { + void preFlightRequestHeaderNotAllowed() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); @@ -332,7 +330,7 @@ void preFlightRequestHeaderNotAllowed() throws ServletException, IOException { } @Test - void preFlightRequestUriNotWhitelisted() throws ServletException, IOException { + void preFlightRequestUriNotWhitelisted() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/login"); @@ -350,7 +348,7 @@ void preFlightRequestUriNotWhitelisted() throws ServletException, IOException { } @Test - void preFlightOriginNotWhitelisted() throws ServletException, IOException { + void preFlightOriginNotWhitelisted() throws Exception { CorsFilter corsFilter = createConfiguredCorsFilter(); MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); @@ -368,7 +366,7 @@ void preFlightOriginNotWhitelisted() throws ServletException, IOException { } @Test - void doInitializeWithNoPropertiesSet() throws ServletException, IOException { + void doInitializeWithNoPropertiesSet() throws Exception { CorsFilter corsFilter = new CorsFilter(mockIdentityZoneManager, false); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java index d3af83c6541..be69c8ed7d5 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/web/CorsFilterNonDefaultZoneTests.java @@ -10,8 +10,6 @@ import org.springframework.mock.web.MockHttpServletResponse; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; -import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -61,7 +59,7 @@ void setUp() { "GET, /uaa/userinfo, bunnyoutlet.com, Illegal origin", "GET, /uaa/login, example.com, Illegal request URI", }) - void requestWithInvalidOrigins(String method, String url, String origin, String message) throws ServletException, IOException { + void requestWithInvalidOrigins(String method, String url, String origin, String message) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(method, url); request.addHeader("Origin", origin); request.addHeader("X-Requested-With", "XMLHttpRequest"); @@ -72,7 +70,7 @@ void requestWithInvalidOrigins(String method, String url, String origin, String } @Test - void sameOriginRequest() throws ServletException, IOException { + void sameOriginRequest() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); request.addHeader("X-Requested-With", "XMLHttpRequest"); corsFilter.doFilter(request, response, filterChain); @@ -82,7 +80,7 @@ void sameOriginRequest() throws ServletException, IOException { // happy path @Test - void requestExpectXhrCorsResponse() throws ServletException, IOException { + void requestExpectXhrCorsResponse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); request.addHeader("Origin", "example.com"); request.addHeader("X-Requested-With", "XMLHttpRequest"); @@ -93,7 +91,7 @@ void requestExpectXhrCorsResponse() throws ServletException, IOException { } @Test - void requestWithAllowedOriginPatterns() throws ServletException, IOException { + void requestWithAllowedOriginPatterns() throws Exception { identityZone.getConfig().getCorsPolicy().getXhrConfiguration().getAllowedOriginPatterns() .add(Pattern.compile("bunnyoutlet-shop.com$")); @@ -106,7 +104,7 @@ void requestWithAllowedOriginPatterns() throws ServletException, IOException { } @Test - void requestWithAllowedUriPatterns() throws ServletException, IOException { + void requestWithAllowedUriPatterns() throws Exception { identityZone.getConfig().getCorsPolicy().getXhrConfiguration().getAllowedUriPatterns() .add(Pattern.compile("/uaa/*")); @@ -119,7 +117,7 @@ void requestWithAllowedUriPatterns() throws ServletException, IOException { } @Test - void requestWithMethodNotAllowed() throws ServletException, IOException { + void requestWithMethodNotAllowed() throws Exception { List allowedMethods = List.of(GET.toString(), OPTIONS.toString(), DELETE.toString()); identityZone.getConfig().getCorsPolicy().getXhrConfiguration().setAllowedMethods(allowedMethods); @@ -134,7 +132,7 @@ void requestWithMethodNotAllowed() throws ServletException, IOException { // preflight happy path @Test - void preFlightExpectXhrCorsResponse() throws ServletException, IOException { + void preFlightExpectXhrCorsResponse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization, X-Requested-With"); request.addHeader("Access-Control-Request-Method", "GET"); @@ -149,7 +147,7 @@ void preFlightExpectXhrCorsResponse() throws ServletException, IOException { } @Test - void preFlightWrongOriginSpecified() throws ServletException, IOException { + void preFlightWrongOriginSpecified() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization, X-Requested-With"); request.addHeader("Access-Control-Request-Method", "GET"); @@ -161,7 +159,7 @@ void preFlightWrongOriginSpecified() throws ServletException, IOException { } @Test - void preFlightRequestNoRequestMethod() throws ServletException, IOException { + void preFlightRequestNoRequestMethod() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization, X-Requested-With"); request.addHeader("Origin", "example.com"); @@ -173,7 +171,7 @@ void preFlightRequestNoRequestMethod() throws ServletException, IOException { } @Test - void preFlightRequestMethodNotAllowed() throws ServletException, IOException { + void preFlightRequestMethodNotAllowed() throws Exception { List allowedMethods = List.of(GET.toString(), PUT.toString(), DELETE.toString()); identityZone.getConfig().getCorsPolicy().getXhrConfiguration().setAllowedMethods(allowedMethods); @@ -188,7 +186,7 @@ void preFlightRequestMethodNotAllowed() throws ServletException, IOException { } @Test - void preFlightRequestHeaderNotAllowed() throws ServletException, IOException { + void preFlightRequestHeaderNotAllowed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization, X-Requested-With, X-Not-Allowed"); request.addHeader("Access-Control-Request-Method", "GET"); @@ -200,7 +198,7 @@ void preFlightRequestHeaderNotAllowed() throws ServletException, IOException { } @Test - void preFlightRequestUriNotAllowed() throws ServletException, IOException { + void preFlightRequestUriNotAllowed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/login"); request.addHeader("Access-Control-Request-Method", "GET"); request.addHeader("Access-Control-Request-Headers", "X-Requested-With"); @@ -212,7 +210,7 @@ void preFlightRequestUriNotAllowed() throws ServletException, IOException { } @Test - void preFlightOriginNotAllowed() throws ServletException, IOException { + void preFlightOriginNotAllowed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Method", "GET"); request.addHeader("Access-Control-Request-Headers", "X-Requested-With"); @@ -230,7 +228,7 @@ void preFlightOriginNotAllowed() throws ServletException, IOException { "GET, /uaa/userinfo, bunnyoutlet.com, Illegal origin", "GET, /uaa/login, example.com, Illegal request URI", }) - void defaultCorsWithInvalidOrigins(String method, String url, String origin, String message) throws ServletException, IOException { + void defaultCorsWithInvalidOrigins(String method, String url, String origin, String message) throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(method, url); request.addHeader("Origin", origin); corsFilter.doFilter(request, response, filterChain); @@ -240,7 +238,7 @@ void defaultCorsWithInvalidOrigins(String method, String url, String origin, Str } @Test - void defaultCorsWithSameOrigin() throws ServletException, IOException { + void defaultCorsWithSameOrigin() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); corsFilter.doFilter(request, response, filterChain); @@ -249,7 +247,7 @@ void defaultCorsWithSameOrigin() throws ServletException, IOException { // happy path @Test - void defaultCorsExpectStandardCorsResponse() throws ServletException, IOException { + void defaultCorsExpectStandardCorsResponse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/uaa/userinfo"); request.addHeader("Origin", "example.com"); corsFilter.doFilter(request, response, filterChain); @@ -259,7 +257,7 @@ void defaultCorsExpectStandardCorsResponse() throws ServletException, IOExceptio } @Test - void defaultCorsWithAllowedOriginPatterns() throws ServletException, IOException { + void defaultCorsWithAllowedOriginPatterns() throws Exception { identityZone.getConfig().getCorsPolicy().getDefaultConfiguration().getAllowedOriginPatterns() .add(Pattern.compile("bunnyoutlet.com$")); @@ -271,7 +269,7 @@ void defaultCorsWithAllowedOriginPatterns() throws ServletException, IOException } @Test - void defaultCorsWithAllowedUriPatterns() throws ServletException, IOException { + void defaultCorsWithAllowedUriPatterns() throws Exception { identityZone.getConfig().getCorsPolicy().getDefaultConfiguration().getAllowedUriPatterns() .add(Pattern.compile("/uaa/*")); @@ -283,7 +281,7 @@ void defaultCorsWithAllowedUriPatterns() throws ServletException, IOException { } @Test - void defaultCorsWithMethodNotAllowed() throws ServletException, IOException { + void defaultCorsWithMethodNotAllowed() throws Exception { List allowedMethods = List.of(GET.toString(), OPTIONS.toString(), DELETE.toString()); identityZone.getConfig().getCorsPolicy().getDefaultConfiguration().setAllowedMethods(allowedMethods); @@ -297,7 +295,7 @@ void defaultCorsWithMethodNotAllowed() throws ServletException, IOException { // preflight happy path @Test - void defaultCorsPreFlightExpectStandardCorsResponse() throws ServletException, IOException { + void defaultCorsPreFlightExpectStandardCorsResponse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization"); request.addHeader("Access-Control-Request-Method", "GET"); @@ -312,7 +310,7 @@ void defaultCorsPreFlightExpectStandardCorsResponse() throws ServletException, I } @Test - void defaultCorsPreFlightWrongOriginSpecified() throws ServletException, IOException { + void defaultCorsPreFlightWrongOriginSpecified() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization"); request.addHeader("Access-Control-Request-Method", "GET"); @@ -324,7 +322,7 @@ void defaultCorsPreFlightWrongOriginSpecified() throws ServletException, IOExcep } @Test - void defaultCorsPreFlightRequestNoRequestMethod() throws ServletException, IOException { + void defaultCorsPreFlightRequestNoRequestMethod() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization"); request.addHeader("Origin", "example.com"); @@ -336,7 +334,7 @@ void defaultCorsPreFlightRequestNoRequestMethod() throws ServletException, IOExc } @Test - void defaultCorsPreFlightRequestMethodNotAllowed() throws ServletException, IOException { + void defaultCorsPreFlightRequestMethodNotAllowed() throws Exception { List allowedMethods = List.of(GET.toString(), PUT.toString(), DELETE.toString()); identityZone.getConfig().getCorsPolicy().getDefaultConfiguration().setAllowedMethods(allowedMethods); @@ -351,7 +349,7 @@ void defaultCorsPreFlightRequestMethodNotAllowed() throws ServletException, IOEx } @Test - void defaultCorsPreFlightRequestHeaderNotAllowed() throws ServletException, IOException { + void defaultCorsPreFlightRequestHeaderNotAllowed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Headers", "Authorization, X-Not-Allowed"); request.addHeader("Access-Control-Request-Method", "GET"); @@ -363,7 +361,7 @@ void defaultCorsPreFlightRequestHeaderNotAllowed() throws ServletException, IOEx } @Test - void defaultCorsPreFlightRequestUriNotAllowed() throws ServletException, IOException { + void defaultCorsPreFlightRequestUriNotAllowed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/login"); request.addHeader("Access-Control-Request-Method", "GET"); request.addHeader("Access-Control-Request-Headers", "Authorization"); @@ -375,7 +373,7 @@ void defaultCorsPreFlightRequestUriNotAllowed() throws ServletException, IOExcep } @Test - void defaultCorsPreFlightOriginNotAllowed() throws ServletException, IOException { + void defaultCorsPreFlightOriginNotAllowed() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("OPTIONS", "/uaa/userinfo"); request.addHeader("Access-Control-Request-Method", "GET"); request.addHeader("Access-Control-Request-Headers", "Authorization"); @@ -387,7 +385,7 @@ void defaultCorsPreFlightOriginNotAllowed() throws ServletException, IOException } @Test - void requestWithAllowedOriginPatternsEnforcingSystemZonePolicy() throws ServletException, IOException { + void requestWithAllowedOriginPatternsEnforcingSystemZonePolicy() throws Exception { CorsFilter corsFilter = new CorsFilter(mockIdentityZoneManager, true); corsFilter.setCorsXhrAllowedOrigins(List.of("example.com")); corsFilter.initialize(); @@ -405,7 +403,7 @@ void requestWithAllowedOriginPatternsEnforcingSystemZonePolicy() throws ServletE } @Test - void defaultCorsPreFlightRequestMethodNotAllowedEnforcingSystemZonePolicy() throws ServletException, IOException { + void defaultCorsPreFlightRequestMethodNotAllowedEnforcingSystemZonePolicy() throws Exception { CorsFilter corsFilter = new CorsFilter(mockIdentityZoneManager, true); corsFilter.setCorsAllowedMethods(List.of(GET.toString(), PUT.toString(), DELETE.toString())); corsFilter.initialize(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java b/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java index d49500d6c0f..d9b3f8d5b92 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/test/TestUtils.java @@ -119,7 +119,7 @@ private static void bootstrapDb(ApplicationContext applicationContext) { ClientAdminBootstrap bootstrap = applicationContext.getBean(ClientAdminBootstrap.class); bootstrap.afterPropertiesSet(); } catch (Exception _) { - + // ignore } } @@ -128,7 +128,7 @@ private static void tryCallAfterPropertiesSet(Appli InitializingBean bootstrap = applicationContext.getBean(clazz); bootstrap.afterPropertiesSet(); } catch (Exception _) { - + // ignore } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java index d1235dde342..209c942321e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java @@ -10,7 +10,7 @@ import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class InMemoryUaaUserDatabaseTests { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java index 1f8934dc2df..af65e6abd70 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java @@ -35,9 +35,7 @@ import java.util.UUID; import java.util.stream.Collectors; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.DEFAULT_CASE_INSENSITIVE_USER_BY_EMAIL_AND_ORIGIN_QUERY; import static org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.DEFAULT_CASE_INSENSITIVE_USER_BY_USERNAME_QUERY; import static org.cloudfoundry.identity.uaa.user.JdbcUaaUserDatabase.DEFAULT_CASE_SENSITIVE_USER_BY_EMAIL_AND_ORIGIN_QUERY; @@ -163,16 +161,16 @@ void storeUserInfo() { jdbcUaaUserDatabase.storeUserInfo(id, info); UserInfo info2 = jdbcUaaUserDatabase.getUserInfo(id); assertThat(info2).isEqualTo(info); - assertThat(info2.getUserAttributes()).isEqualTo(userAttributes); - assertThat(info2.getRoles()).isEqualTo(roles); + assertThat(info2.getUserAttributes()).containsExactlyInAnyOrderEntriesOf(userAttributes); + assertThat(info2.getRoles()).containsExactlyElementsOf(roles); roles.add("role4"); userAttributes.add("multi", "4"); jdbcUaaUserDatabase.storeUserInfo(id, info); UserInfo info3 = jdbcUaaUserDatabase.getUserInfo(id); assertThat(info3).isEqualTo(info); - assertThat(info3.getUserAttributes()).isEqualTo(userAttributes); - assertThat(info3.getRoles()).isEqualTo(roles); + assertThat(info3.getUserAttributes()).containsExactlyInAnyOrderEntriesOf(userAttributes); + assertThat(info3.getRoles()).containsExactlyElementsOf(roles); } @Test @@ -205,7 +203,7 @@ void getSaltValueWorks() { @Test @DisabledIfProfile("mysql") - void hsqlPostgresqlCaseSensitive() throws SQLException { + void hsqlPostgresqlCaseSensitive() throws Exception { JdbcTemplate mockJdbcTemplate = mock(JdbcTemplate.class); jdbcUaaUserDatabase = new JdbcUaaUserDatabase(mockJdbcTemplate, timeService, databaseProperties, mockIdentityZoneManager, dbUtils); @@ -220,7 +218,7 @@ void hsqlPostgresqlCaseSensitive() throws SQLException { @Test @EnabledIfProfile("mysql") - void mysqlCaseInsensitive() throws SQLException { + void mysqlCaseInsensitive() throws Exception { JdbcTemplate mockJdbcTemplate = mock(JdbcTemplate.class); jdbcUaaUserDatabase = new JdbcUaaUserDatabase(mockJdbcTemplate, timeService, databaseProperties, mockIdentityZoneManager, dbUtils); @@ -236,7 +234,7 @@ void mysqlCaseInsensitive() throws SQLException { @Test // TODO: this should be parameterized - void getValidUserCaseInsensitive() throws SQLException { + void getValidUserCaseInsensitive() throws Exception { for (boolean caseInsensitive : Arrays.asList(true, false)) { try { var dbProps = new DatabaseProperties(); @@ -290,7 +288,7 @@ void getUserWithExtraAuthorities() { } @Test - void getUserWithMultipleExtraAuthorities() throws SQLException { + void getUserWithMultipleExtraAuthorities() throws Exception { addAuthority("additional", jdbcTemplate, "zone-the-first", JOE_ID); addAuthority("anotherOne", jdbcTemplate, "zone-the-first", JOE_ID); JdbcTemplate spiedJdbcTemplate = Mockito.spy(jdbcTemplate); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java index 0c871afb384..7826aa8da83 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class UaaUserEditorTests { private static final UaaTestAccounts testAccounts = UaaTestAccounts.standard(null); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/CachingPasswordEncoderTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/CachingPasswordEncoderTest.java index 5fab7fdeb92..ac086367c1d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/CachingPasswordEncoderTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/CachingPasswordEncoderTest.java @@ -6,7 +6,6 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; -import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.util.Set; @@ -81,7 +80,7 @@ void notMatches() { } @Test - void cacheIs10XFasterThanNonCached() throws NoSuchAlgorithmException { + void cacheIs10XFasterThanNonCached() throws Exception { passwordEncoder = new BCryptPasswordEncoder(); cachingPasswordEncoder = new CachingPasswordEncoder(passwordEncoder); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/DomainFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/DomainFilterTest.java index 9598f1cab54..382af1d4c62 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/DomainFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/DomainFilterTest.java @@ -275,7 +275,7 @@ void ipds_for_email_domain() { List idpsForEmailDomain = DomainFilter.getIdpsForEmailDomain(activeProviders, "abc@test.org"); - assertThat(idpsForEmailDomain).hasSize(2) + assertThat(idpsForEmailDomain) .containsExactlyInAnyOrder(samlProvider1, samlProvider2); } @@ -285,7 +285,7 @@ void idp_with_wildcard_for_email_domain() { List idpsForEmailDomain = DomainFilter.getIdpsForEmailDomain(activeProviders, "abc@test.org"); - assertThat(idpsForEmailDomain).hasSize(1) + assertThat(idpsForEmailDomain) .containsExactlyInAnyOrder(samlProvider1); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java index fe0028989a2..b00eab6d9f8 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java @@ -65,9 +65,7 @@ import java.util.Map; import static java.util.Collections.emptyList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.REQUIRED_USER_GROUPS; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.EMAIL; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.GRANTED_SCOPES; @@ -529,7 +527,7 @@ void idTokenValidator_findsScopesFromScopeClaim() { when(validator.getDelegates()).thenReturn(List.of(verifier)); List scopes = buildIdTokenValidator(getToken(), validator, new KeyInfoService("https://localhost")).requestedScopes(); - assertThat(scopes).isEqualTo(Lists.newArrayList("openid")); + assertThat(scopes).containsExactlyElementsOf(Lists.newArrayList("openid")); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/KeyWithCertTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/KeyWithCertTest.java index 3a183ec4e8f..6cbe0b75b23 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/KeyWithCertTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/KeyWithCertTest.java @@ -212,22 +212,22 @@ void keyMismatch() { } @Test - void validCert() throws CertificateException { + void validCert() throws Exception { assertThat(new KeyWithCert(ENCRYPTED_KEY, PASSWORD, GOOD_CERT)).isNotNull(); } @Test - void ellipticCurve() throws CertificateException { + void ellipticCurve() throws Exception { assertThat(new KeyWithCert(EC_PRIVATE_KEY, "", EC_CERTIFICATE)).isNotNull(); } @Test - void embeddedPrivateKey() throws CertificateException { + void embeddedPrivateKey() throws Exception { assertThat(new KeyWithCert(OPEN_SSL_PRIVATE_KEY, "", OPEN_SSL_CERT)).isNotNull(); } @Test - void certOnly() throws CertificateException { + void certOnly() throws Exception { assertThat(new KeyWithCert(GOOD_CERT)) .isNotNull() .extracting(KeyWithCert::getCertificate) diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMapTests.java index e6ea72b39be..885cc20bcb9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/LinkedMaskingMultiValueMapTests.java @@ -58,7 +58,7 @@ void addAll() { map.add("key", "value1"); map.addAll("key", Arrays.asList("value2", "value3")); assertThat(map.size()).isOne(); - assertThat(map.get("key")).hasSize(3) + assertThat(map.get("key")) .containsExactly("value1", "value2", "value3"); } @@ -70,9 +70,9 @@ void addAllFromAnotherMultiValueMap() { map.add("key1", "existing value"); map.addAll(toCopy); assertThat(map).hasSize(2); - assertThat(map.get("key1")).hasSize(2) + assertThat(map.get("key1")) .containsExactly("existing value", "value1"); - assertThat(map.get("key2")).hasSize(1) + assertThat(map.get("key2")) .containsExactly("value2"); } @@ -97,15 +97,15 @@ void set() { @Test void equals() { map.set("key1", "value1"); - assertThat(map).isEqualTo(map); + assertThat(map).containsExactlyInAnyOrderEntriesOf(map); MultiValueMap o1 = new LinkedMaskingMultiValueMap<>(); o1.set("key1", "value1"); - assertThat(o1).isEqualTo(map); - assertThat(map).isEqualTo(o1); + assertThat(o1).containsExactlyInAnyOrderEntriesOf(map); + assertThat(map).containsExactlyInAnyOrderEntriesOf(o1); Map> o2 = new HashMap<>(); o2.put("key1", Collections.singletonList("value1")); - assertThat(o2).isEqualTo(map); - assertThat(map).isEqualTo(o2); + assertThat(o2).containsExactlyInAnyOrderEntriesOf(map); + assertThat(map).containsExactlyInAnyOrderEntriesOf(o2); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/MediaTypeUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/MediaTypeUtilsTest.java index 94fe77dab1a..e41ee29f8b8 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/MediaTypeUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/MediaTypeUtilsTest.java @@ -29,7 +29,7 @@ void sortByQualityValueWithNullThrowsException() { @MethodSource("listsThatShouldNotBeSorted") void sortByQualityValueWithListsThatDoNotNeedSorting(List mediaTypes, List expected) { MediaTypeUtils.sortByQualityValue(mediaTypes); - assertThat(mediaTypes).isEqualTo(expected); + assertThat(mediaTypes).containsExactlyElementsOf(expected); } static Stream listsThatShouldNotBeSorted() { @@ -102,29 +102,28 @@ void byQualityValueComparatorHandlesAllScenarios() { assertThat(comp.compare(audioBasicLevel, audioBasicLevel)).as("Invalid comparison result").isZero(); // specific to unspecific - assertThat(comp.compare(audioBasic, audio)).as("Invalid comparison result").isLessThan(0); - assertThat(comp.compare(audioBasic, all)).as("Invalid comparison result").isLessThan(0); - assertThat(comp.compare(audio, all)).as("Invalid comparison result").isLessThan(0); - assertThat(comp.compare(MediaType.APPLICATION_XHTML_XML, allXml)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audioBasic, audio)).as("Invalid comparison result").isNegative(); + assertThat(comp.compare(audioBasic, all)).as("Invalid comparison result").isNegative(); + assertThat(comp.compare(audio, all)).as("Invalid comparison result").isNegative(); + assertThat(comp.compare(MediaType.APPLICATION_XHTML_XML, allXml)).as("Invalid comparison result").isNegative(); // unspecific to specific - assertThat(comp.compare(audio, audioBasic)).as("Invalid comparison result").isGreaterThan(0); - assertThat(comp.compare(all, audioBasic)).as("Invalid comparison result").isGreaterThan(0); - assertThat(comp.compare(all, audio)).as("Invalid comparison result").isGreaterThan(0); - assertThat(comp.compare(allXml, MediaType.APPLICATION_XHTML_XML)).as("Invalid comparison result") - .isGreaterThan(0); + assertThat(comp.compare(audio, audioBasic)).as("Invalid comparison result").isPositive(); + assertThat(comp.compare(all, audioBasic)).as("Invalid comparison result").isPositive(); + assertThat(comp.compare(all, audio)).as("Invalid comparison result").isPositive(); + assertThat(comp.compare(allXml, MediaType.APPLICATION_XHTML_XML)).as("Invalid comparison result").isPositive(); // qualifiers - assertThat(comp.compare(audio, audio07)).as("Invalid comparison result").isLessThan(0); - assertThat(comp.compare(audio07, audio)).as("Invalid comparison result").isGreaterThan(0); - assertThat(comp.compare(audio07, audio03)).as("Invalid comparison result").isLessThan(0); - assertThat(comp.compare(audio03, audio07)).as("Invalid comparison result").isGreaterThan(0); - assertThat(comp.compare(audio03, all)).as("Invalid comparison result").isGreaterThan(0); - assertThat(comp.compare(all, audio03)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audio, audio07)).as("Invalid comparison result").isNegative(); + assertThat(comp.compare(audio07, audio)).as("Invalid comparison result").isPositive(); + assertThat(comp.compare(audio07, audio03)).as("Invalid comparison result").isNegative(); + assertThat(comp.compare(audio03, audio07)).as("Invalid comparison result").isPositive(); + assertThat(comp.compare(audio03, all)).as("Invalid comparison result").isPositive(); + assertThat(comp.compare(all, audio03)).as("Invalid comparison result").isNegative(); // other parameters - assertThat(comp.compare(audioBasic, audioBasicLevel)).as("Invalid comparison result").isGreaterThan(0); - assertThat(comp.compare(audioBasicLevel, audioBasic)).as("Invalid comparison result").isLessThan(0); + assertThat(comp.compare(audioBasic, audioBasicLevel)).as("Invalid comparison result").isPositive(); + assertThat(comp.compare(audioBasicLevel, audioBasic)).as("Invalid comparison result").isNegative(); // different types assertThat(comp.compare(audioBasic, textHtml)).as("Invalid comparison result").isZero(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java index 1cc4b3f8495..ec3f7ddc1aa 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java @@ -5,7 +5,7 @@ import org.springframework.mock.web.MockHttpSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class SessionUtilsTest { private MockHttpSession mockHttpSession; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java index b5650eb92b5..392ff4c0613 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java @@ -5,7 +5,7 @@ import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class TestUaaUrlBuilderTest { private TestUaaUrlBuilder builder; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java index 66f00a6310d..d18de42265e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaHttpRequestUtilsTest.java @@ -164,10 +164,12 @@ void clientBuilderAppliesReadTimeout() throws Exception { try (ServerSocket ss = new ServerSocket(0, 1, loopback)) { int port = ss.getLocalPort(); Thread acceptThread = new Thread(() -> { - try (var socket = ss.accept()) { + try (var _ = ss.accept()) { // Sleep longer than the read timeout so the client times out first. Thread.sleep(readTimeoutMs * 10L); - } catch (Exception _) {} + } catch (Exception _) { + // ignore + } }); acceptThread.setDaemon(true); acceptThread.start(); @@ -199,12 +201,16 @@ void clientBuilderWithZeroTimeoutsDoesNotTimeOut() throws Exception { // Read until end of HTTP request headers var headerReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.US_ASCII)); String line; - while ((line = headerReader.readLine()) != null && !line.isEmpty()) {} + while ((line = headerReader.readLine()) != null && !line.isEmpty()) { + // do nothing + } String response = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; out.write(response.getBytes(StandardCharsets.US_ASCII)); out.flush(); clientSocket.close(); - } catch (Exception _) {} + } catch (Exception _) { + // ignore + } }); serverThread.setDaemon(true); serverThread.start(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaMapUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaMapUtilsTest.java index a298404f6b1..3852a0df653 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaMapUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaMapUtilsTest.java @@ -106,7 +106,7 @@ void sort_nested_map() { "nullValue" ); assertThat(visit_all_keys(top)).isNotEqualTo(expectedOrder); - assertThat(visit_all_keys(sortByKeys(top))).isEqualTo(expectedOrder); + assertThat(visit_all_keys(sortByKeys(top))).containsExactlyElementsOf(expectedOrder); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaPagingUtilsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaPagingUtilsTests.java index c024492597d..dce393eb39f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaPagingUtilsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaPagingUtilsTests.java @@ -38,7 +38,7 @@ void createList() { void pagingSubListHighCount() { List result = UaaPagingUtils.subList(list, 1, 100); assertThat(result).hasSize(4); - assertThat(result.getFirst()).isEqualTo("one"); + assertThat(result).first().isEqualTo("one"); assertThat(result.get(3)).isEqualTo("four"); } @@ -46,7 +46,7 @@ void pagingSubListHighCount() { void pagingSubListLowCount() { List result = UaaPagingUtils.subList(list, 1, 2); assertThat(result).hasSize(2); - assertThat(result.getFirst()).isEqualTo("one"); + assertThat(result).first().isEqualTo("one"); assertThat(result.get(1)).isEqualTo("two"); } @@ -54,7 +54,7 @@ void pagingSubListLowCount() { void pagingSubListEqualCount() { List result = UaaPagingUtils.subList(list, 1, 4); assertThat(result).hasSize(4); - assertThat(result.getFirst()).isEqualTo("one"); + assertThat(result).first().isEqualTo("one"); assertThat(result.get(3)).isEqualTo("four"); } @@ -63,14 +63,14 @@ void pagingSubListEqualCount() { void pagingSubListOneCount() { List result = UaaPagingUtils.subList(list, 1, 1); assertThat(result).hasSize(1); - assertThat(result.getFirst()).isEqualTo("one"); + assertThat(result).first().isEqualTo("one"); } @Test void pagingSubListPage() { List result = UaaPagingUtils.subList(list, 3, 2); assertThat(result).hasSize(2); - assertThat(result.getFirst()).isEqualTo("three"); + assertThat(result).first().isEqualTo("three"); assertThat(result.get(1)).isEqualTo("four"); } @@ -78,7 +78,7 @@ void pagingSubListPage() { void pagingSubListPageHighCount() { List result = UaaPagingUtils.subList(list, 2, 100); assertThat(result).hasSize(3); - assertThat(result.getFirst()).isEqualTo("two"); + assertThat(result).first().isEqualTo("two"); assertThat(result.get(2)).isEqualTo("four"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java index 5ba62a91c82..b3a9c51cc52 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java @@ -9,7 +9,7 @@ import java.security.NoSuchProviderException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class UaaRandomStringUtilImplTest { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java index a529818b28b..004a19e6f0d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java @@ -16,7 +16,7 @@ import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.CID; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.SUB; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java index 609ef8f1089..dd66b04024b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java @@ -24,9 +24,7 @@ import java.util.Map; import java.util.Set; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.util.UaaUrlUtils.normalizeUrlForPortComparison; import static org.mockito.Mockito.mock; diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java index a94cfe35673..0c783b1c562 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java @@ -14,7 +14,7 @@ import java.sql.SQLException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -36,7 +36,7 @@ void setup() throws MetaDataAccessException { } @Test - void canQuoteHsqldbIdentifiers() throws SQLException { + void canQuoteHsqldbIdentifiers() throws Exception { when(databaseMetaData.getURL()).thenReturn("jdbc:hsqldb:mem:uaa"); String quotedIdentifier = dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate); @@ -44,7 +44,7 @@ void canQuoteHsqldbIdentifiers() throws SQLException { } @Test - void canCacheForHsqldb() throws SQLException { + void canCacheForHsqldb() throws Exception { when(databaseMetaData.getURL()) .thenReturn("jdbc:hsqldb:mem:uaa", "SHOULD NOT SEE THIS"); dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate); @@ -63,7 +63,7 @@ void setup() throws SQLException { } @Test - void canQuoteWithBackticks_ForMysql() throws SQLException { + void canQuoteWithBackticks_ForMysql() throws Exception { when(databaseMetaData.getIdentifierQuoteString()).thenReturn(BACKTICK); String quotedIdentifier = dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate); @@ -71,7 +71,7 @@ void canQuoteWithBackticks_ForMysql() throws SQLException { } @Test - void canQuoteWithDoubleQuote_ForPostgres() throws SQLException { + void canQuoteWithDoubleQuote_ForPostgres() throws Exception { when(databaseMetaData.getIdentifierQuoteString()).thenReturn(DOUBLE_QUOTE); String quotedIdentifier = dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate); @@ -79,7 +79,7 @@ void canQuoteWithDoubleQuote_ForPostgres() throws SQLException { } @Test - void canCache() throws SQLException { + void canCache() throws Exception { when(databaseMetaData.getIdentifierQuoteString()).thenReturn(BACKTICK, DOUBLE_QUOTE); dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate); @@ -90,13 +90,13 @@ void canCache() throws SQLException { @ParameterizedTest @ValueSource(strings = {SINGLE_QUOTE, "", BACKTICK + DOUBLE_QUOTE}) @NullSource - void rejectsInvalidQuoteStrings(String quoteString) throws SQLException { + void rejectsInvalidQuoteStrings(String quoteString) throws Exception { when(databaseMetaData.getIdentifierQuoteString()).thenReturn(quoteString); assertThatExceptionOfType(Throwable.class).isThrownBy(() -> dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate)); } @Test - void abortsWhenCannotGetMetaData() throws MetaDataAccessException { + void abortsWhenCannotGetMetaData() throws Exception { when(metaDataExtractor.extractDatabaseMetaData(any())).thenThrow(MetaDataAccessException.class); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate)); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/web/CookieBasedCsrfTokenRepositoryTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/web/CookieBasedCsrfTokenRepositoryTests.java index 75487928681..01dd81ef995 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/web/CookieBasedCsrfTokenRepositoryTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/web/CookieBasedCsrfTokenRepositoryTests.java @@ -145,9 +145,10 @@ void saveToken_MakeAnExpiredTokenInResponse_whenNoTokenInRequest() { // Spring Framework 7: MockHttpServletResponse.getCookie() no longer parses // Set-Cookie headers added via addHeader(). Check the header directly instead. String setCookieHeader = response.getHeader("Set-Cookie"); - assertThat(setCookieHeader).contains("X-Uaa-Csrf="); - // Max-Age=0 or Expires at Unix epoch indicates expired/deleted cookie - assertThat(setCookieHeader).satisfiesAnyOf( + assertThat(setCookieHeader) + .contains("X-Uaa-Csrf=") + // Max-Age=0 or Expires at Unix epoch indicates expired/deleted cookie + .satisfiesAnyOf( header -> assertThat(header).contains("Max-Age=0"), header -> assertThat(header).contains("Expires=Thu, 1 Jan 1970") ); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerTests.java index 990aaa8be83..2d605c0d240 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerTests.java @@ -23,9 +23,7 @@ import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.web.savedrequest.SavedRequest; -import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpSession; -import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.web.UaaSavedRequestAwareAuthenticationSuccessHandler.FORM_REDIRECT_PARAMETER; @@ -78,7 +76,7 @@ void invalidFormRedirectIsNotReturned() { } @Test - void onAuthenticationSuccess_noSavedRequest_hasRelayStateUrl() throws ServletException, IOException { + void onAuthenticationSuccess_noSavedRequest_hasRelayStateUrl() throws Exception { String redirectUri = "https://test.com/test2"; request.setParameter(Saml2ParameterNames.RELAY_STATE, redirectUri); @@ -90,7 +88,7 @@ void onAuthenticationSuccess_noSavedRequest_hasRelayStateUrl() throws ServletExc } @Test - void onAuthenticationSuccess_noSavedRequest_noRelayStateUrl() throws ServletException, IOException { + void onAuthenticationSuccess_noSavedRequest_noRelayStateUrl() throws Exception { request.setParameter(Saml2ParameterNames.RELAY_STATE, "123"); request.getSession().setAttribute("SPRING_SECURITY_LAST_EXCEPTION", "exception"); @@ -105,7 +103,7 @@ void onAuthenticationSuccess_noSavedRequest_noRelayStateUrl() throws ServletExce } @Test - void onAuthenticationSuccess_withSavedRequest_targetUrlParameter() throws ServletException, IOException { + void onAuthenticationSuccess_withSavedRequest_targetUrlParameter() throws Exception { String redirectUri = "https://test.com/test3"; SavedRequest savedRequest = mock(SavedRequest.class); when(savedRequest.getRedirectUrl()).thenReturn(redirectUri); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerZonePathTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerZonePathTests.java index 6d42eb63298..8e57a7ab9a9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerZonePathTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestAwareAuthenticationSuccessHandlerZonePathTests.java @@ -26,9 +26,6 @@ import org.springframework.security.core.Authentication; import org.cloudfoundry.identity.uaa.extensions.EnabledIfZonePathsEnabled; -import jakarta.servlet.ServletException; -import java.io.IOException; - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -79,7 +76,7 @@ void determineTargetUrl_with_context_path_returns_zone_aware_default(ZoneRequest @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void onAuthenticationSuccess_noSavedRequest_redirects_to_zone_aware_default(ZoneRequestPathMode mode) throws ServletException, IOException { + void onAuthenticationSuccess_noSavedRequest_redirects_to_zone_aware_default(ZoneRequestPathMode mode) throws Exception { mode.setZone(); mode.applyRequestPath(request, "/login.do"); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -93,7 +90,7 @@ void onAuthenticationSuccess_noSavedRequest_redirects_to_zone_aware_default(Zone @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void onAuthenticationSuccess_noSavedRequest_with_context_path_redirects_to_zone_aware_default(ZoneRequestPathMode mode) throws ServletException, IOException { + void onAuthenticationSuccess_noSavedRequest_with_context_path_redirects_to_zone_aware_default(ZoneRequestPathMode mode) throws Exception { mode.setZone(); request.setContextPath("/uaa"); mode.applyRequestPath(request, "/login.do"); @@ -109,7 +106,7 @@ void onAuthenticationSuccess_noSavedRequest_with_context_path_redirects_to_zone_ @ParameterizedTest @EnumSource(ZoneRequestPathMode.class) - void onAuthenticationSuccess_withSavedRequest_redirects_to_saved_url(ZoneRequestPathMode mode) throws ServletException, IOException { + void onAuthenticationSuccess_withSavedRequest_redirects_to_saved_url(ZoneRequestPathMode mode) throws Exception { mode.setZone(); mode.applyRequestPath(request, "/login.do"); // DEFAULT: no zone path in URL; ZONE_PATH: zone path in path diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestCacheTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestCacheTests.java index a515e3403c9..1235a70477a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestCacheTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/web/UaaSavedRequestCacheTests.java @@ -29,12 +29,9 @@ import org.springframework.security.web.savedrequest.SavedRequest; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; -import java.io.IOException; -import java.net.MalformedURLException; import java.net.URI; import static org.assertj.core.api.Assertions.assertThat; @@ -170,7 +167,7 @@ void only_save_for_POST_calls() { } @Test - void should_save_condition_works() throws MalformedURLException { + void should_save_condition_works() throws Exception { assertThat(cache.shouldSaveFormRedirectParameter(request)).isFalse(); request.setPathInfo("/login.do"); @@ -220,7 +217,7 @@ void saved_request_matcher() { } @Test - void unapprovedFormRedirectRequestDoesNotSave() throws IOException, ServletException { + void unapprovedFormRedirectRequestDoesNotSave() throws Exception { request.setPathInfo("/login.do"); request.setRequestURI("/login.do"); request.setMethod(HttpMethod.POST.name()); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java index 885781173fb..e0d8f7ff3e4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -32,7 +32,7 @@ void setUp() { } @Test - void doesNotStopTheServer() throws LifecycleException { + void doesNotStopTheServer() throws Exception { listener.lifecycleEvent(mockLifecycleEvent(server, Lifecycle.AFTER_START_EVENT)); verify(server, times(0)).start(); verify(server, times(0)).destroy(); @@ -51,14 +51,14 @@ void setUp() { } @Test - void stopsTheServer() throws LifecycleException { + void stopsTheServer() throws Exception { listener.lifecycleEvent(mockLifecycleEvent(server, Lifecycle.AFTER_START_EVENT)); verify(server, times(1)).stop(); verify(server, times(1)).destroy(); } @Test - void rethrowsAnyExceptions() throws LifecycleException { + void rethrowsAnyExceptions() throws Exception { doThrow(new LifecycleException()).when(server).stop(); assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> listener.lifecycleEvent(mockLifecycleEvent(server, Lifecycle.AFTER_START_EVENT))); verify(server, times(1)).stop(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/BannerValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/BannerValidatorTest.java index abfabd2af73..38947b5d8a9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/BannerValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/BannerValidatorTest.java @@ -6,7 +6,7 @@ class BannerValidatorTest { @Test - void validatesUrls() throws InvalidIdentityZoneConfigurationException { + void validatesUrls() throws Exception { String[] validUrls = { "https://example.com", "https://example.com/", @@ -58,7 +58,7 @@ void validatesUrls() throws InvalidIdentityZoneConfigurationException { } @Test - void validateColor() throws InvalidIdentityZoneConfigurationException { + void validateColor() throws Exception { String[] validColors = { "#123456", "#000", @@ -101,7 +101,7 @@ void validateColor() throws InvalidIdentityZoneConfigurationException { } @Test - void base64Logo() throws InvalidIdentityZoneConfigurationException { + void base64Logo() throws Exception { String[] validBase64 = { "BIPUQGEWGPIUB64", "" diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneConfigurationValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneConfigurationValidatorTests.java index 8e9b89b9ae4..f6123b92b2d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneConfigurationValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneConfigurationValidatorTests.java @@ -227,7 +227,7 @@ void tearDown() { @MethodSource("parameters") @ParameterizedTest - void validate_with_legacy_key_active(IdentityZoneValidator.Mode mode) throws InvalidIdentityZoneConfigurationException { + void validate_with_legacy_key_active(IdentityZoneValidator.Mode mode) throws Exception { validator.validate(zone, mode); } @@ -252,7 +252,7 @@ void validate_with_invalid_consent_link(IdentityZoneValidator.Mode mode) { @MethodSource("parameters") @ParameterizedTest - void validateConsent_withNotNullTextAndNullLink(IdentityZoneValidator.Mode mode) throws InvalidIdentityZoneConfigurationException { + void validateConsent_withNotNullTextAndNullLink(IdentityZoneValidator.Mode mode) throws Exception { zone.getConfig().getBranding().setConsent(new Consent("Terms and Conditions", null)); validator.validate(zone, mode); } @@ -277,7 +277,7 @@ void validateConsent_withNullTextAndNullLink(IdentityZoneValidator.Mode mode) { @MethodSource("parameters") @ParameterizedTest - void validate_without_legacy_key(IdentityZoneValidator.Mode mode) throws InvalidIdentityZoneConfigurationException { + void validate_without_legacy_key(IdentityZoneValidator.Mode mode) throws Exception { samlConfig.setKeys(emptyMap()); assertThat(samlConfig.getActiveKeyId()).isNull(); samlConfig.addKey("key-1", new SamlKey(KEY_1, PASSPHRASE_1, CERTIFICATE_1)); @@ -331,7 +331,7 @@ void validate_nonUaaZone_withIssuer_andNoTokenPolicy_throwsException(IdentityZon @MethodSource("parameters") @ParameterizedTest - void validate_nonUaaZone_withoutIssuer_andNoActiveKey_succeeds(IdentityZoneValidator.Mode mode) throws InvalidIdentityZoneConfigurationException { + void validate_nonUaaZone_withoutIssuer_andNoActiveKey_succeeds(IdentityZoneValidator.Mode mode) throws Exception { // non-UAA zone without issuer -> condition not triggered, should pass zone.setId("custom-zone"); zone.getConfig().setIssuer("http://localhost:8080/uaa"); @@ -344,7 +344,7 @@ void validate_nonUaaZone_withoutIssuer_andNoActiveKey_succeeds(IdentityZoneValid @MethodSource("parameters") @ParameterizedTest - void validate_uaaZone_withIssuer_andNoActiveKey_succeeds(IdentityZoneValidator.Mode mode) throws InvalidIdentityZoneConfigurationException { + void validate_uaaZone_withIssuer_andNoActiveKey_succeeds(IdentityZoneValidator.Mode mode) throws Exception { // UAA zone is exempt from the issuer check -> should pass even without an active key zone.setId(IdentityZone.getUaaZoneId()); zone.getConfig().setIssuer("http://uaa.example.com/issuer"); @@ -395,7 +395,7 @@ void validate_invalid_corsPolicy_defaultConfiguration_allowedOrigins(IdentityZon @MethodSource("parameters") @ParameterizedTest - void validate_with_token_key_and_certificate(IdentityZoneValidator.Mode mode) throws InvalidIdentityZoneConfigurationException { + void validate_with_token_key_and_certificate(IdentityZoneValidator.Mode mode) throws Exception { setupTokenPolicyWithCertificate(LEGACY_KEY, LEGACY_CERTIFICATE, "RS256"); IdentityZoneConfiguration identityZoneConfiguration = validator.validate(zone, mode); @@ -407,7 +407,7 @@ void validate_with_token_key_and_certificate(IdentityZoneValidator.Mode mode) th @MethodSource("parameters") @ParameterizedTest - void validate_with_token_key_without_certificate(IdentityZoneValidator.Mode mode) throws InvalidIdentityZoneConfigurationException { + void validate_with_token_key_without_certificate(IdentityZoneValidator.Mode mode) throws Exception { setupTokenPolicyWithCertificate("secretkey", null, "HS512"); IdentityZoneConfiguration identityZoneConfiguration = validator.validate(zone, mode); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneValidatorTests.java index 683a86b8362..f1203a445d7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/GeneralIdentityZoneValidatorTests.java @@ -36,7 +36,7 @@ class GeneralIdentityZoneValidatorTests { GeneralIdentityZoneValidator validator; @Test - void validateRightMode() throws InvalidIdentityZoneDetailsException, InvalidIdentityZoneConfigurationException { + void validateRightMode() throws Exception { IdentityZone zone = MultitenancyFixture.identityZone("id", "domain"); IdentityZoneConfiguration config = new IdentityZoneConfiguration(); zone.setConfig(config); @@ -98,7 +98,7 @@ void reservedSubdomainDefault_rejectsForAllModes() { } @Test - void otherZoneInactiveSucceeds() throws InvalidIdentityZoneConfigurationException, InvalidIdentityZoneDetailsException { + void otherZoneInactiveSucceeds() throws Exception { IdentityZone zone = MultitenancyFixture.identityZone("id", "domain"); IdentityZoneConfiguration config = new IdentityZoneConfiguration(); zone.setConfig(config); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java index 41acfc223f3..8c00a4b2e6d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/IdentityZoneEndpointsTests.java @@ -64,7 +64,7 @@ void setUp() { } @Test - void create_zone() throws InvalidIdentityZoneDetailsException { + void create_zone() throws Exception { when(mockIdentityZoneProvisioning.create(any())).then(invocation -> invocation.getArgument(0)); when(mockIdentityZoneValidator.validate(any(), any())).then(invocation -> invocation.getArgument(0)); @@ -87,7 +87,7 @@ void groups_are_created() { } @Test - void group_creation_called_on_create() throws InvalidIdentityZoneDetailsException { + void group_creation_called_on_create() throws Exception { when(mockIdentityZoneProvisioning.create(any())).then(invocation -> invocation.getArgument(0)); when(mockIdentityZoneValidator.validate(any(), any())).then(invocation -> invocation.getArgument(0)); @@ -98,7 +98,7 @@ void group_creation_called_on_create() throws InvalidIdentityZoneDetailsExceptio } @Test - void group_creation_called_on_update() throws InvalidIdentityZoneDetailsException { + void group_creation_called_on_update() throws Exception { when(mockIdentityZoneValidator.validate(any(), any())).then(invocation -> invocation.getArgument(0)); IdentityZoneEndpoints spy = Mockito.spy(endpoints); @@ -140,7 +140,7 @@ void restore_keys() { } @Test - void extend_zone_allowed_groups_on_update() throws InvalidIdentityZoneDetailsException { + void extend_zone_allowed_groups_on_update() throws Exception { when(mockIdentityZoneValidator.validate(any(), any())).then(invocation -> invocation.getArgument(0)); IdentityZoneEndpoints spy = Mockito.spy(endpoints); @@ -157,7 +157,7 @@ void extend_zone_allowed_groups_on_update() throws InvalidIdentityZoneDetailsExc } @Test - void reduce_zone_allowed_groups_on_update_should_fail() throws InvalidIdentityZoneDetailsException { + void reduce_zone_allowed_groups_on_update_should_fail() throws Exception { when(mockIdentityZoneValidator.validate(any(), any())).then(invocation -> invocation.getArgument(0)); identityZone = createZone(); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java index 0c9354fb686..0fcf612ed89 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java @@ -11,9 +11,7 @@ import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; @WithDatabaseContext class JdbcIdentityZoneProvisioningTests { @@ -186,12 +184,7 @@ void createDuplicateIdentityZone() { IdentityZone identityZone = MultitenancyFixture.identityZone("there-can-be-only-one", "there-can-be-only-one"); identityZone.setId(randomValueStringGenerator.generate()); jdbcIdentityZoneProvisioning.create(identityZone); - try { - jdbcIdentityZoneProvisioning.create(identityZone); - fail("Should have thrown exception"); - } catch (ZoneAlreadyExistsException _) { - // success - } + assertThatThrownBy(() -> jdbcIdentityZoneProvisioning.create(identityZone)).isInstanceOf(ZoneAlreadyExistsException.class); } @Test @@ -199,13 +192,10 @@ void createDuplicateIdentityZoneSubdomain() { IdentityZone identityZone = MultitenancyFixture.identityZone("there-can-be-only-one", "there-can-be-only-one"); identityZone.setId(randomValueStringGenerator.generate()); jdbcIdentityZoneProvisioning.create(identityZone); - try { + assertThatThrownBy(() -> { identityZone.setId(new RandomValueStringGenerator().generate()); jdbcIdentityZoneProvisioning.create(identityZone); - fail("Should have thrown exception"); - } catch (ZoneAlreadyExistsException _) { - // success - } + }).isInstanceOf(ZoneAlreadyExistsException.class); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidatorTest.java index 7bb268a752d..33461238213 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/LoginConsentValidatorTest.java @@ -9,13 +9,13 @@ class LoginConsentValidatorTest { @Test - void testValidateNull() { + void validateNull() { List errors = LoginConsentValidator.validate(null); assertThat(errors).isEmpty(); } @Test - void testValidateDisabled() { + void validateDisabled() { LoginConsent consent = new LoginConsent(); consent.setEnabled(false); @@ -24,7 +24,7 @@ void testValidateDisabled() { } @Test - void testValidateEnabledWithAllFields() { + void validateEnabledWithAllFields() { LoginConsent consent = new LoginConsent( true, "Notice", @@ -40,7 +40,7 @@ void testValidateEnabledWithAllFields() { } @Test - void testValidateEnabledWithoutDeclineLink() { + void validateEnabledWithoutDeclineLink() { LoginConsent consent = new LoginConsent( true, "Notice", @@ -56,92 +56,92 @@ void testValidateEnabledWithoutDeclineLink() { } @Test - void testValidateEnabledMissingTitle() { + void validateEnabledMissingTitle() { LoginConsent consent = new LoginConsent( - true, - null, - "You are accessing a system that is provided for authorized use only.", - "I Accept", - "Decline", - "https://www.cloudfoundry.org", - "12h" + true, + null, + "You are accessing a system that is provided for authorized use only.", + "I Accept", + "Decline", + "https://www.cloudfoundry.org", + "12h" ); - + List errors = LoginConsentValidator.validate(consent); - assertThat(errors).hasSize(1); - assertThat(errors.getFirst()).contains("title is required"); + assertThat(errors).hasSize(1) + .contains("loginConsent.title is required when loginConsent is enabled"); } @Test - void testValidateEnabledEmptyTitle() { + void validateEnabledEmptyTitle() { LoginConsent consent = new LoginConsent( - true, - " ", - "You are accessing a system that is provided for authorized use only.", - "I Accept", - "Decline", - "https://www.cloudfoundry.org", - "12h" + true, + " ", + "You are accessing a system that is provided for authorized use only.", + "I Accept", + "Decline", + "https://www.cloudfoundry.org", + "12h" ); - + List errors = LoginConsentValidator.validate(consent); - assertThat(errors).hasSize(1); - assertThat(errors.getFirst()).contains("title is required"); + assertThat(errors).hasSize(1) + .contains("loginConsent.title is required when loginConsent is enabled"); } @Test - void testValidateEnabledMissingText() { + void validateEnabledMissingText() { LoginConsent consent = new LoginConsent( - true, - "Notice", - null, - "I Accept", - "Decline", - "https://www.cloudfoundry.org", - "12h" + true, + "Notice", + null, + "I Accept", + "Decline", + "https://www.cloudfoundry.org", + "12h" ); - + List errors = LoginConsentValidator.validate(consent); - assertThat(errors).hasSize(1); - assertThat(errors.getFirst()).contains("text is required"); + assertThat(errors).hasSize(1) + .contains("loginConsent.text is required when loginConsent is enabled"); } @Test - void testValidateEnabledMissingAcceptButtonText() { + void validateEnabledMissingAcceptButtonText() { LoginConsent consent = new LoginConsent( - true, - "Notice", - "You are accessing a system that is provided for authorized use only.", - null, - "Decline", - "https://www.cloudfoundry.org", - "12h" + true, + "Notice", + "You are accessing a system that is provided for authorized use only.", + null, + "Decline", + "https://www.cloudfoundry.org", + "12h" ); - + List errors = LoginConsentValidator.validate(consent); - assertThat(errors).hasSize(1); - assertThat(errors.getFirst()).contains("acceptButtonText is required"); + assertThat(errors).hasSize(1) + .contains("loginConsent.acceptButtonText is required when loginConsent is enabled"); } @Test - void testValidateEnabledMissingDeclineButtonText() { + void validateEnabledMissingDeclineButtonText() { LoginConsent consent = new LoginConsent( - true, - "Notice", - "You are accessing a system that is provided for authorized use only.", - "I Accept", - null, - "https://www.cloudfoundry.org", - "12h" + true, + "Notice", + "You are accessing a system that is provided for authorized use only.", + "I Accept", + null, + "https://www.cloudfoundry.org", + "12h" ); - + List errors = LoginConsentValidator.validate(consent); - assertThat(errors).hasSize(1); - assertThat(errors.getFirst()).contains("declineButtonText is required"); + assertThat(errors).hasSize(1) + .contains("loginConsent.declineButtonText is required when loginConsent is enabled"); } @Test - void testValidateEnabledMultipleErrors() { + void validateEnabledMultipleErrors() { LoginConsent consent = new LoginConsent( true, null, @@ -157,24 +157,24 @@ void testValidateEnabledMultipleErrors() { } @Test - void testValidateInvalidDeclineLink() { + void validateInvalidDeclineLink() { LoginConsent consent = new LoginConsent( - true, - "Notice", - "You are accessing a system that is provided for authorized use only.", - "I Accept", - "Decline", - "not-a-url", - "12h" + true, + "Notice", + "You are accessing a system that is provided for authorized use only.", + "I Accept", + "Decline", + "not-a-url", + "12h" ); - + List errors = LoginConsentValidator.validate(consent); - assertThat(errors).hasSize(1); - assertThat(errors.getFirst()).contains("must be a valid URL"); + assertThat(errors).hasSize(1) + .contains("loginConsent.declineLink must be a valid URL"); } @Test - void testValidateValidHttpsUrl() { + void validateValidHttpsUrl() { LoginConsent consent = new LoginConsent( true, "Notice", @@ -190,7 +190,7 @@ void testValidateValidHttpsUrl() { } @Test - void testValidateValidHttpUrl() { + void validateValidHttpUrl() { //noinspection HttpUrlsUsage LoginConsent consent = new LoginConsent( true, @@ -207,24 +207,24 @@ void testValidateValidHttpUrl() { } @Test - void testValidateInvalidUrlProtocol() { + void validateInvalidUrlProtocol() { LoginConsent consent = new LoginConsent( - true, - "Notice", - "Text", - "Accept", - "Decline", - "ftp://example.com", - "12h" + true, + "Notice", + "Text", + "Accept", + "Decline", + "ftp://example.com", + "12h" ); - + List errors = LoginConsentValidator.validate(consent); - assertThat(errors).hasSize(1); - assertThat(errors.getFirst()).contains("must be a valid URL"); + assertThat(errors).hasSize(1) + .contains("loginConsent.declineLink must be a valid URL"); } @Test - void testValidateValidDurations() { + void validateValidDurations() { String[] validDurations = {"0", "12h", "7d", "1w", "1m", "24H", "30D"}; for (String duration : validDurations) { @@ -244,7 +244,7 @@ void testValidateValidDurations() { } @Test - void testValidateInvalidDurations() { + void validateInvalidDurations() { String[] invalidDurations = {"invalid", "12x", "abc", "-1h", "0h"}; for (String duration : invalidDurations) { @@ -265,7 +265,7 @@ void testValidateInvalidDurations() { } @Test - void testValidateWithoutDuration() { + void validateWithoutDuration() { LoginConsent consent = new LoginConsent( true, "Title", diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java index bc5e37a9750..05a75cebb14 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java @@ -39,9 +39,7 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.REQUIRED_USER_GROUPS; import static org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification.SECRET; import static org.cloudfoundry.identity.uaa.zone.MultitenantJdbcClientDetailsService.DEFAULT_DELETE_STATEMENT; @@ -114,6 +112,7 @@ void deleteByClientId() { try { service.removeClientDetails("some-client-id"); } catch (Exception _) { + // ignore } verify(service, times(1)).deleteByClient(eq("some-client-id"), eq(zoneId)); reset(service); @@ -131,6 +130,7 @@ void deleteByClientRespectsZoneIdParam() { try { service.deleteByClient("some-client-id", "zone-id"); } catch (Exception _) { + // ignore } verify(service, times(1)).deleteByClient(eq("some-client-id"), eq("zone-id")); verify(spyJdbcTemplate, times(1)).update(DEFAULT_DELETE_STATEMENT, "some-client-id", "zone-id"); @@ -255,8 +255,7 @@ void loadingClientIdWithAdditionalInformation() { additionalInfoMap.put("lastModified", lastModifiedDate); additionalInfoMap.put(REQUIRED_USER_GROUPS, StringUtils.commaDelimitedListToSet(dbRequestedUserGroups)); - assertThat(clientDetails.getAdditionalInformation()).containsEntry("lastModified", lastModifiedDate) - .isEqualTo(additionalInfoMap); + assertThat(clientDetails.getAdditionalInformation()).containsEntry("lastModified", lastModifiedDate).containsExactlyInAnyOrderEntriesOf(additionalInfoMap); } @Test @@ -303,7 +302,7 @@ void loadingClientIdWithSingleDetails() { ClientDetails clientDetails = service .loadClientByClientId("clientIdWithSingleDetails"); - assertThat(clientDetails).isNotNull() + assertThat(clientDetails) .isInstanceOf(UaaClientDetails.class); UaaClientDetails uaaUaaClientDetails = (UaaClientDetails) clientDetails; @@ -345,7 +344,7 @@ void loadGroupsGeneratesEmptyCollection() { s); ClientDetails updatedClient = service.loadClientByClientId(clientId); Object userGroups = updatedClient.getAdditionalInformation().get(REQUIRED_USER_GROUPS); - assertThat(userGroups).isNotNull() + assertThat(userGroups) .isInstanceOf(Collection.class); assertThat(((Collection) userGroups)).isEmpty(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java index 515bd137577..0e433fef90e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java @@ -4,23 +4,23 @@ import java.util.Collections; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; class UserConfigValidatorTest { @Test - void defaultConfig() throws InvalidIdentityZoneConfigurationException { + void defaultConfig() throws Exception { UserConfigValidator.validate(new UserConfig()); // defaultGroups not empty, allowedGroups is null } @Test - void nullConfig() throws InvalidIdentityZoneConfigurationException { + void nullConfig() throws Exception { UserConfigValidator.validate(null); } @Test - void allowedGroupsEmpty() throws InvalidIdentityZoneConfigurationException { + void allowedGroupsEmpty() throws Exception { UserConfig userConfig = new UserConfig(); userConfig.setAllowedGroups(Collections.emptyList()); UserConfigValidator.validate(userConfig); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java index db2379e5f76..6dac42cc8e7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java @@ -5,7 +5,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; @ExtendWith(PollutionPreventionExtension.class) class ZoneAwareClientSecretPolicyValidatorTests { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java index b9a1649fe01..6d5bac62556 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneContextPathSessionTests.java @@ -1,7 +1,6 @@ package org.cloudfoundry.identity.uaa.zone; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -16,7 +15,6 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; -import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicLong; @@ -92,8 +90,9 @@ void getAttributeNames_returnsSubSessionKeysOnly() { @Test void getId_includesContainerIdAndContextPathSuffix() { String id = subSession.getId(); - assertThat(id).startsWith(containerSession.getId()); - assertThat(id).endsWith("-uaa-z-myzone"); + assertThat(id) + .startsWith(containerSession.getId()) + .endsWith("-uaa-z-myzone"); } @Test @@ -165,7 +164,7 @@ void creationTime_preservedOnReconnect() { } @Test - void creationTime_resetAfterInvalidateAndRecreate() throws InterruptedException { + void creationTime_resetAfterInvalidateAndRecreate() throws Exception { long originalCreationTime = subSession.getCreationTime(); subSession.setAttribute("data", "val"); subSession.invalidate(); @@ -180,8 +179,8 @@ void creationTime_independentPerZone() { String otherAttrName = ZoneContextPathSessionRequestWrapper.attributeNameForContextPath("/uaa/z/other"); ZonePathHttpSession otherSubSession = new ZonePathHttpSession( containerSession, "/uaa/z/other", otherAttrName, timeService); - assertThat(subSession.getCreationTime()).isNotEqualTo(0L); - assertThat(otherSubSession.getCreationTime()).isNotEqualTo(0L); + assertThat(subSession.getCreationTime()).isNotZero(); + assertThat(otherSubSession.getCreationTime()).isNotZero(); } @Test @@ -196,7 +195,7 @@ void lastAccessedTime_setOnConstruction() { } @Test - void lastAccessedTime_independentPerZone() throws InterruptedException { + void lastAccessedTime_independentPerZone() throws Exception { subSession.setAttribute("data", "val"); Thread.sleep(5); String otherAttrName = ZoneContextPathSessionRequestWrapper.attributeNameForContextPath("/uaa/z/other"); @@ -249,8 +248,8 @@ void containerSession_invalidated_subSessionGetAttributeThrows() { containerSession.invalidate(); // creationTime and lastAccessedTime are cached locally, so they don't throw - assertThat(subSession.getCreationTime()).isGreaterThan(0); - assertThat(subSession.getLastAccessedTime()).isGreaterThan(0); + assertThat(subSession.getCreationTime()).isPositive(); + assertThat(subSession.getLastAccessedTime()).isPositive(); // getAttribute delegates to the invalidated container and throws assertThatThrownBy(() -> subSession.getAttribute("data")) @@ -839,7 +838,7 @@ private FilterChain capturingChain(Runnable action) { } @Test - void wrapsRequestAndResponse() throws ServletException, IOException { + void wrapsRequestAndResponse() throws Exception { request.setContextPath("/uaa"); filter.doFilter(request, response, capturingChain()); @@ -848,7 +847,7 @@ void wrapsRequestAndResponse() throws ServletException, IOException { } @Test - void sessionInsideChain_isZonePathHttpSession() throws ServletException, IOException { + void sessionInsideChain_isZonePathHttpSession() throws Exception { request.setContextPath("/uaa/z/zone1"); filter.doFilter(request, response, capturingChain(() -> { HttpSession session = capturedRequest.get().getSession(true); @@ -862,7 +861,7 @@ void sessionInsideChain_isZonePathHttpSession() throws ServletException, IOExcep } @Test - void sessionAttributes_storedOnContainerImmediately() throws ServletException, IOException { + void sessionAttributes_storedOnContainerImmediately() throws Exception { request.setContextPath("/uaa/z/zone1"); MockHttpSession containerSession = new MockHttpSession(); request.setSession(containerSession); @@ -877,7 +876,7 @@ void sessionAttributes_storedOnContainerImmediately() throws ServletException, I } @Test - void clearsJSessionId_whenAllSubSessionsRemoved() throws ServletException, IOException { + void clearsJSessionId_whenAllSubSessionsRemoved() throws Exception { request.setContextPath("/uaa"); MockHttpSession containerSession = new MockHttpSession(); request.setSession(containerSession); @@ -895,7 +894,7 @@ void clearsJSessionId_whenAllSubSessionsRemoved() throws ServletException, IOExc } @Test - void doesNotClearJSessionId_whenOtherSubSessionsRemain() throws ServletException, IOException { + void doesNotClearJSessionId_whenOtherSubSessionsRemain() throws Exception { request.setContextPath("/uaa/z/zone1"); MockHttpSession containerSession = new MockHttpSession(); request.setSession(containerSession); @@ -916,7 +915,7 @@ void doesNotClearJSessionId_whenOtherSubSessionsRemain() throws ServletException } @Test - void doesNotClearJSessionId_whenResponseAlreadyCommitted() throws ServletException, IOException { + void doesNotClearJSessionId_whenResponseAlreadyCommitted() throws Exception { request.setContextPath("/uaa"); MockHttpSession containerSession = new MockHttpSession(); request.setSession(containerSession); @@ -936,7 +935,7 @@ void doesNotClearJSessionId_whenResponseAlreadyCommitted() throws ServletExcepti } @Test - void multipleZones_sameContainerSession() throws ServletException, IOException { + void multipleZones_sameContainerSession() throws Exception { MockHttpSession containerSession = new MockHttpSession(); // Login to zone1 @@ -963,7 +962,7 @@ void multipleZones_sameContainerSession() throws ServletException, IOException { } @Test - void containerSessionInvalidated_insideChain_handledGracefully() throws ServletException, IOException { + void containerSessionInvalidated_insideChain_handledGracefully() throws Exception { request.setContextPath("/uaa/z/zone1"); MockHttpSession containerSession = new MockHttpSession(); request.setSession(containerSession); @@ -979,7 +978,7 @@ void containerSessionInvalidated_insideChain_handledGracefully() throws ServletE } @Test - void logoutFromOneZone_leavesOtherZonesIntact() throws ServletException, IOException { + void logoutFromOneZone_leavesOtherZonesIntact() throws Exception { MockHttpSession containerSession = new MockHttpSession(); // Setup: login to default zone and zone1 diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java index 7f5e05b91f4..ecaf8ee4a1b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZonePathContextRewritingFilterTests.java @@ -14,7 +14,6 @@ package org.cloudfoundry.identity.uaa.zone; import jakarta.servlet.FilterChain; -import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; @@ -23,7 +22,6 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; import static org.assertj.core.api.Assertions.assertThat; @@ -46,7 +44,7 @@ void setUp() { } @Test - void pathWithoutZonePrefix_passesRequestUnchanged() throws ServletException, IOException { + void pathWithoutZonePrefix_passesRequestUnchanged() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); request.setServletPath("/login"); // container would set this; filter passes request as-is @@ -63,7 +61,7 @@ void pathWithoutZonePrefix_passesRequestUnchanged() throws ServletException, IOE } @Test - void pathWithOnlyZ_noTrailingSlash_passesRequestUnchanged() throws ServletException, IOException { + void pathWithOnlyZ_noTrailingSlash_passesRequestUnchanged() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z"); // does not start with /z/ so not treated as zone path @@ -75,7 +73,7 @@ void pathWithOnlyZ_noTrailingSlash_passesRequestUnchanged() throws ServletExcept } @Test - void pathWithOnlyZ_prefix_noSubdomain_rejectsWithBadRequest() throws ServletException, IOException { + void pathWithOnlyZ_prefix_noSubdomain_rejectsWithBadRequest() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/"); // starts with /z/ but no subdomain segment @@ -87,7 +85,7 @@ void pathWithOnlyZ_prefix_noSubdomain_rejectsWithBadRequest() throws ServletExce } @Test - void pathWithZAndSubdomainButNoSlashAfter_rejectsWithBadRequest() throws ServletException, IOException { + void pathWithZAndSubdomainButNoSlashAfter_rejectsWithBadRequest() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone"); @@ -99,7 +97,7 @@ void pathWithZAndSubdomainButNoSlashAfter_rejectsWithBadRequest() throws Servlet } @Test - void pathWithEmptySubdomainSegment_rejectsWithBadRequest() throws ServletException, IOException { + void pathWithEmptySubdomainSegment_rejectsWithBadRequest() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z//login"); @@ -111,7 +109,7 @@ void pathWithEmptySubdomainSegment_rejectsWithBadRequest() throws ServletExcepti } @Test - void pathWithDefaultZonePrefix_withContextPath_rewritesToIncludeZonePathAndDoesNotSetZoneSubdomainFromPath() throws ServletException, IOException { + void pathWithDefaultZonePrefix_withContextPath_rewritesToIncludeZonePathAndDoesNotSetZoneSubdomainFromPath() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa" + ZONE_PATH_PREFIX + DEFAULT_ZONE_SUBDOMAIN_PATH + "/login"); request.setServerName("localhost"); @@ -132,7 +130,7 @@ void pathWithDefaultZonePrefix_withContextPath_rewritesToIncludeZonePathAndDoesN } @Test - void pathWithDefaultZonePrefix_withoutContextPath_rewritesToIncludeZonePathAndDoesNotSetZoneSubdomainFromPath() throws ServletException, IOException { + void pathWithDefaultZonePrefix_withoutContextPath_rewritesToIncludeZonePathAndDoesNotSetZoneSubdomainFromPath() throws Exception { request.setContextPath(""); request.setRequestURI(ZONE_PATH_PREFIX + DEFAULT_ZONE_SUBDOMAIN_PATH + "/login"); request.setServerName("localhost"); @@ -151,7 +149,7 @@ void pathWithDefaultZonePrefix_withoutContextPath_rewritesToIncludeZonePathAndDo } @Test - void pathWithDefaultZonePrefix_DEFAULT_caseInsensitive_rewritesSameAsLowercase() throws ServletException, IOException { + void pathWithDefaultZonePrefix_DEFAULT_caseInsensitive_rewritesSameAsLowercase() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/" + DEFAULT_ZONE_SUBDOMAIN_PATH.toUpperCase() + "/profile"); @@ -166,7 +164,7 @@ void pathWithDefaultZonePrefix_DEFAULT_caseInsensitive_rewritesSameAsLowercase() } @Test - void pathWithDefaultZonePrefix_trailingSlash_rewritesWithServletPathEmptyAndPathInfoSlash() throws ServletException, IOException { + void pathWithDefaultZonePrefix_trailingSlash_rewritesWithServletPathEmptyAndPathInfoSlash() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa" + ZONE_PATH_PREFIX + DEFAULT_ZONE_SUBDOMAIN_PATH + "/"); @@ -182,7 +180,7 @@ void pathWithDefaultZonePrefix_trailingSlash_rewritesWithServletPathEmptyAndPath } @Test - void pathWithZonePrefix_rewritesRequestAndSetsAttribute() throws ServletException, IOException { + void pathWithZonePrefix_rewritesRequestAndSetsAttribute() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); request.setServerName("localhost"); @@ -202,7 +200,7 @@ void pathWithZonePrefix_rewritesRequestAndSetsAttribute() throws ServletExceptio } @Test - void pathWithZonePrefix_trailingSlashOnly_rewritesWithServletPathEmptyAndPathInfoSlash() throws ServletException, IOException { + void pathWithZonePrefix_trailingSlashOnly_rewritesWithServletPathEmptyAndPathInfoSlash() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/"); @@ -218,7 +216,7 @@ void pathWithZonePrefix_trailingSlashOnly_rewritesWithServletPathEmptyAndPathInf } @Test - void pathWithZonePrefix_multiplePathSegments_rewritesCorrectly() throws ServletException, IOException { + void pathWithZonePrefix_multiplePathSegments_rewritesCorrectly() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/oauth/authorize"); request.setServerName("localhost"); @@ -237,7 +235,7 @@ void pathWithZonePrefix_multiplePathSegments_rewritesCorrectly() throws ServletE } @Test - void emptyContextPath_rewritesCorrectly() throws ServletException, IOException { + void emptyContextPath_rewritesCorrectly() throws Exception { request.setContextPath(""); request.setRequestURI("/z/testzone/login"); request.setServerName("localhost"); @@ -254,7 +252,7 @@ void emptyContextPath_rewritesCorrectly() throws ServletException, IOException { } @Test - void pathWithZonePrefix_Codes_rewritesServletPathToCodes() throws ServletException, IOException { + void pathWithZonePrefix_Codes_rewritesServletPathToCodes() throws Exception { request.setContextPath(""); request.setRequestURI("/z/myzone/Codes"); request.setServerName("localhost"); @@ -271,7 +269,7 @@ void pathWithZonePrefix_Codes_rewritesServletPathToCodes() throws ServletExcepti } @Test - void pathWithZonePrefix_Codes_withContextPath_rewritesServletPathToCodes() throws ServletException, IOException { + void pathWithZonePrefix_Codes_withContextPath_rewritesServletPathToCodes() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/Codes"); request.setServerName("localhost"); @@ -288,7 +286,7 @@ void pathWithZonePrefix_Codes_withContextPath_rewritesServletPathToCodes() throw } @Test - void getRequestURL_onWrappedRequest_returnsRewrittenPath() throws ServletException, IOException { + void getRequestURL_onWrappedRequest_returnsRewrittenPath() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/foo/login"); request.setServerName("login.example.com"); @@ -300,11 +298,11 @@ void getRequestURL_onWrappedRequest_returnsRewrittenPath() throws ServletExcepti HttpServletRequest passed = requestPassedToChain.get(); StringBuffer url = passed.getRequestURL(); - assertThat(url.toString()).isEqualTo("https://login.example.com/uaa/z/foo/login"); + assertThat(url).hasToString("https://login.example.com/uaa/z/foo/login"); } @Test - void getRequestURL_withNonStandardPort_includesPort() throws ServletException, IOException { + void getRequestURL_withNonStandardPort_includesPort() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/bar/profile"); request.setServerName("localhost"); @@ -315,11 +313,11 @@ void getRequestURL_withNonStandardPort_includesPort() throws ServletException, I filter.doFilter(request, response, chain); HttpServletRequest passed = requestPassedToChain.get(); - assertThat(passed.getRequestURL().toString()).isEqualTo("http://localhost:8080/uaa/z/bar/profile"); + assertThat(passed.getRequestURL()).hasToString("http://localhost:8080/uaa/z/bar/profile"); } @Test - void contextPathSingleSlash_withZonePath_normalizesPathAndRewrites() throws ServletException, IOException { + void contextPathSingleSlash_withZonePath_normalizesPathAndRewrites() throws Exception { request.setContextPath("/"); request.setRequestURI("/z/rootzone/oauth/token"); request.setServerName("localhost"); @@ -335,7 +333,7 @@ void contextPathSingleSlash_withZonePath_normalizesPathAndRewrites() throws Serv } @Test - void pathAfterContextEmpty_normalizedToSlash_noRewrite() throws ServletException, IOException { + void pathAfterContextEmpty_normalizedToSlash_noRewrite() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa"); @@ -346,7 +344,7 @@ void pathAfterContextEmpty_normalizedToSlash_noRewrite() throws ServletException } @Test - void subdomainWithHyphen_rewritesCorrectly() throws ServletException, IOException { + void subdomainWithHyphen_rewritesCorrectly() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/my-zone-name/login"); @@ -362,7 +360,7 @@ void subdomainWithHyphen_rewritesCorrectly() throws ServletException, IOExceptio // --- ZONE_ORIGINAL_CONTEXT_PATH attribute --- @Test - void pathWithZonePrefix_setsZoneOriginalContextPathAttribute() throws ServletException, IOException { + void pathWithZonePrefix_setsZoneOriginalContextPathAttribute() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -374,7 +372,7 @@ void pathWithZonePrefix_setsZoneOriginalContextPathAttribute() throws ServletExc } @Test - void pathWithZonePrefix_emptyContextPath_setsZoneOriginalContextPathToEmpty() throws ServletException, IOException { + void pathWithZonePrefix_emptyContextPath_setsZoneOriginalContextPathToEmpty() throws Exception { request.setContextPath(""); request.setRequestURI("/z/testzone/login"); @@ -386,7 +384,7 @@ void pathWithZonePrefix_emptyContextPath_setsZoneOriginalContextPathToEmpty() th } @Test - void pathWithZonePrefix_contextPathSingleSlash_setsZoneOriginalContextPathToSlash() throws ServletException, IOException { + void pathWithZonePrefix_contextPathSingleSlash_setsZoneOriginalContextPathToSlash() throws Exception { request.setContextPath("/"); request.setRequestURI("/z/rootzone/oauth/token"); @@ -398,7 +396,7 @@ void pathWithZonePrefix_contextPathSingleSlash_setsZoneOriginalContextPathToSlas } @Test - void pathWithoutZonePrefix_setsZoneOriginalContextPathToActualContextPath() throws ServletException, IOException { + void pathWithoutZonePrefix_setsZoneOriginalContextPathToActualContextPath() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); @@ -412,7 +410,7 @@ void pathWithoutZonePrefix_setsZoneOriginalContextPathToActualContextPath() thro // --- Cookie path rewriting (addCookie) --- @Test - void cookieWithPathSlash_whenZonePathRewritten_rewritesToOriginalContextPath() throws ServletException, IOException { + void cookieWithPathSlash_whenZonePathRewritten_rewritesToOriginalContextPath() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -429,7 +427,7 @@ void cookieWithPathSlash_whenZonePathRewritten_rewritesToOriginalContextPath() t } @Test - void cookieWithPathOtherThanSlash_whenZonePathRewritten_leavesPathUnchanged() throws ServletException, IOException { + void cookieWithPathOtherThanSlash_whenZonePathRewritten_leavesPathUnchanged() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -446,7 +444,7 @@ void cookieWithPathOtherThanSlash_whenZonePathRewritten_leavesPathUnchanged() th } @Test - void cookieWithPathNull_whenZonePathRewritten_rewritesToOriginalContextPath() throws ServletException, IOException { + void cookieWithPathNull_whenZonePathRewritten_rewritesToOriginalContextPath() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -462,7 +460,7 @@ void cookieWithPathNull_whenZonePathRewritten_rewritesToOriginalContextPath() th } @Test - void noZonePath_withContextPath_rewritesCookiePathToContextPath() throws ServletException, IOException { + void noZonePath_withContextPath_rewritesCookiePathToContextPath() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); @@ -479,7 +477,7 @@ void noZonePath_withContextPath_rewritesCookiePathToContextPath() throws Servlet } @Test - void emptyOriginalContextPath_cookiePathRemainsSlash() throws ServletException, IOException { + void emptyOriginalContextPath_cookiePathRemainsSlash() throws Exception { request.setContextPath(""); request.setRequestURI("/z/myzone/login"); @@ -496,7 +494,7 @@ void emptyOriginalContextPath_cookiePathRemainsSlash() throws ServletException, } @Test - void originalContextPathSingleSlash_cookiePathRemainsSlash() throws ServletException, IOException { + void originalContextPathSingleSlash_cookiePathRemainsSlash() throws Exception { request.setContextPath("/"); request.setRequestURI("/z/rootzone/login"); @@ -513,7 +511,7 @@ void originalContextPathSingleSlash_cookiePathRemainsSlash() throws ServletExcep } @Test - void multipleCookies_mixedPaths_rewritesOnlySlashPath() throws ServletException, IOException { + void multipleCookies_mixedPaths_rewritesOnlySlashPath() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -537,7 +535,7 @@ void multipleCookies_mixedPaths_rewritesOnlySlashPath() throws ServletException, // --- Set-Cookie header (addHeader / setHeader) --- @Test - void addHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOriginalContext() throws ServletException, IOException { + void addHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOriginalContext() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -545,12 +543,13 @@ void addHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOrigin filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); - assertThat(header).contains("Path=/uaa"); - assertThat(header).contains("HttpOnly"); + assertThat(header) + .contains("Path=/uaa") + .contains("HttpOnly"); } @Test - void addHeaderSetCookie_withNoPath_whenZonePathRewritten_addsPathOriginalContext() throws ServletException, IOException { + void addHeaderSetCookie_withNoPath_whenZonePathRewritten_addsPathOriginalContext() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -562,7 +561,7 @@ void addHeaderSetCookie_withNoPath_whenZonePathRewritten_addsPathOriginalContext } @Test - void addHeaderSetCookie_withPathOtherThanSlash_whenZonePathRewritten_leavesPathUnchanged() throws ServletException, IOException { + void addHeaderSetCookie_withPathOtherThanSlash_whenZonePathRewritten_leavesPathUnchanged() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -574,7 +573,7 @@ void addHeaderSetCookie_withPathOtherThanSlash_whenZonePathRewritten_leavesPathU } @Test - void setHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOriginalContext() throws ServletException, IOException { + void setHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOriginalContext() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -582,12 +581,13 @@ void setHeaderSetCookie_withPathSlash_whenZonePathRewritten_rewritesPathToOrigin filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); - assertThat(header).contains("Path=/uaa"); - assertThat(header).contains("Secure"); + assertThat(header) + .contains("Path=/uaa") + .contains("Secure"); } @Test - void addHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws ServletException, IOException { + void addHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -595,12 +595,13 @@ void addHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws ServletEx filter.doFilter(request, response, chain); String header = response.getHeader("Set-Cookie"); - assertThat(header).contains("Path=/"); - assertThat(header).contains("Current-User="); + assertThat(header) + .contains("Path=/") + .contains("Current-User="); } @Test - void setHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws ServletException, IOException { + void setHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); @@ -612,7 +613,7 @@ void setHeaderSetCookie_ignoredCookieName_leavesPathUnchanged() throws ServletEx } @Test - void addHeaderSetCookie_withPathSlash_whenNoContextPath_leavesPathSlash() throws ServletException, IOException { + void addHeaderSetCookie_withPathSlash_whenNoContextPath_leavesPathSlash() throws Exception { request.setContextPath(""); request.setRequestURI("/z/myzone/login"); @@ -626,7 +627,7 @@ void addHeaderSetCookie_withPathSlash_whenNoContextPath_leavesPathSlash() throws // --- zones.paths.enabled flag --- @Test - void zonePathsDisabled_zonePathRequest_returns404() throws ServletException, IOException { + void zonePathsDisabled_zonePathRequest_returns404() throws Exception { ZonePathContextRewritingFilter disabledFilter = new ZonePathContextRewritingFilter(false); request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -639,7 +640,7 @@ void zonePathsDisabled_zonePathRequest_returns404() throws ServletException, IOE } @Test - void zonePathsDisabled_nonZonePathRequest_passesThrough() throws ServletException, IOException { + void zonePathsDisabled_nonZonePathRequest_passesThrough() throws Exception { ZonePathContextRewritingFilter disabledFilter = new ZonePathContextRewritingFilter(false); request.setContextPath("/uaa"); request.setRequestURI("/uaa/login"); @@ -653,7 +654,7 @@ void zonePathsDisabled_nonZonePathRequest_passesThrough() throws ServletExceptio } @Test - void zonePathsEnabled_zonePathRequest_rewritesNormally() throws ServletException, IOException { + void zonePathsEnabled_zonePathRequest_rewritesNormally() throws Exception { ZonePathContextRewritingFilter enabledFilter = new ZonePathContextRewritingFilter(true); request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); @@ -668,7 +669,7 @@ void zonePathsEnabled_zonePathRequest_rewritesNormally() throws ServletException } @Test - void defaultConstructor_zonePathsEnabled() throws ServletException, IOException { + void defaultConstructor_zonePathsEnabled() throws Exception { request.setContextPath("/uaa"); request.setRequestURI("/uaa/z/myzone/login"); diff --git a/uaa/src/test/java/org/cloudfoundry/experimental/boot/UaaBootServerCustomizerTest.java b/uaa/src/test/java/org/cloudfoundry/experimental/boot/UaaBootServerCustomizerTest.java index 38656fc9560..07a46f5096c 100644 --- a/uaa/src/test/java/org/cloudfoundry/experimental/boot/UaaBootServerCustomizerTest.java +++ b/uaa/src/test/java/org/cloudfoundry/experimental/boot/UaaBootServerCustomizerTest.java @@ -16,7 +16,6 @@ import org.springframework.test.context.TestPropertySource; import java.net.Inet4Address; -import java.net.UnknownHostException; import java.util.Collection; import java.util.List; import java.util.Optional; @@ -39,19 +38,20 @@ void customizerAddedReportValve() { Collection valves = captor.getValue().getEngineValves(); assertThat(valves).isNotEmpty(); Optional valve = valves.stream().filter(v -> v.getClass().equals(ErrorReportValve.class)).findFirst(); - assertThat(valve.isPresent()).isTrue(); + assertThat(valve).isPresent(); ErrorReportValve errorReportValve = (ErrorReportValve) valve.get(); assertThat(errorReportValve.isShowReport()).isFalse(); assertThat(errorReportValve.isShowServerInfo()).isFalse(); } @Test - void localhostConnectorAdded() throws UnknownHostException { + void localhostConnectorAdded() throws Exception { ArgumentCaptor captor = ArgumentCaptor.forClass(TomcatServletWebServerFactory.class); Mockito.verify(customizer, Mockito.atMostOnce()).customize(captor.capture()); List connectors = captor.getValue().getAdditionalConnectors(); - assertThat(connectors).isNotEmpty(); - assertThat(connectors).hasSize(1); + assertThat(connectors) + .isNotEmpty() + .hasSize(1); Connector httpConnector = connectors.getFirst(); assertThat(httpConnector.getProperty("class")).isEqualTo(Http11NioProtocol.class); assertThat(httpConnector.getPort()).isEqualTo(8081); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/MBeanTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/MBeanTests.java index f6d440a6259..b633843062a 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/MBeanTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/MBeanTests.java @@ -32,7 +32,7 @@ void beansAreSet() { } @Test - void testDataSourceExporter() throws Exception { + void dataSourceExporter() throws Exception { ObjectName objectName = new ObjectName("spring.application:type=DataSource,name=dataSource"); assertThat(mBeanServer.isRegistered(objectName)).isTrue(); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java index ed8886cb915..a44ea42d9d3 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java @@ -20,7 +20,7 @@ import jakarta.validation.ConstraintViolationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * @author Luke Taylor diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaWebApplicationInitializerTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaWebApplicationInitializerTest.java index d28423197be..bfa50e08387 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaWebApplicationInitializerTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaWebApplicationInitializerTest.java @@ -2,7 +2,6 @@ import jakarta.servlet.FilterRegistration; import jakarta.servlet.ServletContext; -import jakarta.servlet.ServletException; import jakarta.servlet.ServletRegistration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -54,14 +53,14 @@ void setup() { } @Test - void testServletContextListeners() throws ServletException { + void servletContextListeners() throws Exception { initializer.onStartup(servletContext); ArgumentCaptor listenerArgumentCaptor = ArgumentCaptor.forClass(EventListener.class); verify(servletContext, atLeastOnce()).addListener(listenerArgumentCaptor.capture()); List listeners = listenerArgumentCaptor.getAllValues(); assertThat(listeners).hasSize(2); - assertThat(listeners.getFirst()).isInstanceOf(HttpSessionEventPublisher.class); + assertThat(listeners).first().isInstanceOf(HttpSessionEventPublisher.class); assertThat(listeners.get(1)).isInstanceOf(ContextLoaderListener.class); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicLdapAuthenticationManagerTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicLdapAuthenticationManagerTest.java index 1ce853a58fe..40e1ea01b64 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicLdapAuthenticationManagerTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicLdapAuthenticationManagerTest.java @@ -44,6 +44,6 @@ void getLdapAuthenticationManager() { ChainedAuthenticationManager chainedAuthenticationManager = (ChainedAuthenticationManager) manager; ProviderManager providerManager = (ProviderManager) chainedAuthenticationManager.getDelegates()[0].getAuthenticationManager(); assertThat(providerManager.getProviders()).hasSize(1); - assertThat(providerManager.getProviders().getFirst()).isInstanceOf(LdapAuthenticationProvider.class); + assertThat(providerManager.getProviders()).first().isInstanceOf(LdapAuthenticationProvider.class); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java index 8297203a0d4..fa778cde012 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/DynamicZoneAwareAuthenticationManagerTest.java @@ -23,8 +23,7 @@ import org.springframework.security.authentication.ProviderNotFoundException; import org.springframework.security.core.Authentication; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -114,12 +113,7 @@ void nonUAAZoneUaaActiveAccountNotVerified() { DynamicZoneAwareAuthenticationManager manager = getDynamicZoneAwareAuthenticationManager(true); when(uaaAuthenticationMgr.authenticate(any(Authentication.class))).thenThrow(new AccountNotVerifiedException("mock")); DynamicLdapAuthenticationManager mockManager = manager.getLdapAuthenticationManager(null, null); - try { - manager.authenticate(success); - fail("Expected AccountNotVerifiedException "); - } catch (AccountNotVerifiedException _) { - //expected - } + assertThatThrownBy(() -> manager.authenticate(success)).isInstanceOf(AccountNotVerifiedException.class); verify(mockManager, times(0)).authenticate(any(Authentication.class)); } @@ -131,12 +125,7 @@ void nonUAAZoneUaaActiveAccountLocked() { DynamicZoneAwareAuthenticationManager manager = getDynamicZoneAwareAuthenticationManager(true); when(uaaAuthenticationMgr.authenticate(any(Authentication.class))).thenThrow(new AuthenticationPolicyRejectionException("mock")); DynamicLdapAuthenticationManager mockManager = manager.getLdapAuthenticationManager(null, null); - try { - manager.authenticate(success); - fail("Expected AuthenticationPolicyRejectionException "); - } catch (AuthenticationPolicyRejectionException _) { - //expected - } + assertThatThrownBy(() -> manager.authenticate(success)).isInstanceOf(AuthenticationPolicyRejectionException.class); verify(mockManager, times(0)).authenticate(any(Authentication.class)); } @@ -187,12 +176,7 @@ void authenticateInNoneUaaZoneWithInactiveProviders() { DynamicLdapAuthenticationManager mockManager = manager.getLdapAuthenticationManager(null, null); when(mockManager.authenticate(any(Authentication.class))).thenReturn(success); when(mockManager.getDefinition()).thenReturn(ldapIdentityProviderDefinition); - try { - manager.authenticate(success); - fail("Was expecting a " + ProviderNotFoundException.class); - } catch (ProviderNotFoundException _) { - //expected - } + assertThatThrownBy(() -> manager.authenticate(success)).isInstanceOf(ProviderNotFoundException.class); verifyNoInteractions(uaaAuthenticationMgr); verifyNoInteractions(mockManager); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ClientAdminEndpointsIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ClientAdminEndpointsIntegrationTests.java index 41bd3ad6992..0e885fa3fdf 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ClientAdminEndpointsIntegrationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ClientAdminEndpointsIntegrationTests.java @@ -628,7 +628,7 @@ void changeJwtConfig() { } @Test - void testChangeFederatedJwtConfig() { + void changeFederatedJwtConfig() { headers = getAuthenticatedHeaders(getClientCredentialsAccessToken("clients.read,clients.write,clients.trust,uaa.admin")); UaaClientDetails client = createClient("client_credentials"); @@ -654,7 +654,7 @@ void testChangeFederatedJwtConfig() { } @Test - void testChangeJwtConfigNoAuthorization() { + void changeJwtConfigNoAuthorization() { headers = getAuthenticatedHeaders(getClientCredentialsAccessToken("clients.read,clients.write,clients.trust,uaa.admin")); UaaClientDetails client = createClient("client_credentials"); headers = getAuthenticatedHeaders(getClientCredentialsAccessToken("clients.read,clients.write")); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PasswordGrantIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PasswordGrantIntegrationTests.java index c15a481af95..7d7e089ac26 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PasswordGrantIntegrationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/PasswordGrantIntegrationTests.java @@ -61,7 +61,7 @@ void password_grant_returns_correct_error() { UaaClientDetails client = addUserGroupsRequiredClient(); ResponseEntity responseEntity = makePasswordGrantRequest(testAccounts.getUserName(), testAccounts.getPassword(), client.getClientId(), "secret", serverRunning.getAccessTokenUri()); assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); - assertThat(responseEntity.getHeaders().get("Content-Type").getFirst()).isEqualTo(APPLICATION_JSON_VALUE); + assertThat(responseEntity.getHeaders().get("Content-Type")).first().isEqualTo(APPLICATION_JSON_VALUE); Map errors = JsonUtils.readValue(responseEntity.getBody(), new TypeReference>() { }); assertThat(errors).containsEntry("error_description", "User does not meet the client's required group criteria.") diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ScimGroupEndpointsIntegrationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ScimGroupEndpointsIntegrationTests.java index 6bcdbbd88c0..5129ba78a57 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ScimGroupEndpointsIntegrationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/ScimGroupEndpointsIntegrationTests.java @@ -225,7 +225,7 @@ void createGroupSucceeds() { } @Test - void createAllowedGroupSucceeds() throws URISyntaxException { + void createAllowedGroupSucceeds() throws Exception { String testZoneId = "testzone1"; assertThat(doesSupportZoneDNS()).as("Expected testzone1.localhost and testzone2.localhost to resolve to 127.0.0.1").isTrue(); String adminToken = IntegrationTestUtils.getClientCredentialsToken(serverRunning.getBaseUrl(), "admin", "adminsecret"); @@ -242,7 +242,7 @@ void createAllowedGroupSucceeds() throws URISyntaxException { } @Test - void createNotAllowedGroupFailsCorrectly() throws URISyntaxException { + void createNotAllowedGroupFailsCorrectly() throws Exception { String testZoneId = "testzone1"; assertThat(doesSupportZoneDNS()).as("Expected testzone1.localhost and testzone2.localhost to resolve to 127.0.0.1").isTrue(); final String notAllowed = "not_allowed_" + new RandomValueStringGenerator().generate().toLowerCase(); @@ -267,7 +267,7 @@ void createNotAllowedGroupFailsCorrectly() throws URISyntaxException { } @Test - void relyOnDefaultGroupsShouldAllowedGroupSucceed() throws URISyntaxException { + void relyOnDefaultGroupsShouldAllowedGroupSucceed() throws Exception { String testZoneId = "testzone1"; assertThat(doesSupportZoneDNS()).as("Expected testzone1.localhost and testzone2.localhost to resolve to 127.0.0.1").isTrue(); String adminToken = IntegrationTestUtils.getClientCredentialsToken(serverRunning.getBaseUrl(), "admin", "adminsecret"); @@ -293,7 +293,7 @@ void relyOnDefaultGroupsShouldAllowedGroupSucceed() throws URISyntaxException { } @Test - void changeDefaultGroupsAllowedGroupsUsageShouldSucceed() throws URISyntaxException { + void changeDefaultGroupsAllowedGroupsUsageShouldSucceed() throws Exception { String testZoneId = "testzone1"; assertThat(doesSupportZoneDNS()).as("Expected testzone1.localhost and testzone2.localhost to resolve to 127.0.0.1").isTrue(); String adminToken = IntegrationTestUtils.getClientCredentialsToken(serverRunning.getBaseUrl(), "admin", "adminsecret"); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java index cb67c823141..be95d621e20 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ErrorRoutingIT.java @@ -42,7 +42,7 @@ void methodNotAllowedRoutedToErrorPage() { } @Test - void statusCodeToErrorPage() throws IOException { + void statusCodeToErrorPage() throws Exception { CallErrorPageAndCheckHttpStatusCode("/error", "GET", 200); CallErrorPageAndCheckHttpStatusCode("/error404", "GET", 200); CallErrorPageAndCheckHttpStatusCode("/error429", "GET", 200); @@ -54,7 +54,7 @@ void statusCodeToErrorPage() throws IOException { } @Test - void traceRequestsRejected() throws IOException { + void traceRequestsRejected() throws Exception { // org.springframework.security.web.firewall.StrictHttpFirewall rejects TRACE method HttpURLConnection cn = (HttpURLConnection) new URL(baseUrl + "/info").openConnection(); cn.setRequestMethod("TRACE"); @@ -67,7 +67,7 @@ void traceRequestsRejected() throws IOException { @ParameterizedTest @ValueSource(strings = { "/login?param=%00", "/login?param=val%00ue" } ) - void requestInvalidParameterErrorPage(String invalidParameter) throws IOException { + void requestInvalidParameterErrorPage(String invalidParameter) throws Exception { String body = CallErrorPageAndCheckHttpStatusCode(invalidParameter, "GET", 400); XmlAssert.assertThat(body) .hasXPath("//p") @@ -77,7 +77,7 @@ void requestInvalidParameterErrorPage(String invalidParameter) throws IOExceptio @ParameterizedTest @ValueSource(strings = { "/login;endpoint=x", "/login;?endpoint=x", "/login?%00param=%00value" } ) - void requestRejectedExceptionErrorPage(String rejectedEndpoint) throws IOException { + void requestRejectedExceptionErrorPage(String rejectedEndpoint) throws Exception { // spring security throws RequestRejectedException with status code 400 String body = CallErrorPageAndCheckHttpStatusCode(rejectedEndpoint, "GET", 400); XmlAssert.assertThat(body) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java index 2273e12e50f..ed81cefb0bd 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java @@ -46,9 +46,9 @@ import static org.assertj.core.api.Assertions.assertThat; -@SpringJUnitConfig(classes = DefaultIntegrationTestConfig.class) // public for YamlProcessorTest -public class ImplicitGrantIT { +@SpringJUnitConfig(classes = DefaultIntegrationTestConfig.class) +class ImplicitGrantIT { @Autowired TestAccounts testAccounts; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java index c236d1072c3..657318cb1c3 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/LdapLoginIT.java @@ -99,7 +99,7 @@ void cleanup() { } @Test - public void ldapLogin_with_StartTLS() throws Exception { + void ldapLogin_with_StartTLS() throws Exception { Long beforeTest = System.currentTimeMillis(); performLdapLogin("testzone2", LDAP_URL, "marissa4", "ldap4", LDAP_TLS_SIMPLE); Long afterTest = System.currentTimeMillis(); @@ -110,7 +110,7 @@ public void ldapLogin_with_StartTLS() throws Exception { } @Test - public void ldapLogin_with_TLS() throws Exception { + void ldapLogin_with_TLS() throws Exception { Long beforeTest = System.currentTimeMillis(); performLdapLogin("testzone2", LDAPS_URL, "marissa5", "ldap5", LDAP_TLS_NONE); Long afterTest = System.currentTimeMillis(); @@ -121,7 +121,7 @@ public void ldapLogin_with_TLS() throws Exception { } @Test - public void ldap_login_using_utf8_characters() throws Exception { + void ldap_login_using_utf8_characters() throws Exception { performLdapLogin("testzone2", LDAP_URL, "\u7433\u8D3A", "koala", LDAP_TLS_NONE); assertThat(webDriver.findElement(By.cssSelector("h1")).getText()).contains("Where to?"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java index 3ca0dcad58a..688d9e804bb 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/OIDCLoginIT.java @@ -70,7 +70,6 @@ import java.net.URLEncoder; import java.net.UnknownHostException; import java.nio.charset.StandardCharsets; -import java.text.ParseException; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; @@ -443,7 +442,7 @@ void shadowUserNameDefaultsToOIDCSubjectClaim() { } @Test - void roleMappingAndUserAttributesFromIdTokenOfZone() throws ParseException { + void roleMappingAndUserAttributesFromIdTokenOfZone() throws Exception { // test role and user_attribute claims in id token with external group membership assignment, see issue https://github.com/cloudfoundry/uaa/issues/3813 Map attributeMappings = new HashMap<>(identityProvider.getConfig().getAttributeMappings()); attributeMappings.remove(USER_NAME_ATTRIBUTE_NAME); @@ -469,13 +468,13 @@ void roleMappingAndUserAttributesFromIdTokenOfZone() throws ParseException { JWTClaimsSet jwtClaimsSet = JWTParser.parse(idToken).getJWTClaimsSet(); assertThat(jwtClaimsSet.getStringClaim("origin")).isEqualTo(identityProvider.getOriginKey()); Set rolesInJwt = Arrays.stream(jwtClaimsSet.getStringArrayClaim("roles")).collect(Collectors.toSet()); - assertThat(rolesInJwt).isNotNull().contains(createdGroup.getDisplayName()); + assertThat(rolesInJwt).contains(createdGroup.getDisplayName()); Map userAttributeJwt = jwtClaimsSet.getJSONObjectClaim("user_attributes"); assertThat(userAttributeJwt).isInstanceOf(Map.class); List attr1 = userAttributeJwt.get("the_client_id") instanceof ArrayList arrayList ? arrayList : null; - assertThat(attr1).isNotNull().contains("identity"); + assertThat(attr1).contains("identity"); List attr2 = userAttributeJwt.get("roles") instanceof ArrayList arrayList ? arrayList : null; - assertThat(attr2).isNotNull().contains("openid"); + assertThat(attr2).contains("openid"); } @Test @@ -533,7 +532,7 @@ void claimsComeFromUserInfoEndpoint() { ScimUser shadowUser = IntegrationTestUtils.getUser(anAdminToken, zoneUrl, identityProvider.getOriginKey(), expectedUsername); assertThat(shadowUser.getUserName()).isEqualTo(expectedUsername); //there is no 'scope' attribute exposed on the /userinfo endpoint in this test. - assertThat(shadowUser.getGroups().stream().map(g -> g.getDisplay())).doesNotContain(createdGroup.getDisplayName()); + assertThat(shadowUser.getGroups()).extracting(g -> g.getDisplay()).doesNotContain(createdGroup.getDisplayName()); } @Test @@ -603,7 +602,7 @@ void successfulLoginWithOIDC_and_SAML_Provider_PlusRefreshRotation() throws Exce assertThat(userAttributeMap).isNotNull(); List clientIds = userAttributeMap.get("the_client_id"); assertThat(clientIds).isNotNull(); - assertThat(clientIds.getFirst()).isEqualTo("identity"); + assertThat(clientIds).first().isEqualTo("identity"); setRefreshTokenRotate(false); String refreshToken1 = getRefreshTokenResponse(zoneServerRunning, authCodeTokenResponse.get("refresh_token")); String refreshToken2 = getRefreshTokenResponse(zoneServerRunning, refreshToken1); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PrivateKeyJwtClientAuthIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PrivateKeyJwtClientAuthIT.java index a251a3bf161..786206dee10 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PrivateKeyJwtClientAuthIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/PrivateKeyJwtClientAuthIT.java @@ -284,7 +284,7 @@ void passwordGrantWithClientUsingPrivateKeyJwtAndExpectClientError() { // When String response = getPasswordGrantToken("admin", "access_token", UNAUTHORIZED); // Then - assertThat(response).isNotNull() + assertThat(response) .contains("401"); } @@ -293,7 +293,7 @@ void clientCredentialGrantWithClientUsingPrivateKeyJwtAndExpectClientError() { // When String response = getClientCredentialsGrantToken("any-other-not-existing-client", "access_token", UNAUTHORIZED); // Then - assertThat(response).isNotNull() + assertThat(response) .contains("401"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java index 51315e2ee3e..6c600af0e20 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/RateLimitingIT.java @@ -66,7 +66,7 @@ void logout_and_clear_cookies() { } @Test - void infoEndpointRateLimited() throws InterruptedException { + void infoEndpointRateLimited() throws Exception { RestOperations restTemplate = serverRunning.getRestTemplate(); // Wait for a fresh rate-limit window to avoid interference from prior requests diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java index aa2af94bc89..c526d4657e6 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/SamlLoginIT.java @@ -1157,7 +1157,7 @@ void loginClientIDPAuthorizationAlreadyLoggedIn() { } @Test - void springSamlEndpointsWithEmptyContext() throws IOException { + void springSamlEndpointsWithEmptyContext() throws Exception { CallEmptyPageAndCheckHttpStatusCode("/saml/web/metadata/login", 404); // These endpoints are now redirect to /login CallEmptyPageAndCheckHttpStatusCode("/saml/SingleLogout/alias/foo", 302); @@ -1167,7 +1167,7 @@ void springSamlEndpointsWithEmptyContext() throws IOException { } @Test - public void backportFrom77RelayTest() { + void backportFrom77RelayTest() { final String SIMPLESAMLPHP_UAA_ACCEPTANCE = "http://simplesamlphp.uaa-acceptance.cf-app.com"; final String SIMPLESAMLPHP_LOGIN_PROMPT_XPATH_EXPR = "//h1[contains(text(), 'Enter your username and password')]"; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java index 0d79a8e09f7..45ac35202d8 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/UserTokenGrantIT.java @@ -168,7 +168,7 @@ private String doUserTokenGrant(String clientId, String token, HttpStatus expect } private void checkRefreshToken(String token) { - assertThat(token).isNotNull() + assertThat(token) .hasSize(34) .endsWith("-r"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java index 77d3de1cf8f..80f55225bac 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/util/IntegrationTestUtils.java @@ -203,8 +203,7 @@ public static UserInfoResponse getUserInfo(String url, String token) throws URIS final ResponseEntity response = rest.exchange(request, UserInfoResponse.class); assertStatusCode(response, HttpStatus.OK); final UserInfoResponse responseBody = response.getBody(); - assertThat(responseBody).isNotNull(); - return responseBody; + return assertThat(responseBody).isNotNull().actual(); } public static void deleteZone(String baseUrl, String id, String adminToken) throws URISyntaxException { @@ -338,8 +337,7 @@ public static ScimUser createUserWithPhone(RestTemplate client, final ResponseEntity response = client.postForEntity(url + "/Users", user, ScimUser.class); assertStatusCode(response, HttpStatus.CREATED); final ScimUser responseBody = response.getBody(); - assertThat(responseBody).isNotNull(); - return responseBody; + return assertThat(responseBody).isNotNull().actual(); } public static ScimUser createUser(String token, String url, ScimUser user, String zoneSwitchId) { @@ -589,8 +587,7 @@ public static ScimGroup createGroup( ); assertStatusCode(response, HttpStatus.CREATED); final ScimGroup responseBody = response.getBody(); - assertThat(responseBody).isNotNull(); - return responseBody; + return assertThat(responseBody).isNotNull().actual(); } private static ScimGroup updateGroup(String token, @@ -707,8 +704,7 @@ private static IdentityZone createZoneOrUpdateSubdomain(RestTemplate client, ResponseEntity zone = client.postForEntity(url + "/identity-zones", identityZone, IdentityZone.class); assertStatusCode(zone, HttpStatus.CREATED); final IdentityZone responseBody = zone.getBody(); - assertThat(responseBody).isNotNull(); - return responseBody; + return assertThat(responseBody).isNotNull().actual(); } public static IdentityZone createInactiveIdentityZone(RestTemplate client, String url) { @@ -1395,7 +1391,7 @@ public static void callCheckToken(ServerRunningExtension serverRunning, ResponseEntity tokenResponse = serverRunning.postForMap("/check_token", formData, headers); assertThat(tokenResponse.getStatusCode()).isEqualTo(HttpStatus.OK); final Map tokenResponseBody = tokenResponse.getBody(); - assertThat(tokenResponseBody).isNotNull() + assertThat(tokenResponseBody) .containsKey("iss"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcTests.java index b88724effde..ca98b961b89 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcTests.java @@ -526,7 +526,7 @@ private static void assertResponseAndCodeCorrect(ExpiringCodeStore expiringCodeS assertThat(expiringCode.getIntent()).isEqualTo(ExpiringCodeType.INVITATION.name()); Map data = readValue(expiringCode.getData(), new TypeReference>() { }); - assertThat(data).isNotNull() + assertThat(data) .containsKey(USER_ID) .containsEntry(EMAIL, emails[i]) .containsEntry(ORIGIN, UAA) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java index ff780344b81..b48158fcfc5 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/invitations/InvitationsEndpointMockMvcZonePathTests.java @@ -812,7 +812,7 @@ private static void assertResponseAndCodeCorrect(ExpiringCodeStore expiringCodeS assertThat(expiringCode.getIntent()).isEqualTo(ExpiringCodeType.INVITATION.name()); Map data = readValue(expiringCode.getData(), new TypeReference>() { }); - assertThat(data).isNotNull() + assertThat(data) .containsKey(USER_ID) .containsEntry(EMAIL, emails[i]) .containsEntry(ORIGIN, UAA) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java index 9d2397ea3e4..5944468e5f5 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java @@ -154,7 +154,7 @@ @DirtiesContext // public for LimitedModeLoginMockMvcTests @EnabledIfZonePathsEnabled -public class LoginMockMvcZonePathTests { +class LoginMockMvcZonePathTests { @Autowired private WebApplicationContext webApplicationContext; @@ -421,13 +421,15 @@ void login_page_has_zone_aware_form_action_and_links(ZoneResolutionMode mode) th String body = result.getResponse().getContentAsString(); if (mode == ZoneResolutionMode.ZONE_PATH) { - org.hamcrest.MatcherAssert.assertThat(body, containsString("action=\"/z/" + subdomain + "/login.do\"")); - org.hamcrest.MatcherAssert.assertThat(body, containsString("/z/" + subdomain + "/create_account")); - org.hamcrest.MatcherAssert.assertThat(body, containsString("/z/" + subdomain + "/forgot_password")); + assertThat(body) + .contains("action=\"/z/" + subdomain + "/login.do\"") + .contains("/z/" + subdomain + "/create_account") + .contains("/z/" + subdomain + "/forgot_password"); } else { - org.hamcrest.MatcherAssert.assertThat(body, containsString("action=\"/login.do\"")); - org.hamcrest.MatcherAssert.assertThat(body, containsString("/create_account")); - org.hamcrest.MatcherAssert.assertThat(body, containsString("/forgot_password")); + assertThat(body) + .contains("action=\"/login.do\"") + .contains("/create_account") + .contains("/forgot_password"); } } @@ -1355,8 +1357,13 @@ void defaultBranding(ZoneResolutionMode mode) throws Exception { .andExpect(xpath("//head/link[@rel='shortcut icon']/@href").string(faviconPath)) .andExpect(xpath("//head/link[@href='" + cssPath + "']").exists()); String body = mockMvc.perform(mode.createRequestBuilder(subdomain, HttpMethod.GET, "/login")).andReturn().getResponse().getContentAsString(); - org.hamcrest.MatcherAssert.assertThat("Login page should contain product-logo or login form", body, - CoreMatchers.anyOf(containsString("product-logo"), containsString("username"), containsString("password"))); + assertThat(body) + .as("Login page should contain product-logo or login form") + .satisfiesAnyOf( + arg -> assertThat(arg).contains("product-logo"), + arg -> assertThat(arg).contains("username"), + arg -> assertThat(arg).contains("password") + ); } @Nested @@ -1575,7 +1582,7 @@ void defaultAndCustomSignupLink(ZoneResolutionMode mode) throws Exception { : result -> { @SuppressWarnings("unchecked") Map links = (Map) result.getModelAndView().getModel().get("links"); - assertThat(links).isNotNull().containsKey("createAccountLink"); + assertThat(links).containsKey("createAccountLink"); assertThat(String.valueOf(links.get("createAccountLink"))).contains("create_account"); }); config.getLinks().getSelfService().setSignup("http://www.example.com/signup"); @@ -1587,7 +1594,7 @@ void defaultAndCustomSignupLink(ZoneResolutionMode mode) throws Exception { : result -> { @SuppressWarnings("unchecked") Map links = (Map) result.getModelAndView().getModel().get("links"); - assertThat(links).isNotNull().containsKey("createAccountLink"); + assertThat(links).containsKey("createAccountLink"); assertThat(String.valueOf(links.get("createAccountLink"))).contains("example.com/signup"); }); } @@ -2901,8 +2908,9 @@ void accountChooserWithoutDiscovery_loginWithProvidedLoginHint(ZoneResolutionMod Map queryParams = UriComponentsBuilder.fromUriString(location).build().getQueryParams().toSingleValueMap(); - assertThat(location).startsWith(mode == ZoneResolutionMode.ZONE_PATH ? "/z/" : "/login"); - assertThat(location).contains("/login"); + assertThat(location) + .startsWith(mode == ZoneResolutionMode.ZONE_PATH ? "/z/" : "/login") + .contains("/login"); assertThat(queryParams).containsEntry("login_hint", loginHint) .containsEntry("discoveryPerformed", "true"); } @@ -2929,8 +2937,9 @@ void accountChooserWithoutDiscovery_noDefaultReturnsLoginPage(ZoneResolutionMode Map queryParams = UriComponentsBuilder.fromUriString(location).build().getQueryParams().toSingleValueMap(); - assertThat(location).startsWith(mode == ZoneResolutionMode.ZONE_PATH ? "/z/" : "/login"); - assertThat(location).contains("/login"); + assertThat(location) + .startsWith(mode == ZoneResolutionMode.ZONE_PATH ? "/z/" : "/login") + .contains("/login"); assertThat(queryParams) .containsEntry("discoveryPerformed", "true") .doesNotContainKey("login_hint"); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcTests.java index 5f2a63a7129..c7c55cf5ee7 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcTests.java @@ -81,7 +81,6 @@ void resettingAPasswordUsingUsernameToEnsureNoModification() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); PasswordChange change = new PasswordChange(users.getFirst().getId(), users.getFirst().getUserName(), users.getFirst().getPasswordLastModified(), "", ""); @@ -97,7 +96,6 @@ void resettingAPasswordUsingUsernameToEnsureNoModification() throws Exception { void resettingPasswordDoesNotUpdateLastLogonTime() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); Long lastLogonBeforeReset = users.getFirst().getLastLogonTime(); PasswordChange change = new PasswordChange(users.getFirst().getId(), users.getFirst().getUserName(), users.getFirst().getPasswordLastModified(), "", ""); @@ -123,7 +121,6 @@ void resettingAPasswordFailsWhenUsernameChanged() throws Exception { ScimUserProvisioning userProvisioning = webApplicationContext.getBean(ScimUserProvisioning.class); List users = userProvisioning.query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ScimUser user = users.getFirst(); PasswordChange change = new PasswordChange(user.getId(), user.getUserName(), user.getPasswordLastModified(), "", ""); @@ -334,7 +331,6 @@ void resettingAPasswordFailsWhenPasswordChanged() throws Exception { void resettingAPasswordNoCsrfParameter() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ExpiringCode code = codeStore.generateCode(users.getFirst().getId(), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null, IdentityZoneHolder.get().getId()); @@ -347,7 +343,6 @@ void resettingAPasswordNoCsrfParameter() throws Exception { void resettingAPasswordUsingTimestampForUserModification() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); PasswordChange passwordChange = new PasswordChange(users.getFirst().getId(), users.getFirst().getUserName(), null, null, null); ExpiringCode code = codeStore.generateCode(JsonUtils.writeValueAsString(passwordChange), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null, IdentityZoneHolder.get().getId()); @@ -365,7 +360,6 @@ void resetPassword_ReturnsUnprocessableEntity_NewPasswordSameAsOld() throws Exce ScimUserProvisioning userProvisioning = webApplicationContext.getBean(ScimUserProvisioning.class); List users = userProvisioning.query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ScimUser user = users.getFirst(); PasswordChange passwordChange = new PasswordChange(user.getId(), user.getUserName(), null, null, null); @@ -393,7 +387,6 @@ void resetPassword_ReturnsUnprocessableEntity_NewPasswordNotAccordingToPolicy() ScimUserProvisioning userProvisioning = webApplicationContext.getBean(ScimUserProvisioning.class); List users = userProvisioning.query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ScimUser user = users.getFirst(); PasswordChange passwordChange = new PasswordChange(user.getId(), user.getUserName(), null, null, null); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcZonePathTests.java index e4c0a564d8d..995e2f0a59a 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/ResetPasswordControllerMockMvcZonePathTests.java @@ -96,7 +96,6 @@ void resettingAPasswordUsingUsernameToEnsureNoModification() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); PasswordChange change = new PasswordChange(users.getFirst().getId(), users.getFirst().getUserName(), users.getFirst().getPasswordLastModified(), "", ""); @@ -112,7 +111,6 @@ void resettingAPasswordUsingUsernameToEnsureNoModification() throws Exception { void resettingPasswordDoesNotUpdateLastLogonTime() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); Long lastLogonBeforeReset = users.getFirst().getLastLogonTime(); PasswordChange change = new PasswordChange(users.getFirst().getId(), users.getFirst().getUserName(), users.getFirst().getPasswordLastModified(), "", ""); @@ -138,7 +136,6 @@ void resettingAPasswordFailsWhenUsernameChanged() throws Exception { ScimUserProvisioning userProvisioning = webApplicationContext.getBean(ScimUserProvisioning.class); List users = userProvisioning.query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ScimUser user = users.getFirst(); PasswordChange change = new PasswordChange(user.getId(), user.getUserName(), user.getPasswordLastModified(), "", ""); @@ -349,7 +346,6 @@ void resettingAPasswordFailsWhenPasswordChanged() throws Exception { void resettingAPasswordNoCsrfParameter() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ExpiringCode code = codeStore.generateCode(users.getFirst().getId(), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null, IdentityZoneHolder.get().getId()); @@ -362,7 +358,6 @@ void resettingAPasswordNoCsrfParameter() throws Exception { void resettingAPasswordUsingTimestampForUserModification() throws Exception { List users = webApplicationContext.getBean(ScimUserProvisioning.class).query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); PasswordChange passwordChange = new PasswordChange(users.getFirst().getId(), users.getFirst().getUserName(), null, null, null); ExpiringCode code = codeStore.generateCode(JsonUtils.writeValueAsString(passwordChange), new Timestamp(System.currentTimeMillis() + UaaResetPasswordService.PASSWORD_RESET_LIFETIME), null, IdentityZoneHolder.get().getId()); @@ -380,7 +375,6 @@ void resetPassword_ReturnsUnprocessableEntity_NewPasswordSameAsOld() throws Exce ScimUserProvisioning userProvisioning = webApplicationContext.getBean(ScimUserProvisioning.class); List users = userProvisioning.query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ScimUser user = users.getFirst(); PasswordChange passwordChange = new PasswordChange(user.getId(), user.getUserName(), null, null, null); @@ -408,7 +402,6 @@ void resetPassword_ReturnsUnprocessableEntity_NewPasswordNotAccordingToPolicy() ScimUserProvisioning userProvisioning = webApplicationContext.getBean(ScimUserProvisioning.class); List users = userProvisioning.query("username eq \"marissa\"", IdentityZoneHolder.get().getId()); assertThat(users) - .isNotNull() .hasSize(1); ScimUser user = users.getFirst(); PasswordChange passwordChange = new PasswordChange(user.getId(), user.getUserName(), null, null, null); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/util/LocalUaaRestTemplateMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/util/LocalUaaRestTemplateMockMvcTests.java index 1ca0c3f62d3..d9bccb50f78 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/util/LocalUaaRestTemplateMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/util/LocalUaaRestTemplateMockMvcTests.java @@ -67,9 +67,9 @@ void uaaRestTemplateContainsBearerHeader() throws Exception { Method createRequest = OAuth2RestTemplate.class.getDeclaredMethod("createRequest", URI.class, HttpMethod.class); ReflectionUtils.makeAccessible(createRequest); ClientHttpRequest request = (ClientHttpRequest) createRequest.invoke(localUaaRestTemplate, new URI("http://localhost/oauth/token"), HttpMethod.POST); - assertThat(request.getHeaders().get("Authorization")).as("authorization bearer header should be present").hasSize(1); - assertThat(request.getHeaders().get("Authorization").getFirst()).as("authorization bearer header should be present").isNotNull(); + assertThat(request.getHeaders().get("Authorization")).as("authorization bearer header should be present").hasSize(1) + .first().as("authorization bearer header should be present").isNotNull(); assertThat(request.getHeaders().get("Authorization").getFirst().toLowerCase()).startsWith("bearer "); - assertThat(request.getHeaders().get("Authorization").getFirst()).endsWith(token.getValue()); + assertThat(request.getHeaders().get("Authorization").get(0)).endsWith(token.getValue()); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/audit/AuditCheckMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/audit/AuditCheckMockMvcTests.java index cd0ea90d0aa..7bb43c131fd 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/audit/AuditCheckMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/audit/AuditCheckMockMvcTests.java @@ -1448,6 +1448,6 @@ private static void assertGroupMembershipLogMessage(String actualLogMessage, Aud Matcher patternMatcher = groupLogPattern.matcher(actualLogMessage); assertThat(patternMatcher.find()).isTrue(); Set memberIdsFromLogMessage = StringUtils.commaDelimitedListToSet(patternMatcher.group(1).replaceAll("\"", "")); - assertThat(memberIdsFromLogMessage).isEqualTo(Sets.newHashSet(expectedUserIds)); + assertThat(memberIdsFromLogMessage).hasSameElementsAs(Sets.newHashSet(expectedUserIds)); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/clients/ClientJwtCredentialsEndpointMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/clients/ClientJwtCredentialsEndpointMockMvcTests.java index 461bfe3f8b2..96635173839 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/clients/ClientJwtCredentialsEndpointMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/clients/ClientJwtCredentialsEndpointMockMvcTests.java @@ -63,7 +63,7 @@ void createWithTopLevelJwtCreds_getReturnsCredsAndStripsAdditionalKeys() throws .andExpect(status().isCreated()); ClientDetailsModification retrieved = getClient(clientId); - assertThat(retrieved.getClientJwtCredentials()).isNotNull().isNotEmpty(); + assertThat(retrieved.getClientJwtCredentials()).isNotEmpty(); assertThat(retrieved.getAdditionalInformation()).doesNotContainKey(ClientJwtConfiguration.JWT_CREDS); assertThat(retrieved.getAdditionalInformation()).doesNotContainKey("client_jwt_config"); } @@ -89,7 +89,7 @@ void createWithNestedClientJwtConfig_getReturnsCredsAndStripsAdditionalKeys() th .andExpect(status().isCreated()); ClientDetailsModification retrieved = getClient(clientId); - assertThat(retrieved.getClientJwtCredentials()).isNotNull().isNotEmpty(); + assertThat(retrieved.getClientJwtCredentials()).isNotEmpty(); } @Test @@ -125,7 +125,7 @@ void updateAddsNewJwtCredToExistingOne() throws Exception { .andExpect(status().isOk()); ClientDetailsModification after = getClient(clientId); - assertThat(after.getClientJwtCredentials()).isNotNull().hasSize(2); + assertThat(after.getClientJwtCredentials()).hasSize(2); } @Test @@ -163,7 +163,7 @@ void updateReplacesClientJwtConfigWithFullMergedString() throws Exception { .andExpect(status().isOk()); ClientDetailsModification after = getClient(clientId); - assertThat(after.getClientJwtCredentials()).isNotNull().hasSize(2); + assertThat(after.getClientJwtCredentials()).hasSize(2); } @Test @@ -192,7 +192,7 @@ void getResponseJsonDoesNotDuplicateJwtCredsKey() throws Exception { .getResponse() .getContentAsString(); int n = body.split("\"jwt_creds\"").length - 1; - assertThat(n).isEqualTo(1); + assertThat(n).isOne(); } private ClientDetailsModification getClient(String clientId) throws Exception { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java index aafa746bc3b..9e141586671 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/ldap/AbstractLdapMockMvcTest.java @@ -378,12 +378,10 @@ void external_groups_whitelist() throws Exception { IdentityZoneHolder.set(zone.getZone().getIdentityZone()); Authentication auth = manager.authenticate(token); - assertThat(auth).isNotNull() - .isInstanceOf(UaaAuthentication.class); + assertThat(auth).isInstanceOf(UaaAuthentication.class); UaaAuthentication uaaAuth = (UaaAuthentication) auth; Set externalGroups = uaaAuth.getExternalGroups(); assertThat(externalGroups) - .hasSize(2) .containsExactlyInAnyOrder("admins", "thirdmarissa"); //default whitelist @@ -443,7 +441,7 @@ void customUserAttributes() throws Exception { .as("Expected cost center attribute").containsKey(costCenters) .as("Expected manager attribute").containsKey(managers); assertThat(authentication.getUserAttributes().getFirst(costCenters)).isEqualTo(denverCo); - assertThat(authentication.getUserAttributes().get(managers)).as("Expected 2 manager attribute values").hasSize(2) + assertThat(authentication.getUserAttributes().get(managers)).as("Expected 2 manager attribute values") .containsExactlyInAnyOrder(johnTheSloth, kariTheAntEater); assertThat(getFamilyName(username)).isEqualTo("8885550986"); @@ -1128,7 +1126,7 @@ void nestedLdapScopes() { Set actualAuthorities = UaaStringUtils.getStringsFromAuthorities(auth.getAuthorities()).stream() .filter(a -> a != null && !a.startsWith("FACTOR_")) .collect(java.util.stream.Collectors.toSet()); - assertThat(actualAuthorities).containsExactlyInAnyOrderElementsOf(defaultAuthorities); + assertThat(actualAuthorities).hasSameElementsAs(defaultAuthorities); IdentityZoneHolder.clear(); } @@ -1173,7 +1171,7 @@ void validateUserAuthorities(String[] expected, Authentication auth) { Set actualAuthorities = UaaStringUtils.getStringsFromAuthorities(auth.getAuthorities()).stream() .filter(a -> a != null && !a.startsWith("FACTOR_")) .collect(java.util.stream.Collectors.toSet()); - assertThat(actualAuthorities).containsExactlyInAnyOrderElementsOf(defaultAuthorities); + assertThat(actualAuthorities).hasSameElementsAs(defaultAuthorities); } @Test @@ -1267,7 +1265,7 @@ void doTestNestedLdapGroupsMappedToScopesWithDefaultScopes(String username, Stri Set actualAuthorities = UaaStringUtils.getStringsFromAuthorities(auth.getAuthorities()).stream() .filter(a -> a != null && !a.startsWith("FACTOR_")) .collect(java.util.stream.Collectors.toSet()); - assertThat(actualAuthorities).containsExactlyInAnyOrderElementsOf(defaultAuthorities); + assertThat(actualAuthorities).hasSameElementsAs(defaultAuthorities); } String[] getAuthorities(Collection authorities) { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java index a4f78a6bbd1..3e42790a47d 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java @@ -138,7 +138,7 @@ private void shouldStillReturnAliasPropertiesOfIdpsWithAliasCreatedBeforehand( final Optional> createdIdp = allIdps.stream() .filter(it -> it.getOriginKey().equals(existingIdp.getOriginKey())) .findFirst(); - assertThat(createdIdp).contains(existingIdp); + assertThat(createdIdp).hasValue(existingIdp); assertThat(createdIdp.get().getAliasZid()).isEqualTo(zone2.getId()); } } @@ -355,8 +355,7 @@ private void shouldRejectCreation(final IdentityZone zone, final IdentityProvide // after the failed creation, the IdP must not exist final List> idpsInZoneAfterFailedCreation = readAllIdpsInZone(zone); - assertThat(idpsInZoneAfterFailedCreation.stream().map(IdentityProvider::getOriginKey).collect(toSet())) - .doesNotContain(idp.getOriginKey()); + assertThat(idpsInZoneAfterFailedCreation.stream().map(IdentityProvider::getOriginKey)).doesNotContain(idp.getOriginKey()); } } @@ -991,7 +990,7 @@ private IdentityProvider updateIdp(final IdentityZone zone, final IdentityPro private MvcResult updateIdpAndReturnResult(final IdentityZone zone, final IdentityProvider updatePayload) throws Exception { final String id = updatePayload.getId(); - assertThat(id).isNotNull().isNotBlank(); + assertThat(id).isNotBlank(); final MockHttpServletRequestBuilder updateRequestBuilder = put("/identity-providers/" + id) .header("Authorization", "Bearer " + getAccessTokenForZone(zone.getId())) @@ -1033,7 +1032,7 @@ private void shouldRejectUpdate(final IdentityZone zone, final IdentityProvider< zone.getId(), idp.getId() ); - assertThat(idpAfterFailedUpdateOpt).contains(idpBeforeUpdate); + assertThat(idpAfterFailedUpdateOpt).hasValue(idpBeforeUpdate); // if an alias IdP was present before update, check if it also remains unchanged if (aliasIdpBeforeUpdate != null) { @@ -1041,7 +1040,7 @@ private void shouldRejectUpdate(final IdentityZone zone, final IdentityProvider< idpBeforeUpdate.getAliasZid(), idpBeforeUpdate.getAliasId() ); - assertThat(aliasIdpAfterFailedUpdateOpt).contains(aliasIdpBeforeUpdate); + assertThat(aliasIdpAfterFailedUpdateOpt).hasValue(aliasIdpBeforeUpdate); } } } @@ -1192,7 +1191,7 @@ private MvcResult deleteIdpAndReturnResult(final IdentityZone zone, final String private void assertIdpDoesNotExist(final String id, final String zoneId) throws Exception { final Optional> idp = readIdpFromZoneIfExists(zoneId, id); - assertThat(idp).isNotPresent(); + assertThat(idp).isEmpty(); } } @@ -1332,8 +1331,8 @@ private void deleteIdpViaDb(final String originKey, final String zoneId) { private void assertIdpAndAliasHaveSameRelyingPartySecretInDb(final IdentityProvider originalIdp) { assertThat(originalIdp.getType()).isEqualTo(OIDC10); - assertThat(originalIdp.getAliasId()).isNotNull().isNotBlank(); - assertThat(originalIdp.getAliasZid()).isNotNull().isNotBlank(); + assertThat(originalIdp.getAliasId()).isNotBlank(); + assertThat(originalIdp.getAliasZid()).isNotBlank(); final Optional relyingPartySecretOriginalIdpOpt = readIdpViaDb(originalIdp.getId(), originalIdp.getIdentityZoneId()) .map(IdentityProvider::getConfig) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcTests.java index f56e0344adb..c13a61bf782 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcTests.java @@ -72,7 +72,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.USER_NAME_ATTRIBUTE_NAME; import static org.springframework.http.MediaType.APPLICATION_JSON; @@ -204,9 +204,9 @@ void create_and_delete_saml_provider() throws Exception { assertThat(created.getConfig()).isNotNull(); createIdentityProvider(null, created, accessToken, status().isConflict()); SamlIdentityProviderDefinition samlCreated = created.getConfig(); - assertThat(samlCreated.getEmailDomain()).isEqualTo(Arrays.asList("test.com", "test2.com")); - assertThat(samlCreated.getExternalGroupsWhitelist()).isEqualTo(externalGroupsWhitelist); - assertThat(samlCreated.getAttributeMappings()).isEqualTo(attributeMappings); + assertThat(samlCreated.getEmailDomain()).containsExactlyElementsOf(Arrays.asList("test.com", "test2.com")); + assertThat(samlCreated.getExternalGroupsWhitelist()).containsExactlyElementsOf(externalGroupsWhitelist); + assertThat(samlCreated.getAttributeMappings()).containsExactlyInAnyOrderEntriesOf(attributeMappings); assertThat(samlCreated.getZoneId()).isEqualTo(IdentityZone.getUaaZoneId()); assertThat(samlCreated.getIdpEntityAlias()).isEqualTo(provider.getOriginKey()); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcZonePathTests.java index 3c1c7175880..f5f1d036ee7 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsMockMvcZonePathTests.java @@ -82,7 +82,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.cloudfoundry.identity.uaa.mock.clients.AdminClientCreator.SECRET; import static org.cloudfoundry.identity.uaa.mock.util.MockMvcUtils.createClient; @@ -218,9 +218,9 @@ void create_and_delete_saml_provider() throws Exception { assertThat(created.getConfig()).isNotNull(); createIdentityProvider(null, created, accessToken, status().isConflict()); SamlIdentityProviderDefinition samlCreated = created.getConfig(); - assertThat(samlCreated.getEmailDomain()).isEqualTo(Arrays.asList("test.com", "test2.com")); - assertThat(samlCreated.getExternalGroupsWhitelist()).isEqualTo(externalGroupsWhitelist); - assertThat(samlCreated.getAttributeMappings()).isEqualTo(attributeMappings); + assertThat(samlCreated.getEmailDomain()).containsExactlyElementsOf(Arrays.asList("test.com", "test2.com")); + assertThat(samlCreated.getExternalGroupsWhitelist()).containsExactlyElementsOf(externalGroupsWhitelist); + assertThat(samlCreated.getAttributeMappings()).containsExactlyInAnyOrderEntriesOf(attributeMappings); assertThat(samlCreated.getZoneId()).isEqualTo(IdentityZone.getUaaZoneId()); assertThat(samlCreated.getIdpEntityAlias()).isEqualTo(provider.getOriginKey()); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java index 87d9866fa96..374b50d2e93 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeDefaultConfigMockMvcTests.java @@ -24,7 +24,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -public class TokenExchangeDefaultConfigMockMvcTests extends TokenExchangeMockMvcBase { +class TokenExchangeDefaultConfigMockMvcTests extends TokenExchangeMockMvcBase { @Test @@ -60,29 +60,28 @@ void token_exchange_three_idps_using_id_token() throws Exception { .andExpect(jsonPath(".refresh_token").isNotEmpty()); Map tokens = JsonUtils.readValueAsMap(tokenExchangeResult.andReturn().getResponse().getContentAsString()); - assertThat(tokens.get(ISSUED_TOKEN_TYPE)).isEqualTo(TOKEN_TYPE_ACCESS); - assertThat(tokens.get(TOKEN_TYPE)).isEqualTo(BEARER_TYPE.toLowerCase()); + assertThat(tokens).containsEntry(ISSUED_TOKEN_TYPE, TOKEN_TYPE_ACCESS) + .containsEntry(TOKEN_TYPE, BEARER_TYPE.toLowerCase()); Jwt tokenClaims = JwtHelper.decode((String) tokens.get("id_token")); Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); - assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); - assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); + assertThat(claims).containsEntry("user_name", thirdParty.user().getUserName()) + .containsEntry("email", thirdParty.user().getEmails().getFirst().getValue()) + .containsEntry("origin", workerServer.identityProvider().getOriginKey()); Map act = (Map) claims.get("act"); - assertThat(act).isNotNull(); assertThat(act).isNotEmpty(); Map controlServerClaims = JsonUtils.readValueAsMap( multiAuthSetup.getTokenClaims( - (String)multiAuthSetup.controlServerTokens().get("id_token"), - "id_token", - "controlServer" + (String) multiAuthSetup.controlServerTokens().get("id_token"), + "id_token", + "controlServer" ).getClaims() ); - assertThat(act.get("sub")).isEqualTo(controlServerClaims.get("sub")); - assertThat(act.get("iss")).isEqualTo(controlServerClaims.get("iss")); - assertThat(act.get("client_id")).isEqualTo(workerServer.client().getClientId()); + assertThat(act).containsEntry("sub", controlServerClaims.get("sub")) + .containsEntry("iss", controlServerClaims.get("iss")) + .containsEntry("client_id", workerServer.client().getClientId()); } @Test @@ -116,15 +115,15 @@ void token_exchange_three_idps_using_access_token() throws Exception { .andExpect(jsonPath(".access_token").isNotEmpty()); Map tokens = JsonUtils.readValueAsMap(tokenExchangeResult.andReturn().getResponse().getContentAsString()); - assertThat(tokens.get(ISSUED_TOKEN_TYPE)).isEqualTo(TOKEN_TYPE_ACCESS); - assertThat(tokens.get(TOKEN_TYPE)).isEqualTo(BEARER_TYPE.toLowerCase()); + assertThat(tokens).containsEntry(ISSUED_TOKEN_TYPE, TOKEN_TYPE_ACCESS) + .containsEntry(TOKEN_TYPE, BEARER_TYPE.toLowerCase()); Jwt tokenClaims = JwtHelper.decode((String) tokens.get("access_token")); Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); - assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); - assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); + assertThat(claims).containsEntry("user_name", thirdParty.user().getUserName()) + .containsEntry("email", thirdParty.user().getEmails().getFirst().getValue()) + .containsEntry("origin", workerServer.identityProvider().getOriginKey()); } @Test @@ -175,15 +174,15 @@ void token_exchange_three_idps_using_opaque_access_token() throws Exception { .andExpect(jsonPath(".access_token").isNotEmpty()); Map tokens = JsonUtils.readValueAsMap(tokenExchangeResult.andReturn().getResponse().getContentAsString()); - assertThat(tokens.get(ISSUED_TOKEN_TYPE)).isEqualTo(TOKEN_TYPE_ACCESS); - assertThat(tokens.get(TOKEN_TYPE)).isEqualTo(BEARER_TYPE.toLowerCase()); + assertThat(tokens).containsEntry(ISSUED_TOKEN_TYPE, TOKEN_TYPE_ACCESS) + .containsEntry(TOKEN_TYPE, BEARER_TYPE.toLowerCase()); Jwt tokenClaims = JwtHelper.decode((String) tokens.get("access_token")); Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); - assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); - assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); + assertThat(claims).containsEntry("user_name", thirdParty.user().getUserName()) + .containsEntry("email", thirdParty.user().getEmails().getFirst().getValue()) + .containsEntry("origin", workerServer.identityProvider().getOriginKey()); } @Test @@ -243,23 +242,25 @@ void token_exchange_three_idps_using_client_assertion() throws Exception { .andExpect(jsonPath(".refresh_token").isNotEmpty()); Map tokens = JsonUtils.readValueAsMap(tokenExchangeResult.andReturn().getResponse().getContentAsString()); - assertThat(tokens.get(ISSUED_TOKEN_TYPE)).isEqualTo(TOKEN_TYPE_ACCESS); - assertThat(tokens.get(TOKEN_TYPE)).isEqualTo(BEARER_TYPE.toLowerCase()); + assertThat(tokens).containsEntry(ISSUED_TOKEN_TYPE, TOKEN_TYPE_ACCESS) + .containsEntry(TOKEN_TYPE, BEARER_TYPE.toLowerCase()); Jwt tokenClaims = JwtHelper.decode((String) tokens.get("access_token")); Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); - assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); - assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); + assertThat(claims) + .containsEntry("user_name", thirdParty.user().getUserName()) + .containsEntry("email", thirdParty.user().getEmails().getFirst().getValue()) + .containsEntry("origin", workerServer.identityProvider().getOriginKey()); Map subjectTokenClaims = JsonUtils.readValueAsMap(JwtHelper.decode(idToken).getClaims()); Map actClaim = (Map) claims.get(ClaimConstants.ACT); - assertThat(actClaim.get(ClaimConstants.CLIENT_ID)).isEqualTo(workerServer.client().getClientId()); - assertThat(actClaim.get(ClaimConstants.SUB)).isEqualTo(subjectTokenClaims.get(ClaimConstants.SUB)); - assertThat(actClaim.get(ClaimConstants.USER_NAME)).isEqualTo(subjectTokenClaims.get(ClaimConstants.USER_NAME)); - assertThat(actClaim.get(ClaimConstants.USER_ID)).isEqualTo(subjectTokenClaims.get(ClaimConstants.USER_ID)); - assertThat(actClaim.get(ClaimConstants.ORIGIN)).isEqualTo(subjectTokenClaims.get(ClaimConstants.ORIGIN)); + assertThat(actClaim) + .containsEntry(ClaimConstants.CLIENT_ID, workerServer.client().getClientId()) + .containsEntry(ClaimConstants.SUB, subjectTokenClaims.get(ClaimConstants.SUB)) + .containsEntry(ClaimConstants.USER_NAME, subjectTokenClaims.get(ClaimConstants.USER_NAME)) + .containsEntry(ClaimConstants.USER_ID, subjectTokenClaims.get(ClaimConstants.USER_ID)) + .containsEntry(ClaimConstants.ORIGIN, subjectTokenClaims.get(ClaimConstants.ORIGIN)); } @Test @@ -317,19 +318,21 @@ void token_exchange_impersonate_client() throws Exception { Jwt tokenClaims = JwtHelper.decode((String) tokens.get("access_token")); Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); - assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); - assertThat(claims.get("origin")).isEqualTo(workerServer.identityProvider().getOriginKey()); - assertThat(claims.get("client_id")).isEqualTo(audience.getClientId()); - assertThat(claims.get("cid")).isEqualTo(audience.getClientId()); + assertThat(claims) + .containsEntry("user_name", thirdParty.user().getUserName()) + .containsEntry("email", thirdParty.user().getEmails().getFirst().getValue()) + .containsEntry("origin", workerServer.identityProvider().getOriginKey()) + .containsEntry("client_id", audience.getClientId()) + .containsEntry("cid", audience.getClientId()); Map subjectTokenClaims = JsonUtils.readValueAsMap(JwtHelper.decode(accessToken).getClaims()); Map actClaim = (Map) claims.get(ClaimConstants.ACT); - assertThat(actClaim.get(ClaimConstants.CLIENT_ID)).isEqualTo(workerServer.client().getClientId()); - assertThat(actClaim.get(ClaimConstants.SUB)).isEqualTo(subjectTokenClaims.get(ClaimConstants.SUB)); - assertThat(actClaim.get(ClaimConstants.USER_NAME)).isEqualTo(subjectTokenClaims.get(ClaimConstants.USER_NAME)); - assertThat(actClaim.get(ClaimConstants.USER_ID)).isEqualTo(subjectTokenClaims.get(ClaimConstants.USER_ID)); - assertThat(actClaim.get(ClaimConstants.ORIGIN)).isEqualTo(subjectTokenClaims.get(ClaimConstants.ORIGIN)); + assertThat(actClaim) + .containsEntry(ClaimConstants.CLIENT_ID, workerServer.client().getClientId()) + .containsEntry(ClaimConstants.SUB, subjectTokenClaims.get(ClaimConstants.SUB)) + .containsEntry(ClaimConstants.USER_NAME, subjectTokenClaims.get(ClaimConstants.USER_NAME)) + .containsEntry(ClaimConstants.USER_ID, subjectTokenClaims.get(ClaimConstants.USER_ID)) + .containsEntry(ClaimConstants.ORIGIN, subjectTokenClaims.get(ClaimConstants.ORIGIN)); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java index 49d1987d998..5f0c476564a 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeMockMvcBase.java @@ -1,7 +1,6 @@ package org.cloudfoundry.identity.uaa.mock.token; import org.apache.commons.codec.binary.Base64; -import org.assertj.core.api.Assertions; import org.cloudfoundry.identity.uaa.client.ClientJwtConfiguration; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.constants.OriginKeys; @@ -37,6 +36,7 @@ import java.util.function.Function; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.jwk.RsaJsonWebKeyTestUtils.SAMPLE_RSA_PRIVATE_KEY; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_JWT_BEARER; @@ -124,13 +124,12 @@ public AuthorizationServer workerServer() { public Jwt getTokenClaims(String token, String tokenKey, String serverKey) { assertThat(token) .withFailMessage(String.format("Server: %s does not have a token under key: %s", serverKey, tokenKey)) - .isNotNull() .isNotEmpty(); try { return JwtHelper.decode(token); } catch (RuntimeException _) { - Assertions.fail( + fail( String.format("Unable to decode token: %s for server: %s and key: %s", token, serverKey, tokenKey) ); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java index 1d73e57a68e..6d6def24798 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenExchangeOverrideAuthManagerMockMvcTests.java @@ -37,7 +37,7 @@ @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @Import(TokenExchangeOverrideAuthManagerMockMvcTests.TokenExchangeConfiguration.class) @DefaultTestContext -public class TokenExchangeOverrideAuthManagerMockMvcTests extends TokenExchangeMockMvcBase { +class TokenExchangeOverrideAuthManagerMockMvcTests extends TokenExchangeMockMvcBase { static class TokenExchangeConfiguration { @Bean @@ -139,9 +139,10 @@ void token_exchange_modify_origin_based_on_bean_override() throws Exception { Jwt tokenClaims = JwtHelper.decode((String) tokens.get("access_token")); Map claims = JsonUtils.readValueAsMap(tokenClaims.getClaims()); - assertThat(claims.get("user_name")).isEqualTo(thirdParty.user().getUserName()); - assertThat(claims.get("email")).isEqualTo(thirdParty.user().getEmails().getFirst().getValue()); - assertThat(claims.get("origin")).isEqualTo("override-origin"); + assertThat(claims) + .containsEntry("user_name", thirdParty.user().getUserName()) + .containsEntry("email", thirdParty.user().getEmails().getFirst().getValue()) + .containsEntry("origin", "override-origin"); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockTests.java index abd02af7a29..fb674c427d6 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockTests.java @@ -326,7 +326,7 @@ void authorization_code_missing_required_scopes() throws Exception { MultiValueMap queryParams = UriComponentsBuilder.fromUri(new URI(location)).build().getQueryParams(); assertThat(queryParams).isNotNull(); assertThat(queryParams.getFirst("error")).isNotNull(); - assertThat(queryParams.getFirst("error_description")).isNotNull() + assertThat(queryParams.getFirst("error_description")) .contains(UriUtils.encodeQueryParam("User does not meet the client's required group criteria.", "ISO-8859-1")); } @@ -1244,7 +1244,7 @@ void oauth_authorize_api_endpoint() throws Exception { // zone context needs to be set again because MVC calls mutate it IdentityZoneHolder.set(testZone); - assertThat(body).as("Token body must not be null.").isNotNull() + assertThat(body).as("Token body must not be null.") .contains(ACCESS_TOKEN, REFRESH_TOKEN); Map map = JsonUtils.readValue(body, new TypeReference<>() { }); @@ -1377,8 +1377,8 @@ void openIdTokenHybridFlowWithNoImplicitGrant() throws Exception { assertThat(location).contains("#"); URL url = new URL(location.replace("redirect#", "redirect?")); Map query = splitQuery(url); - assertThat(((List) query.get("id_token")).getFirst()).isNotNull(); - assertThat(((List) query.get("code")).getFirst()).isNotNull(); + assertThat(((List) query.get("id_token"))).first().isNotNull(); + assertThat(((List) query.get("code"))).first().isNotNull(); assertThat(query).doesNotContainKey("token"); } @@ -1482,8 +1482,8 @@ void openIdTokenHybridFlowWithNoImplicitGrantWhenStrictWhenAppNotApproved() thro Map query = splitQuery(url); assertThat(query).containsKey("id_token") .doesNotContainKey("token"); - assertThat(((List) query.get("id_token")).getFirst()).isNotNull(); - assertThat(((List) query.get("code")).getFirst()).isNotNull(); + assertThat(((List) query.get("id_token"))).first().isNotNull(); + assertThat(((List) query.get("code"))).first().isNotNull(); } @Test @@ -1924,8 +1924,8 @@ void legacyUserAuthentication_IdTokenRequest() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("access_token").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("id_token").getFirst()).isNotNull() + assertThat(hashFragmentParams.get("access_token")).first().isNotNull(); + assertThat(hashFragmentParams.get("id_token")).first().isNotNull() .isNotEqualTo(hashFragmentParams.get("access_token").getFirst()); validateOpenIdConnectToken(hashFragmentParams.get("id_token").getFirst(), developer.getId(), clientId); } @@ -1974,7 +1974,7 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType_withBasicAuth() throws Ex .containsKey(REFRESH_TOKEN) .containsKey("id_token"); if (authorizeRedirectQueryParams.get("id_token") != null) { - assertThat(authorizeRedirectQueryParams.get("id_token").getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(authorizeRedirectQueryParams.get("id_token")).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); Map claims = getClaimsForToken(tokenResponse.get("id_token")); @@ -2006,14 +2006,14 @@ void gettingOpenIdToken_HybridFlow_withCodePlusTokenPlusIdToken() throws Excepti URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("token_type").getFirst()).isEqualTo("bearer"); - assertThat(hashFragmentParams.get("access_token").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("id_token").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("code").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("state").getFirst()).isEqualTo(state); - assertThat(hashFragmentParams.get("expires_in").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("nonce").getFirst()).isEqualTo("testnonce"); - assertThat(hashFragmentParams.get("jti").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("token_type")).first().isEqualTo("bearer"); + assertThat(hashFragmentParams.get("access_token")).first().isNotNull(); + assertThat(hashFragmentParams.get("id_token")).first().isNotNull(); + assertThat(hashFragmentParams.get("code")).first().isNotNull(); + assertThat(hashFragmentParams.get("state")).first().isEqualTo(state); + assertThat(hashFragmentParams.get("expires_in")).first().isNotNull(); + assertThat(hashFragmentParams.get("nonce")).first().isEqualTo("testnonce"); + assertThat(hashFragmentParams.get("jti")).first().isNotNull(); validateOpenIdConnectToken(hashFragmentParams.get("id_token").getFirst(), developer.getId(), clientId); String code = hashFragmentParams.get("code").getFirst(); @@ -2030,7 +2030,7 @@ void gettingOpenIdToken_HybridFlow_withCodePlusTokenPlusIdToken() throws Excepti Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); - assertThat(hashFragmentParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(hashFragmentParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); assertThat(tokenResponse).containsKey(REFRESH_TOKEN) .doesNotContainEntry("id_token", tokenResponse.get(ACCESS_TOKEN)); validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); @@ -2061,15 +2061,15 @@ void gettingOpenIdToken_HybridFlow_withCodePlusIdToken() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("token_type").getFirst()).isEqualTo("bearer"); + assertThat(hashFragmentParams.get("token_type")).first().isEqualTo("bearer"); assertThat(hashFragmentParams).doesNotContainKey("access_token"); - assertThat(hashFragmentParams.get("id_token").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("id_token")).first().isNotNull(); validateOpenIdConnectToken(hashFragmentParams.get("id_token").getFirst(), developer.getId(), clientId); - assertThat(hashFragmentParams.get("code").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("state").getFirst()).isEqualTo(state); - assertThat(hashFragmentParams.get("expires_in").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("nonce").getFirst()).isEqualTo("testnonce"); - assertThat(hashFragmentParams.get("jti").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("code")).first().isNotNull(); + assertThat(hashFragmentParams.get("state")).first().isEqualTo(state); + assertThat(hashFragmentParams.get("expires_in")).first().isNotNull(); + assertThat(hashFragmentParams.get("nonce")).first().isEqualTo("testnonce"); + assertThat(hashFragmentParams.get("jti")).first().isNotNull(); String code = hashFragmentParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2086,7 +2086,7 @@ void gettingOpenIdToken_HybridFlow_withCodePlusIdToken() throws Exception { Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); if (hashFragmentParams.get(ACCESS_TOKEN) != null) { - assertThat(hashFragmentParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(hashFragmentParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } assertThat(tokenResponse).containsKey(REFRESH_TOKEN) .doesNotContainEntry("id_token", tokenResponse.get(ACCESS_TOKEN)); @@ -2118,14 +2118,14 @@ void gettingOpenIdToken_HybridFlow_withCodePlusToken() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("token_type").getFirst()).isEqualTo("bearer"); - assertThat(hashFragmentParams.get("access_token").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("token_type")).first().isEqualTo("bearer"); + assertThat(hashFragmentParams.get("access_token")).first().isNotNull(); assertThat(hashFragmentParams).doesNotContainKey("id_token"); - assertThat(hashFragmentParams.get("code").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("state").getFirst()).isEqualTo(state); - assertThat(hashFragmentParams.get("expires_in").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("nonce").getFirst()).isEqualTo("testnonce"); - assertThat(hashFragmentParams.get("jti").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("code")).first().isNotNull(); + assertThat(hashFragmentParams.get("state")).first().isEqualTo(state); + assertThat(hashFragmentParams.get("expires_in")).first().isNotNull(); + assertThat(hashFragmentParams.get("nonce")).first().isEqualTo("testnonce"); + assertThat(hashFragmentParams.get("jti")).first().isNotNull(); String code = hashFragmentParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2141,7 +2141,7 @@ void gettingOpenIdToken_HybridFlow_withCodePlusToken() throws Exception { Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); - assertThat(hashFragmentParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(hashFragmentParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); assertThat(tokenResponse).containsKey(REFRESH_TOKEN) .doesNotContainEntry("id_token", tokenResponse.get(ACCESS_TOKEN)); validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); @@ -2174,8 +2174,8 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType() throws Exception { assertThat(redirectUri).as("Redirect URL should not be a fragment.").doesNotContain("#") .as("Redirect URL should contain query params.").contains("?"); Map> queryParams = splitQuery(new URL(redirectUri)); - assertThat(queryParams.get("state").getFirst()).isEqualTo(state); - assertThat(queryParams.get("code").getFirst()).isNotNull(); + assertThat(queryParams.get("state")).first().isEqualTo(state); + assertThat(queryParams.get("code")).first().isNotNull(); String code = queryParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2192,7 +2192,7 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType() throws Exception { Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); if (queryParams.get(ACCESS_TOKEN) != null) { - assertThat(queryParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(queryParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } assertThat(tokenResponse).containsKey(REFRESH_TOKEN) // Successful OIDC token response should include ID Token even when scope=openid is not present. @@ -2203,7 +2203,7 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType() throws Exception { validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); Map claims = getClaimsForToken(tokenResponse.get("id_token")); assertThat(claims).containsEntry(ClaimConstants.NONCE, "testnonce"); - assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope")).getFirst()).isEqualTo("openid"); + assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope"))).first().isEqualTo("openid"); } @Test @@ -2230,8 +2230,8 @@ void attemptingToGetOpenIdToken_withAuthorizationCodeGrantType_whenClientMissing assertThat(redirectUri).as("Redirect URL should not be a fragment.").doesNotContain("#") .as("Redirect URL should contain query params.").contains("?"); Map> queryParams = splitQuery(new URL(redirectUri)); - assertThat(queryParams.get("state").getFirst()).isEqualTo(state); - assertThat(queryParams.get("code").getFirst()).isNotNull(); + assertThat(queryParams.get("state")).first().isEqualTo(state); + assertThat(queryParams.get("code")).first().isNotNull(); String code = queryParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2248,9 +2248,9 @@ void attemptingToGetOpenIdToken_withAuthorizationCodeGrantType_whenClientMissing Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); if (queryParams.get(ACCESS_TOKEN) != null) { - assertThat(queryParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(queryParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } - assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope")).getFirst()).isEqualTo("not-openid"); + assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope"))).first().isEqualTo("not-openid"); assertThat(tokenResponse).containsKey(REFRESH_TOKEN) // Successful OIDC token response should include ID Token even when scope=openid is not present. @@ -2287,7 +2287,7 @@ void gettingOpenIdToken_HybridFlow_withTokenPlusIdToken() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); assertThat(hashFragmentParams).containsKey(OAuth2Utils.STATE); - assertThat(hashFragmentParams.get(OAuth2Utils.STATE).getFirst()).isEqualTo("random-state"); + assertThat(hashFragmentParams.get(OAuth2Utils.STATE)).first().isEqualTo("random-state"); String code = hashFragmentParams.get("code").getFirst(); assertThat(code).isNotNull(); @@ -2329,7 +2329,7 @@ void gettingOpenIdToken_andNoAccessToken_withImplicitGrantType() throws Exceptio Map> tokenResponse = splitQuery(url); assertThat(tokenResponse).containsKey(OAuth2Utils.STATE) .containsKey("id_token"); - assertThat(tokenResponse.get(OAuth2Utils.STATE).getFirst()).isEqualTo("random-state"); + assertThat(tokenResponse.get(OAuth2Utils.STATE)).first().isEqualTo("random-state"); } @Test @@ -3502,7 +3502,6 @@ void getTokenScopesNotInAuthentication() throws Exception { OAuth2Authentication authContext = tokenServices.loadAuthentication(oauthToken.accessToken); assertThat(authContext.getOAuth2Request().getScope()) - .hasSize(4) .containsExactlyInAnyOrder(zoneAdminGroup, "openid", "cloud_controller.read", "cloud_controller.write"); } @@ -3873,7 +3872,7 @@ private String validatePasswordGrantToken(String clientId, String username, Stri Set grantedScopes = authContext.getOAuth2Request().getScope(); assertThat(grantedScopes).hasSameSizeAs(expectedScopes); - assertThat(new HashSet<>(expectedScopes)).isEqualTo(grantedScopes); + assertThat(new HashSet<>(expectedScopes)).hasSameElementsAs(grantedScopes); IdentityZoneHolder.clear(); return pwdToken; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockZonePathTests.java index 8f680062272..df029a9ab47 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenMvcMockZonePathTests.java @@ -166,8 +166,7 @@ "uaa.oauth.redirect_uri.allow_unsafe_matching=true" }) @EnabledIfZonePathsEnabled -@DefaultTestContext -public // NOSONAR public for LimitedModeTokenMockMvcTests +@DefaultTestContext // NOSONAR public for LimitedModeTokenMockMvcTests class TokenMvcMockZonePathTests extends AbstractTokenMockMvcTests { private static final String BAD_SECRET = "badsecret"; protected AlphanumericRandomValueStringGenerator generator = new AlphanumericRandomValueStringGenerator(); @@ -332,7 +331,7 @@ void authorization_code_missing_required_scopes() throws Exception { MultiValueMap queryParams = UriComponentsBuilder.fromUri(new URI(location)).build().getQueryParams(); assertThat(queryParams).isNotNull(); assertThat(queryParams.getFirst("error")).isNotNull(); - assertThat(queryParams.getFirst("error_description")).isNotNull() + assertThat(queryParams.getFirst("error_description")) .contains(UriUtils.encodeQueryParam("User does not meet the client's required group criteria.", "ISO-8859-1")); } @@ -1299,7 +1298,7 @@ void oauth_authorize_api_endpoint(ZoneResolutionMode mode) throws Exception { // zone context needs to be set again because MVC calls mutate it IdentityZoneHolder.set(testZone); - assertThat(body).as("Token body must not be null.").isNotNull() + assertThat(body).as("Token body must not be null.") .contains(ACCESS_TOKEN, REFRESH_TOKEN); Map map = JsonUtils.readValue(body, new TypeReference<>() { }); @@ -1432,8 +1431,8 @@ void openIdTokenHybridFlowWithNoImplicitGrant() throws Exception { assertThat(location).contains("#"); URL url = new URL(location.replace("redirect#", "redirect?")); Map query = splitQuery(url); - assertThat(((List) query.get("id_token")).getFirst()).isNotNull(); - assertThat(((List) query.get("code")).getFirst()).isNotNull(); + assertThat(((List) query.get("id_token"))).first().isNotNull(); + assertThat(((List) query.get("code"))).first().isNotNull(); assertThat(query).doesNotContainKey("token"); } @@ -1537,8 +1536,8 @@ void openIdTokenHybridFlowWithNoImplicitGrantWhenStrictWhenAppNotApproved() thro Map query = splitQuery(url); assertThat(query).containsKey("id_token") .doesNotContainKey("token"); - assertThat(((List) query.get("id_token")).getFirst()).isNotNull(); - assertThat(((List) query.get("code")).getFirst()).isNotNull(); + assertThat(((List) query.get("id_token"))).first().isNotNull(); + assertThat(((List) query.get("code"))).first().isNotNull(); } @Test @@ -1979,8 +1978,8 @@ void legacyUserAuthentication_IdTokenRequest() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("access_token").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("id_token").getFirst()).isNotNull() + assertThat(hashFragmentParams.get("access_token")).first().isNotNull(); + assertThat(hashFragmentParams.get("id_token")).first().isNotNull() .isNotEqualTo(hashFragmentParams.get("access_token").getFirst()); validateOpenIdConnectToken(hashFragmentParams.get("id_token").getFirst(), developer.getId(), clientId); } @@ -2029,7 +2028,7 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType_withBasicAuth() throws Ex .containsKey(REFRESH_TOKEN) .containsKey("id_token"); if (authorizeRedirectQueryParams.get("id_token") != null) { - assertThat(authorizeRedirectQueryParams.get("id_token").getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(authorizeRedirectQueryParams.get("id_token")).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); Map claims = getClaimsForToken(tokenResponse.get("id_token")); @@ -2061,14 +2060,14 @@ void gettingOpenIdToken_HybridFlow_withCodePlusTokenPlusIdToken() throws Excepti URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("token_type").getFirst()).isEqualTo("bearer"); - assertThat(hashFragmentParams.get("access_token").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("id_token").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("code").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("state").getFirst()).isEqualTo(state); - assertThat(hashFragmentParams.get("expires_in").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("nonce").getFirst()).isEqualTo("testnonce"); - assertThat(hashFragmentParams.get("jti").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("token_type")).first().isEqualTo("bearer"); + assertThat(hashFragmentParams.get("access_token")).first().isNotNull(); + assertThat(hashFragmentParams.get("id_token")).first().isNotNull(); + assertThat(hashFragmentParams.get("code")).first().isNotNull(); + assertThat(hashFragmentParams.get("state")).first().isEqualTo(state); + assertThat(hashFragmentParams.get("expires_in")).first().isNotNull(); + assertThat(hashFragmentParams.get("nonce")).first().isEqualTo("testnonce"); + assertThat(hashFragmentParams.get("jti")).first().isNotNull(); validateOpenIdConnectToken(hashFragmentParams.get("id_token").getFirst(), developer.getId(), clientId); String code = hashFragmentParams.get("code").getFirst(); @@ -2085,7 +2084,7 @@ void gettingOpenIdToken_HybridFlow_withCodePlusTokenPlusIdToken() throws Excepti Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); - assertThat(hashFragmentParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(hashFragmentParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); assertThat(tokenResponse).containsKey(REFRESH_TOKEN) .doesNotContainEntry("id_token", tokenResponse.get(ACCESS_TOKEN)); validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); @@ -2116,15 +2115,15 @@ void gettingOpenIdToken_HybridFlow_withCodePlusIdToken() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("token_type").getFirst()).isEqualTo("bearer"); + assertThat(hashFragmentParams.get("token_type")).first().isEqualTo("bearer"); assertThat(hashFragmentParams).doesNotContainKey("access_token"); - assertThat(hashFragmentParams.get("id_token").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("id_token")).first().isNotNull(); validateOpenIdConnectToken(hashFragmentParams.get("id_token").getFirst(), developer.getId(), clientId); - assertThat(hashFragmentParams.get("code").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("state").getFirst()).isEqualTo(state); - assertThat(hashFragmentParams.get("expires_in").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("nonce").getFirst()).isEqualTo("testnonce"); - assertThat(hashFragmentParams.get("jti").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("code")).first().isNotNull(); + assertThat(hashFragmentParams.get("state")).first().isEqualTo(state); + assertThat(hashFragmentParams.get("expires_in")).first().isNotNull(); + assertThat(hashFragmentParams.get("nonce")).first().isEqualTo("testnonce"); + assertThat(hashFragmentParams.get("jti")).first().isNotNull(); String code = hashFragmentParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2141,7 +2140,7 @@ void gettingOpenIdToken_HybridFlow_withCodePlusIdToken() throws Exception { Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); if (hashFragmentParams.get(ACCESS_TOKEN) != null) { - assertThat(hashFragmentParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(hashFragmentParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } assertThat(tokenResponse).containsKey(REFRESH_TOKEN) .doesNotContainEntry("id_token", tokenResponse.get(ACCESS_TOKEN)); @@ -2173,14 +2172,14 @@ void gettingOpenIdToken_HybridFlow_withCodePlusToken() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); - assertThat(hashFragmentParams.get("token_type").getFirst()).isEqualTo("bearer"); - assertThat(hashFragmentParams.get("access_token").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("token_type")).first().isEqualTo("bearer"); + assertThat(hashFragmentParams.get("access_token")).first().isNotNull(); assertThat(hashFragmentParams).doesNotContainKey("id_token"); - assertThat(hashFragmentParams.get("code").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("state").getFirst()).isEqualTo(state); - assertThat(hashFragmentParams.get("expires_in").getFirst()).isNotNull(); - assertThat(hashFragmentParams.get("nonce").getFirst()).isEqualTo("testnonce"); - assertThat(hashFragmentParams.get("jti").getFirst()).isNotNull(); + assertThat(hashFragmentParams.get("code")).first().isNotNull(); + assertThat(hashFragmentParams.get("state")).first().isEqualTo(state); + assertThat(hashFragmentParams.get("expires_in")).first().isNotNull(); + assertThat(hashFragmentParams.get("nonce")).first().isEqualTo("testnonce"); + assertThat(hashFragmentParams.get("jti")).first().isNotNull(); String code = hashFragmentParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2196,7 +2195,7 @@ void gettingOpenIdToken_HybridFlow_withCodePlusToken() throws Exception { Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); - assertThat(hashFragmentParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(hashFragmentParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); assertThat(tokenResponse).containsKey(REFRESH_TOKEN) .doesNotContainEntry("id_token", tokenResponse.get(ACCESS_TOKEN)); validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); @@ -2229,8 +2228,8 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType() throws Exception { assertThat(redirectUri).as("Redirect URL should not be a fragment.").doesNotContain("#") .as("Redirect URL should contain query params.").contains("?"); Map> queryParams = splitQuery(new URL(redirectUri)); - assertThat(queryParams.get("state").getFirst()).isEqualTo(state); - assertThat(queryParams.get("code").getFirst()).isNotNull(); + assertThat(queryParams.get("state")).first().isEqualTo(state); + assertThat(queryParams.get("code")).first().isNotNull(); String code = queryParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2247,7 +2246,7 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType() throws Exception { Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); if (queryParams.get(ACCESS_TOKEN) != null) { - assertThat(queryParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(queryParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } assertThat(tokenResponse).containsKey(REFRESH_TOKEN) // Successful OIDC token response should include ID Token even when scope=openid is not present. @@ -2258,7 +2257,7 @@ void gettingOpenIdToken_withAuthorizationCodeGrantType() throws Exception { validateOpenIdConnectToken(tokenResponse.get("id_token"), developer.getId(), clientId); Map claims = getClaimsForToken(tokenResponse.get("id_token")); assertThat(claims).containsEntry(ClaimConstants.NONCE, "testnonce"); - assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope")).getFirst()).isEqualTo("openid"); + assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope"))).first().isEqualTo("openid"); } @Test @@ -2285,8 +2284,8 @@ void attemptingToGetOpenIdToken_withAuthorizationCodeGrantType_whenClientMissing assertThat(redirectUri).as("Redirect URL should not be a fragment.").doesNotContain("#") .as("Redirect URL should contain query params.").contains("?"); Map> queryParams = splitQuery(new URL(redirectUri)); - assertThat(queryParams.get("state").getFirst()).isEqualTo(state); - assertThat(queryParams.get("code").getFirst()).isNotNull(); + assertThat(queryParams.get("state")).first().isEqualTo(state); + assertThat(queryParams.get("code")).first().isNotNull(); String code = queryParams.get("code").getFirst(); result = mockMvc.perform(post("/oauth/token") @@ -2303,9 +2302,9 @@ void attemptingToGetOpenIdToken_withAuthorizationCodeGrantType_whenClientMissing Map tokenResponse = JsonUtils.readValue(result.getResponse().getContentAsString(), Map.class); assertThat(tokenResponse).containsKey(ACCESS_TOKEN); if (queryParams.get(ACCESS_TOKEN) != null) { - assertThat(queryParams.get(ACCESS_TOKEN).getFirst()).isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); + assertThat(queryParams.get(ACCESS_TOKEN)).first().isNotEqualTo(tokenResponse.get(ACCESS_TOKEN)); } - assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope")).getFirst()).isEqualTo("not-openid"); + assertThat(((ArrayList) getClaimsForToken(tokenResponse.get(ACCESS_TOKEN)).get("scope"))).first().isEqualTo("not-openid"); assertThat(tokenResponse).containsKey(REFRESH_TOKEN) // Successful OIDC token response should include ID Token even when scope=openid is not present. @@ -2342,7 +2341,7 @@ void gettingOpenIdToken_HybridFlow_withTokenPlusIdToken() throws Exception { URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map> hashFragmentParams = splitQuery(url); assertThat(hashFragmentParams).containsKey(OAuth2Utils.STATE); - assertThat(hashFragmentParams.get(OAuth2Utils.STATE).getFirst()).isEqualTo("random-state"); + assertThat(hashFragmentParams.get(OAuth2Utils.STATE)).first().isEqualTo("random-state"); String code = hashFragmentParams.get("code").getFirst(); assertThat(code).isNotNull(); @@ -2384,7 +2383,7 @@ void gettingOpenIdToken_andNoAccessToken_withImplicitGrantType() throws Exceptio Map> tokenResponse = splitQuery(url); assertThat(tokenResponse).containsKey(OAuth2Utils.STATE) .containsKey("id_token"); - assertThat(tokenResponse.get(OAuth2Utils.STATE).getFirst()).isEqualTo("random-state"); + assertThat(tokenResponse.get(OAuth2Utils.STATE)).first().isEqualTo("random-state"); } @Test @@ -3536,7 +3535,6 @@ void getTokenScopesNotInAuthentication(ZoneResolutionMode mode) throws Exception OAuth2Authentication authContext = tokenServices.loadAuthentication(oauthToken.accessToken); assertThat(authContext.getOAuth2Request().getScope()) - .hasSize(4) .containsExactlyInAnyOrder(zoneAdminGroup, "openid", "cloud_controller.read", "cloud_controller.write"); } @@ -3907,7 +3905,7 @@ private String validatePasswordGrantToken(String clientId, String username, Stri Set grantedScopes = authContext.getOAuth2Request().getScope(); assertThat(grantedScopes).hasSameSizeAs(expectedScopes); - assertThat(new HashSet<>(expectedScopes)).isEqualTo(grantedScopes); + assertThat(new HashSet<>(expectedScopes)).hasSameElementsAs(grantedScopes); IdentityZoneHolder.clear(); return pwdToken; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java index bda6250eeee..fb76f4a6c33 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcTest.java @@ -200,12 +200,7 @@ void revokeOtherClientTokenByClientId(String scope) throws Exception { .header("Authorization", "Bearer " + revokeAccessToken)) .andExpect(status().isOk()); - try { - revocableTokenProvisioning.retrieve(tokenToBeRevoked, IdentityZoneHolder.get().getId()); - fail("Token should have been deleted"); - } catch (EmptyResultDataAccessException _) { - // expected - } + assertThatThrownBy(() -> revocableTokenProvisioning.retrieve(tokenToBeRevoked, IdentityZoneHolder.get().getId())).isInstanceOf(EmptyResultDataAccessException.class); } @Test @@ -266,6 +261,7 @@ void revokeOpaqueTokenWithOpaqueToken() throws Exception { try { revocableTokenProvisioning.retrieve(opaqueUserToken, IdentityZoneHolder.get().getId()); } catch (EmptyResultDataAccessException _) { + // ignore } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java index 8f589800902..9f4a0eaeb69 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/TokenRevocationEndpointMockMvcZonePathTest.java @@ -209,12 +209,7 @@ void revokeOtherClientTokenByClientId(String scope) throws Exception { .header("Authorization", "Bearer " + revokeAccessToken)) .andExpect(status().isOk()); - try { - revocableTokenProvisioning.retrieve(tokenToBeRevoked, IdentityZoneHolder.get().getId()); - fail("Token should have been deleted"); - } catch (EmptyResultDataAccessException _) { - // expected - } + assertThatThrownBy(() -> revocableTokenProvisioning.retrieve(tokenToBeRevoked, IdentityZoneHolder.get().getId())).isInstanceOf(EmptyResultDataAccessException.class); } @Test @@ -275,6 +270,7 @@ void revokeOpaqueTokenWithOpaqueToken() throws Exception { try { revocableTokenProvisioning.retrieve(opaqueUserToken, IdentityZoneHolder.get().getId()); } catch (EmptyResultDataAccessException _) { + // ignore } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/ZonePathTokenMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/ZonePathTokenMockMvcTests.java index 961ecb8b2c2..8a21f873575 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/ZonePathTokenMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/token/ZonePathTokenMockMvcTests.java @@ -1,6 +1,5 @@ package org.cloudfoundry.identity.uaa.mock.token; -import org.assertj.core.api.Assertions; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils; import org.cloudfoundry.identity.uaa.oauth.jwt.Jwt; @@ -16,6 +15,7 @@ import java.util.Map; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.authentication.AbstractClientParametersAuthenticationFilter.CLIENT_SECRET; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.ISS; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_CLIENT_CREDENTIALS; @@ -25,7 +25,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @EnabledIfZonePathsEnabled -public class ZonePathTokenMockMvcTests extends AbstractTokenMockMvcTests { +class ZonePathTokenMockMvcTests extends AbstractTokenMockMvcTests { @ParameterizedTest @EnumSource(ZoneResolutionMode.class) @@ -55,7 +55,7 @@ void clientCredentialsGrant(ZoneResolutionMode mode) throws Exception { .andReturn().getResponse().getContentAsString(); Map response = JsonUtils.readValueAsMap(tokenResult); Jwt tokenClaims = JwtHelper.decode((String) response.get("access_token")); - Assertions.assertThat(tokenClaims.getClaimSet().getStringClaim(ISS)) + assertThat(tokenClaims.getClaimSet().getStringClaim(ISS)) .isEqualTo("http://%s.localhost:8080/uaa/oauth/token".formatted(testZone.getSubdomain())); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcTests.java index aaa79ea28a7..1b65af0b11a 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcTests.java @@ -659,7 +659,7 @@ void createAndUpdateDoesNotReturnKeys() throws Exception { String id = generator.generate(); IdentityZone created = createZone(id, HttpStatus.CREATED, identityClientToken, new IdentityZoneConfiguration()); - assertThat(created.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(created.getConfig().getTokenPolicy().getKeys()).isEmpty(); assertThat(created.getConfig().getTokenPolicy().getActiveKeyId()).isEqualTo("kid"); assertThat(created.getConfig().getSamlConfig().getPrivateKey()).isNull(); assertThat(created.getConfig().getSamlConfig().getPrivateKeyPassword()).isNull(); @@ -681,7 +681,7 @@ void createAndUpdateDoesNotReturnKeys() throws Exception { IdentityZone updated = updateZone(created, HttpStatus.OK, identityClientToken); assertThat(updated.getDescription()).isEqualTo("updated description"); - assertThat(updated.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(updated.getConfig().getTokenPolicy().getKeys()).isEmpty(); assertThat(updated.getConfig().getTokenPolicy().getActiveKeyId()).isEqualTo("key1"); assertThat(updated.getConfig().getSamlConfig().getPrivateKey()).isNull(); assertThat(updated.getConfig().getSamlConfig().getPrivateKeyPassword()).isNull(); @@ -1759,7 +1759,7 @@ void deleteZonePublishesEvent() throws Exception { .accept(APPLICATION_JSON)) .andExpect(status().isOk()); IdentityZone deletedZone = JsonUtils.readValue(result.andReturn().getResponse().getContentAsString(), IdentityZone.class); - assertThat(deletedZone.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(deletedZone.getConfig().getTokenPolicy().getKeys()).isEmpty(); assertThat(deletedZone.getConfig().getSamlConfig().getPrivateKey()).isNull(); assertThat(deletedZone.getConfig().getSamlConfig().getPrivateKeyPassword()).isNull(); assertThat(deletedZone.getConfig().getSamlConfig().getCertificate()).isEqualTo(SERVICE_PROVIDER_CERTIFICATE); @@ -2124,7 +2124,7 @@ void userCanReadAZone_withZoneZoneIdReadToken() throws Exception { }); assertThat(zoneResult).isEqualTo(identityZone); assertThat(zoneResult.getConfig().getSamlConfig().getPrivateKey()).isNull(); - assertThat(zoneResult.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(zoneResult.getConfig().getTokenPolicy().getKeys()).containsExactlyInAnyOrderEntriesOf(emptyMap()); String userAccessTokenReadAndAdmin = MockMvcUtils.getUserOAuthAccessTokenAuthCode(mockMvc, "identity", "identitysecret", user.getId(), user.getUserName(), user.getPassword(), "zones." + identityZone.getId() + ".read " + "zones." + identityZone.getId() + ".admin "); result = mockMvc.perform( @@ -2135,7 +2135,7 @@ void userCanReadAZone_withZoneZoneIdReadToken() throws Exception { .andExpect(status().isOk()) .andReturn(); - zoneResult = JsonUtils.readValue(result.getResponse().getContentAsString(), new TypeReference() { + zoneResult = JsonUtils.readValue(result.getResponse().getContentAsString(), new TypeReference<>() { }); assertThat(zoneResult).isEqualTo(identityZone); assertThat(zoneResult.getConfig().getSamlConfig()) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcZonePathTests.java index 1483de915ee..8cee8b89ca3 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/zones/IdentityZoneEndpointsMockMvcZonePathTests.java @@ -667,7 +667,7 @@ void createAndUpdateDoesNotReturnKeys() throws Exception { String id = generator.generate(); IdentityZone created = createZone(id, HttpStatus.CREATED, identityClientToken, new IdentityZoneConfiguration()); - assertThat(created.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(created.getConfig().getTokenPolicy().getKeys()).containsExactlyInAnyOrderEntriesOf(emptyMap()); assertThat(created.getConfig().getTokenPolicy().getActiveKeyId()).isEqualTo("kid"); assertThat(created.getConfig().getSamlConfig().getPrivateKey()).isNull(); assertThat(created.getConfig().getSamlConfig().getPrivateKeyPassword()).isNull(); @@ -689,7 +689,7 @@ void createAndUpdateDoesNotReturnKeys() throws Exception { IdentityZone updated = updateZone(created, HttpStatus.OK, identityClientToken); assertThat(updated.getDescription()).isEqualTo("updated description"); - assertThat(updated.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(updated.getConfig().getTokenPolicy().getKeys()).containsExactlyInAnyOrderEntriesOf(emptyMap()); assertThat(updated.getConfig().getTokenPolicy().getActiveKeyId()).isEqualTo("key1"); assertThat(updated.getConfig().getSamlConfig().getPrivateKey()).isNull(); assertThat(updated.getConfig().getSamlConfig().getPrivateKeyPassword()).isNull(); @@ -1767,7 +1767,7 @@ void deleteZonePublishesEvent() throws Exception { .accept(APPLICATION_JSON)) .andExpect(status().isOk()); IdentityZone deletedZone = JsonUtils.readValue(result.andReturn().getResponse().getContentAsString(), IdentityZone.class); - assertThat(deletedZone.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(deletedZone.getConfig().getTokenPolicy().getKeys()).containsExactlyInAnyOrderEntriesOf(emptyMap()); assertThat(deletedZone.getConfig().getSamlConfig().getPrivateKey()).isNull(); assertThat(deletedZone.getConfig().getSamlConfig().getPrivateKeyPassword()).isNull(); assertThat(deletedZone.getConfig().getSamlConfig().getCertificate()).isEqualTo(SERVICE_PROVIDER_CERTIFICATE); @@ -2129,7 +2129,7 @@ void userCanReadAZone_withZoneZoneIdReadToken() throws Exception { }); assertThat(zoneResult).isEqualTo(identityZone); assertThat(zoneResult.getConfig().getSamlConfig().getPrivateKey()).isNull(); - assertThat(zoneResult.getConfig().getTokenPolicy().getKeys()).isEqualTo(emptyMap()); + assertThat(zoneResult.getConfig().getTokenPolicy().getKeys()).containsExactlyInAnyOrderEntriesOf(emptyMap()); String userAccessTokenReadAndAdmin = MockMvcUtils.getUserOAuthAccessTokenAuthCode(mockMvc, "identity", "identitysecret", user.getId(), user.getUserName(), user.getPassword(), "zones." + identityZone.getId() + ".read " + "zones." + identityZone.getId() + ".admin "); result = mockMvc.perform( diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java index edbac6ee642..566a3d40e7c 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java @@ -68,7 +68,7 @@ import static org.apache.logging.log4j.Level.DEBUG; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.HamcrestCondition.matching; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.ISSUER_URI; @@ -270,8 +270,9 @@ public Map enhance(Map claims, OAuth2Authenticat Jwt parsedToken = JwtHelper.decode(jwt); Map claims = JsonUtils.readValue(parsedToken.getClaims(), new TypeReference>() {}); - assertThat(claims).containsEntry("claim1", "value1"); - assertThat(claims).containsEntry("claim2", "value2"); + assertThat(claims) + .containsEntry("claim1", "value1") + .containsEntry("claim2", "value2"); } finally { tokenServices.setUaaTokenEnhancers(new ArrayList<>()); } @@ -320,8 +321,9 @@ public Map enhance(Map claims, OAuth2Authenticat Jwt parsedToken = JwtHelper.decode(jwt); Map claims = JsonUtils.readValue(parsedToken.getClaims(), new TypeReference>() {}); - assertThat(claims).containsEntry("claim1", "value1"); - assertThat(claims).containsEntry("claim2", "value1_modified"); + assertThat(claims) + .containsEntry("claim1", "value1") + .containsEntry("claim2", "value1_modified"); } finally { tokenServices.setUaaTokenEnhancers(new ArrayList<>()); } @@ -603,7 +605,7 @@ void happyCase(List acrs) { assertThat(refreshedToken).isNotNull(); Map claims = UaaTokenUtils.getClaims(refreshedToken.getIdTokenValue(), Map.class); - assertThat(claims).isNotEmpty() + assertThat(claims) .containsKey(ClaimConstants.ACR) .containsKey(ClaimConstants.ACR); assertThat((Map) claims.get(ClaimConstants.ACR)).containsKey("values"); @@ -726,7 +728,7 @@ void happyCase(List amrs) { assertThat(refreshedToken).isNotNull(); Map claims = UaaTokenUtils.getClaims(refreshedToken.getIdTokenValue(), Map.class); - assertThat(claims).isNotEmpty() + assertThat(claims) .containsKey(ClaimConstants.AMR) .containsKey(ClaimConstants.AMR); List actualAmrs = (List) claims.get(ClaimConstants.AMR); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterMockMvcTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterMockMvcTest.java index 25ef36d260f..1280a1670db 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterMockMvcTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterMockMvcTest.java @@ -22,7 +22,7 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @DefaultTestContext -public class RateLimiterMockMvcTest { +class RateLimiterMockMvcTest { @Autowired WebApplicationContext webApplicationContext; @@ -52,7 +52,7 @@ void clearSecContext() { } @Test - public void happyTokenPathWithoutSlash() throws Exception { + void happyTokenPathWithoutSlash() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON); @@ -63,7 +63,7 @@ public void happyTokenPathWithoutSlash() throws Exception { } @Test - public void happyTokenPathWithSlash() throws Exception { + void happyTokenPathWithSlash() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus/") .header("Authorization", "Bearer " + adminToken) .accept(APPLICATION_JSON); @@ -74,7 +74,7 @@ public void happyTokenPathWithSlash() throws Exception { } @Test - public void failBasicAuthPathWithSlash() throws Exception { + void failBasicAuthPathWithSlash() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus/") .header("Authorization", getAuthorizationHeader("admin", "adminsecret")) .accept(APPLICATION_JSON); @@ -84,7 +84,7 @@ public void failBasicAuthPathWithSlash() throws Exception { } @Test - public void failBasicAuthPathWithoutSlash() throws Exception { + void failBasicAuthPathWithoutSlash() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .header("Authorization", getAuthorizationHeader("admin", "adminsecret")) .accept(APPLICATION_JSON); @@ -94,7 +94,7 @@ public void failBasicAuthPathWithoutSlash() throws Exception { } @Test - public void improperClientWithoutScopeShouldFail() throws Exception { + void improperClientWithoutScopeShouldFail() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .header("Authorization", "Bearer " + loginClientToken) .accept(APPLICATION_JSON); @@ -104,7 +104,7 @@ public void improperClientWithoutScopeShouldFail() throws Exception { } @Test - public void missingScopeInTokenShouldFail() throws Exception { + void missingScopeInTokenShouldFail() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .header("Authorization", "Bearer " + noUaaAdminToken) .accept(APPLICATION_JSON); @@ -114,7 +114,7 @@ public void missingScopeInTokenShouldFail() throws Exception { } @Test - public void improperClientBasicAuthShouldFail() throws Exception { + void improperClientBasicAuthShouldFail() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .header("Authorization", getAuthorizationHeader("login", "loginsecret")) .accept(APPLICATION_JSON); @@ -124,7 +124,7 @@ public void improperClientBasicAuthShouldFail() throws Exception { } @Test - public void improperClientTokenAuthShouldFail() throws Exception { + void improperClientTokenAuthShouldFail() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .header("Authorization", "Bearer " + loginClientToken) .accept(APPLICATION_JSON); @@ -134,7 +134,7 @@ public void improperClientTokenAuthShouldFail() throws Exception { } @Test - public void zoneClientTokenAuthShouldFail() throws Exception { + void zoneClientTokenAuthShouldFail() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .with(new SetServerNameRequestPostProcessor(zone.getIdentityZone().getSubdomain() + ".localhost")) .header("Authorization", "Bearer " + zone.getZoneAdminToken()) @@ -145,7 +145,7 @@ public void zoneClientTokenAuthShouldFail() throws Exception { } @Test - public void zoneUaaAdminClientTokenAuthShouldFail() throws Exception { + void zoneUaaAdminClientTokenAuthShouldFail() throws Exception { String zoneUaaAdminToken = MockMvcUtils.getClientCredentialsOAuthAccessToken( mockMvc, "admin", "adminsecret", "uaa.admin", zone.getIdentityZone().getSubdomain(), false ); @@ -159,7 +159,7 @@ public void zoneUaaAdminClientTokenAuthShouldFail() throws Exception { } @Test - public void zoneClientBasicAuthShouldFail() throws Exception { + void zoneClientBasicAuthShouldFail() throws Exception { MockHttpServletRequestBuilder get = get("/RateLimitingStatus") .with(new SetServerNameRequestPostProcessor(zone.getIdentityZone().getSubdomain() + ".localhost")) .header("Authorization", getAuthorizationHeader("admin", "adminsecret")) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterZonePathMockMvcTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterZonePathMockMvcTest.java index c59562e037b..476be5ed742 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterZonePathMockMvcTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimitingFilterZonePathMockMvcTest.java @@ -26,7 +26,7 @@ @DefaultTestContext @EnabledIfZonePathsEnabled -public class RateLimitingFilterZonePathMockMvcTest { +class RateLimitingFilterZonePathMockMvcTest { @Autowired WebApplicationContext webApplicationContext; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/PasswordResetEndpointMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/PasswordResetEndpointMockMvcTests.java index 8c867feac79..8c9edd4d653 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/PasswordResetEndpointMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/PasswordResetEndpointMockMvcTests.java @@ -103,7 +103,6 @@ void changePasswordIsSuccessful() throws Exception { Map data = JsonUtils.readValue(expiringCode.getData(), new TypeReference>() { }); assertThat(data) - .isNotNull() .containsEntry("user_id", scimUser.getId()) .containsEntry("username", scimUser.getUserName()) .containsEntry(OAuth2Utils.CLIENT_ID, "login") @@ -134,7 +133,6 @@ void changePasswordIsSuccessfulWithOverridenClientId() throws Exception { Map data = JsonUtils.readValue(expiringCode.getData(), new TypeReference>() { }); assertThat(data) - .isNotNull() .containsEntry(OAuth2Utils.CLIENT_ID, "another-client"); } @@ -159,7 +157,6 @@ void changePasswordWithClientidAndRedirecturi() throws Exception { }); assertThat(resultingCodeData) - .isNotNull() .containsEntry("client_id", "app") .containsEntry("username", email) .containsEntry("user_id", scimUser.getId()) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java index c09ac0e0ec7..be14a86e2c7 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcTests.java @@ -1323,7 +1323,6 @@ void validateMembers(List expected, Collection for (String s : expected) { String[] data = s.split("\\|"); assertThat(data) - .isNotNull() .hasSize(2); String displayName = data[0]; String externalId = data[1]; @@ -1392,6 +1391,7 @@ private ScimUser createUserAndAddToGroups(IdentityZone zone, Set groupNa try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); } catch (MemberAlreadyExistsException _) { + // ignore } } } finally { @@ -1433,6 +1433,7 @@ private ScimGroup createGroupWithinGroups(IdentityZone zone, Set groupNa try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); } catch (MemberAlreadyExistsException _) { + // ignore } } } finally { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java index efba385aee8..733ae59644b 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsMockMvcZonePathTests.java @@ -1325,7 +1325,6 @@ void validateMembers(List expected, Collection for (String s : expected) { String[] data = s.split("\\|"); assertThat(data) - .isNotNull() .hasSize(2); String displayName = data[0]; String externalId = data[1]; @@ -1394,6 +1393,7 @@ private ScimUser createUserAndAddToGroups(IdentityZone zone, Set groupNa try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); } catch (MemberAlreadyExistsException _) { + // ignore } } } finally { @@ -1435,6 +1435,7 @@ private ScimGroup createGroupWithinGroups(IdentityZone zone, Set groupNa try { scimGroupMembershipManager.addMember(group.getId(), member, IdentityZoneHolder.get().getId()); } catch (MemberAlreadyExistsException _) { + // ignore } } } finally { diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java index 8ac0a10f971..a9c14f12ab2 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java @@ -52,11 +52,7 @@ import java.util.UUID; import static java.util.Collections.emptyList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatNoException; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.atLeastOnce; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasMockMvcTests.java index 84ee99c50f0..5ce5418dcfe 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsAliasMockMvcTests.java @@ -1510,7 +1510,7 @@ private MvcResult deleteScimUserAndReturnResult(final String userId, final Ident private void assertUserDoesNotExist(final String id, final String zoneId) throws Exception { final Optional user = readUserFromZoneIfExists(id, zoneId); - assertThat(user).isNotPresent(); + assertThat(user).isEmpty(); } } @@ -1580,7 +1580,7 @@ private static void assertIsCorrectAliasPair( .map(UserConfig::getDefaultGroups); assertThat(defaultGroupNamesAliasZoneOpt).isPresent(); final List defaultGroupNamesAliasZone = defaultGroupNamesAliasZoneOpt.get(); - assertThat(aliasUser.getGroups()).hasSize(defaultGroupNamesAliasZone.size()); + assertThat(aliasUser.getGroups()).hasSameSizeAs(defaultGroupNamesAliasZone); final List directGroupNamesAliasUser = aliasUser.getGroups().stream() .filter(group -> group.getType() == DIRECT) .map(ScimUser.Group::getDisplay) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcTests.java index 7e395dd5b41..e59b9906410 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcTests.java @@ -147,7 +147,7 @@ void unauthorized_put_returns_401() throws Exception { @ParameterizedTest @ValueSource(strings = {"/Users", "/Users/"}) - public void canCreateUsersWithEndpointEndingWithSlash(String url) throws Exception { + void canCreateUsersWithEndpointEndingWithSlash(String url) throws Exception { ScimUser user = getScimUser(); String password = hasText(user.getPassword()) ? user.getPassword() : "pas5word"; user.setPassword(password); @@ -1085,7 +1085,6 @@ void updateUserChangingOriginReturns400() throws Exception { assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); final Map responseBody = JsonUtils.readValueAsMap(response.getContentAsString()); assertThat(responseBody) - .isNotNull() .containsEntry("error_description", "Cannot change user's origin in update operation.") .containsEntry("error", "invalid_scim_resource") .containsEntry("message", "Cannot change user's origin in update operation."); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcZonePathTests.java index 8f3f3ce4ed7..4d9c40de62c 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsMockMvcZonePathTests.java @@ -156,7 +156,7 @@ void unauthorized_put_returns_401() throws Exception { @ParameterizedTest @ValueSource(strings = {"/Users", "/Users/"}) - public void canCreateUsersWithEndpointEndingWithSlash(String url) throws Exception { + void canCreateUsersWithEndpointEndingWithSlash(String url) throws Exception { ScimUser user = getScimUser(); String password = hasText(user.getPassword()) ? user.getPassword() : "pas5word"; user.setPassword(password); @@ -1117,7 +1117,6 @@ void updateUserChangingOriginReturns400() throws Exception { assertThat(response.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST.value()); final Map responseBody = JsonUtils.readValueAsMap(response.getContentAsString()); assertThat(responseBody) - .isNotNull() .containsEntry("error_description", "Cannot change user's origin in update operation.") .containsEntry("error", "invalid_scim_resource") .containsEntry("message", "Cannot change user's origin in update operation."); diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java index 78a6a4f2f55..3f13b46ef78 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java @@ -78,9 +78,7 @@ import java.util.UUID; import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -430,7 +428,7 @@ void create_with_non_uaa_origin_does_not_validate_password() { //1. this method, 2. user scimUserEndpoints, 3. user provisioning assertThat(passwords.getAllValues()).hasSize(3); - assertThat(passwords.getAllValues().getFirst()).isEqualTo("bla bla"); + assertThat(passwords.getAllValues()).first().isEqualTo("bla bla"); assertThat(passwords.getAllValues().get(1)).isEmpty(); } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserLookupMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserLookupMockMvcTests.java index eee580f3af9..4431d1a321e 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserLookupMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserLookupMockMvcTests.java @@ -107,7 +107,7 @@ void lookupId_DoesntReturnInactiveIdp_ByDefault() throws Exception { Map map = JsonUtils.readValue(response.getContentAsString(), Map.class); List> resources = (List>) map.get("resources"); assertThat(resources).hasSize(1); - assertThat(resources.getFirst()).doesNotContainEntry("origin", "test-origin"); + assertThat(resources.get(0)).doesNotContainEntry("origin", "test-origin"); } @Test diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserInfoEndpointMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserInfoEndpointMockMvcTests.java index 9c0cad6a580..c80d1b362c9 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserInfoEndpointMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/UserInfoEndpointMockMvcTests.java @@ -105,7 +105,7 @@ void testGetUserInfo() throws Exception { } @Test - void testPostUserInfo() throws Exception { + void postUserInfo() throws Exception { UserInfoResponse userInfoResponse = performUserInfoRequest(post("/userinfo"), "openid"); assertThat(userInfoResponse.getUserName()).isEqualTo(user.getUserName()); @@ -115,9 +115,7 @@ void testPostUserInfo() throws Exception { void attributesWithRolesAndUserAttributes() throws Exception { UserInfoResponse userInfo = getUserInfo("openid user_attributes roles"); Map> uas = userInfo.getUserAttributes(); - assertThat(uas) - .isNotNull() - .isEqualTo(userAttributes); + assertThat(uas).containsExactlyInAnyOrderEntriesOf(userAttributes); Object r = userInfo.getRoles(); assertThat(r) From c7c8dffe11e8e5f05eff265f873c27524ea97e91 Mon Sep 17 00:00:00 2001 From: Duane May Date: Thu, 4 Jun 2026 00:48:12 -0400 Subject: [PATCH 6/7] Assertj Rewrite Replace assertThatExceptionOfType with assertThatThrownBy --- .../identity/uaa/util/JsonUtilsTest.java | 7 +- .../InMemoryClientDetailsServiceTest.java | 9 ++- ...efaultOAuth2RequestAuthenticatorTests.java | 7 +- .../oauth/client/OAuth2RestTemplateTests.java | 12 +-- .../client/http/OAuth2ErrorHandlerTests.java | 36 +++++---- .../FormOAuth2ExceptionHttpMessageTest.java | 7 +- .../token/AccessTokenProviderChainTests.java | 15 ++-- ...orizationCodeAccessTokenProviderTests.java | 13 ++-- .../ImplicitAccessTokenProviderTests.java | 11 +-- ...OwnerPasswordAccessTokenProviderTests.java | 7 +- .../util/RandomValueStringGeneratorTests.java | 7 +- .../uaa/oauth/jwk/JsonWebKeyTests.java | 5 +- .../token/OAuth2AccessTokenSupportTests.java | 8 +- .../uaa/oauth/token/UaaTokenTests.java | 13 ++-- .../token/VerificationKeyResponseTest.java | 5 +- .../identity/uaa/scim/ScimGroupTests.java | 11 +-- .../identity/uaa/zone/TokenPolicyTest.java | 20 ++--- .../account/EmailChangeEmailServiceTest.java | 9 ++- .../account/PasswordChangeEndpointTests.java | 10 +-- ...tityAliasHandlerEnsureConsistencyTest.java | 7 +- .../event/ApprovalModifiedEventTest.java | 5 +- .../UaaClientAuthenticationProviderTest.java | 25 +++--- .../AuthzAuthenticationManagerTests.java | 21 ++--- ...ckIdpEnabledAuthenticationManagerTest.java | 5 +- ...xternalLoginAuthenticationManagerTest.java | 9 ++- .../LoginAuthenticationManagerTests.java | 8 +- ...asswordGrantAuthenticationManagerTest.java | 5 +- .../ScopeAuthenticationManagerTests.java | 7 +- .../uaa/client/ClientAdminBootstrapTests.java | 14 ++-- .../uaa/client/ClientAdminEndpointsTests.java | 77 ++++++++++--------- .../ClientAdminEndpointsValidatorTests.java | 9 ++- .../client/ClientJwtConfigurationTest.java | 26 ++++--- .../JdbcClientMetadataProvisioningTest.java | 7 +- ...aaClientDetailsUserDetailsServiceTest.java | 7 +- .../uaa/codestore/ExpiringCodeStoreTests.java | 13 ++-- .../codestore/JdbcExpiringCodeStoreTest.java | 9 ++- .../config/IdentityProviderBootstrapTest.java | 4 +- ...entityZoneConfigurationBootstrapTests.java | 4 +- .../AutologinAuthenticationManagerTest.java | 13 ++-- .../EmailAccountCreationServiceTests.java | 8 +- .../uaa/login/LoginInfoEndpointTests.java | 4 +- .../login/UaaChangePasswordServiceTest.java | 14 ++-- .../login/UaaResetPasswordServiceTests.java | 7 +- .../uaa/oauth/CheckTokenEndpointTests.java | 69 +++++++++-------- .../oauth/ClientAccessTokenValidityTest.java | 5 +- .../oauth/ClientRefreshTokenValidityTest.java | 5 +- .../DeprecatedUaaTokenServicesTests.java | 41 +++++----- .../uaa/oauth/RemoteTokenServicesTests.java | 5 +- .../uaa/oauth/TokenEndpointBuilderTest.java | 5 +- .../oauth/UaaAuthorizationEndpointTest.java | 51 ++++++------ .../UaaAuthorizationRequestManagerTests.java | 10 ++- .../uaa/oauth/UaaTokenStoreTests.java | 13 ++-- ...eEndpointsClientDetailsValidatorTests.java | 12 +-- .../ApprovalsAdminEndpointsTests.java | 6 +- .../beans/LegacyRedirectResolverTest.java | 8 +- .../uaa/oauth/beans/RedirectResolverTest.java | 11 +-- .../uaa/oauth/jwk/JsonWebKeySetTests.java | 5 +- .../jwt/ChainedSignatureVerifierTests.java | 15 ++-- .../uaa/oauth/jwt/CommonSignerTest.java | 7 +- .../jwt/JwtClientAuthenticationTest.java | 4 +- .../uaa/oauth/jwt/JwtHeaderHelperTest.java | 6 +- .../identity/uaa/oauth/jwt/JwtHelperTest.java | 15 ++-- .../uaa/oauth/jwt/JwtHelperX5tTest.java | 11 +-- .../uaa/oauth/jwt/SignatureVerifierTest.java | 7 +- .../oauth/pkce/PkceValidationServiceTest.java | 15 ++-- .../provider/CompositeTokenGranterTests.java | 7 +- .../OAuth2ClientContextFilterTests.java | 16 ++-- .../DefaultRedirectResolverTests.java | 73 +++++++++--------- .../provider/endpoint/TokenEndpointTests.java | 23 +++--- .../OAuth2ExpressionParserTests.java | 7 +- ...2MethodSecurityExpressionHandlerTests.java | 11 +-- .../OAuth2SecurityExpressionMethodsTests.java | 11 +-- ...uth2WebSecurityExpressionHandlerTests.java | 7 +- .../implicit/ImplicitTokenGranterTests.java | 7 +- ...esourceOwnerPasswordTokenGranterTests.java | 27 +++---- .../refresh/RefreshTokenGranterTests.java | 19 ++--- .../DefaultOAuth2RequestFactoryTests.java | 7 +- .../AbstractDefaultTokenServicesTests.java | 11 +-- .../token/DefaultTokenServicesTests.java | 7 +- ...DefaultTokenServicesWithInMemoryTests.java | 8 +- ...faultUserAuthenticationConverterTests.java | 7 +- .../oauth/provider/vote/ScopeVoterTests.java | 5 +- .../JdbcRevocableTokenProvisioningTest.java | 19 ++--- ...ncedAuthorizationCodeTokenGranterTest.java | 5 +- .../oauth/token/TokenKeyEndpointTests.java | 7 +- .../oauth/token/UaaTokenEndpointTests.java | 7 +- .../uaa/oauth/token/UserTokenGranterTest.java | 31 ++++---- .../uaa/openid/UserInfoEndpointTests.java | 7 +- .../uaa/passcode/PasscodeInformationTest.java | 11 +-- ...iderAliasHandlerEnsureConsistencyTest.java | 3 +- .../IdentityProviderEndpointsTest.java | 2 +- ...JdbcIdentityProviderProvisioningTests.java | 9 ++- .../LdapIdentityProviderDefinitionTest.java | 28 +++---- .../ldap/ProcessLdapPropertiesTest.java | 5 +- ...ExternalOAuthAuthenticationFilterTest.java | 20 ++--- .../ExternalOAuthAuthenticationManagerIT.java | 34 +++----- ...thIdentityProviderConfigValidatorTest.java | 47 +++++------ ...tityProviderDefinitionFactoryBeanTest.java | 5 +- .../oauth/OidcMetadataFetcherTest.java | 11 +-- ...RelyingPartyRegistrationResolverTests.java | 4 +- ...aaIdentityProviderConfigValidatorTest.java | 11 +-- .../uaa/ratelimiting/RateLimiterImplTest.java | 5 +- .../uaa/ratelimiting/util/IntUtilsTest.java | 5 +- .../ratelimiting/util/SourcedFileTest.java | 5 +- .../resources/jdbc/JdbcPagingListTests.java | 6 +- .../bootstrap/ScimUserBootstrapTests.java | 3 +- ...imGroupExternalMembershipManagerTests.java | 7 +- .../JdbcScimGroupMembershipManagerTests.java | 13 ++-- .../jdbc/JdbcScimGroupProvisioningTests.java | 35 +++++---- .../jdbc/JdbcScimUserProvisioningTests.java | 62 +++++++-------- .../jdbc/ScimSearchQueryConverterTests.java | 5 +- .../scim/services/ScimUserServiceTest.java | 4 +- .../identity/uaa/scim/util/ScimUtilsTest.java | 9 ++- ...rfAwareEntryPointAndDeniedHandlerTest.java | 12 +-- .../user/InMemoryUaaUserDatabaseTests.java | 15 ++-- .../uaa/user/JdbcUaaUserDatabaseTests.java | 9 ++- .../identity/uaa/user/UaaUserEditorTests.java | 5 +- .../uaa/util/JwtTokenSignedByThisUAATest.java | 76 +++++++++--------- .../identity/uaa/util/SessionUtilsTest.java | 5 +- .../uaa/util/TestUaaUrlBuilderTest.java | 5 +- .../uaa/util/UaaRandomStringUtilImplTest.java | 5 +- .../identity/uaa/util/UaaTokenUtilsTest.java | 7 +- .../identity/uaa/util/UaaUrlUtilsTest.java | 14 ++-- .../identity/uaa/util/beans/DbUtilsTest.java | 7 +- .../tomcat/UaaStartupFailureListenerTest.java | 5 +- .../JdbcIdentityZoneProvisioningTests.java | 11 +-- ...titenantJdbcClientDetailsServiceTests.java | 14 ++-- .../uaa/zone/UserConfigValidatorTest.java | 11 +-- ...AwareClientSecretPolicyValidatorTests.java | 13 ++-- .../identity/uaa/UaaConfigurationTests.java | 8 +- ...ityProviderEndpointsAliasMockMvcTests.java | 2 +- .../uaa/oauth/UaaTokenServicesTests.java | 7 +- .../endpoints/ScimGroupEndpointsTests.java | 17 ++-- .../endpoints/ScimUserEndpointsTests.java | 28 +++---- 134 files changed, 949 insertions(+), 851 deletions(-) diff --git a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java index a79d32edc0c..0cb81dfdb51 100644 --- a/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java +++ b/metrics-data/src/test/java/org/cloudfoundry/identity/uaa/util/JsonUtilsTest.java @@ -5,7 +5,6 @@ import tools.jackson.databind.DeserializationContext; import tools.jackson.databind.JsonNode; import tools.jackson.databind.annotation.JsonDeserialize; -import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.metrics.UrlGroup; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -65,8 +64,7 @@ void readValueAsMap() { @ParameterizedTest @ValueSource(strings = {"{", "}", "{\"prop1\":\"abc\","}) void readValueAsMapInvalid(final String input) { - assertThatThrownBy(() -> JsonUtils.readValueAsMap(input)) - .asInstanceOf(InstanceOfAssertFactories.throwable(JsonUtils.JsonUtilException.class)); + assertThatThrownBy(() -> JsonUtils.readValueAsMap(input)).isInstanceOf(JsonUtils.JsonUtilException.class); } @Test @@ -102,8 +100,7 @@ void serializeExcludingProperties() { void serializeExcludingPropertiesInnerCallFails() { Map groupProperties = JsonUtils.readValue(JSON_TEST_OBJECT_STRING, new TypeReference<>() { }); - assertThatThrownBy(() -> JsonUtils.serializeExcludingProperties(groupProperties, "limit.unknown")) - .asInstanceOf(InstanceOfAssertFactories.throwable(JsonUtils.JsonUtilException.class)); + assertThatThrownBy(() -> JsonUtils.serializeExcludingProperties(groupProperties, "limit.unknown")).isInstanceOf(JsonUtils.JsonUtilException.class); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java index a344ec2aeec..f4c1f558221 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/client/InMemoryClientDetailsServiceTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.provider.ClientAlreadyExistsException; import org.cloudfoundry.identity.uaa.provider.ClientRegistrationException; import org.cloudfoundry.identity.uaa.provider.NoSuchClientException; @@ -9,7 +10,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Test for InMemoryClientDetailsService @@ -45,16 +46,16 @@ void addClientDetails() { @Test void addClientDetailsNull() { - assertThatExceptionOfType(ClientRegistrationException.class).isThrownBy(() -> inMemoryClientDetailsService.addClientDetails(null)); + assertThatThrownBy(() -> inMemoryClientDetailsService.addClientDetails(null)).asInstanceOf(InstanceOfAssertFactories.throwable(ClientRegistrationException.class)); } @Test void addClientDetailsButExistsAlready() { - assertThatExceptionOfType(ClientAlreadyExistsException.class).isThrownBy(() -> inMemoryClientDetailsService.addClientDetails(new UaaClientDetails("admin", null, null, null, null))); + assertThatThrownBy(() -> inMemoryClientDetailsService.addClientDetails(new UaaClientDetails("admin", null, null, null, null))).asInstanceOf(InstanceOfAssertFactories.throwable(ClientAlreadyExistsException.class)); } @Test void addClientDetailsButDoesNotExist() { - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> inMemoryClientDetailsService.loadClientByClientId("user")); + assertThatThrownBy(() -> inMemoryClientDetailsService.loadClientByClientId("user")).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } } \ No newline at end of file diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java index c2dad87633c..c088971864e 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/DefaultOAuth2RequestAuthenticatorTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.http.AccessTokenRequiredException; import org.cloudfoundry.identity.uaa.oauth.client.resource.BaseOAuth2ProtectedResourceDetails; import org.cloudfoundry.identity.uaa.oauth.common.DefaultOAuth2AccessToken; @@ -8,7 +9,7 @@ import org.springframework.mock.http.client.MockClientHttpRequest; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -25,8 +26,8 @@ class DefaultOAuth2RequestAuthenticatorTests { @Test void missingAccessToken() { BaseOAuth2ProtectedResourceDetails resource = new BaseOAuth2ProtectedResourceDetails(); - assertThatExceptionOfType(AccessTokenRequiredException.class).isThrownBy(() -> - authenticator.authenticate(resource, new DefaultOAuth2ClientContext(), request)); + assertThatThrownBy(() -> + authenticator.authenticate(resource, new DefaultOAuth2ClientContext(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(AccessTokenRequiredException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java index d1e2e6771ed..253a713cb09 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/OAuth2RestTemplateTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.http.AccessTokenRequiredException; import org.cloudfoundry.identity.uaa.oauth.client.resource.BaseOAuth2ProtectedResourceDetails; import org.cloudfoundry.identity.uaa.oauth.client.resource.OAuth2ProtectedResourceDetails; @@ -32,7 +33,8 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; /** * Moved test class of from spring-security-oauth2 into UAA @@ -162,9 +164,9 @@ void noRetryAccessDeniedExceptionForNoExistingToken() { restTemplate.setRequestFactory((_, _) -> { throw new AccessTokenRequiredException(resource); }); - assertThatExceptionOfType(AccessTokenRequiredException.class).isThrownBy(() -> + assertThatThrownBy(() -> restTemplate.doExecute(new URI("https://foo"), null, HttpMethod.GET, new NullRequestCallback(), - new SimpleResponseExtractor())); + new SimpleResponseExtractor())).asInstanceOf(InstanceOfAssertFactories.throwable(AccessTokenRequiredException.class)); } @Test @@ -242,8 +244,8 @@ void newTokenNotAcquiredIfGreaterThanConfiguredClockSkew() { // gh-1478 @Test void negativeClockSkew() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - restTemplate.setClockSkew(-1)); + assertThatThrownBy(() -> + restTemplate.setClockSkew(-1)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } // gh-1909 diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java index 4f1555f32ad..4c5576222d2 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/OAuth2ErrorHandlerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client.http; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.resource.BaseOAuth2ProtectedResourceDetails; import org.cloudfoundry.identity.uaa.oauth.client.resource.OAuth2AccessDeniedException; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.UserDeniedAuthorizationException; @@ -31,7 +32,8 @@ import java.util.ArrayList; import java.util.List; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; /** @@ -142,24 +144,24 @@ public void handleError(URI url, HttpMethod method, ClientHttpResponse response) void handle500Error() { HttpHeaders headers = new HttpHeaders(); ClientHttpResponse response = new TestClientHttpResponse(headers, 500); - assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(HttpServerErrorException.class)); } @Test void handleGeneric400Error() { HttpHeaders headers = new HttpHeaders(); ClientHttpResponse response = new TestClientHttpResponse(headers, 400); - assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(HttpClientErrorException.class)); } @Test void handleGeneric403Error() { HttpHeaders headers = new HttpHeaders(); ClientHttpResponse response = new TestClientHttpResponse(headers, 403); - assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(HttpClientErrorException.class)); } // See https://github.com/spring-projects/spring-security-oauth/issues/387 @@ -170,8 +172,8 @@ void handleGeneric403ErrorWithBody() { ClientHttpResponse response = new TestClientHttpResponse(headers, 403, new ByteArrayInputStream("{}".getBytes())); handler = new OAuth2ErrorHandler(new DefaultResponseErrorHandler(), resource); - assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(HttpClientErrorException.class)); } @Test @@ -208,8 +210,8 @@ void handleErrorWithMissingHeader() throws Exception { when(response.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); when(response.getBody()).thenReturn(new ByteArrayInputStream(new byte[0])); when(response.getStatusText()).thenReturn(HttpStatus.BAD_REQUEST.toString()); - assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(HttpClientErrorException.class)); } // gh-875 @@ -220,8 +222,8 @@ void handleErrorWhenAccessDeniedMessageAndStatus400ThenThrowsUserDeniedAuthoriza HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ClientHttpResponse response = new TestClientHttpResponse(headers, 400, messageBody); - assertThatExceptionOfType(UserDeniedAuthorizationException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(UserDeniedAuthorizationException.class)); } // gh-875 @@ -232,8 +234,8 @@ void handleErrorWhenAccessDeniedMessageAndStatus403ThenThrowsOAuth2AccessDeniedE HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ClientHttpResponse response = new TestClientHttpResponse(headers, 403, messageBody); - assertThatExceptionOfType(OAuth2AccessDeniedException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(OAuth2AccessDeniedException.class)); } @Test @@ -271,7 +273,7 @@ public void write(Object o, MediaType contentType, HttpOutputMessage outputMessa final String appSpecificBodyContent = "This user is not authorized"; InputStream appSpecificErrorBody = new ByteArrayInputStream(appSpecificBodyContent.getBytes("UTF-8")); ClientHttpResponse response = new TestClientHttpResponse(headers, 401, appSpecificErrorBody); - assertThatExceptionOfType(HttpClientErrorException.class).isThrownBy(() -> - handler.handleError(null, null, response)); + assertThatThrownBy(() -> + handler.handleError(null, null, response)).asInstanceOf(InstanceOfAssertFactories.throwable(HttpClientErrorException.class)); } } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java index 3ff92f8bbc3..f34d8da0586 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/http/converter/FormOAuth2ExceptionHttpMessageTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client.http.converter; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.DefaultOAuth2AccessToken; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.BadClientCredentialsException; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.OAuth2Exception; @@ -13,7 +14,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class FormOAuth2ExceptionHttpMessageTest { @@ -50,8 +51,8 @@ void read() throws Exception { @Test void writeInternal() { - assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> - auth2AccessTokenMessageConverter.writeInternal(new DefaultOAuth2AccessToken(""), new MockHttpOutputMessage())); + assertThatThrownBy(() -> + auth2AccessTokenMessageConverter.writeInternal(new DefaultOAuth2AccessToken(""), new MockHttpOutputMessage())).asInstanceOf(InstanceOfAssertFactories.throwable(UnsupportedOperationException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java index d6d6153e4b9..c47d44cd1b8 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/AccessTokenProviderChainTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.grant.AuthorizationCodeAccessTokenProvider; import org.cloudfoundry.identity.uaa.oauth.client.resource.AuthorizationCodeResourceDetails; import org.cloudfoundry.identity.uaa.oauth.client.resource.BaseOAuth2ProtectedResourceDetails; @@ -34,7 +35,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; @@ -188,8 +189,8 @@ void sunnyDayWithExpiredTokenAndExpiredRefreshToken() { AccessTokenRequest request = new DefaultAccessTokenRequest(); request.setExistingToken(accessToken); SecurityContextHolder.getContext().setAuthentication(user); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - chain.obtainAccessToken(resource, request)); + assertThatThrownBy(() -> + chain.obtainAccessToken(resource, request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -227,8 +228,8 @@ void anonymousUser() { SecurityContextHolder.getContext() .setAuthentication(new AnonymousAuthenticationToken("foo", "bar", user.getAuthorities())); AccessTokenRequest request = new DefaultAccessTokenRequest(); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> - chain.obtainAccessToken(resource, request)); + assertThatThrownBy(() -> + chain.obtainAccessToken(resource, request)).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test @@ -241,8 +242,8 @@ public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails detail throw new UserRedirectRequiredException("redirect test", request.toSingleValueMap()); } })); - assertThatExceptionOfType(UserRedirectRequiredException.class).isThrownBy(() -> - chain.obtainAccessToken(resource, request)); + assertThatThrownBy(() -> + chain.obtainAccessToken(resource, request)).asInstanceOf(InstanceOfAssertFactories.throwable(UserRedirectRequiredException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java index 0fe2c11a73c..ea8f1376017 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/AuthorizationCodeAccessTokenProviderTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client.token.grant; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.grant.AuthorizationCodeAccessTokenProvider; import org.cloudfoundry.identity.uaa.oauth.client.resource.AuthorizationCodeResourceDetails; import org.cloudfoundry.identity.uaa.oauth.client.resource.OAuth2ProtectedResourceDetails; @@ -75,8 +76,8 @@ void getCode() { request.setPreservedState(new Object()); request.setStateKey("key"); resource.setAccessTokenUri("http://localhost/oauth/token"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - assertThat(provider.obtainAccessToken(resource, request).getValue()).isEqualTo("FOO")); + assertThatThrownBy(() -> + assertThat(provider.obtainAccessToken(resource, request).getValue()).isEqualTo("FOO")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -84,8 +85,8 @@ void getAccessTokenFailsWithNoState() { AccessTokenRequest request = new DefaultAccessTokenRequest(); request.setAuthorizationCode("foo"); resource.setAccessTokenUri("http://localhost/oauth/token"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - assertThat(provider.obtainAccessToken(resource, request).getValue()).isEqualTo("FOO")); + assertThatThrownBy(() -> + assertThat(provider.obtainAccessToken(resource, request).getValue()).isEqualTo("FOO")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -107,8 +108,8 @@ void redirectToAuthorizationEndpoint() { void redirectNotSpecified() { AccessTokenRequest request = new DefaultAccessTokenRequest(); resource.setUserAuthorizationUri("http://localhost/oauth/authorize"); - assertThatExceptionOfType(UserRedirectRequiredException.class).isThrownBy(() -> - provider.obtainAccessToken(resource, request)); + assertThatThrownBy(() -> + provider.obtainAccessToken(resource, request)).asInstanceOf(InstanceOfAssertFactories.throwable(UserRedirectRequiredException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java index 3325fc8ece9..f96d77b2cd6 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ImplicitAccessTokenProviderTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client.token.grant; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.grant.ImplicitAccessTokenProvider; import org.cloudfoundry.identity.uaa.oauth.client.resource.ImplicitResourceDetails; import org.cloudfoundry.identity.uaa.oauth.client.resource.OAuth2ProtectedResourceDetails; @@ -19,7 +20,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -43,8 +44,8 @@ protected OAuth2AccessToken retrieveToken(AccessTokenRequest request, OAuth2Prot @Test void redirectNotSpecified() { AccessTokenRequest request = new DefaultAccessTokenRequest(); - assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> - provider.obtainAccessToken(resource, request)); + assertThatThrownBy(() -> + provider.obtainAccessToken(resource, request)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalStateException.class)); } @Test @@ -82,8 +83,8 @@ void obtainAccessTokenNoRecdirect() { ImplicitResourceDetails details = new ImplicitResourceDetails(); details.setScope(Set.of("openid").stream().toList()); assertThat(details.isClientOnly()).isFalse(); - assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> - assertThat(provider.obtainAccessToken(details, new DefaultAccessTokenRequest(Map.of("scope", new String[]{"x"}, "client_id", new String[]{"x"})))).isNotNull()); + assertThatThrownBy(() -> + assertThat(provider.obtainAccessToken(details, new DefaultAccessTokenRequest(Map.of("scope", new String[]{"x"}, "client_id", new String[]{"x"})))).isNotNull()).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalStateException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java index 5850ca42611..55950aac814 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/client/token/grant/ResourceOwnerPasswordAccessTokenProviderTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.client.token.grant; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.grant.ResourceOwnerPasswordAccessTokenProvider; import org.cloudfoundry.identity.uaa.oauth.client.resource.AuthorizationCodeResourceDetails; import org.cloudfoundry.identity.uaa.oauth.client.resource.OAuth2ProtectedResourceDetails; @@ -17,7 +18,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -57,9 +58,9 @@ void supportsRefresh() { @Test void refreshAccessToken() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> + assertThatThrownBy(() -> assertThat(provider.refreshAccessToken(new AuthorizationCodeResourceDetails(), new DefaultOAuth2RefreshToken(""), new DefaultAccessTokenRequest( - Collections.emptyMap()))).isNull()); + Collections.emptyMap()))).isNull()).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java index 922f5241d72..ff97922a103 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/common/util/RandomValueStringGeneratorTests.java @@ -1,12 +1,13 @@ package org.cloudfoundry.identity.uaa.oauth.common.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.security.SecureRandom; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -51,8 +52,8 @@ void setLength() { @Test void setLength_NonPositiveNumber() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - generator.setLength(-1)); + assertThatThrownBy(() -> + generator.setLength(-1)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java index ba717d155be..757ad053e9f 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeyTests.java @@ -1,6 +1,7 @@ package org.cloudfoundry.identity.uaa.oauth.jwk; import tools.jackson.core.type.TypeReference; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.util.JsonUtils; import org.junit.jupiter.api.Test; @@ -8,7 +9,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; class JsonWebKeyTests { @@ -34,7 +35,7 @@ void webKeyPublic() { void webKeyPublicNoTypeException() { // given Map jsonMap = Map.of("kid", "uaa-key"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new JsonWebKey(jsonMap)); + assertThatThrownBy(() -> new JsonWebKey(jsonMap)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java index 66c36aa2c3b..d5f7a0ef3ad 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/OAuth2AccessTokenSupportTests.java @@ -2,7 +2,7 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.resource.ClientCredentialsResourceDetails; import org.cloudfoundry.identity.uaa.oauth.client.resource.OAuth2AccessDeniedException; import org.cloudfoundry.identity.uaa.oauth.common.AuthenticationScheme; @@ -31,7 +31,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -75,8 +75,8 @@ public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IO void retrieveTokenFailsWhenTokenEndpointNotAvailable() { error = new IOException("Planned"); response.setStatus(HttpStatus.BAD_REQUEST); - assertThatExceptionOfType(OAuth2AccessDeniedException.class).isThrownBy(() -> - support.retrieveToken(request, resource, form, requestHeaders)); + assertThatThrownBy(() -> + support.retrieveToken(request, resource, form, requestHeaders)).asInstanceOf(InstanceOfAssertFactories.throwable(OAuth2AccessDeniedException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java index bcba1e41c9e..523f552bb6f 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.grant.AuthorizationCodeAccessTokenProvider; import org.cloudfoundry.identity.uaa.oauth.client.grant.ClientCredentialsAccessTokenProvider; import org.cloudfoundry.identity.uaa.oauth.client.http.AccessTokenRequiredException; @@ -24,7 +25,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.common.OAuth2AccessToken.BEARER_TYPE; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -102,8 +103,8 @@ void accessTokenProviderChain() { void accessTokenProviderChainException() { ClientCredentialsAccessTokenProvider clientCredentialsAccessTokenProvider = new ClientCredentialsAccessTokenProvider(); AccessTokenProviderChain accessTokenProviderChain = new AccessTokenProviderChain(List.of(clientCredentialsAccessTokenProvider)); - assertThatExceptionOfType(OAuth2AccessDeniedException.class).isThrownBy(() -> - accessTokenProviderChain.refreshAccessToken(new ClientCredentialsResourceDetails(), new DefaultOAuth2RefreshToken(""), null)); + assertThatThrownBy(() -> + accessTokenProviderChain.refreshAccessToken(new ClientCredentialsResourceDetails(), new DefaultOAuth2RefreshToken(""), null)).asInstanceOf(InstanceOfAssertFactories.throwable(OAuth2AccessDeniedException.class)); } @Test @@ -120,7 +121,7 @@ void defaultAccessTokenRequest() { accessTokenRequest.addAll(parameters); accessTokenRequest.clear(); accessTokenRequest.add("key", "value"); - assertThat(accessTokenRequest.keySet()).hasSameElementsAs(Set.of("key")); + assertThat(accessTokenRequest).containsOnlyKeys(Set.of("key")); assertThat(accessTokenRequest.values()).hasToString(List.of(List.of("value")).toString()); // parameters @@ -159,7 +160,7 @@ void authorizationCodeAccessTokenProvider() { when(request.getHeaders()).thenReturn(new HashMap<>(Map.of(OAuth2Utils.USER_OAUTH_APPROVAL, List.of("true")))); when(request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)).thenReturn(true); authorizationCodeAccessTokenProvider.setRequestFactory(clientHttpRequestFactory); - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> - authorizationCodeAccessTokenProvider.obtainAuthorizationCode(authorizationCodeResourceDetails, request)); + assertThatThrownBy(() -> + authorizationCodeAccessTokenProvider.obtainAuthorizationCode(authorizationCodeResourceDetails, request)).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } } diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java index fa6b6d24981..09cbd52b780 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/VerificationKeyResponseTest.java @@ -2,6 +2,7 @@ import com.nimbusds.jose.HeaderParameterNames; import com.nimbusds.jose.jwk.JWKParameterNames; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey; import org.junit.jupiter.api.Test; @@ -9,7 +10,7 @@ import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class VerificationKeyResponseTest { @@ -43,7 +44,7 @@ void x509ThumbPrintSet() { @Test void keyTypeNullException() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> setupResponse(null, "thumbprint", "certificate")); + assertThatThrownBy(() -> setupResponse(null, "thumbprint", "certificate")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java index 142ecb93196..afdc21c5c23 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/scim/ScimGroupTests.java @@ -14,6 +14,7 @@ package org.cloudfoundry.identity.uaa.scim; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.util.JsonUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -23,7 +24,7 @@ import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class ScimGroupTests { private static final String GROUP_BEFORE_DESCRIPTION = "{\"meta\":{\"version\":0,\"created\":\"2016-01-13T09:01:33.909Z\"},\"zoneId\":\"zoneId\",\"displayName\":\"name\",\"schemas\":[\"urn:scim:schemas:core:1.0\"],\"id\":\"id\"}"; @@ -121,15 +122,15 @@ void dropDisplayName() { @Test void cant_drop_zone_id() { patch.getMeta().setAttributes(new String[]{"zoneID"}); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - group.patch(patch)); + assertThatThrownBy(() -> + group.patch(patch)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cant_drop_id() { patch.getMeta().setAttributes(new String[]{"id"}); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - group.patch(patch)); + assertThatThrownBy(() -> + group.patch(patch)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java index cd00c99e037..ba97a8caba3 100644 --- a/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java +++ b/model/src/test/java/org/cloudfoundry/identity/uaa/zone/TokenPolicyTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.zone; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.token.TokenConstants; import org.cloudfoundry.identity.uaa.util.JsonUtils; import org.junit.jupiter.api.Test; @@ -7,7 +8,8 @@ import java.util.Collections; import java.util.Map; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; class TokenPolicyTest { @@ -57,29 +59,29 @@ void set_values() { @Test void nullSigningKey() { TokenPolicy tokenPolicy = new TokenPolicy(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - tokenPolicy.setKeys(Collections.singletonMap("key-id", null))); + assertThatThrownBy(() -> + tokenPolicy.setKeys(Collections.singletonMap("key-id", null))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void emptySigningKey() { TokenPolicy tokenPolicy = new TokenPolicy(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - tokenPolicy.setKeys(Collections.singletonMap("key-id", " "))); + assertThatThrownBy(() -> + tokenPolicy.setKeys(Collections.singletonMap("key-id", " "))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void nullKeyId() { TokenPolicy tokenPolicy = new TokenPolicy(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - tokenPolicy.setKeys(Collections.singletonMap(null, "signing-key"))); + assertThatThrownBy(() -> + tokenPolicy.setKeys(Collections.singletonMap(null, "signing-key"))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void emptyKeyId() { TokenPolicy tokenPolicy = new TokenPolicy(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - tokenPolicy.setKeys(Collections.singletonMap(" ", "signing-key"))); + assertThatThrownBy(() -> + tokenPolicy.setKeys(Collections.singletonMap(" ", "signing-key"))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java index 94f7e25af94..86c48fb6a9c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/account/EmailChangeEmailServiceTest.java @@ -1,6 +1,7 @@ package org.cloudfoundry.identity.uaa.account; import org.apache.commons.lang3.RandomStringUtils; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.codestore.ExpiringCode; import org.cloudfoundry.identity.uaa.codestore.ExpiringCodeStore; @@ -42,7 +43,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.account.EmailChangeEmailService.CHANGE_EMAIL_REDIRECT_URL; import static org.cloudfoundry.identity.uaa.codestore.ExpiringCodeType.EMAIL; import static org.mockito.Mockito.any; @@ -150,7 +151,7 @@ void beginEmailChangeWithUsernameConflict() { eq(zoneId)) ).thenReturn(Collections.singletonList(new ScimUser())); - assertThatExceptionOfType(UaaException.class).isThrownBy(() -> emailChangeEmailService.beginEmailChange("user-001", "user@example.com", "new@example.com", null, null)); + assertThatThrownBy(() -> emailChangeEmailService.beginEmailChange("user-001", "user@example.com", "new@example.com", null, null)).asInstanceOf(InstanceOfAssertFactories.throwable(UaaException.class)); } @Test @@ -253,14 +254,14 @@ void completeVerificationWhereUsernameEqualsEmail() { void completeVerificationWithInvalidCode() { when(mockExpiringCodeStore.retrieveCode("invalid_code", zoneId)).thenReturn(null); - assertThatExceptionOfType(UaaException.class).isThrownBy(() -> emailChangeEmailService.completeVerification("invalid_code")); + assertThatThrownBy(() -> emailChangeEmailService.completeVerification("invalid_code")).asInstanceOf(InstanceOfAssertFactories.throwable(UaaException.class)); } @Test void completeVerificationWithInvalidIntent() { when(mockExpiringCodeStore.retrieveCode("invalid_code", zoneId)).thenReturn(new ExpiringCode("invalid_code", new Timestamp(System.currentTimeMillis()), null, "invalid-intent")); - assertThatExceptionOfType(UaaException.class).isThrownBy(() -> emailChangeEmailService.completeVerification("invalid_code")); + assertThatThrownBy(() -> emailChangeEmailService.completeVerification("invalid_code")).asInstanceOf(InstanceOfAssertFactories.throwable(UaaException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java index c6973b217c2..bfcaffc7ac3 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/account/PasswordChangeEndpointTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.account; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.oauth.common.util.RandomValueStringGenerator; import org.cloudfoundry.identity.uaa.resources.jdbc.JdbcPagingListFactory; @@ -25,7 +26,6 @@ import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.crypto.password.PasswordEncoder; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -112,7 +112,7 @@ void userCantChangeAnotherUsersPassword() { PasswordChangeRequest change = new PasswordChangeRequest(); change.setOldPassword("password"); change.setPassword("newpassword"); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> passwordChangeEndpoint.changePassword(dale.getId(), change)); + assertThatThrownBy(() -> passwordChangeEndpoint.changePassword(dale.getId(), change)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test @@ -128,14 +128,14 @@ void adminCanChangeAnotherUsersPassword() { void changePasswordRequestFailsForUserWithoutCurrentPassword() { PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword("newpassword"); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> passwordChangeEndpoint.changePassword(joel.getId(), change)); + assertThatThrownBy(() -> passwordChangeEndpoint.changePassword(joel.getId(), change)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test void changePasswordRequestFailsForAdminWithoutOwnCurrentPassword() { PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword("newpassword"); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> passwordChangeEndpoint.changePassword(joel.getId(), change)); + assertThatThrownBy(() -> passwordChangeEndpoint.changePassword(joel.getId(), change)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test @@ -151,7 +151,7 @@ void changePasswordFailsForUserIfTheySupplyWrongCurrentPassword() { PasswordChangeRequest change = new PasswordChangeRequest(); change.setPassword("newpassword"); change.setOldPassword("wrongpassword"); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> passwordChangeEndpoint.changePassword(joel.getId(), change)); + assertThatThrownBy(() -> passwordChangeEndpoint.changePassword(joel.getId(), change)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java index 06139c6c7c3..ecbc3905f3a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/alias/EntityAliasHandlerEnsureConsistencyTest.java @@ -1,6 +1,5 @@ package org.cloudfoundry.identity.uaa.alias; -import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.EntityWithAlias; import org.cloudfoundry.identity.uaa.scim.ScimUser; import org.junit.jupiter.api.BeforeEach; @@ -91,8 +90,7 @@ final void shouldThrow_WhenAliasZidSetButZoneDoesNotExist() { arrangeZoneDoesNotExist(customZoneId); assertThatThrownBy(() -> - aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) - .asInstanceOf(InstanceOfAssertFactories.throwable(EntityAliasFailedException.class)); + aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)).isInstanceOf(EntityAliasFailedException.class); } @Test @@ -149,8 +147,7 @@ final void shouldThrow_WhenReferencedAliasEntityAndAliasZoneDoNotExist() { arrangeEntityDoesNotExist(aliasId, customZoneId); arrangeZoneDoesNotExist(customZoneId); - assertThatThrownBy(() -> aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)) - .asInstanceOf(InstanceOfAssertFactories.throwable(EntityAliasFailedException.class)); + assertThatThrownBy(() -> aliasHandler.ensureConsistencyOfAliasEntity(originalEntity, existingEntity)).isInstanceOf(EntityAliasFailedException.class); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java index 6c258f1c872..159707be58f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/audit/event/ApprovalModifiedEventTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.audit.event; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.approval.Approval; import org.cloudfoundry.identity.uaa.audit.AuditEvent; import org.cloudfoundry.identity.uaa.audit.AuditEventType; @@ -7,13 +8,13 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class ApprovalModifiedEventTest { @Test void raisesWithBadSource() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new ApprovalModifiedEvent(new Object(), new MockAuthentication())); + assertThatThrownBy(() -> new ApprovalModifiedEvent(new Object(), new MockAuthentication())).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java index e5ce8618315..87f68db57b0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/UaaClientAuthenticationProviderTest.java @@ -1,5 +1,5 @@ package org.cloudfoundry.identity.uaa.authentication; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.account.UaaUserDetails; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.client.UaaClient; @@ -31,7 +31,8 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification.SECRET; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -164,7 +165,7 @@ void provider_refresh_client_with_password_inAuthorizationHeader_public_boolean( request.addParameter("refresh_token", "1234567890"); request.addParameter("grant_type", "refresh_token"); UsernamePasswordAuthenticationToken a = getAuthenticationToken(request); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)); + assertThatThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -175,7 +176,7 @@ void provider_refresh_client_without_wrong_endpoint() { request.addParameter("refresh_token", "1234567890"); request.addParameter("grant_type", "refresh_token"); UsernamePasswordAuthenticationToken a = getAuthenticationToken(request); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)); + assertThatThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -190,7 +191,7 @@ void provider_authenticate_client_without_password_public_boolean() { void provider_authenticate_client_without_password_public_wrong_grant_type() { client = createClient(ClientConstants.ALLOW_PUBLIC, true); UsernamePasswordAuthenticationToken a = getAuthenticationToken("client_credentials"); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret secret2", Collections.emptyList(), client.getAdditionalInformation(), null), a)); + assertThatThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret secret2", Collections.emptyList(), client.getAdditionalInformation(), null), a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -198,7 +199,7 @@ void provider_authenticate_no_details() { client = createClient(ClientConstants.ALLOW_PUBLIC, true); UsernamePasswordAuthenticationToken a = getAuthenticationToken("authorization_code"); UserDetails userDetails = new UaaUserDetails(new UaaUser("client", "secret", "mail@user", "", "")); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(userDetails, a)); + assertThatThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(userDetails, a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -206,7 +207,7 @@ void provider_authenticate_no_authenticationDetails() { client = createClient(ClientConstants.ALLOW_PUBLIC, true); UsernamePasswordAuthenticationToken a = getAuthenticationToken("authorization_code"); when(a.getDetails()).thenReturn(null); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret secret2", Collections.emptyList(), client.getAdditionalInformation(), null), a)); + assertThatThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret secret2", Collections.emptyList(), client.getAdditionalInformation(), null), a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -217,7 +218,7 @@ void provider_authenticate_client_without_password_public_missing_code() { when(a.getDetails()).thenReturn(uaaAuthenticationDetails); Map requestParameters = new HashMap<>(); when(uaaAuthenticationDetails.getParameterMap()).thenReturn(requestParameters); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)); + assertThatThrownBy(() -> authenticationProvider.additionalAuthenticationChecks(new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -241,7 +242,7 @@ void provider_authenticate_client_without_password_public_false() { UsernamePasswordAuthenticationToken a = mock(UsernamePasswordAuthenticationToken.class); UaaAuthenticationDetails uaaAuthenticationDetails = mock(UaaAuthenticationDetails.class); when(a.getDetails()).thenReturn(uaaAuthenticationDetails); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> testClientAuthentication(a)); + assertThatThrownBy(() -> testClientAuthentication(a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -259,14 +260,14 @@ void provider_authenticate_client_with_two_passwords_test_2() { @Test void provider_authenticate_client_with_two_passwords_test_3() { jdbcClientDetailsService.addClientSecret(client.getClientId(), "secret2", IdentityZoneHolder.get().getId()); - assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> testClientAuthentication(getToken(client.getClientId(), "secret3"))); + assertThatThrownBy(() -> testClientAuthentication(getToken(client.getClientId(), "secret3"))).asInstanceOf(InstanceOfAssertFactories.throwable(AuthenticationException.class)); } @Test void clientJwt_authenticate_client_without_config() { UsernamePasswordAuthenticationToken a = getAuthenticationTokenClientJwt("authorization_code"); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> authenticationProvider.additionalAuthenticationChecks( - new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)); + assertThatThrownBy(() -> authenticationProvider.additionalAuthenticationChecks( + new UaaClient("client", "secret", Collections.emptyList(), client.getAdditionalInformation(), null), a)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java index d22b03c0158..71c47a79c2c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/AuthzAuthenticationManagerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.authentication.manager; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.AccountNotVerifiedException; import org.cloudfoundry.identity.uaa.authentication.AuthenticationPolicyRejectionException; import org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest; @@ -46,7 +47,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -158,14 +159,14 @@ void unsuccessfulPasswordExpired() { @Test void unsuccessfulLoginServerUserAuthentication() { when(db.retrieveUserByName(loginServerUserName, OriginKeys.UAA)).thenReturn(null); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest(loginServerUserName, ""))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest(loginServerUserName, ""))).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); verify(db, times(0)).updateLastLogonTime(anyString()); } @Test void unsuccessfulLoginServerUserWithPasswordAuthentication() { when(db.retrieveUserByName(loginServerUserName, OriginKeys.UAA)).thenReturn(null); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest(loginServerUserName, "dadas"))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest(loginServerUserName, "dadas"))).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -184,7 +185,7 @@ void successfulAuthenticationReturnsTokenAndPublishesEvent() { void invalidPasswordPublishesAuthenticationFailureEvent() { when(db.retrieveUserByName("auser", OriginKeys.UAA)).thenReturn(user); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "wrongpassword"))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "wrongpassword"))).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); verify(publisher).publishEvent(isA(IdentityProviderAuthenticationFailureEvent.class)); verify(publisher).publishEvent(isA(UserAuthenticationFailureEvent.class)); @@ -197,14 +198,14 @@ void authenticationIsDeniedIfRejectedByLoginPolicy() { AccountLoginPolicy lp = mock(AccountLoginPolicy.class); when(lp.isAllowed(any(UaaUser.class), any(Authentication.class))).thenReturn(false); mgr.setAccountLoginPolicy(lp); - assertThatExceptionOfType(AuthenticationPolicyRejectionException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))).asInstanceOf(InstanceOfAssertFactories.throwable(AuthenticationPolicyRejectionException.class)); verify(db, times(0)).updateLastLogonTime(anyString()); } @Test void missingUserPublishesNotFoundEvent() { when(db.retrieveUserByName("aguess", OriginKeys.UAA)).thenThrow(new UsernameNotFoundException("mocked")); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest("aguess", "password"))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest("aguess", "password"))).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); verify(publisher).publishEvent(isA(UserNotFoundEvent.class)); } @@ -222,7 +223,7 @@ void successfulVerifyOriginAuthentication1() { @Test void originAuthenticationFail() { when(db.retrieveUserByName("auser", "not UAA")).thenReturn(user); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -241,7 +242,7 @@ void unverifiedAuthenticationForNewUserFailsEvenWhenAllowed() { mgr.setAllowUnverifiedUsers(true); user.setVerified(false); when(db.retrieveUserByName("auser", OriginKeys.UAA)).thenReturn(user); - assertThatExceptionOfType(AccountNotVerifiedException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))).asInstanceOf(InstanceOfAssertFactories.throwable(AccountNotVerifiedException.class)); verify(publisher).publishEvent(isA(UnverifiedUserAuthenticationEvent.class)); } @@ -260,7 +261,7 @@ void unverifiedAuthenticationFailsWhenNotAllowed() { mgr.setAllowUnverifiedUsers(false); user.setVerified(false); when(db.retrieveUserByName("auser", OriginKeys.UAA)).thenReturn(user); - assertThatExceptionOfType(AccountNotVerifiedException.class).isThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))); + assertThatThrownBy(() -> mgr.authenticate(createAuthRequest("auser", "password"))).asInstanceOf(InstanceOfAssertFactories.throwable(AccountNotVerifiedException.class)); verify(publisher).publishEvent(isA(UnverifiedUserAuthenticationEvent.class)); } @@ -301,7 +302,7 @@ void userIsLockedOutAfterNumberOfUnsuccessfulTriesIsExceeded() { Authentication authentication = createAuthRequest("auser", "password"); when(lockoutPolicy.isAllowed(any(UaaUser.class), eq(authentication))).thenReturn(false); - assertThatExceptionOfType(AuthenticationPolicyRejectionException.class).isThrownBy(() -> mgr.authenticate(authentication)); + assertThatThrownBy(() -> mgr.authenticate(authentication)).asInstanceOf(InstanceOfAssertFactories.throwable(AuthenticationPolicyRejectionException.class)); assertThat(authentication.isAuthenticated()).isFalse(); verify(publisher).publishEvent(isA(AuthenticationFailureLockedEvent.class)); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java index a7b5fd94810..df6f49281d6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/CheckIdpEnabledAuthenticationManagerTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.authentication.manager; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.provider.IdentityProvider; @@ -20,7 +21,7 @@ import java.sql.SQLException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -62,7 +63,7 @@ void authenticateIdpDisabled() { IdentityProvider provider = identityProviderProvisioning.retrieveByOrigin(OriginKeys.UAA, IdentityZoneHolder.get().getId()); provider.setActive(false); identityProviderProvisioning.update(provider, IdentityZoneHolder.get().getId()); - assertThatExceptionOfType(ProviderNotFoundException.class).isThrownBy(() -> manager.authenticate(token)); + assertThatThrownBy(() -> manager.authenticate(token)).asInstanceOf(InstanceOfAssertFactories.throwable(ProviderNotFoundException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java index 682ea96f51a..0d0cfbf59f1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ExternalLoginAuthenticationManagerTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.authentication.manager; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.AccountNotPreCreatedException; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails; @@ -241,8 +242,8 @@ void noUsernameNoEmail() { when(inputAuth.getDetails()).thenReturn(uaaAuthenticationDetails); when(uaaUserDatabase.retrieveUserByName(anyString(), eq(origin))).thenReturn(null); when(userDetails.getUsername()).thenReturn(null); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> - manager.authenticate(inputAuth)); + assertThatThrownBy(() -> + manager.authenticate(inputAuth)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -325,8 +326,8 @@ void emptyEmail() { @Test void authenticateUserInsertFails() { when(uaaUserDatabase.retrieveUserByName(anyString(), anyString())).thenThrow(new UsernameNotFoundException("")); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> - manager.authenticate(inputAuth)); + assertThatThrownBy(() -> + manager.authenticate(inputAuth)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java index 4cc3c48219b..dbe4daa39cd 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/LoginAuthenticationManagerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.authentication.manager; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest; import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationTestFactory; import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal; @@ -32,7 +33,8 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.HamcrestCondition.matching; import static org.cloudfoundry.identity.uaa.user.UaaUserMatcher.aUaaUser; import static org.mockito.Mockito.mock; @@ -101,7 +103,7 @@ void happyDayWithAuthorities() { @Test void userNotFoundNoAutoAdd() { Mockito.when(userDatabase.retrieveUserByName("foo", OriginKeys.LOGIN_SERVER)).thenThrow(new UsernameNotFoundException("planned")); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> manager.authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo"))); + assertThatThrownBy(() -> manager.authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo"))).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -117,7 +119,7 @@ void happyDayAutoAddButWithExistingUser() { @Test void unsuccessfulAutoAddButWithNewUser() { Mockito.when(userDatabase.retrieveUserByName("foo", OriginKeys.LOGIN_SERVER)).thenThrow(new UsernameNotFoundException("planned")); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> manager.authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo", true))); + assertThatThrownBy(() -> manager.authenticate(UaaAuthenticationTestFactory.getAuthenticationRequest("foo", true))).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java index f3ca0d908b6..b0c634c3cd4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/PasswordGrantAuthenticationManagerTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.authentication.manager; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent; import org.cloudfoundry.identity.uaa.authentication.ProviderConfigurationException; import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails; @@ -687,7 +688,7 @@ void oidcPasswordGrant_credentialsMustNotBeNull() { .setRelyingPartyId("client-id") .setRelyingPartySecret("client-secret"); idp.setConfig(config); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> instance.oidcPasswordGrant(authentication, idp)); + assertThatThrownBy(() -> instance.oidcPasswordGrant(authentication, idp)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -697,6 +698,6 @@ void oidcPasswordGrant_credentialsMustBeString() { .setRelyingPartyId("client-id") .setRelyingPartySecret("client-secret"); idp.setConfig(config); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> instance.oidcPasswordGrant(authentication, idp)); + assertThatThrownBy(() -> instance.oidcPasswordGrant(authentication, idp)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java index 76987b28aa7..4b156359e56 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/authentication/manager/ScopeAuthenticationManagerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.authentication.manager; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InsufficientScopeException; import org.cloudfoundry.identity.uaa.oauth.provider.AuthorizationRequest; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; @@ -21,7 +22,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -74,8 +75,8 @@ void testAuthenticate() { @Test void authenticateInsufficientScope() { clientCredentials.put("scope", "oauth.approval"); - assertThatExceptionOfType(InsufficientScopeException.class).isThrownBy(() -> - authenticate(null)); + assertThatThrownBy(() -> + authenticate(null)).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientScopeException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java index e188b744264..aa3c282ddae 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminBootstrapTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.authentication.SystemAuthentication; @@ -35,7 +36,8 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_IMPLICIT; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_JWT_BEARER; @@ -206,8 +208,8 @@ void noRegisteredRedirectUrlForAuthCode() { map.put("scope", "openid"); map.put("authorized-grant-types", GRANT_TYPE_AUTHORIZATION_CODE); map.put("authorities", "uaa.none"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> - doSimpleTest(map, clientAdminBootstrap, multitenantJdbcClientDetailsService, clients)); + assertThatThrownBy(() -> + doSimpleTest(map, clientAdminBootstrap, multitenantJdbcClientDetailsService, clients)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -218,8 +220,8 @@ void noRegisteredRedirectUrlForImplicit() { map.put("scope", "openid"); map.put("authorized-grant-types", GRANT_TYPE_IMPLICIT); map.put("authorities", "uaa.none"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> - doSimpleTest(map, clientAdminBootstrap, multitenantJdbcClientDetailsService, clients)); + assertThatThrownBy(() -> + doSimpleTest(map, clientAdminBootstrap, multitenantJdbcClientDetailsService, clients)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -286,7 +288,7 @@ void simpleInvalidClientWithJwkSet() { map.put("authorities", "uaa.none"); map.put("redirect-uri", "http://localhost/callback"); map.put("jwks", "invalid"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> doSimpleTest(map, clientAdminBootstrap, multitenantJdbcClientDetailsService, clients)); + assertThatThrownBy(() -> doSimpleTest(map, clientAdminBootstrap, multitenantJdbcClientDetailsService, clients)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java index f0ef13359fa..e30c76e2c9c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.approval.ApprovalStore; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.audit.event.SystemDeletable; @@ -241,7 +242,7 @@ void createClientDetailsWithSecretLengthLessThanMinLength() { testZone.getConfig().setClientSecretPolicy(new ClientSecretPolicy(7, 255, 0, 0, 0, 0, 6)); IdentityZoneHolder.set(testZone); when(clientDetailsService.retrieve(anyString(), anyString())).thenReturn(input); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -249,7 +250,7 @@ void createClientDetailsWithSecretLengthGreaterThanMaxLength() { testZone.getConfig().setClientSecretPolicy(new ClientSecretPolicy(0, 5, 0, 0, 0, 0, 6)); IdentityZoneHolder.set(testZone); when(clientDetailsService.retrieve(anyString(), anyString())).thenReturn(input); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -257,7 +258,7 @@ void createClientDetailsWithSecretRequireDigit() { testZone.getConfig().setClientSecretPolicy(new ClientSecretPolicy(0, 5, 0, 0, 1, 0, 6)); IdentityZoneHolder.set(testZone); when(clientDetailsService.retrieve(anyString(), anyString())).thenReturn(input); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -265,7 +266,7 @@ void createClientDetailsWithSecretRequireUppercase() { testZone.getConfig().setClientSecretPolicy(new ClientSecretPolicy(0, 5, 1, 0, 0, 0, 6)); IdentityZoneHolder.set(testZone); when(clientDetailsService.retrieve(anyString(), anyString())).thenReturn(input); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -273,7 +274,7 @@ void createClientDetailsWithSecretRequireLowercase() { testZone.getConfig().setClientSecretPolicy(new ClientSecretPolicy(0, 5, 0, 1, 0, 0, 6)); IdentityZoneHolder.set(testZone); when(clientDetailsService.retrieve(anyString(), anyString())).thenReturn(input); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -281,7 +282,7 @@ void createClientDetailsWithSecretRequireSpecialCharacter() { testZone.getConfig().setClientSecretPolicy(new ClientSecretPolicy(0, 5, 0, 0, 0, 1, 6)); IdentityZoneHolder.set(testZone); when(clientDetailsService.retrieve(anyString(), anyString())).thenReturn(input); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -341,52 +342,52 @@ void cannotCreateRestrictedClientSpScopes() { void cannotCreateRestrictedClientInvalidScopes() { input.setClientId("admin"); input.setScope(new UaaScopes().getUaaScopes()); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createRestrictedClientDetails(input)); + assertThatThrownBy(() -> endpoints.createRestrictedClientDetails(input)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void cannotCreateRestrictedClientInvalidAuthorities() { input.setAuthorities(new UaaScopes().getUaaAuthorities()); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createRestrictedClientDetails(input)); + assertThatThrownBy(() -> endpoints.createRestrictedClientDetails(input)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void cannotUpdateRestrictedClientInvalidScopes() { input.setScope(new UaaScopes().getUaaScopes()); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.updateRestrictedClientDetails(input, input.getClientId())); + assertThatThrownBy(() -> endpoints.updateRestrictedClientDetails(input, input.getClientId())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void cannotUpdateRestrictedClientInvalidAuthorities() { input.setAuthorities(new UaaScopes().getUaaAuthorities()); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.updateRestrictedClientDetails(input, input.getClientId())); + assertThatThrownBy(() -> endpoints.updateRestrictedClientDetails(input, input.getClientId())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void multipleCreateClientDetailsNullArray() { - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> endpoints.createClientDetailsTx(null)); + assertThatThrownBy(() -> endpoints.createClientDetailsTx(null)).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } @Test void multipleCreateClientDetailsEmptyArray() { - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> endpoints.createClientDetailsTx(new ClientDetailsModification[0])); + assertThatThrownBy(() -> endpoints.createClientDetailsTx(new ClientDetailsModification[0])).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } @Test void multipleCreateClientDetailsNonExistent() { ClientDetailsModification detailsModification = new ClientDetailsModification(); detailsModification.setClientId("unknown"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetailsTx(new ClientDetailsModification[]{detailsModification})); + assertThatThrownBy(() -> endpoints.createClientDetailsTx(new ClientDetailsModification[]{detailsModification})).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void multipleUpdateClientDetailsNullArray() { - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.updateClientDetailsTx(null)); + assertThatThrownBy(() -> endpoints.updateClientDetailsTx(null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void multipleUpdateClientDetailsEmptyArray() { - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.updateClientDetailsTx(new ClientDetailsModification[0])); + assertThatThrownBy(() -> endpoints.updateClientDetailsTx(new ClientDetailsModification[0])).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -402,33 +403,33 @@ void multipleCreateClientDetails() { @Test void createClientDetailsWithReservedId() { input.setClientId("uaa"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void createClientDetailsWithInvalidClientId() { input.setClientId("foo/bar"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); input.setClientId("foo\\bar"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void createMultipleClientDetailsWithReservedId() { inputs[inputs.length - 1].setClientId("uaa"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetailsTx(inputs)); + assertThatThrownBy(() -> endpoints.createClientDetailsTx(inputs)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void createClientDetailsWithNoGrantType() { input.setAuthorizedGrantTypes(Collections.emptySet()); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void createMultipleClientDetailsWithNoGrantType() { inputs[inputs.length - 1].setAuthorizedGrantTypes(Collections.emptySet()); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetailsTx(inputs)); + assertThatThrownBy(() -> endpoints.createClientDetailsTx(inputs)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -481,7 +482,7 @@ void resourceServerCreation() { @Test void createClientDetailsWithPasswordGrant() { input.setAuthorizedGrantTypes(Collections.singletonList("password")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(input))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); verify(clientRegistrationService, never()).addClientDetails(any()); } @@ -500,7 +501,7 @@ void findClientDetails() { @Test void findClientDetailsInvalidFilter() { Mockito.when(clientDetailsService.query("filter", "sortBy", true, IdentityZoneHolder.get().getId())).thenThrow(new IllegalArgumentException()); - assertThatExceptionOfType(UaaException.class).isThrownBy(() -> endpoints.listClientDetails("client_id", "filter", "sortBy", "ascending", 1, 100)); + assertThatThrownBy(() -> endpoints.listClientDetails("client_id", "filter", "sortBy", "ascending", 1, 100)).asInstanceOf(InstanceOfAssertFactories.throwable(UaaException.class)); } @Test @@ -524,20 +525,20 @@ void updateClientDetailsWithNullCallerAndInvalidScope() { Mockito.when(clientDetailsService.retrieve(input.getClientId(), IdentityZoneHolder.get().getId())).thenReturn( new UaaClientDetails(input)); input.setScope(Collections.singletonList("read")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.updateClientDetails(input, input.getClientId())); + assertThatThrownBy(() -> endpoints.updateClientDetails(input, input.getClientId())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); verify(clientRegistrationService, never()).updateClientDetails(any()); } @Test void nonExistentClient1() { Mockito.when(clientDetailsService.retrieve(input.getClientId(), IdentityZoneHolder.get().getId())).thenThrow(new InvalidClientDetailsException("")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.getClientDetails(input.getClientId())); + assertThatThrownBy(() -> endpoints.getClientDetails(input.getClientId())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void nonExistentClient2() { Mockito.when(clientDetailsService.retrieve(input.getClientId(), IdentityZoneHolder.get().getId())).thenThrow(new BadClientCredentialsException()); - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> endpoints.getClientDetails(input.getClientId())); + assertThatThrownBy(() -> endpoints.getClientDetails(input.getClientId())).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } @Test @@ -776,7 +777,7 @@ void changeSecretDeniedTooLong() { SecretChangeRequest change = new SecretChangeRequest(); change.setOldSecret(detail.getClientSecret()); change.setSecret(complexPolicySatisfyingSecret); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> endpoints.changeSecret(detail.getClientId(), change)); + assertThatThrownBy(() -> endpoints.changeSecret(detail.getClientId(), change)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -801,7 +802,7 @@ void scopeIsRestrictedByCaller() { when(clientDetailsService.retrieve("caller", IdentityZoneHolder.get().getId())).thenReturn(caller); when(mockSecurityContextAccessor.getClientId()).thenReturn("caller"); detail.setScope(Collections.singletonList("some")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -828,7 +829,7 @@ void authorityIsRestrictedByCaller() { when(clientDetailsService.retrieve("caller", IdentityZoneHolder.get().getId())).thenReturn(caller); when(mockSecurityContextAccessor.getClientId()).thenReturn("caller"); detail.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("uaa.some")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -848,28 +849,28 @@ void cannotExpandScope() { when(clientDetailsService.retrieve("caller", IdentityZoneHolder.get().getId())).thenReturn(caller); detail.setAuthorizedGrantTypes(Collections.singletonList("implicit")); detail.setClientSecret("hello"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void implicitClientWithNonEmptySecretIsRejected() { detail.setAuthorizedGrantTypes(Collections.singletonList("implicit")); detail.setClientSecret("hello"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void implicitAndAuthorizationCodeClientIsRejected() { detail.setAuthorizedGrantTypes(Arrays.asList("implicit", GRANT_TYPE_AUTHORIZATION_CODE)); detail.setClientSecret("hello"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void implicitAndAuthorizationCodeClientIsRejectedWithNullPassword() { detail.setAuthorizedGrantTypes(Arrays.asList("implicit", GRANT_TYPE_AUTHORIZATION_CODE)); detail.setClientSecret(null); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -877,14 +878,14 @@ void implicitAndAuthorizationCodeClientIsRejectedForAdmin() { when(mockSecurityContextAccessor.isAdmin()).thenReturn(true); detail.setAuthorizedGrantTypes(Arrays.asList("implicit", GRANT_TYPE_AUTHORIZATION_CODE)); detail.setClientSecret("hello"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void nonImplicitClientWithEmptySecretIsRejected() { detail.setAuthorizedGrantTypes(Collections.singletonList(GRANT_TYPE_AUTHORIZATION_CODE)); detail.setClientSecret(""); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -900,13 +901,13 @@ void updateNonImplicitClientAndMakeItImplicit() { assertThat(detail.getAuthorizedGrantTypes()).doesNotContain("implicit"); detail.setAuthorizedGrantTypes(Arrays.asList(GRANT_TYPE_AUTHORIZATION_CODE, "implicit")); detail.setClientSecret(null); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.updateClientDetails(detail, detail.getClientId())); + assertThatThrownBy(() -> endpoints.updateClientDetails(detail, detail.getClientId())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void invalidGrantTypeIsRejected() { detail.setAuthorizedGrantTypes(Collections.singletonList("not_a_grant_type")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))); + assertThatThrownBy(() -> endpoints.createClientDetails(createClientDetailsCreation(detail))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -1096,7 +1097,7 @@ void createClientWithJsonWebKeyUriInvalid() { detail.setAuthorizedGrantTypes(input.getAuthorizedGrantTypes()); ClientDetailsCreation createRequest = createClientDetailsCreation(input); createRequest.setJsonWebKeySet("invalid"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> endpoints.createClientDetails(createRequest)); + assertThatThrownBy(() -> endpoints.createClientDetails(createRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java index 82a56d2e5f8..3f4288bcf3c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientAdminEndpointsValidatorTests.java @@ -14,6 +14,7 @@ package org.cloudfoundry.identity.uaa.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; import org.cloudfoundry.identity.uaa.resources.QueryableResourceManager; import org.cloudfoundry.identity.uaa.security.beans.SecurityContextAccessor; @@ -228,8 +229,8 @@ void validateOneValidOneInvalidURL() { urls.add("http://invalid*"); client.setAuthorizedGrantTypes(Collections.singleton(GRANT_TYPE_AUTHORIZATION_CODE)); client.setRegisteredRedirectUri(urls); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> - validator.validateClientRedirectUri(client)); + assertThatThrownBy(() -> + validator.validateClientRedirectUri(client)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -239,8 +240,8 @@ void anotherOptionOneInvalidURL() { urls.add("http://invalid.com/with/path,subpath"); client.setAuthorizedGrantTypes(Collections.singleton(GRANT_TYPE_AUTHORIZATION_CODE)); client.setRegisteredRedirectUri(urls); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> - validator.validateClientRedirectUri(client)); + assertThatThrownBy(() -> + validator.validateClientRedirectUri(client)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java index effbbaf1fc0..ca56c2e918f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/ClientJwtConfigurationTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.ClientJwtCredential; import org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey; import org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKeySet; @@ -10,7 +11,8 @@ import java.util.Collections; import java.util.List; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -34,11 +36,11 @@ void jwksValidity() { @Test void jwksInvalid() { - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse("custom://any.domain.net/openid/jwks-uri", null)); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse("test", null)); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse("http://any.domain.net/openid/jwks-uri")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse("https://")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse("ftp://any.domain.net/openid/jwks-uri")); + assertThatThrownBy(() -> ClientJwtConfiguration.parse("custom://any.domain.net/openid/jwks-uri", null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); + assertThatThrownBy(() -> ClientJwtConfiguration.parse("test", null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); + assertThatThrownBy(() -> ClientJwtConfiguration.parse("http://any.domain.net/openid/jwks-uri")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); + assertThatThrownBy(() -> ClientJwtConfiguration.parse("https://")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); + assertThatThrownBy(() -> ClientJwtConfiguration.parse("ftp://any.domain.net/openid/jwks-uri")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -49,14 +51,14 @@ void jwkSetValidity() { @Test void jwkSetInvalid() { - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse(jsonJwkSetEmtpy)); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse(jsonWebKeyNoId)); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> ClientJwtConfiguration.parse("{\"keys\": \"x\"}")); + assertThatThrownBy(() -> ClientJwtConfiguration.parse(jsonJwkSetEmtpy)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); + assertThatThrownBy(() -> ClientJwtConfiguration.parse(jsonWebKeyNoId)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); + assertThatThrownBy(() -> ClientJwtConfiguration.parse("{\"keys\": \"x\"}")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void jwkSetInvalidSize() { - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> new ClientJwtConfiguration(null, new JsonWebKeySet<>(Collections.emptyList()))); + assertThatThrownBy(() -> new ClientJwtConfiguration(null, new JsonWebKeySet<>(Collections.emptyList()))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test @@ -113,7 +115,7 @@ void getCleanConfigInvalid() { when(mockedKey.getKeys()).thenReturn(keyList); ClientJwtConfiguration privateKey = new ClientJwtConfiguration(null, mockedKey); when(mockedKey.getKeySetMap()).thenThrow(new IllegalStateException("error")); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(privateKey::hasConfiguration); + assertThatThrownBy(privateKey::hasConfiguration).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); ClientJwtConfiguration privateKey2 = new ClientJwtConfiguration("hello", null); assertThat(privateKey2.hasConfiguration()).isFalse(); } @@ -123,7 +125,7 @@ void jwtSetValidate() { JsonWebKeySet mockedKey = mock(JsonWebKeySet.class); List keyList = ClientJwtConfiguration.parse(jsonJwkSet).getJwkSet().getKeys(); when(mockedKey.getKeys()).thenReturn(Arrays.asList(keyList.getFirst(), keyList.getFirst())); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> new ClientJwtConfiguration(null, mockedKey)); + assertThatThrownBy(() -> new ClientJwtConfiguration(null, mockedKey)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java index 7b997d93238..cef58325d20 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/JdbcClientMetadataProvisioningTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.extensions.profiles.DisabledIfProfile; import org.cloudfoundry.identity.uaa.util.AlphanumericRandomValueStringGenerator; @@ -62,7 +63,7 @@ void constraintViolation_WhenNoMatchingClientFound() throws Exception { base64EncodedImg, createdBy); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcClientMetadataProvisioning.update(clientMetadata, identityZoneId)); + assertThatThrownBy(() -> jdbcClientMetadataProvisioning.update(clientMetadata, identityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } /** @@ -118,8 +119,8 @@ void retrieve_ThatDoesNotExist() { assertThatNoException().isThrownBy( () -> jdbcClientMetadataProvisioning.retrieve(clientId2, "zone2")); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcClientMetadataProvisioning.retrieve(clientId1, "zone2")); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcClientMetadataProvisioning.retrieve(clientId2, "zone1")); + assertThatThrownBy(() -> jdbcClientMetadataProvisioning.retrieve(clientId1, "zone2")).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); + assertThatThrownBy(() -> jdbcClientMetadataProvisioning.retrieve(clientId2, "zone1")).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java index 42f834b0391..3a12f877bef 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/client/UaaClientDetailsUserDetailsServiceTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.client; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetailsService; import org.cloudfoundry.identity.uaa.oauth.provider.token.UserAuthenticationConverter; import org.cloudfoundry.identity.uaa.provider.ClientRegistrationException; @@ -11,7 +12,7 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class UaaClientDetailsUserDetailsServiceTest { @SuppressWarnings("unchecked") @@ -23,7 +24,7 @@ void shouldThrowUsernameNotFoundExceptionWhenNoSuchClient() { ClientDetailsService clientDetailsService = Mockito.mock(ClientDetailsService.class); Mockito.when(clientDetailsService.loadClientByClientId("test_user")).thenThrow(NoSuchClientException.class); UaaClientDetailsUserDetailsService testee = new UaaClientDetailsUserDetailsService(clientDetailsService); - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> testee.loadUserByUsername("test_user")); + assertThatThrownBy(() -> testee.loadUserByUsername("test_user")).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } @SuppressWarnings("unchecked") @@ -35,6 +36,6 @@ void shouldConductOriginalException() { ClientDetailsService clientDetailsService = Mockito.mock(ClientDetailsService.class); Mockito.when(clientDetailsService.loadClientByClientId("test_user")).thenThrow(ClientRegistrationException.class); UaaClientDetailsUserDetailsService testee = new UaaClientDetailsUserDetailsService(clientDetailsService); - assertThatExceptionOfType(ClientRegistrationException.class).isThrownBy(() -> testee.loadUserByUsername("test_user")); + assertThatThrownBy(() -> testee.loadUserByUsername("test_user")).asInstanceOf(InstanceOfAssertFactories.throwable(ClientRegistrationException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java index 20b25f3f094..fcd7e667300 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/ExpiringCodeStoreTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.codestore; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.util.RandomValueStringGenerator; import org.cloudfoundry.identity.uaa.util.TimeService; import org.cloudfoundry.identity.uaa.util.TimeServiceImpl; @@ -15,7 +16,7 @@ import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -50,14 +51,14 @@ void generateCode() { void generateCodeWithNullData() { String data = null; Timestamp expiresAt = new Timestamp(System.currentTimeMillis() + 60000); - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test void generateCodeWithNullExpiresAt() { String data = "{}"; Timestamp expiresAt = null; - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test @@ -66,7 +67,7 @@ void generateCodeWithExpiresAtInThePast() { when(mockTimeService.getCurrentTimeMillis()).thenReturn(now); String data = "{}"; Timestamp expiresAt = new Timestamp(now - 60000); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -78,7 +79,7 @@ void generateCodeWithDuplicateCode() { String data = "{}"; Timestamp expiresAt = new Timestamp(System.currentTimeMillis() + 60000); expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId()); - assertThatExceptionOfType(DataIntegrityViolationException.class).isThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(DataIntegrityViolationException.class)); } @Test @@ -127,7 +128,7 @@ void retrieveCodeWithCodeNotFound() { @Test void retrieveCodeWithNullCode() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> expiringCodeStore.retrieveCode(null, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> expiringCodeStore.retrieveCode(null, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java index 0dc96d84976..e440b04cf8a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/codestore/JdbcExpiringCodeStoreTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.codestore; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.test.TestUtils; import org.cloudfoundry.identity.uaa.zone.IdentityZone; @@ -13,7 +14,7 @@ import java.sql.SQLException; import java.sql.Timestamp; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -40,7 +41,7 @@ void databaseDown() throws Exception { ((JdbcExpiringCodeStore) expiringCodeStore).setDataSource(mockDataSource); String data = "{}"; Timestamp expiresAt = new Timestamp(System.currentTimeMillis() + 10000000); - assertThatExceptionOfType(DataAccessException.class).isThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> expiringCodeStore.generateCode(data, expiresAt, null, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(DataAccessException.class)); } @Test @@ -48,11 +49,11 @@ void expirationCleaner() { when(mockTimeService.getCurrentTimeMillis()).thenReturn(System.currentTimeMillis()); jdbcTemplate.update(JdbcExpiringCodeStore.insert, "test", System.currentTimeMillis() - 1000, "{}", null, IdentityZone.getUaaZoneId()); ((JdbcExpiringCodeStore) expiringCodeStore).cleanExpiredEntries(); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcTemplate.queryForObject( + assertThatThrownBy(() -> jdbcTemplate.queryForObject( JdbcExpiringCodeStore.selectAllFields, new JdbcExpiringCodeStore.JdbcExpiringCodeMapper(), "test", - IdentityZone.getUaaZoneId())); + IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @Override diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java index 7f0dd1eba17..bcbeee22699 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityProviderBootstrapTest.java @@ -1,6 +1,5 @@ package org.cloudfoundry.identity.uaa.config; -import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.constants.OriginKeys; @@ -400,8 +399,7 @@ void bootstrapFailsIfSamlAndOauthHaveTheSameAlias() throws Exception { setOauthIDPWrappers(); bootstrap.setSamlProviders(configurator); - assertThatThrownBy(() -> bootstrap.afterPropertiesSet()) - .asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); + assertThatThrownBy(() -> bootstrap.afterPropertiesSet()).isInstanceOf(IllegalArgumentException.class); } private AbstractExternalOAuthIdentityProviderDefinition setCommonProperties(AbstractExternalOAuthIdentityProviderDefinition definition) throws MalformedURLException { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java index f45b403ad4a..3209674902c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/config/IdentityZoneConfigurationBootstrapTests.java @@ -1,6 +1,5 @@ package org.cloudfoundry.identity.uaa.config; -import org.assertj.core.api.InstanceOfAssertFactories; import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.impl.config.IdentityZoneConfigurationBootstrap; @@ -132,8 +131,7 @@ void keyIdNullException() { keys.put(null, key1); bootstrap.setActiveKeyId(null); bootstrap.setSamlKeys(keys); - assertThatThrownBy(() -> bootstrap.afterPropertiesSet()) - .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidIdentityZoneDetailsException.class)); + assertThatThrownBy(() -> bootstrap.afterPropertiesSet()).isInstanceOf(InvalidIdentityZoneDetailsException.class); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java index 21f5ea204c6..8a4b2db51e9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/AutologinAuthenticationManagerTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.login; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.AuthzAuthenticationRequest; import org.cloudfoundry.identity.uaa.authentication.InvalidCodeException; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; @@ -31,7 +32,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -118,7 +119,7 @@ void authentication_fails_withInvalidClient() { codeData.put("action", ExpiringCodeType.AUTOLOGIN.name()); when(codeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId())).thenReturn(new ExpiringCode("the_secret_code", new Timestamp(123), JsonUtils.writeValueAsString(codeData), null)); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> manager.authenticate(authenticationToken)); + assertThatThrownBy(() -> manager.authenticate(authenticationToken)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test @@ -130,13 +131,13 @@ void authentication_fails_withNoClientId() { codeData.put("action", ExpiringCodeType.AUTOLOGIN.name()); when(codeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId())).thenReturn(new ExpiringCode("the_secret_code", new Timestamp(123), JsonUtils.writeValueAsString(codeData), null)); - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> manager.authenticate(authenticationToken)); + assertThatThrownBy(() -> manager.authenticate(authenticationToken)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test void authentication_fails_withExpiredCode() { when(codeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId())).thenReturn(null); - assertThatExceptionOfType(InvalidCodeException.class).isThrownBy(() -> manager.authenticate(authenticationToken)); + assertThatThrownBy(() -> manager.authenticate(authenticationToken)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidCodeException.class)); } @Test @@ -148,7 +149,7 @@ void authentication_fails_withCodeIntendedForDifferentPurpose() { codeData.put(OriginKeys.ORIGIN, OriginKeys.UAA); when(codeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId())).thenReturn(new ExpiringCode("the_secret_code", new Timestamp(123), JsonUtils.writeValueAsString(codeData), null)); - assertThatExceptionOfType(InvalidCodeException.class).isThrownBy(() -> manager.authenticate(authenticationToken)); + assertThatThrownBy(() -> manager.authenticate(authenticationToken)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidCodeException.class)); } @Test @@ -157,6 +158,6 @@ void authentication_fails_withInvalidCode() { codeData.put("action", "someotheraction"); when(codeStore.retrieveCode("the_secret_code", IdentityZoneHolder.get().getId())).thenReturn(new ExpiringCode("the_secret_code", new Timestamp(123), JsonUtils.writeValueAsString(codeData), null)); - assertThatExceptionOfType(InvalidCodeException.class).isThrownBy(() -> manager.authenticate(authenticationToken)); + assertThatThrownBy(() -> manager.authenticate(authenticationToken)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidCodeException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java index 007024462d9..eb1e2bde8bc 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/EmailAccountCreationServiceTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.login; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.account.AccountCreationService; import org.cloudfoundry.identity.uaa.account.EmailAccountCreationService; import org.cloudfoundry.identity.uaa.codestore.ExpiringCode; @@ -45,7 +46,8 @@ import java.util.HashMap; import java.util.Map; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.codestore.ExpiringCodeType.REGISTRATION; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.anyInt; @@ -198,7 +200,7 @@ void beginActivationWithExistingUser() { ).thenReturn(Collections.singletonList(user)); when(mockScimUserProvisioning.createUser(any(ScimUser.class), anyString(), eq(currentIdentityZoneId))).thenThrow(new ScimResourceAlreadyExistsException("duplicate")); - assertThatExceptionOfType(UaaException.class).isThrownBy(() -> emailAccountCreationService.beginActivation("user@example.com", "password", "login", null)); + assertThatThrownBy(() -> emailAccountCreationService.beginActivation("user@example.com", "password", "login", null)).asInstanceOf(InstanceOfAssertFactories.throwable(UaaException.class)); } @Test @@ -328,7 +330,7 @@ void completeActivationWithExpiredCode() { void beginActivation_throwsException_ifPasswordViolatesPolicy() { doThrow(new InvalidPasswordException("Oh hell no")).when(mockPasswordValidator).validate(anyString()); - assertThatExceptionOfType(InvalidPasswordException.class).isThrownBy(() -> emailAccountCreationService.beginActivation("user@example.com", "some password", null, null)); + assertThatThrownBy(() -> emailAccountCreationService.beginActivation("user@example.com", "some password", null, null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidPasswordException.class)); verify(mockPasswordValidator).validate("some password"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java index 487ac48af06..2766dad97eb 100755 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/LoginInfoEndpointTests.java @@ -1,5 +1,4 @@ package org.cloudfoundry.identity.uaa.login; -import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.codestore.InMemoryExpiringCodeStore; @@ -947,8 +946,7 @@ void externalOAuthCallback_redirectsToSavedRequestIfPresent() { @Test void loginWithInvalidMediaType() { LoginInfoEndpoint endpoint = getEndpoint(IdentityZoneHolder.get()); - assertThatThrownBy(() -> endpoint.loginForHtml(extendedModelMap, null, new MockHttpServletRequest(), singletonList(MediaType.TEXT_XML))) - .asInstanceOf(InstanceOfAssertFactories.throwable(HttpMediaTypeNotAcceptableException.class)); + assertThatThrownBy(() -> endpoint.loginForHtml(extendedModelMap, null, new MockHttpServletRequest(), singletonList(MediaType.TEXT_XML))).isInstanceOf(HttpMediaTypeNotAcceptableException.class); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java index 9d5b1091d4f..9f1791a3001 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaChangePasswordServiceTest.java @@ -13,6 +13,7 @@ *******************************************************************************/ package org.cloudfoundry.identity.uaa.login; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.account.UaaChangePasswordService; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.scim.ScimUser; @@ -31,7 +32,6 @@ import java.util.List; import static java.util.Collections.emptyList; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -56,23 +56,23 @@ void setUp() { @Test void changePasswordWithNoCurrentPasswordOrUsername() { - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> - subject.changePassword(null, null, "newPassword")); + assertThatThrownBy(() -> + subject.changePassword(null, null, "newPassword")).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test void changePasswordWithInvalidNewPassword() { doThrow(new InvalidPasswordException("")).when(passwordValidator).validate("invPawd"); - assertThatExceptionOfType(InvalidPasswordException.class).isThrownBy(() -> - subject.changePassword("username", "currentPassword", "invPawd")); + assertThatThrownBy(() -> + subject.changePassword("username", "currentPassword", "invPawd")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidPasswordException.class)); } @Test void changePasswordWithUserNotFound() { String zoneId = IdentityZoneHolder.get().getId(); when(scimUserProvisioning.query(anyString(), eq(zoneId))).thenReturn(emptyList()); - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> - subject.changePassword("username", "currentPassword", "validPassword")); + assertThatThrownBy(() -> + subject.changePassword("username", "currentPassword", "validPassword")).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); verify(passwordValidator).validate("validPassword"); verify(scimUserProvisioning).retrieveByUsernameAndOriginAndZone(anyString(), eq(OriginKeys.UAA), eq(zoneId)); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java index 8706ca043e1..1240f6d8da0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/login/UaaResetPasswordServiceTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.login; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.account.ConflictException; import org.cloudfoundry.identity.uaa.account.ForgotPasswordInfo; import org.cloudfoundry.identity.uaa.account.NotFoundException; @@ -170,7 +171,7 @@ void forgotPassword_ThrowsConflictException() { @Test void forgotPassword_ThrowsNotFoundException_ScimUserNotFoundInUaa() { - assertThatExceptionOfType(NotFoundException.class).isThrownBy(() -> uaaResetPasswordService.forgotPassword("exampleUser", "", "")); + assertThatThrownBy(() -> uaaResetPasswordService.forgotPassword("exampleUser", "", "")).asInstanceOf(InstanceOfAssertFactories.throwable(NotFoundException.class)); } @Test @@ -193,7 +194,7 @@ void resetPassword_validatesNewPassword() { doThrow(new InvalidPasswordException("foo")).when(passwordValidator).validate("new_secret"); ExpiringCode code1 = new ExpiringCode("secret_code", new Timestamp(System.currentTimeMillis() + 1000 * 60 * 10), "{}", null); - assertThatExceptionOfType(InvalidPasswordException.class).isThrownBy(() -> uaaResetPasswordService.resetPassword(code1, "new_secret")); + assertThatThrownBy(() -> uaaResetPasswordService.resetPassword(code1, "new_secret")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidPasswordException.class)); } @Test @@ -295,7 +296,7 @@ void resetPassword_ForcedChange_NewPasswordSameAsOld() { when(scimUserProvisioning.checkPasswordMatches("user-id", "password", currentZoneId)) .thenThrow(new InvalidPasswordException("Your new password cannot be the same as the old password.", UNPROCESSABLE_ENTITY)); - assertThatExceptionOfType(InvalidPasswordException.class).isThrownBy(() -> uaaResetPasswordService.resetUserPassword(userId, "password")); + assertThatThrownBy(() -> uaaResetPasswordService.resetUserPassword(userId, "password")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidPasswordException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java index b7b8adae10c..d2729ac365a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/CheckTokenEndpointTests.java @@ -15,6 +15,7 @@ import com.google.common.collect.Sets; import org.apache.logging.log4j.util.Strings; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.approval.Approval; import org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus; import org.cloudfoundry.identity.uaa.approval.ApprovalService; @@ -365,8 +366,8 @@ void rejectInvalidVerifier(String signerKey, boolean useOpaque) throws Exception OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); configureDefaultZoneKeys(Map.of("testKey", alternateSignerKey)); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -391,8 +392,8 @@ void rejectUserSaltChange(String signerKey, boolean useOpaque) { "changedsalt", new Date(nowMillis - 2000)); resetAndMockUserDatabase(userId, user); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } @MethodSource("data") @@ -417,8 +418,8 @@ void rejectUserUsernameChange(String signerKey, boolean useOpaque) { "salt", new Date(nowMillis - 2000)); resetAndMockUserDatabase(userId, user); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } @MethodSource("data") @@ -443,8 +444,8 @@ void rejectUserEmailChange(String signerKey, boolean useOpaque) { "salt", new Date(nowMillis - 2000)); resetAndMockUserDatabase(userId, user); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } @MethodSource("data") @@ -469,8 +470,8 @@ void rejectUserPasswordChange(String signerKey, boolean useOpaque) { "salt", new Date(nowMillis - 2000)); resetAndMockUserDatabase(userId, user); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } @MethodSource("data") @@ -479,8 +480,8 @@ void rejectClientSaltChange(String signerKey, boolean useOpaque) { initCheckTokenEndpointTests(signerKey, useOpaque); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); defaultClient.addAdditionalInformation(ClientConstants.TOKEN_SALT, "changedsalt"); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } @MethodSource("data") @@ -489,8 +490,8 @@ void rejectClientPasswordChange(String signerKey, boolean useOpaque) { initCheckTokenEndpointTests(signerKey, useOpaque); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); defaultClient.setClientSecret("changedsecret"); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } private static String missingScopeMessage(String... scopes) { @@ -569,8 +570,8 @@ void revokingScopesFromUser_invalidatesToken(String signerKey, boolean useOpaque OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); user = user.authorities(UaaAuthority.NONE_AUTHORITIES); resetAndMockUserDatabase(userId, user); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -581,8 +582,8 @@ void revokingScopesFromClient_invalidatesToken(String signerKey, boolean useOpaq defaultClient = new UaaClientDetails("client", "scim, cc", "write", "authorization_code, password", "scim.read, scim.write", "http://localhost:8080/uaa"); clientDetailsStore = Map.of("client", defaultClient); clientDetailsService.setClientDetailsStore(IdentityZoneHolder.get().getId(), clientDetailsStore); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -599,8 +600,8 @@ void revokingAuthoritiesFromClients_invalidatesToken(String signerKey, boolean u authentication = new OAuth2Authentication(new AuthorizationRequest("client", Set.of("scim.read")).createOAuth2Request(), null); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -710,7 +711,7 @@ void issuerInResultsInNonDefaultZone(String signerKey, boolean useOpaque) throws void zoneRejectsTokenSignedWithKeyFromOtherZone(String signerKey, boolean useOpaque) { initCheckTokenEndpointTests(signerKey, useOpaque); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> { + assertThatThrownBy(() -> { try { zone.getConfig().getTokenPolicy().setKeys(Map.of("testKey", @@ -746,7 +747,7 @@ void zoneRejectsTokenSignedWithKeyFromOtherZone(String signerKey, boolean useOpa } finally { IdentityZoneHolder.clear(); } - }); + }).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -852,8 +853,8 @@ void defaultZoneRejectsTokenSignedWithOtherZoneKey(String signerKey, boolean use tokenServices.setTokenEndpointBuilder(new TokenEndpointBuilder("http://some.other.issuer")); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); IdentityZoneHolder.clear(); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -902,7 +903,7 @@ void by_default_get_is_allowed(String signerKey, boolean useOpaque) throws Excep void disable_query_string(String signerKey, boolean useOpaque) { initCheckTokenEndpointTests(signerKey, useOpaque); endpoint.setAllowQueryString(false); - assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(this::internal_byDefaultQueryStringIsAllowed); + assertThatThrownBy(this::internal_byDefaultQueryStringIsAllowed).asInstanceOf(InstanceOfAssertFactories.throwable(HttpRequestMethodNotSupportedException.class)); } @MethodSource("data") @@ -910,7 +911,7 @@ void disable_query_string(String signerKey, boolean useOpaque) { void disable_get_method(String signerKey, boolean useOpaque) { initCheckTokenEndpointTests(signerKey, useOpaque); endpoint.setAllowQueryString(false); - assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(this::internal_ByDefaultGetIsAllowed); + assertThatThrownBy(this::internal_ByDefaultGetIsAllowed).asInstanceOf(InstanceOfAssertFactories.throwable(HttpRequestMethodNotSupportedException.class)); } @MethodSource("data") @@ -942,8 +943,8 @@ void revokedToken_ThrowsTokenRevokedException(String signerKey, boolean useOpaqu IdentityZoneHolder.get().getConfig().getTokenPolicy().setJwtRevocable(true); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } @MethodSource("data") @@ -1019,8 +1020,8 @@ void expiredToken(String signerKey, boolean useOpaque) { when(timeService.getCurrentTimeMillis()).thenReturn(1000L); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); when(timeService.getCurrentTimeMillis()).thenReturn(nowMillis + validitySeconds.longValue() * 1000 + 1L); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1044,8 +1045,8 @@ void deniedApprovals(String signerKey, boolean useOpaque) { .setExpiresAt(thirtySecondsAhead) .setStatus(ApprovalStatus.DENIED) .setLastUpdatedAt(oneSecondAgo), IdentityZoneHolder.get().getId()); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1066,8 +1067,8 @@ void expiredApprovals(String signerKey, boolean useOpaque) { .setExpiresAt(new Date(nowMillis)) .setStatus(ApprovalStatus.APPROVED), IdentityZoneHolder.get().getId()); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - endpoint.checkToken(accessToken.getValue(), List.of(), request)); + assertThatThrownBy(() -> + endpoint.checkToken(accessToken.getValue(), List.of(), request)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java index 27b59e01c79..c29c74b4221 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientAccessTokenValidityTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.extensions.PollutionPreventionExtension; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; import org.cloudfoundry.identity.uaa.provider.ClientRegistrationException; @@ -20,7 +21,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -80,7 +81,7 @@ void whenClientPresent_ButUnableToRetrieveTheClient() { when(mockMultitenantClientServices.loadClientByClientId("clientId", currentIdentityZoneId)) .thenThrow(RuntimeException.class); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> clientAccessTokenValidity.getValiditySeconds("clientId")); + assertThatThrownBy(() -> clientAccessTokenValidity.getValiditySeconds("clientId")).asInstanceOf(InstanceOfAssertFactories.throwable(RuntimeException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java index b52ccde9ce4..91afb300bdc 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ClientRefreshTokenValidityTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.extensions.PollutionPreventionExtension; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; import org.cloudfoundry.identity.uaa.provider.ClientRegistrationException; @@ -20,7 +21,7 @@ import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -80,7 +81,7 @@ void whenClientPresent_ButUnableToRetrieveTheClient() { when(mockMultitenantClientServices.loadClientByClientId("clientId", currentIdentityZoneId)) .thenThrow(RuntimeException.class); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> clientRefreshTokenValidity.getValiditySeconds("clientId")); + assertThatThrownBy(() -> clientRefreshTokenValidity.getValiditySeconds("clientId")).asInstanceOf(InstanceOfAssertFactories.throwable(RuntimeException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java index 968279ebb7a..2ba9215a175 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/DeprecatedUaaTokenServicesTests.java @@ -4,6 +4,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.approval.Approval; import org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus; import org.cloudfoundry.identity.uaa.approval.ApprovalService; @@ -412,8 +413,8 @@ void isOpaqueTokenRequired(TestTokenEnhancer enhancer) { @ParameterizedTest(name = "{index}: {0}") void nullRefreshTokenString(TestTokenEnhancer enhancer) { initDeprecatedUaaTokenServicesTests(enhancer); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - tokenServices.refreshAccessToken(null, null)); + assertThatThrownBy(() -> + tokenServices.refreshAccessToken(null, null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1145,9 +1146,9 @@ void createAccessTokenRefreshGrantNoScopesAutoApprovedIncompleteApprovals(TestTo Map refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))); + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1458,8 +1459,8 @@ void createAccessTokenAuthcodeGrantExpandedScopes(TestTokenEnhancer enhancer) { Map refreshAzParameters = new HashMap<>(expandedScopeAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); expandedScopeAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(InvalidScopeException.class).isThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(expandedScopeAuthorizationRequest, "refresh_token"))); + assertThatThrownBy(() -> + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(expandedScopeAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidScopeException.class)); } @MethodSource("data") @@ -1529,9 +1530,9 @@ void userUpdatedAfterRefreshTokenIssued(TestTokenEnhancer enhancer) { Map refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(TokenRevokedException.class).isThrownBy(() -> + assertThatThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))); + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(TokenRevokedException.class)); } @MethodSource("data") @@ -1612,9 +1613,9 @@ void refreshTokenAfterApprovalsRevoked(TestTokenEnhancer enhancer) { Map refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))); + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1648,9 +1649,9 @@ void refreshTokenAfterApprovalsExpired(TestTokenEnhancer enhancer) { Map refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))); + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1684,9 +1685,9 @@ void refreshTokenAfterApprovalsDenied(TestTokenEnhancer enhancer) { Map refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))); + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1714,9 +1715,9 @@ void refreshTokenAfterApprovalsMissing(TestTokenEnhancer enhancer) { Map refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))); + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1736,9 +1737,9 @@ void refreshTokenAfterApprovalsMissing2(TestTokenEnhancer enhancer) { Map refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters()); refreshAzParameters.put(GRANT_TYPE, GRANT_TYPE_REFRESH_TOKEN); refreshAuthorizationRequest.setRequestParameters(refreshAzParameters); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> - tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))); + tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(), tokenSupport.requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") @@ -1832,8 +1833,8 @@ void readAccessTokenForDeletedUserId(TestTokenEnhancer enhancer) { OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(), userAuthentication); OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication); this.tokenSupport.userDatabase.clear(); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - assertThat(tokenServices.readAccessToken(accessToken.getValue())).isEqualTo(accessToken)); + assertThatThrownBy(() -> + assertThat(tokenServices.readAccessToken(accessToken.getValue())).isEqualTo(accessToken)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @MethodSource("data") diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java index 20864a6c06e..acd2915d7d0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/RemoteTokenServicesTests.java @@ -13,6 +13,7 @@ *******************************************************************************/ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Authentication; import org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants; import org.cloudfoundry.identity.uaa.util.JsonUtils; @@ -30,7 +31,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; @@ -113,7 +114,7 @@ void noBodyReceived() { when(restTemplate.exchange(anyString(), (HttpMethod) any(), any(), (Class) any())).thenReturn(responseEntity); when(responseEntity.getBody()).thenReturn(null); services.setRestTemplate(restTemplate); - assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> services.loadAuthentication("FOO")); + assertThatThrownBy(() -> services.loadAuthentication("FOO")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalStateException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java index c11a6662731..ce32022301a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/TokenEndpointBuilderTest.java @@ -1,17 +1,18 @@ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import java.net.MalformedURLException; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class TokenEndpointBuilderTest { @Test void validatesIssuerBaseUrl() { - assertThatExceptionOfType(MalformedURLException.class).isThrownBy(() -> new TokenEndpointBuilder("not-a-url")); + assertThatThrownBy(() -> new TokenEndpointBuilder("not-a-url")).asInstanceOf(InstanceOfAssertFactories.throwable(MalformedURLException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java index 2df9229e3a2..efcbeb99ed1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationEndpointTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails; import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal; @@ -36,7 +37,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_IMPLICIT; import static org.mockito.ArgumentMatchers.any; @@ -212,8 +213,8 @@ void approveWithModifiedScope() { authorizationRequest.setScope(Arrays.asList("read", "write")); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -225,8 +226,8 @@ void approveWithModifiedClientId() { authorizationRequest.setClientId("bar"); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -238,8 +239,8 @@ void approveWithModifiedState() { authorizationRequest.setState("state-5678"); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -251,8 +252,8 @@ void approveWithModifiedRedirectUri() { authorizationRequest.setRedirectUri("http://somewhere.com"); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -264,8 +265,8 @@ void approveWithModifiedResponseTypes() { authorizationRequest.setResponseTypes(Collections.singleton("implicit")); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -278,8 +279,8 @@ void approveWithModifiedApproved() { authorizationRequest.setApproved(true); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -291,8 +292,8 @@ void approveWithModifiedResourceIds() { authorizationRequest.setResourceIds(Collections.singleton("resource-other")); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -304,8 +305,8 @@ void approveWithModifiedAuthorities() { authorizationRequest.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList("authority-other")); Map approvalParameters = new HashMap<>(); approvalParameters.put("user_oauth_approval", "true"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.approveOrDeny(approvalParameters, model, sessionStatus, principal)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -330,24 +331,24 @@ void approveWithModifiedApprovalParameters() { void shortCodeChallengeParameter() { Map parameters = new HashMap<>(); parameters.put(PkceValidationService.CODE_CHALLENGE, "ShortCodeChallenge"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test void longCodeChallengeParameter() { Map parameters = new HashMap<>(); parameters.put(PkceValidationService.CODE_CHALLENGE, "LongCodeChallenge12346574382823193700987654321326352173528351287635126532123452534234254323254325325325432342532532254325432532532"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test void forbiddenCodeChallengeParameter() { Map parameters = new HashMap<>(); parameters.put(PkceValidationService.CODE_CHALLENGE, "#ForbiddenCodeChallenge098765445647544743211234657438282319370#"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -355,8 +356,8 @@ void unsupportedCodeChallengeMethodParameter() { Map parameters = new HashMap<>(); parameters.put(PkceValidationService.CODE_CHALLENGE, UaaTestAccounts.CODE_CHALLENGE); parameters.put(PkceValidationService.CODE_CHALLENGE_METHOD, "unsupportedMethod"); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)); + assertThatThrownBy(() -> + uaaAuthorizationEndpoint.validateAuthorizationRequestPkceParameters(parameters)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java index 28c20efc4c9..8a8e88ba2f6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaAuthorizationRequestManagerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.extensions.PollutionPreventionExtension; @@ -40,7 +41,8 @@ import java.util.Set; import java.util.TreeSet; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.CLIENT_ID; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -106,21 +108,21 @@ void clientIDPAuthorizationInUAAzoneListSucceeds() { void clientIDPAuthorizationInUAAzoneListFails() { when(providerProvisioning.retrieveByOrigin(anyString(), anyString())).thenReturn(MultitenancyFixture.identityProvider("random", "random")); client.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Collections.singletonList("random2")); - assertThatExceptionOfType(UnauthorizedClientException.class).isThrownBy(() -> factory.checkClientIdpAuthorization(client, user)); + assertThatThrownBy(() -> factory.checkClientIdpAuthorization(client, user)).asInstanceOf(InstanceOfAssertFactories.throwable(UnauthorizedClientException.class)); } @Test void clientIDPAuthorizationInUAAzoneNullProvider() { when(providerProvisioning.retrieveByOrigin(anyString(), anyString())).thenReturn(null); client.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Collections.singletonList("random2")); - assertThatExceptionOfType(UnauthorizedClientException.class).isThrownBy(() -> factory.checkClientIdpAuthorization(client, user)); + assertThatThrownBy(() -> factory.checkClientIdpAuthorization(client, user)).asInstanceOf(InstanceOfAssertFactories.throwable(UnauthorizedClientException.class)); } @Test void clientIDPAuthorizationInUAAzoneEmptyResultSetException() { when(providerProvisioning.retrieveByOrigin(anyString(), anyString())).thenThrow(new EmptyResultDataAccessException(1)); client.addAdditionalInformation(ClientConstants.ALLOWED_PROVIDERS, Collections.singletonList("random2")); - assertThatExceptionOfType(UnauthorizedClientException.class).isThrownBy(() -> factory.checkClientIdpAuthorization(client, user)); + assertThatThrownBy(() -> factory.checkClientIdpAuthorization(client, user)).asInstanceOf(InstanceOfAssertFactories.throwable(UnauthorizedClientException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java index 0d7f710b851..ea7d05f607a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenStoreTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails; @@ -49,7 +50,7 @@ import java.util.logging.Logger; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -194,14 +195,14 @@ void retrieveExpiredToken() { String code = store.createAuthorizationCode(clientAuthentication); assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM oauth_code WHERE code = ?", Integer.class, new Object[]{code})).isOne(); doReturn(Instant.now().plus(UaaTokenStore.DEFAULT_EXPIRATION_TIME)).when(timeService).getCurrentInstant(); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> store.consumeAuthorizationCode(code)); + assertThatThrownBy(() -> store.consumeAuthorizationCode(code)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test void retrieveNonExistentToken() { String code = store.createAuthorizationCode(clientAuthentication); assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM oauth_code WHERE code = ?", Integer.class, new Object[]{code})).isOne(); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> store.consumeAuthorizationCode("non-existent")); + assertThatThrownBy(() -> store.consumeAuthorizationCode("non-existent")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -216,7 +217,7 @@ void cleanUpExpiredTokensBasedOnExpiresField() { doReturn(Instant.now().plus(UaaTokenStore.LEGACY_CODE_EXPIRATION_TIME)).when(timeService).getCurrentInstant(); final String finalLastCode = lastCode; - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> store.consumeAuthorizationCode(finalLastCode)); + assertThatThrownBy(() -> store.consumeAuthorizationCode(finalLastCode)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM oauth_code", Integer.class)).isZero(); } @@ -228,10 +229,10 @@ void cleanUpLegacyCodesCodesWithoutExpiresAtAfter3Days() { } assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM oauth_code", Integer.class)).isEqualTo(count); doReturn(Instant.now().plus(Duration.ofDays(2))).when(timeService).getCurrentInstant(); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> store.consumeAuthorizationCode("non-existent")); + assertThatThrownBy(() -> store.consumeAuthorizationCode("non-existent")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM oauth_code", Integer.class)).isEqualTo(count); doReturn(Instant.now().plus(Duration.ofDays(4))).when(timeService).getCurrentInstant(); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> store.consumeAuthorizationCode("non-existent")); + assertThatThrownBy(() -> store.consumeAuthorizationCode("non-existent")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); assertThat(jdbcTemplate.queryForObject("SELECT count(*) FROM oauth_code", Integer.class)).isZero(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java index de9947135dc..8d20909fba5 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/ZoneEndpointsClientDetailsValidatorTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.ClientDetailsValidator.Mode; import org.cloudfoundry.identity.uaa.client.InvalidClientDetailsException; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; @@ -18,7 +19,8 @@ import java.util.Collections; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.ALLOWED_PROVIDERS; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_JWT_BEARER; @@ -55,7 +57,7 @@ void createLimitedClient() { void createClientNoNameIsInvalid() { UaaClientDetails clientDetails = new UaaClientDetails("", null, "openid", GRANT_TYPE_AUTHORIZATION_CODE, "uaa.resource"); clientDetails.setClientSecret("secret"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)); + assertThatThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @ParameterizedTest @@ -90,18 +92,18 @@ void createClientNoSecretForImplicitIsValid() { void reject_invalid_grant_type() { UaaClientDetails clientDetails = new UaaClientDetails("client", null, "openid", "invalid_grant_type", "uaa.resource"); clientDetails.addAdditionalInformation(ALLOWED_PROVIDERS, Collections.singletonList(OriginKeys.UAA)); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)); + assertThatThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void createAdminScopeClientIsInvalid() { ClientDetails clientDetails = new UaaClientDetails("admin-client", null, "uaa.admin", GRANT_TYPE_AUTHORIZATION_CODE, "uaa.resource"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)); + assertThatThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } @Test void createAdminAuthorityClientIsInvalid() { ClientDetails clientDetails = new UaaClientDetails("admin-client", null, "openid", GRANT_TYPE_AUTHORIZATION_CODE, "uaa.admin"); - assertThatExceptionOfType(InvalidClientDetailsException.class).isThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)); + assertThatThrownBy(() -> zoneEndpointsClientDetailsValidator.validate(clientDetails, Mode.CREATE)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientDetailsException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java index a41343c53b9..fd36e19a6b0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/approval/ApprovalsAdminEndpointsTests.java @@ -3,6 +3,7 @@ import tools.jackson.core.type.TypeReference; import com.unboundid.scim.sdk.AttributePath; import com.unboundid.scim.sdk.SCIMFilter; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.approval.Approval; import org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus; @@ -40,7 +41,8 @@ import java.util.Set; import java.util.UUID; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus.APPROVED; import static org.cloudfoundry.identity.uaa.approval.Approval.ApprovalStatus.DENIED; import static org.mockito.Mockito.mock; @@ -341,7 +343,7 @@ void userCannotUpdateApprovalsForAnotherUser() { .setExpiresAt(Approval.timeFromNow(2000)) .setStatus(APPROVED)}; - assertThatExceptionOfType(UaaException.class).isThrownBy(() -> endpoints.updateApprovals(approvals)); + assertThatThrownBy(() -> endpoints.updateApprovals(approvals)).asInstanceOf(InstanceOfAssertFactories.throwable(UaaException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java index 9f1077fb3b9..5b9b31baa40 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/LegacyRedirectResolverTest.java @@ -5,6 +5,7 @@ import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.RedirectMismatchException; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; @@ -23,7 +24,8 @@ import java.util.List; import static org.apache.logging.log4j.Level.WARN; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -247,7 +249,7 @@ void doesNotWarnForPortExpansion() { ClientDetails client = createClient("foo", configuredRedirectUri); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> resolver.resolveRedirect(requestedRedirectUri, client)); + assertThatThrownBy(() -> resolver.resolveRedirect(requestedRedirectUri, client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); assertThat(logEvents).isEmpty(); } @@ -259,7 +261,7 @@ void doesNotWarnWhenThereIsNoMatch() { ClientDetails client = createClient("foo", configuredRedirectUri); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> resolver.resolveRedirect(requestedRedirectUri, client)); + assertThatThrownBy(() -> resolver.resolveRedirect(requestedRedirectUri, client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); assertThat(logEvents).isEmpty(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java index ca9ebfbba48..a12d4f3a6bd 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/beans/RedirectResolverTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.beans; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.RedirectMismatchException; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; @@ -13,7 +14,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.HamcrestCondition.matching; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; import static org.hamcrest.Matchers.is; @@ -395,8 +396,8 @@ private void assertResolveRedirect(String requestedRedirect, Matcher expectedExceptionClassForBothNewAndLegacyResult) { - assertThatExceptionOfType(expectedExceptionClassForBothNewAndLegacyResult).isThrownBy(() -> legacyResolver.resolveRedirect(requestedRedirect, mockClientDetails)); - assertThatExceptionOfType(expectedExceptionClassForBothNewAndLegacyResult).isThrownBy(() -> springResolver.resolveRedirect(requestedRedirect, mockClientDetails)); + assertThatThrownBy(() -> legacyResolver.resolveRedirect(requestedRedirect, mockClientDetails)).asInstanceOf(InstanceOfAssertFactories.throwable(expectedExceptionClassForBothNewAndLegacyResult)); + assertThatThrownBy(() -> springResolver.resolveRedirect(requestedRedirect, mockClientDetails)).asInstanceOf(InstanceOfAssertFactories.throwable(expectedExceptionClassForBothNewAndLegacyResult)); } // For when only the new implementation should throw @@ -405,12 +406,12 @@ private void assertResolveRedirect(String requestedRedirect, Matcher springResolver.resolveRedirect(requestedRedirect, mockClientDetails)); + assertThatThrownBy(() -> springResolver.resolveRedirect(requestedRedirect, mockClientDetails)).asInstanceOf(InstanceOfAssertFactories.throwable(expectedExceptionClassForNewResult)); } // For when only the legacy implementation should throw private void assertResolveRedirect(String requestedRedirect, Class expectedExceptionClassForLegacyResult, Matcher matcherForNewResult) { - assertThatExceptionOfType(expectedExceptionClassForLegacyResult).isThrownBy(() -> legacyResolver.resolveRedirect(requestedRedirect, mockClientDetails)); + assertThatThrownBy(() -> legacyResolver.resolveRedirect(requestedRedirect, mockClientDetails)).asInstanceOf(InstanceOfAssertFactories.throwable(expectedExceptionClassForLegacyResult)); assertThat(springResolver.resolveRedirect(requestedRedirect, mockClientDetails)) .as("test failed for " + springResolver.getClass().getSimpleName()) diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java index 876ab9f5651..4e309f5714e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwk/JsonWebKeySetTests.java @@ -16,6 +16,7 @@ package org.cloudfoundry.identity.uaa.oauth.jwk; import com.nimbusds.jose.jwk.JWKSet; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -23,7 +24,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey.KeyUse.sig; class JsonWebKeySetTests { @@ -202,7 +203,7 @@ void jsonKeySetParsePublicKey() throws Exception { @Test void jsonKeySetParseFailurePEM() { String publicKey = "-----BEGIN PUBLIC KEY-----tokenKey-----END PUBLIC KEY-----"; - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JsonWebKeyHelper.parseConfiguration(publicKey)); + assertThatThrownBy(() -> JsonWebKeyHelper.parseConfiguration(publicKey)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java index 9026cc3f168..60d2eb1b777 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/ChainedSignatureVerifierTests.java @@ -15,6 +15,7 @@ package org.cloudfoundry.identity.uaa.oauth.jwt; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.InvalidSignatureException; import org.cloudfoundry.identity.uaa.oauth.KeyInfo; import org.cloudfoundry.identity.uaa.oauth.KeyInfoBuilder; @@ -36,7 +37,7 @@ import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey.KeyType.MAC; import static org.mockito.Mockito.mock; @@ -89,8 +90,8 @@ void single_key_valid() { @Test void single_key_invalid() { verifier = new ChainedSignatureVerifier(new JsonWebKeySet<>(Collections.singletonList(invalidKey))); - assertThatExceptionOfType(InvalidSignatureException.class).isThrownBy(() -> - JwtHelper.decode(signedValidContent.getEncoded()).verifySignature(verifier)); + assertThatThrownBy(() -> + JwtHelper.decode(signedValidContent.getEncoded()).verifySignature(verifier)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidSignatureException.class)); } @Test @@ -108,8 +109,8 @@ void multi_key_last_valid() { @Test void multi_key_invalid() { verifier = new ChainedSignatureVerifier(new JsonWebKeySet<>(Arrays.asList(invalidKey, invalidKey))); - assertThatExceptionOfType(InvalidSignatureException.class).isThrownBy(() -> - JwtHelper.decode(signedValidContent.getEncoded()).verifySignature(verifier)); + assertThatThrownBy(() -> + JwtHelper.decode(signedValidContent.getEncoded()).verifySignature(verifier)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidSignatureException.class)); } @Test @@ -163,9 +164,9 @@ void no_supported_key_types_causes_error() { q.put("kty", "oct"); q.put("k", "octkeyvalue"); JsonWebKeySet keySet = JsonUtils.convertValue(singletonMap("keys", Arrays.asList(p, q)), JsonWebKeySet.class); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { + assertThatThrownBy(() -> { verifier = new ChainedSignatureVerifier(keySet); - }); + }).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java index 7b62f7dc431..7057f9af8cb 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/CommonSignerTest.java @@ -22,6 +22,7 @@ import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; import com.nimbusds.jwt.SignedJWT; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.KeyInfoBuilder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -32,7 +33,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.util.UaaStringUtils.DEFAULT_UAA_URL; class CommonSignerTest { @@ -85,9 +86,9 @@ void mac_key_with_id() { @Test void null_key_is_rejected() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { + assertThatThrownBy(() -> { new CommonSigner("id", null, "http://localhost/uaa"); - }); + }).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java index 17763affc7f..7a748a2d691 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtClientAuthenticationTest.java @@ -11,7 +11,6 @@ import com.nimbusds.jwt.JWT; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.JWTParser; -import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.ClientJwtConfiguration; import org.cloudfoundry.identity.uaa.oauth.KeyInfo; import org.cloudfoundry.identity.uaa.oauth.KeyInfoBuilder; @@ -478,8 +477,7 @@ void signatureInvalidateClientAssertion() throws Exception { void getClientIdOfInvalidClientAssertionOidcCompliance() { // Then assertThat(JwtClientAuthentication.getClientIdOidcAssertion(INVALID_CLIENT_JWT)).isNull(); - assertThatThrownBy(() -> JwtClientAuthentication.getClientIdOidcAssertion("eyXXX")) - .asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); + assertThatThrownBy(() -> JwtClientAuthentication.getClientIdOidcAssertion("eyXXX")).isInstanceOf(BadCredentialsException.class); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java index cd6db2be1ed..955b75a907c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHeaderHelperTest.java @@ -3,6 +3,7 @@ import tools.jackson.databind.ObjectMapper; import tools.jackson.databind.json.JsonMapper; import tools.jackson.databind.node.ObjectNode; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.test.RandomParametersJunitExtension; import org.cloudfoundry.identity.uaa.test.RandomParametersJunitExtension.RandomValue; import org.junit.jupiter.api.BeforeEach; @@ -17,7 +18,8 @@ import java.util.Base64; import java.util.List; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; @Tag("https://tools.ietf.org/html/rfc7519#section-5") @DisplayName("JOSE Header") @@ -179,7 +181,7 @@ void shouldAllowCritHeader() { @Test void invalidHeader() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> JwtHeaderHelper.create("")); + assertThatThrownBy(() -> JwtHeaderHelper.create("")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java index 877718a020d..9e01aa6707c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperTest.java @@ -1,6 +1,7 @@ package org.cloudfoundry.identity.uaa.oauth.jwt; import com.nimbusds.jose.jwk.JWKParameterNames; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.InvalidSignatureException; import org.cloudfoundry.identity.uaa.oauth.KeyInfo; import org.cloudfoundry.identity.uaa.oauth.KeyInfoBuilder; @@ -17,7 +18,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; import static org.cloudfoundry.identity.uaa.util.UaaStringUtils.DEFAULT_UAA_URL; @@ -90,24 +91,24 @@ void legacyHmacVerify() { Jwt legacyVerify = JwtHelper.decode(legacySignature.getEncoded()); assertThat(legacyVerify).isNotNull(); legacyVerify.verifySignature(cs); - assertThatExceptionOfType(InvalidSignatureException.class).isThrownBy(() -> legacyVerify.verifySignature(keyInfo.getVerifier())); + assertThatThrownBy(() -> legacyVerify.verifySignature(keyInfo.getVerifier())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidSignatureException.class)); key.put("value", "wrong"); - assertThatExceptionOfType(InvalidSignatureException.class).isThrownBy(() -> legacyVerify.verifySignature(new SignatureVerifier(new JsonWebKey(key)))); + assertThatThrownBy(() -> legacyVerify.verifySignature(new SignatureVerifier(new JsonWebKey(key)))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidSignatureException.class)); } @Test void legacyHmacFailed() { - assertThatExceptionOfType(InvalidSignatureException.class).isThrownBy(() -> UaaMacSigner.verify("x", null)); + assertThatThrownBy(() -> UaaMacSigner.verify("x", null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidSignatureException.class)); } @Test void jwtInvalidPayload() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> JwtHelper.encode(null, keyInfo)); + assertThatThrownBy(() -> JwtHelper.encode(null, keyInfo)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void jwtInvalidContent() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> JwtHelper.decode("invalid")); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> JwtHelper.decode("")); + assertThatThrownBy(() -> JwtHelper.decode("invalid")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); + assertThatThrownBy(() -> JwtHelper.decode("")).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java index 320baab49a7..98714ad0682 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/JwtHelperX5tTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.jwt; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.KeyInfo; import org.cloudfoundry.identity.uaa.oauth.KeyInfoBuilder; import org.junit.jupiter.api.BeforeEach; @@ -8,7 +9,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.test.ModelTestUtils.getResourceAsString; public class JwtHelperX5tTest { @@ -53,14 +54,14 @@ void jwtKeysShouldContainX5t() { @Test void jwtHeaderShouldFailWithInvalidCert() { KeyInfo keyInfo1 = KeyInfoBuilder.build("testKid", SIGNING_KEY_1, "http://localhost/uaa", "RS256", "X"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - JwtHelper.encodePlusX5t(Map.of("key", new Object()), keyInfo1, keyInfo1.verifierCertificate().orElse(null))); + assertThatThrownBy(() -> + JwtHelper.encodePlusX5t(Map.of("key", new Object()), keyInfo1, keyInfo1.verifierCertificate().orElse(null))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void getX509CertThumbprintInvalidAlg() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - JwtHelper.getX509CertThumbprint("test".getBytes(), "unknown")); + assertThatThrownBy(() -> + JwtHelper.getX509CertThumbprint("test".getBytes(), "unknown")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java index ab6e96bd4c1..ecbe59d53f1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/jwt/SignatureVerifierTest.java @@ -16,6 +16,7 @@ package org.cloudfoundry.identity.uaa.oauth.jwt; import com.nimbusds.jose.jwk.JWKParameterNames; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -24,13 +25,13 @@ import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class SignatureVerifierTest { @Test void null_is_not_an_acceptable_key() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new SignatureVerifier(null)); + assertThatThrownBy(() -> new SignatureVerifier(null)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @ParameterizedTest @@ -72,6 +73,6 @@ void getRsaPublicKeyFromConfigInvalid() { key.put(JWKParameterNames.KEY_TYPE, "RSA"); key.put("value", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxMi4Z4"); JsonWebKey jsonWebKey = new JsonWebKey(key); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> new SignatureVerifier(jsonWebKey)); + assertThatThrownBy(() -> new SignatureVerifier(jsonWebKey)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java index 3e3c7972bf6..67324a35e55 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/pkce/PkceValidationServiceTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.pkce; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.ClientConstants; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidGrantException; import org.cloudfoundry.identity.uaa.oauth.pkce.verifiers.PlainPkceVerifier; @@ -15,7 +16,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -93,17 +94,17 @@ void noPkceParametersForEvaluation() throws Exception { @Test void codeChallengeMissingForEvaluation() { - assertThatExceptionOfType(PkceValidationException.class).isThrownBy(() -> + assertThatThrownBy(() -> pkceValidationService.checkAndValidate(authorizeRequestParameters, - validPlainCodeChallengeOrCodeVerifierParameter, null)); + validPlainCodeChallengeOrCodeVerifierParameter, null)).asInstanceOf(InstanceOfAssertFactories.throwable(PkceValidationException.class)); } @Test void codeVerifierMissingForEvaluation() { authorizeRequestParameters.put(PkceValidationService.CODE_CHALLENGE, validPlainCodeChallengeOrCodeVerifierParameter); - assertThatExceptionOfType(PkceValidationException.class).isThrownBy(() -> - pkceValidationService.checkAndValidate(authorizeRequestParameters, "", null)); + assertThatThrownBy(() -> + pkceValidationService.checkAndValidate(authorizeRequestParameters, "", null)).asInstanceOf(InstanceOfAssertFactories.throwable(PkceValidationException.class)); } @Test @@ -126,8 +127,8 @@ void plainCodeChallengeMethodForPublicUse() { when(client.getAdditionalInformation()).thenReturn(Map.of(ClientConstants.ALLOW_PUBLIC, "true")); authorizeRequestParameters.put(PkceValidationService.CODE_CHALLENGE, validPlainCodeChallengeOrCodeVerifierParameter); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> pkceValidationService.checkAndValidate(authorizeRequestParameters, - validPlainCodeChallengeOrCodeVerifierParameter, client)); + assertThatThrownBy(() -> pkceValidationService.checkAndValidate(authorizeRequestParameters, + validPlainCodeChallengeOrCodeVerifierParameter, client)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java index 8134b9a9323..5bd77b072b5 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/CompositeTokenGranterTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.OAuth2AccessToken; import org.cloudfoundry.identity.uaa.oauth.provider.code.AuthorizationCodeServices; import org.cloudfoundry.identity.uaa.oauth.provider.implicit.ImplicitTokenGranter; @@ -16,7 +17,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -74,7 +75,7 @@ void grant() { @Test void addTokenGranter() { compositeTokenGranter.addTokenGranter(mock(ImplicitTokenGranter.class)); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - compositeTokenGranter.addTokenGranter(null)); + assertThatThrownBy(() -> + compositeTokenGranter.addTokenGranter(null)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } \ No newline at end of file diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java index efb3c5cce8a..560a9d516cb 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/client/OAuth2ClientContextFilterTests.java @@ -1,5 +1,5 @@ package org.cloudfoundry.identity.uaa.oauth.provider.client; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.client.resource.UserRedirectRequiredException; import org.cloudfoundry.identity.uaa.oauth.provider.error.DefaultThrowableAnalyzer; import org.junit.jupiter.api.Test; @@ -16,7 +16,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -48,8 +48,8 @@ void testdoFilterIOException() throws Exception { doThrow(new IOException("")).when(filterChain).doFilter(any(), any()); filter.setThrowableAnalyzer(new DefaultThrowableAnalyzer()); filter.afterPropertiesSet(); - assertThatExceptionOfType(IOException.class).isThrownBy(() -> - filter.doFilter(request, response, filterChain)); + assertThatThrownBy(() -> + filter.doFilter(request, response, filterChain)).asInstanceOf(InstanceOfAssertFactories.throwable(IOException.class)); } @Test @@ -63,8 +63,8 @@ void testdoFilterException() throws Exception { doThrow(new IllegalArgumentException("")).when(filterChain).doFilter(any(), any()); filter.setThrowableAnalyzer(new DefaultThrowableAnalyzer()); filter.afterPropertiesSet(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - filter.doFilter(request, response, filterChain)); + assertThatThrownBy(() -> + filter.doFilter(request, response, filterChain)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -78,8 +78,8 @@ void testdoFilterServletException() throws Exception { doThrow(new ServletException("")).when(filterChain).doFilter(any(), any()); filter.setThrowableAnalyzer(new DefaultThrowableAnalyzer()); filter.afterPropertiesSet(); - assertThatExceptionOfType(ServletException.class).isThrownBy(() -> - filter.doFilter(request, response, filterChain)); + assertThatThrownBy(() -> + filter.doFilter(request, response, filterChain)).asInstanceOf(InstanceOfAssertFactories.throwable(ServletException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java index 6d68d14ae9c..abc40438c3a 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/DefaultRedirectResolverTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.endpoint; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidGrantException; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidRequestException; @@ -42,8 +43,8 @@ void redirectMatchesRegisteredValue() { @Test void redirectWithNoRegisteredValue() { String requestedRedirect = "https://anywhere.com/myendpoint"; - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> - resolver.resolveRedirect(requestedRedirect, client)); + assertThatThrownBy(() -> + resolver.resolveRedirect(requestedRedirect, client)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } // If only one redirect has been registered, then we should use it @@ -59,8 +60,8 @@ void redirectWithNoRequestedValue() { void redirectWithNoRequestedValueAndMultipleRegistered() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com", "https://nowhere.com")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect(null, client)); + assertThatThrownBy(() -> + resolver.resolveRedirect(null, client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } @Test @@ -68,8 +69,8 @@ void noGrantType() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com", "https://nowhere.com")); client.setRegisteredRedirectUri(redirectUris); client.setAuthorizedGrantTypes(Collections.emptyList()); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - resolver.resolveRedirect(null, client)); + assertThatThrownBy(() -> + resolver.resolveRedirect(null, client)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -77,8 +78,8 @@ void wrongGrantType() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com", "https://nowhere.com")); client.setRegisteredRedirectUri(redirectUris); client.setAuthorizedGrantTypes(Collections.singleton("client_credentials")); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - resolver.resolveRedirect(null, client)); + assertThatThrownBy(() -> + resolver.resolveRedirect(null, client)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -86,8 +87,8 @@ void wrongCustomGrantType() { resolver.setRedirectGrantTypes(Collections.singleton("foo")); Set redirectUris = new HashSet<>(List.of("https://anywhere.com", "https://nowhere.com")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - resolver.resolveRedirect(null, client)); + assertThatThrownBy(() -> + resolver.resolveRedirect(null, client)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -95,8 +96,8 @@ void redirectNotMatching() { Set redirectUris = new HashSet<>(List.of("https://nowhere.com")); String requestedRedirect = "https://anywhere.com/myendpoint"; client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - assertThat(resolver.resolveRedirect(requestedRedirect, client)).isEqualTo(redirectUris.iterator().next())); + assertThatThrownBy(() -> + assertThat(resolver.resolveRedirect(requestedRedirect, client)).isEqualTo(redirectUris.iterator().next())).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } @Test @@ -104,8 +105,8 @@ void redirectNotMatchingWithTraversal() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com/foo")); String requestedRedirect = "https://anywhere.com/foo/../bar"; client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - assertThat(resolver.resolveRedirect(requestedRedirect, client)).isEqualTo(redirectUris.iterator().next())); + assertThatThrownBy(() -> + assertThat(resolver.resolveRedirect(requestedRedirect, client)).isEqualTo(redirectUris.iterator().next())).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-1331 @@ -114,8 +115,8 @@ void redirectNotMatchingWithHexEncodedTraversal() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com/foo")); client.setRegisteredRedirectUri(redirectUris); String requestedRedirect = "https://anywhere.com/foo/%2E%2E"; - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> // hexadecimal encoding of '..' represents '%2E%2E' - resolver.resolveRedirect(requestedRedirect, client)); + assertThatThrownBy(() -> // hexadecimal encoding of '..' represents '%2E%2E' + resolver.resolveRedirect(requestedRedirect, client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-747 @@ -123,8 +124,8 @@ void redirectNotMatchingWithHexEncodedTraversal() { void redirectNotMatchingSubdomain() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com/foo")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://2anywhere.com/foo", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://2anywhere.com/foo", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-747 @@ -142,8 +143,8 @@ void redirectMatchingSubdomain() { void redirectMatchSubdomainsDefaultsFalse() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://2.anywhere.com", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://2.anywhere.com", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-746 @@ -151,8 +152,8 @@ void redirectMatchSubdomainsDefaultsFalse() { void redirectNotMatchingPort() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com:90")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://anywhere.com:91/foo", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://anywhere.com:91/foo", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-746 @@ -169,8 +170,8 @@ void redirectMatchingPort() { void redirectRegisteredPortSetRequestedPortNotSet() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com:90")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://anywhere.com/foo", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://anywhere.com/foo", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-746 @@ -178,8 +179,8 @@ void redirectRegisteredPortSetRequestedPortNotSet() { void redirectRegisteredPortNotSetRequestedPortSet() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://anywhere.com:8443/foo", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://anywhere.com:8443/foo", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-746 @@ -211,8 +212,8 @@ void redirectNotMatchingReturnsGenericErrorMessage() { void redirectRegisteredUserInfoNotMatching() { Set redirectUris = new HashSet<>(List.of("https://userinfo@anywhere.com")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://otheruserinfo@anywhere.com", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://otheruserinfo@anywhere.com", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-1566 @@ -220,8 +221,8 @@ void redirectRegisteredUserInfoNotMatching() { void redirectRegisteredNoUserInfoNotMatching() { Set redirectUris = new HashSet<>(List.of("https://userinfo@anywhere.com")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://anywhere.com", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://anywhere.com", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-1566 @@ -274,8 +275,8 @@ void redirectRegisteredQueryParamsMatchingDifferentOrder() { void redirectRegisteredQueryParamsWithDifferentValues() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com/?p1=v1&p2=v2")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://anywhere.com/?p1=v1&p2=v3", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://anywhere.com/?p1=v1&p2=v3", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-1566 @@ -283,8 +284,8 @@ void redirectRegisteredQueryParamsWithDifferentValues() { void redirectRegisteredQueryParamsNotMatching() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com/?p1=v1")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://anywhere.com/?p2=v2", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://anywhere.com/?p2=v2", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-1566 @@ -292,8 +293,8 @@ void redirectRegisteredQueryParamsNotMatching() { void redirectRegisteredQueryParamsPartiallyMatching() { Set redirectUris = new HashSet<>(List.of("https://anywhere.com/?p1=v1&p2=v2")); client.setRegisteredRedirectUri(redirectUris); - assertThatExceptionOfType(RedirectMismatchException.class).isThrownBy(() -> - resolver.resolveRedirect("https://anywhere.com/?p2=v2&p3=v3", client)); + assertThatThrownBy(() -> + resolver.resolveRedirect("https://anywhere.com/?p2=v2&p3=v3", client)).asInstanceOf(InstanceOfAssertFactories.throwable(RedirectMismatchException.class)); } // gh-1566 diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java index 19cc591ba03..9429cd6e313 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/endpoint/TokenEndpointTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.endpoint; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.UaaOauth2RequestValidator; import org.cloudfoundry.identity.uaa.oauth.common.DefaultOAuth2AccessToken; @@ -38,7 +39,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; @@ -149,8 +150,8 @@ void getAccessTokenWithScope() { @Test void getAccessTokenWithUnsupportedRequestParameters() { - assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(() -> - endpoint.getAccessToken(clientAuthentication, new HashMap<>())); + assertThatThrownBy(() -> + endpoint.getAccessToken(clientAuthentication, new HashMap<>())).asInstanceOf(InstanceOfAssertFactories.throwable(HttpRequestMethodNotSupportedException.class)); } @Test @@ -189,8 +190,8 @@ void implicitGrant() { when(authorizationRequestFactory.createTokenRequest(anyMap, eq(clientDetails))).thenReturn( createFromParameters(parameters)); when(clientDetailsService.loadClientByClientId(CLIENT_ID)).thenReturn(clientDetails); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - endpoint.postAccessToken(clientAuthentication, parameters)); + assertThatThrownBy(() -> + endpoint.postAccessToken(clientAuthentication, parameters)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } // gh-1268 @@ -227,9 +228,9 @@ void refreshTokenGrantTypeWithoutRefreshTokenParameter() { parameters.put("grant_type", "refresh_token"); when(authorizationRequestFactory.createTokenRequest(any(Map.class), eq(clientDetails))).thenReturn( createFromParameters(parameters)); - assertThatExceptionOfType(InvalidRequestException.class).isThrownBy(() -> + assertThatThrownBy(() -> - endpoint.postAccessToken(clientAuthentication, parameters)); + endpoint.postAccessToken(clientAuthentication, parameters)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidRequestException.class)); } @Test @@ -256,14 +257,14 @@ void getAccessTokenWithRefreshToken() { @Test void postAccessException() { - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> - endpoint.postAccessToken(null, Collections.emptyMap())); + assertThatThrownBy(() -> + endpoint.postAccessToken(null, Collections.emptyMap())).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test void getClientIdException() { - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> - endpoint.getClientId(new UsernamePasswordAuthenticationToken("FOO", "bar"))); + assertThatThrownBy(() -> + endpoint.getClientId(new UsernamePasswordAuthenticationToken("FOO", "bar"))).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java index aaa58fb8c99..7f7e898de54 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2ExpressionParserTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.expression; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -8,7 +9,7 @@ import org.springframework.expression.ExpressionParser; import org.springframework.expression.ParserContext; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.verify; /** @@ -35,9 +36,9 @@ void setUp() { @Test void constructorNull() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> { + assertThatThrownBy(() -> { new OAuth2ExpressionParser(null); - }); + }).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java index 0afa642ee97..6b7909e171f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2MethodSecurityExpressionHandlerTests.java @@ -1,6 +1,7 @@ package org.cloudfoundry.identity.uaa.oauth.provider.expression; import org.aopalliance.intercept.MethodInvocation; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.provider.AuthorizationRequest; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Authentication; @@ -19,7 +20,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -60,8 +61,8 @@ void scopesInsufficient() { "oauthClient")); EvaluationContext context = handler.createEvaluationContext(oAuth2Authentication, invocation); Expression expression = handler.getExpressionParser().parseExpression("#oauth2.hasAnyScope('write')"); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> - expression.getValue(context)); + assertThatThrownBy(() -> + expression.getValue(context)).asInstanceOf(InstanceOfAssertFactories.throwable(AccessDeniedException.class)); } @Test @@ -130,8 +131,8 @@ void scopesRegexThrowsException() { EvaluationContext context = handler.createEvaluationContext(oAuth2Authentication, invocation); Expression expression = handler.getExpressionParser().parseExpression( "#oauth2.hasScopeMatching('.*_admin:write')"); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> - assertThat((Boolean) expression.getValue(context)).isFalse()); + assertThatThrownBy(() -> + assertThat((Boolean) expression.getValue(context)).isFalse()).asInstanceOf(InstanceOfAssertFactories.throwable(AccessDeniedException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java index 1e64524a2cb..13bbd51c2ce 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2SecurityExpressionMethodsTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.expression; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.provider.AuthorizationRequest; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Authentication; @@ -14,7 +15,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -68,8 +69,8 @@ void scopesWithException() { OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(clientAuthentication, userAuthentication); OAuth2SecurityExpressionMethods root = new OAuth2SecurityExpressionMethods(oAuth2Authentication); boolean hasAnyScope = root.hasAnyScope("foo"); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> - assertThat(root.throwOnError(hasAnyScope)).isFalse()); + assertThatThrownBy(() -> + assertThat(root.throwOnError(hasAnyScope)).isFalse()).asInstanceOf(InstanceOfAssertFactories.throwable(AccessDeniedException.class)); } @Test @@ -79,8 +80,8 @@ void insufficientScope() { OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(clientAuthentication, userAuthentication); OAuth2SecurityExpressionMethods root = new OAuth2SecurityExpressionMethods(oAuth2Authentication); boolean hasAnyScope = root.hasAnyScope("foo"); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> - root.throwOnError(hasAnyScope)); + assertThatThrownBy(() -> + root.throwOnError(hasAnyScope)).asInstanceOf(InstanceOfAssertFactories.throwable(AccessDeniedException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java index 70aac2b1f61..21eada91a33 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/expression/OAuth2WebSecurityExpressionHandlerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.expression; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.provider.AuthorizationRequest; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Authentication; @@ -17,7 +18,7 @@ import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -84,8 +85,8 @@ void insufficientScope() { OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(clientAuthentication, userAuthentication); OAuth2SecurityExpressionMethods root = new OAuth2SecurityExpressionMethods(oAuth2Authentication); boolean hasAnyScope = root.hasAnyScope("foo"); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> - root.throwOnError(hasAnyScope)); + assertThatThrownBy(() -> + root.throwOnError(hasAnyScope)).asInstanceOf(InstanceOfAssertFactories.throwable(AccessDeniedException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java index b29e16d41e0..39b4d7f1599 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/implicit/ImplicitTokenGranterTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.implicit; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetailsService; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Request; @@ -13,7 +14,7 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -59,8 +60,8 @@ void getOAuth2AuthenticationException() { Authentication authentication = mock(Authentication.class); when(authentication.isAuthenticated()).thenReturn(false); SecurityContextHolder.getContext().setAuthentication(authentication); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> - implicitTokenGranter.getOAuth2Authentication(mock(ClientDetails.class), implicitTokenRequest)); + assertThatThrownBy(() -> + implicitTokenGranter.getOAuth2Authentication(mock(ClientDetails.class), implicitTokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java index b4cd3ccdad1..20e5093ae67 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/password/ResourceOwnerPasswordTokenGranterTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.password; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.OAuth2AccessToken; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidClientException; @@ -31,7 +32,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -115,8 +116,8 @@ public Authentication authenticate(Authentication authentication) throws Authent }; ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(authenticationManager, providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> - granter.grant("password", tokenRequest)); + assertThatThrownBy(() -> + granter.grant("password", tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test @@ -126,8 +127,8 @@ public Authentication authenticate(Authentication authentication) throws Authent throw new BadCredentialsException("test"); } }, providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - granter.grant("password", tokenRequest)); + assertThatThrownBy(() -> + granter.grant("password", tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -135,8 +136,8 @@ void grantTypeNotSupported() { ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(authenticationManager, providerTokenServices, clientDetailsService, requestFactory); client.setAuthorizedGrantTypes(Collections.singleton("client_credentials")); - assertThatExceptionOfType(InvalidClientException.class).isThrownBy(() -> - granter.grant("password", tokenRequest)); + assertThatThrownBy(() -> + granter.grant("password", tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientException.class)); } @Test @@ -146,8 +147,8 @@ public Authentication authenticate(Authentication authentication) throws Authent throw new LockedException("test"); } }, providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - granter.grant("password", tokenRequest)); + assertThatThrownBy(() -> + granter.grant("password", tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -155,8 +156,8 @@ void unauthenticated() { validUser = new UsernamePasswordAuthenticationToken("foo", "bar"); ResourceOwnerPasswordTokenGranter granter = new ResourceOwnerPasswordTokenGranter(authenticationManager, providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - granter.grant("password", tokenRequest)); + assertThatThrownBy(() -> + granter.grant("password", tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -167,7 +168,7 @@ public Authentication authenticate(final Authentication authentication) throws A throw new UsernameNotFoundException("test"); } }, providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - granter.grant("password", tokenRequest)); + assertThatThrownBy(() -> + granter.grant("password", tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java index 723276533de..00b662aabd4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/refresh/RefreshTokenGranterTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.refresh; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.OAuth2AccessToken; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidClientException; @@ -31,7 +32,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -106,16 +107,16 @@ void sunnyDay() { @Test void badCredentials() { RefreshTokenGranter granter = new RefreshTokenGranter(providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - granter.grant("refresh_token", createRefreshTokenRequest(accessToken.getRefreshToken().getValue() + "invalid_token"))); + assertThatThrownBy(() -> + granter.grant("refresh_token", createRefreshTokenRequest(accessToken.getRefreshToken().getValue() + "invalid_token"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test void grantTypeNotSupported() { RefreshTokenGranter granter = new RefreshTokenGranter(providerTokenServices, clientDetailsService, requestFactory); client.setAuthorizedGrantTypes(Collections.singleton("client_credentials")); - assertThatExceptionOfType(InvalidClientException.class).isThrownBy(() -> - granter.grant("refresh_token", validRefreshTokenRequest)); + assertThatThrownBy(() -> + granter.grant("refresh_token", validRefreshTokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientException.class)); } @Test @@ -126,8 +127,8 @@ public Authentication authenticate(Authentication authentication) throws Authent } }); RefreshTokenGranter granter = new RefreshTokenGranter(providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - granter.grant("refresh_token", validRefreshTokenRequest)); + assertThatThrownBy(() -> + granter.grant("refresh_token", validRefreshTokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -138,7 +139,7 @@ public Authentication authenticate(Authentication authentication) throws Authent } }); RefreshTokenGranter granter = new RefreshTokenGranter(providerTokenServices, clientDetailsService, requestFactory); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - granter.grant("refresh_token", validRefreshTokenRequest)); + assertThatThrownBy(() -> + granter.grant("refresh_token", validRefreshTokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java index 33b6c114a33..c56c5791118 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/request/DefaultOAuth2RequestFactoryTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.request; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidClientException; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetails; import org.cloudfoundry.identity.uaa.oauth.provider.ClientDetailsService; @@ -15,7 +16,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -76,8 +77,8 @@ void testCreateTokenRequest() { @Test void createTokenRequestDifferentClientId() { when(clientDetails.getClientId()).thenReturn("my-client-id"); - assertThatExceptionOfType(InvalidClientException.class).isThrownBy(() -> - defaultOAuth2RequestFactory.createTokenRequest(requestParameters, clientDetails)); + assertThatThrownBy(() -> + defaultOAuth2RequestFactory.createTokenRequest(requestParameters, clientDetails)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java index c070f5166da..dd6fdfa3f3e 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/AbstractDefaultTokenServicesTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.DefaultExpiringOAuth2RefreshToken; import org.cloudfoundry.identity.uaa.oauth.common.ExpiringOAuth2RefreshToken; @@ -28,7 +29,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -78,7 +79,7 @@ public void clientInvalidated() { }); OAuth2AccessToken token = tokenServices.createAccessToken(createAuthentication()); deleted.set(true); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> tokenServices.loadAuthentication(token.getValue())); + assertThatThrownBy(() -> tokenServices.loadAuthentication(token.getValue())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -89,7 +90,7 @@ public void refreshedTokenInvalidWithWrongClient() { TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "wrong"), "wrong", null, null); String value = expectedExpiringRefreshToken.getValue(); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> tokenServices.refreshAccessToken(value, tokenRequest)); + assertThatThrownBy(() -> tokenServices.refreshAccessToken(value, tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test @@ -146,8 +147,8 @@ public void tokenRevokedException() { services.readAccessToken(original.getValue()); services.getClientId(original.getValue()); getTokenStore().removeAccessToken(original); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - services.loadAuthentication(original.getValue())); + assertThatThrownBy(() -> + services.loadAuthentication(original.getValue())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java index 986dde1c3d0..89c9277b42c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.DefaultOAuth2AccessToken; import org.cloudfoundry.identity.uaa.oauth.common.DefaultOAuth2RefreshToken; import org.cloudfoundry.identity.uaa.oauth.common.OAuth2AccessToken; @@ -27,7 +28,7 @@ import java.util.Arrays; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -51,8 +52,8 @@ void accidentalNullAuthentication() { new DefaultOAuth2AccessToken("FOO")); Mockito.when(tokenStore.readAuthentication(Mockito.any(OAuth2AccessToken.class))) .thenReturn(null); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - services.loadAuthentication("FOO")); + assertThatThrownBy(() -> + services.loadAuthentication("FOO")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java index c63a58129a1..b5a87a14638 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultTokenServicesWithInMemoryTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.DefaultOAuth2AccessToken; import org.cloudfoundry.identity.uaa.oauth.common.ExpiringOAuth2RefreshToken; @@ -24,7 +25,8 @@ import java.util.Collections; import java.util.Date; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; /** * Moved test class of from spring-security-oauth2 into UAA @@ -78,8 +80,8 @@ public Authentication authenticate(Authentication authentication) throws Authent expectedAuthentication); assertThat(firstAccessToken.getRefreshToken()).isNotNull(); TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "id"), "id", null, null); - assertThatExceptionOfType(AccountExpiredException.class).isThrownBy(() -> - getTokenServices().refreshAccessToken(firstAccessToken.getRefreshToken().getValue(), tokenRequest)); + assertThatThrownBy(() -> + getTokenServices().refreshAccessToken(firstAccessToken.getRefreshToken().getValue(), tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(AccountExpiredException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java index 774daf4fac6..b9e66922eae 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/token/DefaultUserAuthenticationConverterTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; @@ -14,7 +15,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -112,7 +113,7 @@ void shouldConvertUserWithCustomUsernameClaimWhenSet() { @Test void shouldAuthorities() { DefaultUserAuthenticationConverter converter = new DefaultUserAuthenticationConverter(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - converter.getAuthorities(Map.of("authorities", 1))); + assertThatThrownBy(() -> + converter.getAuthorities(Map.of("authorities", 1))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java index bf8c4152685..ca802845573 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/provider/vote/ScopeVoterTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.provider.vote; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Authentication; import org.cloudfoundry.identity.uaa.oauth.provider.OAuth2Request; import org.cloudfoundry.identity.uaa.oauth.provider.RequestTokenFactory; @@ -15,7 +16,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Moved test class of from spring-security-oauth2 into UAA @@ -77,6 +78,6 @@ void exceptionThrownIfWrongScopesPresent() { voter.setDenyAccess("DENY_OAUTH"); assertThat(voter.supports(ScopeVoter.class)).isTrue(); Set scopeWrite = Collections.singleton(new SecurityConfig("SCOPE_WRITE")); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> voter.vote(oAuth2Authentication, null, scopeWrite)); + assertThatThrownBy(() -> voter.vote(oAuth2Authentication, null, scopeWrite)).asInstanceOf(InstanceOfAssertFactories.throwable(AccessDeniedException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java index e9a00712604..7634fb5f6b6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/JdbcRevocableTokenProvisioningTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.AbstractUaaEvent; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; @@ -134,7 +135,7 @@ void retrieveAllReturnsNothing() { @Test void tokenNotFound() { - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @Test @@ -146,7 +147,7 @@ void getFound() { @Test void addDuplicateFails() { jdbcRevocableTokenProvisioning.create(revocableToken, IdentityZoneHolder.get().getId()); - assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.create(revocableToken, IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.create(revocableToken, IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(DuplicateKeyException.class)); } @Test @@ -155,7 +156,7 @@ void getFoundInZone() { jdbcRevocableTokenProvisioning.create(revocableToken, IdentityZoneHolder.get().getId()); assertThat(jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())).isNotNull(); IdentityZoneHolder.clear(); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @Test @@ -171,12 +172,12 @@ void listUserTokens() { @Test void getUserTokens_WithNullClientId() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.getUserTokens("userid", null, IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.getUserTokens("userid", null, IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test void getUserTokens_WithEmptyClientId() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.getUserTokens("userid", "", IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.getUserTokens("userid", "", IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test @@ -229,7 +230,7 @@ void delete() { jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId()); jdbcRevocableTokenProvisioning.delete(revocableToken.getTokenId(), 8, IdentityZoneHolder.get().getId()); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @Test @@ -250,7 +251,7 @@ void deleteRefreshTokenForClientIdUserId() { void ensureExpiredTokenIsDeleted() { jdbcRevocableTokenProvisioning.create(revocableToken, IdentityZoneHolder.get().getId()); jdbcTemplate.update("UPDATE revocable_tokens SET expires_at=? WHERE token_id=?", System.currentTimeMillis() - 10000, revocableToken.getTokenId()); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); assertThat(getCountOfTokens(jdbcTemplate)).isZero(); } @@ -276,7 +277,7 @@ void periodicDeletionOfExpiredTokens() { assertThat(getCountOfTokens(jdbcTemplate)).isEqualTo(2); jdbcTemplate.update("UPDATE revocable_tokens SET expires_at=?", System.currentTimeMillis() - 10000); jdbcRevocableTokenProvisioning.resetLastExpiredCheck(); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); assertThat(getCountOfTokens(jdbcTemplate)).isZero(); } @@ -288,7 +289,7 @@ void deleteByIdentityZone() { jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId()); EntityDeletedEvent zoneDeleted = new EntityDeletedEvent<>(zone, null, IdentityZoneHolder.getCurrentZoneId()); jdbcRevocableTokenProvisioning.onApplicationEvent(zoneDeleted); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())); + assertThatThrownBy(() -> jdbcRevocableTokenProvisioning.retrieve(revocableToken.getTokenId(), IdentityZoneHolder.get().getId())).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java index bca51c0ff1c..0b07a5baef5 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/PkceEnhancedAuthorizationCodeTokenGranterTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.oauth.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidGrantException; import org.cloudfoundry.identity.uaa.oauth.pkce.PkceValidationService; @@ -19,7 +20,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.CLIENT_AUTH_NONE; import static org.cloudfoundry.identity.uaa.oauth.token.TokenConstants.GRANT_TYPE_AUTHORIZATION_CODE; @@ -87,7 +88,7 @@ void setup() { @Test void getOAuth2Authentication() throws Exception { when(pkceValidationService.checkAndValidate(any(), any(), any())).thenReturn(false); - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> granter.getOAuth2Authentication((ClientDetails) requestingClient, tokenRequest)); + assertThatThrownBy(() -> granter.getOAuth2Authentication((ClientDetails) requestingClient, tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java index d8dc8983676..fbd5bfe5064 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/TokenKeyEndpointTests.java @@ -1,6 +1,7 @@ package org.cloudfoundry.identity.uaa.oauth.token; import com.nimbusds.jose.JWSSigner; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.extensions.PollutionPreventionExtension; import org.cloudfoundry.identity.uaa.oauth.KeyInfo; import org.cloudfoundry.identity.uaa.oauth.KeyInfoService; @@ -39,7 +40,7 @@ import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.jwt.JwtHelperX5tTest.CERTIFICATE_1; import static org.cloudfoundry.identity.uaa.oauth.jwt.JwtHelperX5tTest.SIGNING_KEY_1; import static org.cloudfoundry.identity.uaa.util.UaaStringUtils.DEFAULT_UAA_URL; @@ -108,9 +109,9 @@ void sharedSecretIsReturnedFromTokenKeyEndpoint() { void sharedSecretCannotBeAnonymouslyRetrievedFromTokenKeyEndpoint() { configureKeysForDefaultZone(Collections.singletonMap("anotherKeyId", "someKey")); - assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(() -> tokenKeyEndpoint.getKey( + assertThatThrownBy(() -> tokenKeyEndpoint.getKey( new AnonymousAuthenticationToken("anon", "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")) - )); + )).asInstanceOf(InstanceOfAssertFactories.throwable(AccessDeniedException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java index 5f4dff4c901..90101779814 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UaaTokenEndpointTests.java @@ -1,5 +1,5 @@ package org.cloudfoundry.identity.uaa.oauth.token; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.OAuth2AccessToken; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -16,7 +16,8 @@ import java.util.Set; import static java.util.Collections.emptyMap; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; @@ -48,7 +49,7 @@ void allowsGetByDefault() throws Exception { @Test void getIsDisabled() { endpoint = spy(new UaaTokenEndpoint(null, null, null, null, false)); - assertThatExceptionOfType(HttpRequestMethodNotSupportedException.class).isThrownBy(() -> endpoint.doDelegateGet(mock(Principal.class), emptyMap())); + assertThatThrownBy(() -> endpoint.doDelegateGet(mock(Principal.class), emptyMap())).asInstanceOf(InstanceOfAssertFactories.throwable(HttpRequestMethodNotSupportedException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java index c3b6eacb62c..3fc2d1eaf69 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/oauth/token/UserTokenGranterTest.java @@ -14,6 +14,7 @@ package org.cloudfoundry.identity.uaa.oauth.token; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.UaaOauth2Authentication; @@ -39,7 +40,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.CLIENT_ID; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.JTI; @@ -108,49 +109,49 @@ void teardown() { @Test void no_authentication() { SecurityContextHolder.clearContext(); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> - granter.validateRequest(tokenRequest)); + assertThatThrownBy(() -> + granter.validateRequest(tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test void not_authenticated() { when(authentication.isAuthenticated()).thenReturn(false); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> - granter.validateRequest(tokenRequest)); + assertThatThrownBy(() -> + granter.validateRequest(tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test void not_a_user_authentication() { when(authentication.isAuthenticated()).thenReturn(true); when(authentication.getUserAuthentication()).thenReturn(null); - assertThatExceptionOfType(InsufficientAuthenticationException.class).isThrownBy(() -> - granter.validateRequest(tokenRequest)); + assertThatThrownBy(() -> + granter.validateRequest(tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); } @Test void invalid_grant_type() { - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - missing_parameter(GRANT_TYPE)); + assertThatThrownBy(() -> + missing_parameter(GRANT_TYPE)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test void requesting_client_id_missing() { - assertThatExceptionOfType(InvalidGrantException.class).isThrownBy(() -> - missing_parameter(USER_TOKEN_REQUESTING_CLIENT_ID)); + assertThatThrownBy(() -> + missing_parameter(USER_TOKEN_REQUESTING_CLIENT_ID)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidGrantException.class)); } @Test void wrong_requesting_grant_type() { requestingClient.setAuthorizedGrantTypes(Collections.singletonList("password")); - assertThatExceptionOfType(InvalidClientException.class).isThrownBy(() -> - missing_parameter("non existent")); + assertThatThrownBy(() -> + missing_parameter("non existent")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientException.class)); } @Test void wrong_receiving_grant_type() { receivingClient.setAuthorizedGrantTypes(Collections.singletonList("password")); - assertThatExceptionOfType(InvalidClientException.class).isThrownBy(() -> - missing_parameter("non existent")); + assertThatThrownBy(() -> + missing_parameter("non existent")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java index f2abbb437bc..c98fdd76608 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/openid/UserInfoEndpointTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.openid; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.account.UserInfoEndpoint; import org.cloudfoundry.identity.uaa.account.UserInfoResponse; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; @@ -28,7 +29,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.ROLES; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.USER_ATTRIBUTES; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.USER_ID; @@ -179,10 +180,10 @@ void sunnyDay_WithCustomAttributes() { void missingUser() { UaaAuthentication authentication = UaaAuthenticationTestFactory.getAuthentication("nonexist-id", "Dale", "olds@vmware.com"); - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> endpoint.loginInfo( + assertThatThrownBy(() -> endpoint.loginInfo( new OAuth2Authentication(createOauthRequest( Collections.singletonList("openid")), - authentication))); + authentication))).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } private static OAuth2Request createOauthRequest(final List scopes) { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java index a93ba6d4533..ef1f022ee4f 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/passcode/PasscodeInformationTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.passcode; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.authentication.UaaAuthenticationDetails; import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal; @@ -16,7 +17,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -78,8 +79,8 @@ void buildPasscodeInformationFromUaaAuthentication() { @Test void passcodeInformationThrowsExceptionOnUnknownPrincipal() { UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("unknown principal type", ""); - assertThatExceptionOfType(PasscodeEndpoint.UnknownPrincipalException.class).isThrownBy(() -> - new PasscodeInformation(token, authorizationParameters)); + assertThatThrownBy(() -> + new PasscodeInformation(token, authorizationParameters)).asInstanceOf(InstanceOfAssertFactories.throwable(PasscodeEndpoint.UnknownPrincipalException.class)); } @Test @@ -87,7 +88,7 @@ void passcodeInformationThrowExceptionOnNonUaaPrincipal() { Authentication authentication = mock(Authentication.class); when(authentication.getPrincipal()).thenReturn(mock(Principal.class)); - assertThatExceptionOfType(PasscodeEndpoint.UnknownPrincipalException.class).isThrownBy(() -> - new PasscodeInformation(authentication, authorizationParameters)); + assertThatThrownBy(() -> + new PasscodeInformation(authentication, authorizationParameters)).asInstanceOf(InstanceOfAssertFactories.throwable(PasscodeEndpoint.UnknownPrincipalException.class)); } } \ No newline at end of file diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandlerEnsureConsistencyTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandlerEnsureConsistencyTest.java index 9a0f6691a4c..dd392d4536c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandlerEnsureConsistencyTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderAliasHandlerEnsureConsistencyTest.java @@ -157,8 +157,7 @@ protected IdentityProvider shallowCloneEntity(final IdentityProvider idp) cloneIdp.setAliasId(idp.getAliasId()); cloneIdp.setAliasZid(idp.getAliasZid()); cloneIdp.setActive(idp.isActive()); - assertThat(cloneIdp).isEqualTo(idp); - return cloneIdp; + return assertThat(cloneIdp).isEqualTo(idp).actual(); } @Override diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java index 4c2acbb67fc..6f9cd955bc8 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/IdentityProviderEndpointsTest.java @@ -875,7 +875,7 @@ void create_oauth_provider_set_auth_method_none() { IdentityProvider created = response.getBody(); assertThat(created).isNotNull(); assertThat(created.getType()).isEqualTo(type); - assertThat(created.getConfig()).isNotNull() + assertThat(created.getConfig()) .isInstanceOf(AbstractExternalOAuthIdentityProviderDefinition.class); assertThat(((AbstractExternalOAuthIdentityProviderDefinition) created.getConfig()).getRelyingPartySecret()).isNull(); assertThat(((AbstractExternalOAuthIdentityProviderDefinition) created.getConfig()).getAuthMethod()).isEqualTo(ClientAuthentication.CLIENT_SECRET_BASIC); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioningTests.java index ce7bddaa135..dea3faa092b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/JdbcIdentityProviderProvisioningTests.java @@ -1,6 +1,7 @@ package org.cloudfoundry.identity.uaa.provider; import org.apache.commons.collections4.SetUtils; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.oauth.common.util.RandomValueStringGenerator; @@ -28,7 +29,7 @@ import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.KEYSTONE; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LOGIN_SERVER; @@ -296,14 +297,14 @@ void createIdentityProviderInOtherZone() { void createIdentityProviderWithNonUniqueOriginKeyInDefaultZone() { IdentityProvider idp = MultitenancyFixture.identityProvider(origin, uaaZoneId); jdbcIdentityProviderProvisioning.create(idp, uaaZoneId); - assertThatExceptionOfType(IdpAlreadyExistsException.class).isThrownBy(() -> jdbcIdentityProviderProvisioning.create(idp, uaaZoneId)); + assertThatThrownBy(() -> jdbcIdentityProviderProvisioning.create(idp, uaaZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IdpAlreadyExistsException.class)); } @Test void createIdentityProviderWithNonUniqueOriginKeyInOtherZone() { IdentityProvider idp = MultitenancyFixture.identityProvider(origin, otherZoneId1); jdbcIdentityProviderProvisioning.create(idp, otherZoneId1); - assertThatExceptionOfType(IdpAlreadyExistsException.class).isThrownBy(() -> jdbcIdentityProviderProvisioning.create(idp, otherZoneId1)); + assertThatThrownBy(() -> jdbcIdentityProviderProvisioning.create(idp, otherZoneId1)).asInstanceOf(InstanceOfAssertFactories.throwable(IdpAlreadyExistsException.class)); } @Test @@ -405,7 +406,7 @@ void retrieveIdentityProviderByOriginInDifferentZone() { IdentityProvider idp = MultitenancyFixture.identityProvider(origin, otherZoneId1); idp.setId(idpId); IdentityProvider idp1 = jdbcIdentityProviderProvisioning.create(idp, otherZoneId1); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcIdentityProviderProvisioning.retrieveByOrigin(idp1.getOriginKey(), otherZoneId2)); + assertThatThrownBy(() -> jdbcIdentityProviderProvisioning.retrieveByOrigin(idp1.getOriginKey(), otherZoneId2)).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @ParameterizedTest diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java index ac22d7839df..9bad68d29d9 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/LdapIdentityProviderDefinitionTest.java @@ -13,6 +13,7 @@ *******************************************************************************/ package org.cloudfoundry.identity.uaa.provider.ldap; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition; import org.cloudfoundry.identity.uaa.util.JsonUtils; import org.cloudfoundry.identity.uaa.util.LdapUtils; @@ -31,7 +32,8 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.constants.OriginKeys.LDAP; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_PROPERTY_TYPES; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_SSL_TLS; @@ -470,15 +472,15 @@ void set_valid_files() { @Test void set_unknown_profile_file_throws_error() { ldapIdentityProviderDefinition = new LdapIdentityProviderDefinition(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - ldapIdentityProviderDefinition.setLdapProfileFile("some.other.file")); + assertThatThrownBy(() -> + ldapIdentityProviderDefinition.setLdapProfileFile("some.other.file")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void set_unknown_group_file_throws_error() { ldapIdentityProviderDefinition = new LdapIdentityProviderDefinition(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - ldapIdentityProviderDefinition.setLdapGroupFile("some.other.file")); + assertThatThrownBy(() -> + ldapIdentityProviderDefinition.setLdapGroupFile("some.other.file")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -501,9 +503,9 @@ void deserialize_unknown_profile_file_throws_error() { mailSubstituteOverridesLdap: true ssl: skipverification: true"""; - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> + assertThatThrownBy(() -> - LdapUtils.fromConfig(getLdapConfig(config))); + LdapUtils.fromConfig(getLdapConfig(config))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -534,9 +536,9 @@ void deserialize_unknown_group_file_throws_error() { autoAdd: false ssl: skipverification: true"""; - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> + assertThatThrownBy(() -> - LdapUtils.fromConfig(getLdapConfig(config))); + LdapUtils.fromConfig(getLdapConfig(config))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -548,8 +550,8 @@ void set_correct_password_compare() { @Test void set_wrong_password_compare_complains() { ldapIdentityProviderDefinition = new LdapIdentityProviderDefinition(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - ldapIdentityProviderDefinition.setPasswordEncoder("some.other.encoder")); + assertThatThrownBy(() -> + ldapIdentityProviderDefinition.setPasswordEncoder("some.other.encoder")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -571,9 +573,9 @@ void deserialize_unknown_comparator_throws_error() { mailSubstitute: 'generated-{0}@company.example.com' mailSubstituteOverridesLdap: true """; - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> + assertThatThrownBy(() -> - LdapUtils.fromConfig(getLdapConfig(config))); + LdapUtils.fromConfig(getLdapConfig(config))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java index ac0cab56f13..91969a90808 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/ldap/ProcessLdapPropertiesTest.java @@ -15,6 +15,7 @@ package org.cloudfoundry.identity.uaa.provider.ldap; import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.provider.ldap.extension.DefaultTlsDirContextAuthenticationStrategy; import org.cloudfoundry.identity.uaa.provider.ldap.extension.ExternalTlsDirContextAuthenticationStrategy; import org.junit.jupiter.api.Test; @@ -28,7 +29,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_TLS_EXTERNAL; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_TLS_NONE; import static org.cloudfoundry.identity.uaa.provider.LdapIdentityProviderDefinition.LDAP_TLS_SIMPLE; @@ -78,7 +79,7 @@ void authenticationStrategy() throws Exception { @Test void invalid_authenticationStrategy() { ProcessLdapProperties process = new ProcessLdapProperties("ldap://localhost:389", false, "asdadasda"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(process::getAuthenticationStrategy); + assertThatThrownBy(process::getAuthenticationStrategy).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java index 9ec6fb59ec6..9a21438d1bc 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationFilterTest.java @@ -1,5 +1,5 @@ package org.cloudfoundry.identity.uaa.provider.oauth; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.extensions.PollutionPreventionExtension; import org.cloudfoundry.identity.uaa.login.AccountSavingAuthenticationSuccessHandler; import org.cloudfoundry.identity.uaa.util.SessionUtils; @@ -19,7 +19,7 @@ import jakarta.servlet.http.HttpSession; import java.util.function.Consumer; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -116,8 +116,8 @@ void itThrowsIfNoSession() throws Exception { }); HttpServletResponse mockResponse = mock(HttpServletResponse.class); - assertThatExceptionOfType(HttpSessionRequiredException.class).isThrownBy(() -> - externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)); + assertThatThrownBy(() -> + externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)).asInstanceOf(InstanceOfAssertFactories.throwable(HttpSessionRequiredException.class)); verify(mockFilterChain, never()).doFilter(mockRequest, mockResponse); } @@ -129,8 +129,8 @@ void itThrowsIfNoStateInSession() throws Exception { }); HttpServletResponse mockResponse = mock(HttpServletResponse.class); - assertThatExceptionOfType(CsrfException.class).isThrownBy(() -> - externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)); + assertThatThrownBy(() -> + externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)).asInstanceOf(InstanceOfAssertFactories.throwable(CsrfException.class)); verify(mockFilterChain, never()).doFilter(mockRequest, mockResponse); } @@ -142,8 +142,8 @@ void itThrowsIfNoStateInRequest() throws Exception { }); HttpServletResponse mockResponse = mock(HttpServletResponse.class); - assertThatExceptionOfType(CsrfException.class).isThrownBy(() -> - externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)); + assertThatThrownBy(() -> + externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)).asInstanceOf(InstanceOfAssertFactories.throwable(CsrfException.class)); verify(mockFilterChain, never()).doFilter(mockRequest, mockResponse); } @@ -156,8 +156,8 @@ void itThrowsIfStateIsMismatched() throws Exception { }); HttpServletResponse mockResponse = mock(HttpServletResponse.class); - assertThatExceptionOfType(CsrfException.class).isThrownBy(() -> - externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)); + assertThatThrownBy(() -> + externalOAuthAuthenticationFilter.doFilter(mockRequest, mockResponse, mockFilterChain)).asInstanceOf(InstanceOfAssertFactories.throwable(CsrfException.class)); verify(mockFilterChain, never()).doFilter(mockRequest, mockResponse); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java index 546a9b25a4c..52d01aa2954 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthAuthenticationManagerIT.java @@ -5,7 +5,6 @@ import com.nimbusds.jose.JWSSigner; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.RandomStringUtils; -import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.authentication.AccountNotPreCreatedException; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; import org.cloudfoundry.identity.uaa.authentication.UaaPrincipal; @@ -376,8 +375,7 @@ void when_unable_to_find_an_idp_that_matches_the_id_token_issuer() { claims.put("iss", issuerURL); CompositeToken token = getCompositeAccessToken(); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.resolveOriginProvider(token.getIdTokenValue())) - .asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.resolveOriginProvider(token.getIdTokenValue())).isInstanceOf(InsufficientAuthenticationException.class); } @Test @@ -423,8 +421,7 @@ void when_exchanging_an_id_token_issuedby_the_uaa_idp_but_not_uaa_origin(String xCodeToken.setIdToken(idToken); xCodeToken.setOrigin(null); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.getExternalAuthenticationDetails(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(InsufficientAuthenticationException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.getExternalAuthenticationDetails(xCodeToken)).isInstanceOf(InsufficientAuthenticationException.class); } @Test @@ -802,8 +799,7 @@ void doesNotCreateShadowUserAndFailsAuthentication_IfAddShadowUserOnLoginIsFalse config.setAddShadowUserOnLogin(false); mockToken(); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(AccountNotPreCreatedException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(AccountNotPreCreatedException.class); } @Test @@ -812,16 +808,14 @@ void rejectTokenWithInvalidSignature() { config.setTokenKey("WRONG_KEY"); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(InvalidTokenException.class); } @Test void rejectTokenWithInvalidSignatureAccordingToTokenKeyEndpoint() throws Exception { configureTokenKeyResponse("http://localhost/token_key", INVALID_RSA_SIGNING_KEY, "wrongKey"); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(InvalidTokenException.class); } @Test @@ -829,8 +823,7 @@ void rejectTokenWithInvalidIssuer() { claims.put("iss", "http://wrong.issuer/"); mockToken(); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(InvalidTokenException.class); } @Test @@ -838,8 +831,7 @@ void rejectExpiredToken() { claims.put("exp", Instant.now().getEpochSecond() - 1); mockToken(); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(InvalidTokenException.class); } @Test @@ -847,8 +839,7 @@ void rejectWrongAudience() { claims.put("aud", Arrays.asList("another_client", "a_complete_stranger")); mockToken(); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(InvalidTokenException.class); } @Test @@ -1065,8 +1056,7 @@ void getUserIssuerOverrideUsedNoMatch() { assertThatThrownBy(() -> externalOAuthAuthenticationManager.getUser( xCodeToken, externalOAuthAuthenticationManager.getExternalAuthenticationDetails(xCodeToken) - )) - .asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); + )).isInstanceOf(InvalidTokenException.class); } @Test @@ -1119,8 +1109,7 @@ void tokenCannotBeFetchedFromCodeBecauseOfServerError() { when(provisioning.retrieveByOrigin(eq(ORIGIN), anyString())).thenReturn(identityProvider); mockUaaServer.expect(requestTo("http://localhost/oauth/token")).andRespond(withServerError()); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(HttpServerErrorException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(HttpServerErrorException.class); } @Test @@ -1130,8 +1119,7 @@ void tokenCannotBeFetchedFromInvalidCode() { when(provisioning.retrieveByOrigin(eq(ORIGIN), anyString())).thenReturn(identityProvider); mockUaaServer.expect(requestTo("http://localhost/oauth/token")).andRespond(withBadRequest()); - assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)) - .asInstanceOf(InstanceOfAssertFactories.throwable(HttpClientErrorException.class)); + assertThatThrownBy(() -> externalOAuthAuthenticationManager.authenticate(xCodeToken)).isInstanceOf(HttpClientErrorException.class); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java index 7c430381a90..ca6a7bd3f03 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/ExternalOAuthIdentityProviderConfigValidatorTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.provider.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.constants.ClientAuthentication; import org.cloudfoundry.identity.uaa.provider.AbstractExternalOAuthIdentityProviderDefinition; import org.cloudfoundry.identity.uaa.provider.BaseIdentityProviderValidator; @@ -12,7 +13,7 @@ import java.util.Collections; import java.util.Map; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class ExternalOAuthIdentityProviderConfigValidatorTest { private AbstractExternalOAuthIdentityProviderDefinition definition; @@ -47,24 +48,24 @@ void discovery_url_renders_other_urls_nullable() throws Exception { void configWithNullAuthUrl_ThrowsException() { definition.setAuthUrl(null); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void configWithNullTokenUrl_ThrowsException() { definition.setTokenUrl(null); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void configWithNullRelyingPartyId_ThrowsException() { definition.setRelyingPartyId(null); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -72,8 +73,8 @@ void configWithNullRelyingPartySecret_ThrowsException() { definition.setRelyingPartySecret(null); definition.setAuthMethod(ClientAuthentication.CLIENT_SECRET_BASIC); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -81,24 +82,24 @@ void configWithJwtClientConfiguratButAuthMethodSecret_ThrowsException() { definition.setRelyingPartySecret("secret"); ((OIDCIdentityProviderDefinition) definition).setJwtClientAuthentication(new Object()); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void configWithPrivateKeyJwtButNoJwtConfiguration_ThrowsException() { definition.setAuthMethod(ClientAuthentication.PRIVATE_KEY_JWT); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void configWithInvalidAuthMethod_ThrowsException() { definition.setAuthMethod("no-sure-about-this"); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -106,8 +107,8 @@ void configWithShowLinkTextTrue_mustHaveLinkText() { definition.setShowLinkText(true); definition.setLinkText(null); validator = new ExternalOAuthIdentityProviderConfigValidator(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -128,16 +129,16 @@ void no_client_secret_needed_for_implicit() { @Test void configCannotBeNull() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate((AbstractExternalOAuthIdentityProviderDefinition) null)); + assertThatThrownBy(() -> + validator.validate((AbstractExternalOAuthIdentityProviderDefinition) null)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void tokenKeyUrl_orTokenKeyMustBeSpecified() { definition.setTokenKey(null); definition.setTokenKeyUrl(null); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -158,7 +159,7 @@ void additionalParametersAdd() { void additionalParametersError() { OIDCIdentityProviderDefinition oidcIdentityProviderDefinition = (OIDCIdentityProviderDefinition) definition; oidcIdentityProviderDefinition.setAdditionalAuthzParameters(Map.of("token_format", "jwt", "code", "1234")); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - validator.validate(definition)); + assertThatThrownBy(() -> + validator.validate(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java index f3302f1f2a4..9b154059ed6 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OauthIdentityProviderDefinitionFactoryBeanTest.java @@ -15,6 +15,7 @@ package org.cloudfoundry.identity.uaa.provider.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.constants.ClientAuthentication; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.provider.IdentityProvider; @@ -28,7 +29,7 @@ import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.GROUP_ATTRIBUTE_NAME; import static org.cloudfoundry.identity.uaa.provider.ExternalIdentityProviderDefinition.STORE_CUSTOM_ATTRIBUTES_NAME; import static org.cloudfoundry.identity.uaa.util.UaaMapUtils.entry; @@ -280,7 +281,7 @@ void authMethodNotSet() { @Test void authMethodSetInvalidValue() { idpDefinitionMap.put("authMethod", "empty"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> factoryBean.setCommonProperties(idpDefinitionMap, providerDefinition)); + assertThatThrownBy(() -> factoryBean.setCommonProperties(idpDefinitionMap, providerDefinition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java index f36adfc7e3e..c53d182aa78 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/oauth/OidcMetadataFetcherTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.provider.oauth; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.cache.UrlContentCache; import org.cloudfoundry.identity.uaa.client.ClientJwtConfiguration; import org.cloudfoundry.identity.uaa.oauth.jwk.JsonWebKey; @@ -21,7 +22,7 @@ import java.net.URI; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.anyString; import static org.mockito.Mockito.eq; @@ -168,7 +169,7 @@ void shouldPerformTokenKeyUrlNoCacheUsedError() throws Exception { .thenReturn(responseEntity); when(responseEntity.getStatusCode()).thenReturn(HttpStatus.FORBIDDEN); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> metadataDiscoverer.fetchWebKeySet(definition)); + assertThatThrownBy(() -> metadataDiscoverer.fetchWebKeySet(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); verify(urlContentCache, times(0)) .getUrlContent( @@ -225,7 +226,7 @@ void failWithEmptyContent() throws Exception { when(urlContentCache.getUrlContent(anyString(), any(RestTemplate.class), any(HttpMethod.class), any(HttpEntity.class))) .thenReturn("".getBytes()); - assertThatExceptionOfType(OidcMetadataFetchingException.class).isThrownBy(() -> metadataDiscoverer.fetchWebKeySet(definition)); + assertThatThrownBy(() -> metadataDiscoverer.fetchWebKeySet(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(OidcMetadataFetchingException.class)); } @Test @@ -234,7 +235,7 @@ void failWithInvalidContent() throws Exception { when(urlContentCache.getUrlContent(anyString(), any(RestTemplate.class), any(HttpMethod.class), any(HttpEntity.class))) .thenReturn("{x}".getBytes()); - assertThatExceptionOfType(OidcMetadataFetchingException.class).isThrownBy(() -> metadataDiscoverer.fetchWebKeySet(definition)); + assertThatThrownBy(() -> metadataDiscoverer.fetchWebKeySet(definition)).asInstanceOf(InstanceOfAssertFactories.throwable(OidcMetadataFetchingException.class)); } } @@ -271,7 +272,7 @@ void getConfigFromJwks() throws Exception { @Test void failWithInvalidConfig() throws Exception { - assertThatExceptionOfType(OidcMetadataFetchingException.class).isThrownBy(() -> metadataDiscoverer.fetchWebKeySet(new ClientJwtConfiguration(null, null))); + assertThatThrownBy(() -> metadataDiscoverer.fetchWebKeySet(new ClientJwtConfiguration(null, null))).asInstanceOf(InstanceOfAssertFactories.throwable(OidcMetadataFetchingException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java index b420ce10e75..efbfaf2d0ed 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/saml/UaaRelyingPartyRegistrationResolverTests.java @@ -15,7 +15,6 @@ */ package org.cloudfoundry.identity.uaa.provider.saml; -import org.assertj.core.api.InstanceOfAssertFactories; import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider; import org.cloudfoundry.identity.uaa.zone.IdentityZone; import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder; @@ -99,8 +98,7 @@ void resolveWhenRequestIsWithInvalidSamlResponse() { request.setRequestURI("/some/path/cloudfoundry-saml-login"); request.setMethod("POST"); request.setParameter("SAMLResponse", "PGJhc2U2ND4="); - assertThatThrownBy(() -> resolver.resolve(request, null)) - .asInstanceOf(InstanceOfAssertFactories.throwable(Saml2AuthenticationException.class)); + assertThatThrownBy(() -> resolver.resolve(request, null)).isInstanceOf(Saml2AuthenticationException.class); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java index 1549dce9201..3e493471b62 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/provider/uaa/UaaIdentityProviderConfigValidatorTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.provider.uaa; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.provider.AbstractIdentityProviderDefinition; import org.cloudfoundry.identity.uaa.provider.LockoutPolicy; import org.cloudfoundry.identity.uaa.provider.PasswordPolicy; @@ -7,7 +8,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class UaaIdentityProviderConfigValidatorTest { @@ -42,15 +43,15 @@ void nullPasswordPolicy_isAllowed() { @Test void passwordPolicyIsNotNullAndIncomplete() { uaaIdentityProviderDef.setPasswordPolicy(new PasswordPolicy(8, 8, -1, 1, 8, 1, 3)); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - configValidator.validate(uaaIdentityProviderDef)); + assertThatThrownBy(() -> + configValidator.validate(uaaIdentityProviderDef)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void lockoutPolicyIsNotNullAndIncomplete() { uaaIdentityProviderDef.setLockoutPolicy(new LockoutPolicy(-1, 1, 1)); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> - configValidator.validate(uaaIdentityProviderDef)); + assertThatThrownBy(() -> + configValidator.validate(uaaIdentityProviderDef)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java index d1dfeaf8c9a..6417bc5f900 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/RateLimiterImplTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.ratelimiting; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.ratelimiting.core.Limiter; import org.cloudfoundry.identity.uaa.ratelimiting.core.LimiterManager; import org.cloudfoundry.identity.uaa.ratelimiting.core.RateLimiterInternalException; @@ -7,7 +8,7 @@ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; class RateLimiterImplTest { @@ -38,7 +39,7 @@ public Limiter getLimiter(RequestInfo info) { @Test void internalExceptionTest() { - assertThatExceptionOfType(RateLimiterInternalException.class).isThrownBy(() -> check(null)); // Force Error + assertThatThrownBy(() -> check(null)).asInstanceOf(InstanceOfAssertFactories.throwable(RateLimiterInternalException.class)); // Force Error } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java index 762a8bb546f..a2dac064ef4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/IntUtilsTest.java @@ -1,9 +1,10 @@ package org.cloudfoundry.identity.uaa.ratelimiting.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class IntUtilsTest { @@ -16,7 +17,7 @@ void parsing() { assertThat(IntUtils.parse(null, -2)).isEqualTo(-2); assertThat(IntUtils.parseNoException(null, -2)).isEqualTo(-2); - assertThatExceptionOfType(NumberFormatException.class).isThrownBy(() -> IntUtils.parse("!Number", -1)); + assertThatThrownBy(() -> IntUtils.parse("!Number", -1)).asInstanceOf(InstanceOfAssertFactories.throwable(NumberFormatException.class)); assertThat(IntUtils.parseNoException("!Number", -1)).isEqualTo(-1); } } \ No newline at end of file diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java index 5eadb91a324..6c904644ff1 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/ratelimiting/util/SourcedFileTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.ratelimiting.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; @@ -7,7 +8,7 @@ import java.nio.charset.StandardCharsets; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; class SourcedFileTest { @@ -51,7 +52,7 @@ void loadEnv() { @Test void loadStreamException() { InputStream in = mock(InputStream.class); - assertThatExceptionOfType(IllegalStateException.class).isThrownBy(() -> SourcedFile.loadFile(in, "")); + assertThatThrownBy(() -> SourcedFile.loadFile(in, "")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalStateException.class)); } private void check(String fileContents, String source) { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java index f038fb14015..b1c3699d8a3 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/resources/jdbc/JdbcPagingListTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.resources.jdbc; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.extensions.profiles.DisabledIfProfile; import org.cloudfoundry.identity.uaa.extensions.profiles.EnabledIfProfile; @@ -20,7 +21,8 @@ import java.util.Map; import java.util.Set; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; @WithDatabaseContext class JdbcPagingListTests { @@ -187,7 +189,7 @@ void iterationOverSubListWithSameSize() { void subListExtendsBeyondSize() { list = new JdbcPagingList<>(jdbcTemplate, limitSqlAdapter, "SELECT * from foo", new ColumnMapRowMapper(), 3); - assertThatExceptionOfType(IndexOutOfBoundsException.class).isThrownBy(() -> list.subList(1, 40)); + assertThatThrownBy(() -> list.subList(1, 40)).asInstanceOf(InstanceOfAssertFactories.throwable(IndexOutOfBoundsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java index 0d15b4ae97b..b0010b2f9fe 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/bootstrap/ScimUserBootstrapTests.java @@ -1,6 +1,7 @@ package org.cloudfoundry.identity.uaa.scim.bootstrap; import org.apache.commons.lang3.tuple.Triple; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.authentication.manager.ExternalGroupAuthorizationEvent; @@ -256,7 +257,7 @@ void cannotAddUserWithNoPassword() { UaaUser joe = new UaaUser("joe", "", "joe@test.org", "Joe", "User", OriginKeys.UAA, null); joe = joe.authorities(AuthorityUtils.commaSeparatedStringToAuthorityList("openid,read")); ScimUserBootstrap bootstrap = new ScimUserBootstrap(jdbcScimUserProvisioning, scimUserService, jdbcScimGroupProvisioning, jdbcScimGroupMembershipManager, identityZoneManager, Collections.singletonList(joe), false, Collections.emptyList(), false); - assertThatExceptionOfType(InvalidPasswordException.class).isThrownBy(bootstrap::afterPropertiesSet); + assertThatThrownBy(bootstrap::afterPropertiesSet).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidPasswordException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java index 50b43259367..f67273f90eb 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupExternalMembershipManagerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.scim.jdbc; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.oauth.common.util.RandomValueStringGenerator; @@ -28,7 +29,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @WithDatabaseContext class JdbcScimGroupExternalMembershipManagerTests { @@ -143,12 +144,12 @@ private void createGroupMapping() { @Test void cannot_Retrieve_ById_For_OtherZone() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> edao.getExternalGroupMapsByGroupId("g1-" + otherZone.getId(), origin, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> edao.getExternalGroupMapsByGroupId("g1-" + otherZone.getId(), origin, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test void cannot_Map_ById_For_OtherZone() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> edao.mapExternalGroup("g1-" + otherZone.getId(), "CN=engineering,OU=groups,DC=example,DC=com", origin, IdentityZone.getUaaZoneId())); + assertThatThrownBy(() -> edao.mapExternalGroup("g1-" + otherZone.getId(), "CN=engineering,OU=groups,DC=example,DC=com", origin, IdentityZone.getUaaZoneId())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java index 5082daf51cb..1a1a8355974 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupMembershipManagerTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.scim.jdbc; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.constants.OriginKeys; @@ -429,7 +430,7 @@ void addMemberInDifferentZoneCausesIssues() { IdentityZoneHolder.set(otherIdentityZone); ScimGroupMember m1 = new ScimGroupMember("m1", ScimGroupMember.Type.USER); m1.setOrigin(OriginKeys.UAA); - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimGroupMembershipManager.addMember("g2", m1, otherIdentityZone.getId())); + assertThatThrownBy(() -> jdbcScimGroupMembershipManager.addMember("g2", m1, otherIdentityZone.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -439,7 +440,7 @@ void canAddMemberValidateOriginAndZoneId() throws Exception { validateCount(0, jdbcTemplate, otherIdentityZone.getId()); ScimGroupMember m1 = new ScimGroupMember("m1", ScimGroupMember.Type.USER); m1.setOrigin(OriginKeys.UAA); - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimGroupMembershipManager.addMember("g2", m1, otherIdentityZone.getId())); + assertThatThrownBy(() -> jdbcScimGroupMembershipManager.addMember("g2", m1, otherIdentityZone.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -456,7 +457,7 @@ void canAddNestedGroupMember() { @Test void cannotNestGroupWithinItself() { ScimGroupMember g2 = new ScimGroupMember("g2", ScimGroupMember.Type.GROUP); - assertThatExceptionOfType(InvalidScimResourceException.class).isThrownBy(() -> jdbcScimGroupMembershipManager.addMember("g2", g2, uaaIdentityZone.getId())); + assertThatThrownBy(() -> jdbcScimGroupMembershipManager.addMember("g2", g2, uaaIdentityZone.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidScimResourceException.class)); } @Test @@ -558,7 +559,7 @@ void canRemoveMemberById() throws Exception { jdbcScimGroupMembershipManager.removeMemberById("g1", "m1", uaaIdentityZone.getId()); validateCount(0, jdbcTemplate, uaaIdentityZone.getId()); - assertThatExceptionOfType(MemberNotFoundException.class).isThrownBy(() -> jdbcScimGroupMembershipManager.getMemberById("g1", "m1", uaaIdentityZone.getId())); + assertThatThrownBy(() -> jdbcScimGroupMembershipManager.getMemberById("g1", "m1", uaaIdentityZone.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(MemberNotFoundException.class)); } @Test @@ -571,7 +572,7 @@ void canRemoveNestedGroupMember() throws Exception { validateUserGroups("m2", jdbcScimGroupMembershipManager, uaaIdentityZone.getId(), "test2", "test1.i"); jdbcScimGroupMembershipManager.removeMemberById("g1", "g2", uaaIdentityZone.getId()); - assertThatExceptionOfType(MemberNotFoundException.class).isThrownBy(() -> jdbcScimGroupMembershipManager.getMemberById("g1", "g2", uaaIdentityZone.getId())); + assertThatThrownBy(() -> jdbcScimGroupMembershipManager.getMemberById("g1", "g2", uaaIdentityZone.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(MemberNotFoundException.class)); validateCount(2, jdbcTemplate, uaaIdentityZone.getId()); validateUserGroups("m1", jdbcScimGroupMembershipManager, uaaIdentityZone.getId(), "test1"); validateUserGroups("m2", jdbcScimGroupMembershipManager, uaaIdentityZone.getId(), "test2"); @@ -589,7 +590,7 @@ void canRemoveAllMembers() throws Exception { jdbcScimGroupMembershipManager.removeMembersByGroupId("g1", uaaIdentityZone.getId()); validateCount(1, jdbcTemplate, uaaIdentityZone.getId()); - assertThatExceptionOfType(MemberNotFoundException.class).isThrownBy(() -> jdbcScimGroupMembershipManager.getMemberById("g1", "m1", uaaIdentityZone.getId())); + assertThatThrownBy(() -> jdbcScimGroupMembershipManager.getMemberById("g1", "m1", uaaIdentityZone.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(MemberNotFoundException.class)); validateUserGroups("m1", jdbcScimGroupMembershipManager, uaaIdentityZone.getId()); validateUserGroups("m2", jdbcScimGroupMembershipManager, uaaIdentityZone.getId(), "test2"); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java index c9af937019c..5355a8721b7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimGroupProvisioningTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.scim.jdbc; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.oauth.common.util.RandomValueStringGenerator; import org.cloudfoundry.identity.uaa.resources.jdbc.JdbcPagingListFactory; @@ -221,22 +222,22 @@ void canRetrieveGroupsWithFilterAndSortBy() { @Test void cannotRetrieveGroupsWithIllegalQuotesFilter() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName eq \"bar", zoneId)); + assertThatThrownBy(() -> dao.query("displayName eq \"bar", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveGroupsWithMissingQuotesFilter() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName eq bar", zoneId)); + assertThatThrownBy(() -> dao.query("displayName eq bar", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveGroupsWithInvalidFieldsFilter() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("name eq \"openid\"", zoneId)); + assertThatThrownBy(() -> dao.query("name eq \"openid\"", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveGroupsWithWrongFilter() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName pr \"r\"", zoneId)); + assertThatThrownBy(() -> dao.query("displayName pr \"r\"", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -247,7 +248,7 @@ void canRetrieveGroup() { @Test void cannotRetrieveNonExistentGroup() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> dao.retrieve("invalidgroup", zoneId)); + assertThatThrownBy(() -> dao.retrieve("invalidgroup", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -434,32 +435,32 @@ void sqlInjectionAttackInSortByFieldFails() { @Test void sqlInjectionAttack1Fails() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName='something'; select " + SQL_INJECTION_FIELDS - + " from groups where displayName='something'", zoneId)); + assertThatThrownBy(() -> dao.query("displayName='something'; select " + SQL_INJECTION_FIELDS + + " from groups where displayName='something'", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void sqlInjectionAttack2Fails() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName gt 'a'; select " + SQL_INJECTION_FIELDS - + " from groups where displayName='something'", zoneId)); + assertThatThrownBy(() -> dao.query("displayName gt 'a'; select " + SQL_INJECTION_FIELDS + + " from groups where displayName='something'", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void sqlInjectionAttack3Fails() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName eq \"something\"; select " + SQL_INJECTION_FIELDS - + " from groups where displayName='something'", zoneId)); + assertThatThrownBy(() -> dao.query("displayName eq \"something\"; select " + SQL_INJECTION_FIELDS + + " from groups where displayName='something'", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void sqlInjectionAttack4Fails() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName eq \"something\"; select id from " + groupName + " where id='''; select " + SQL_INJECTION_FIELDS - + " from groups where displayName='something'", zoneId)); + assertThatThrownBy(() -> dao.query("displayName eq \"something\"; select id from " + groupName + " where id='''; select " + SQL_INJECTION_FIELDS + + " from groups where displayName='something'", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void sqlInjectionAttack5Fails() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> dao.query("displayName eq \"something\"'; select " + SQL_INJECTION_FIELDS - + " from groups where displayName='something''", zoneId)); + assertThatThrownBy(() -> dao.query("displayName eq \"something\"'; select " + SQL_INJECTION_FIELDS + + " from groups where displayName='something''", zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -470,9 +471,9 @@ void createGroupNullZoneId() { ScimGroupMember m2 = new ScimGroupMember("m2", ScimGroupMember.Type.USER); g.setMembers(Arrays.asList(m1, m2)); ScimGroup errorGroup = g; - assertThatExceptionOfType(ScimResourceConstraintFailedException.class).isThrownBy(() -> dao.create(errorGroup, null)); + assertThatThrownBy(() -> dao.create(errorGroup, null)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceConstraintFailedException.class)); g.setZoneId(zoneId); - assertThatExceptionOfType(ScimResourceConstraintFailedException.class).isThrownBy(() -> dao.create(errorGroup, null)); + assertThatThrownBy(() -> dao.create(errorGroup, null)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceConstraintFailedException.class)); g = dao.create(g, zoneId); assertThat(g).isNotNull(); assertThat(g.getZoneId()).isEqualTo(zoneId); diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java index 42f897a751b..cacbec3094b 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/JdbcScimUserProvisioningTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.scim.jdbc; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.constants.OriginKeys; @@ -618,8 +619,7 @@ void updateUserShouldPersistAliasProperties(final String zone1, final String zon } private void assertUserDoesNotExist(final String zoneId, final String userId) { - assertThatExceptionOfType(ScimResourceNotFoundException.class) - .isThrownBy(() -> jdbcScimUserProvisioning.retrieve(userId, zoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.retrieve(userId, zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } private static Stream fromUaaToCustomZoneAndViceVersa() { @@ -771,7 +771,7 @@ void canCreateUserWithSingleQuoteInEmailAndUsername() { @Test void cannotCreateScimUserWithEmptyEmail() { ScimUser user = new ScimUser(null, "joeyjoejoe", "joe", "young"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> user.addEmail("")); + assertThatThrownBy(() -> user.addEmail("")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -888,14 +888,14 @@ void updateWithWrongVersionIsError() { ScimUser jo = new ScimUser(null, "josephine", "Jo", "NewUser"); jo.addEmail("jo@blah.com"); jo.setVersion(1); - assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> jdbcScimUserProvisioning.update(joeId, jo, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.update(joeId, jo, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(OptimisticLockingFailureException.class)); } @Test void updateWithBadUsernameIsError() { ScimUser jo = jdbcScimUserProvisioning.retrieve(joeId, currentIdentityZoneId); jo.setUserName("jo$ephione"); - assertThatExceptionOfType(InvalidScimResourceException.class).isThrownBy(() -> jdbcScimUserProvisioning.update(joeId, jo, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.update(joeId, jo, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidScimResourceException.class)); } @Test @@ -931,12 +931,12 @@ void canChangePasswordWithCorrectOldPassword() { @Test void cannotChangePasswordNonexistentUser() { - assertThatExceptionOfType(BadCredentialsException.class).isThrownBy(() -> jdbcScimUserProvisioning.changePassword(joeId, "notjoespassword", "newpassword", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.changePassword(joeId, "notjoespassword", "newpassword", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(BadCredentialsException.class)); } @Test void cannotChangePasswordIfOldPasswordDoesntMatch() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimUserProvisioning.changePassword("9999", null, "newpassword", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.changePassword("9999", null, "newpassword", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -954,7 +954,7 @@ void canRetrieveExistingUser() { @Test void cannotRetrieveNonexistentUser() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimUserProvisioning.retrieve("9999", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.retrieve("9999", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -971,17 +971,17 @@ void cannotDeactivateExistingUserAndThenCreateHimAgain() { String tmpUserId = createUserForDelete(jdbcTemplate, currentIdentityZoneId); ScimUser deletedUser = jdbcScimUserProvisioning.delete(tmpUserId, 0, currentIdentityZoneId); deletedUser.setActive(true); - assertThatExceptionOfType(ScimResourceAlreadyExistsException.class).isThrownBy(() -> jdbcScimUserProvisioning.createUser(deletedUser, "foobarspam1234", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.createUser(deletedUser, "foobarspam1234", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceAlreadyExistsException.class)); } @Test void cannotDeactivateNonexistentUser() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimUserProvisioning.delete("9999", 0, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.delete("9999", 0, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test void deactivateWithWrongVersionIsError() { - assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> jdbcScimUserProvisioning.delete(joeId, 1, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.delete(joeId, 1, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(OptimisticLockingFailureException.class)); } @Nested @@ -1035,12 +1035,12 @@ void canDeleteExistingUserAndThenCreateHimAgain() { @Test void cannotDeleteNonexistentUser() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimUserProvisioning.delete("9999", 0, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.delete("9999", 0, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test void deleteWithWrongVersionIsError() { - assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> jdbcScimUserProvisioning.delete(joeId, 1, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.delete(joeId, 1, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(OptimisticLockingFailureException.class)); } } @@ -1151,7 +1151,7 @@ void createUserWithNoZoneDefaultsToUAAZone() { @Test void createUserWithNoZoneFailsIfUserAlreadyExistsInUaaZone() { addUser(jdbcTemplate, UUID.randomUUID().toString(), "test-username", "password", "test@email.com", "givenName", "familyName", "1234567890", IdentityZone.getUaaZoneId()); - assertThatExceptionOfType(DuplicateKeyException.class).isThrownBy(() -> jdbcTemplate.execute(OLD_ADD_USER_SQL_FORMAT.formatted(UUID.randomUUID().toString(), "test-username", "password", "test@email.com", "givenName", "familyName", "1234567890"))); + assertThatThrownBy(() -> jdbcTemplate.execute(OLD_ADD_USER_SQL_FORMAT.formatted(UUID.randomUUID().toString(), "test-username", "password", "test@email.com", "givenName", "familyName", "1234567890"))).asInstanceOf(InstanceOfAssertFactories.throwable(DuplicateKeyException.class)); } @Test @@ -1178,7 +1178,7 @@ void userVerifiedInvalidUserId() { String tmpUserIdString = createUserForDelete(jdbcTemplate, currentIdentityZoneId); ScimUser user = jdbcScimUserProvisioning.retrieve(tmpUserIdString, currentIdentityZoneId); assertThat(user.isVerified()).isFalse(); - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimUserProvisioning.verifyUser("-1-1-1", -1, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.verifyUser("-1-1-1", -1, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -1187,7 +1187,7 @@ void userUpdateInvalidUserId() { ScimUser user = jdbcScimUserProvisioning.retrieve(tmpUserIdString, currentIdentityZoneId); assertThat(user.isVerified()).isFalse(); user.setVerified(true); - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> jdbcScimUserProvisioning.update("-1-1-1", user, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.update("-1-1-1", user, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -1195,7 +1195,7 @@ void updatedIncorrectVersionUserVerified() { String tmpUserIdString = createUserForDelete(jdbcTemplate, currentIdentityZoneId); ScimUser user = jdbcScimUserProvisioning.retrieve(tmpUserIdString, currentIdentityZoneId); assertThat(user.isVerified()).isFalse(); - assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> jdbcScimUserProvisioning.verifyUser(tmpUserIdString, user.getVersion() + 50, currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.verifyUser(tmpUserIdString, user.getVersion() + 50, currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(OptimisticLockingFailureException.class)); } @Test @@ -1319,62 +1319,62 @@ void canRetrieveUsersWithFilterBooleanOrMatchesSecond() { @Test void cannotRetrieveUsersWithIllegalFilterField() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> assertThat(jdbcScimUserProvisioning.query("emails.type eq \"bar\"", currentIdentityZoneId)).hasSize(2)); + assertThatThrownBy(() -> assertThat(jdbcScimUserProvisioning.query("emails.type eq \"bar\"", currentIdentityZoneId)).hasSize(2)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveUsersWithIllegalPhoneNumberFilterField() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> assertThat(jdbcScimUserProvisioning.query("phoneNumbers.type eq \"bar\"", currentIdentityZoneId)).hasSize(2)); + assertThatThrownBy(() -> assertThat(jdbcScimUserProvisioning.query("phoneNumbers.type eq \"bar\"", currentIdentityZoneId)).hasSize(2)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveUsersWithIllegalFilterQuotes() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> assertThat(jdbcScimUserProvisioning.query("username eq \"bar", currentIdentityZoneId)).hasSize(2)); + assertThatThrownBy(() -> assertThat(jdbcScimUserProvisioning.query("username eq \"bar", currentIdentityZoneId)).hasSize(2)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveUsersWithNativeSqlInjectionAttack() { String password = jdbcTemplate.queryForObject("select password from users where username='joe'", String.class); assertThat(password).isNotNull(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> jdbcScimUserProvisioning.query("username=\"joe\"; select " + SQL_INJECTION_FIELDS - + " from users where username='joe'", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.query("username=\"joe\"; select " + SQL_INJECTION_FIELDS + + " from users where username='joe'", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveUsersWithSqlInjectionAttackOnGt() { String password = jdbcTemplate.queryForObject("select password from users where username='joe'", String.class); assertThat(password).isNotNull(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> jdbcScimUserProvisioning.query("username gt \"h\"; select " + SQL_INJECTION_FIELDS - + " from users where username='joe'", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.query("username gt \"h\"; select " + SQL_INJECTION_FIELDS + + " from users where username='joe'", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveUsersWithSqlInjectionAttack() { String password = jdbcTemplate.queryForObject("select password from users where username='joe'", String.class); assertThat(password).isNotNull(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> jdbcScimUserProvisioning.query("username eq \"joe\"; select " + SQL_INJECTION_FIELDS - + " from users where username='joe'", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.query("username eq \"joe\"; select " + SQL_INJECTION_FIELDS + + " from users where username='joe'", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveUsersWithAnotherSqlInjectionAttack() { String password = jdbcTemplate.queryForObject("select password from users where username='joe'", String.class); assertThat(password).isNotNull(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> jdbcScimUserProvisioning.query("username eq \"joe\"\"; select id from users where id='''; select " - + SQL_INJECTION_FIELDS + " from users where username='joe'", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.query("username eq \"joe\"\"; select id from users where id='''; select " + + SQL_INJECTION_FIELDS + " from users where username='joe'", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void cannotRetrieveUsersWithYetAnotherSqlInjectionAttack() { String password = jdbcTemplate.queryForObject("select password from users where username='joe'", String.class); assertThat(password).isNotNull(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> jdbcScimUserProvisioning.query("username eq \"joe\"'; select " + SQL_INJECTION_FIELDS - + " from users where username='joe''", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.query("username eq \"joe\"'; select " + SQL_INJECTION_FIELDS + + " from users where username='joe''", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void filterEqWithoutQuotesIsRejected() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> jdbcScimUserProvisioning.query("username eq joe", currentIdentityZoneId)); + assertThatThrownBy(() -> jdbcScimUserProvisioning.query("username eq joe", currentIdentityZoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java index ce359186120..85294742548 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/jdbc/ScimSearchQueryConverterTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.scim.jdbc; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.resources.SimpleAttributeNameMapper; import org.cloudfoundry.identity.uaa.resources.jdbc.SearchQueryConverter.ProcessedFilter; import org.cloudfoundry.identity.uaa.resources.jdbc.SimpleSearchQueryConverter; @@ -11,7 +12,7 @@ import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class ScimSearchQueryConverterTests { @@ -118,7 +119,7 @@ void canConvertLegacyValidFilters() { @Test void illegalUnquotedValueInFilter() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> filterProcessor.convert("username eq joe", null, false, zoneId)); + assertThatThrownBy(() -> filterProcessor.convert("username eq joe", null, false, zoneId)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java index 7aeee58fd93..64104763c68 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/services/ScimUserServiceTest.java @@ -2,7 +2,6 @@ import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; -import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.alias.AliasPropertiesInvalidException; import org.cloudfoundry.identity.uaa.scim.ScimUser; import org.cloudfoundry.identity.uaa.scim.ScimUserAliasHandler; @@ -76,8 +75,7 @@ final void updateShouldThrowWhenAliasPropertiesAreInvalid() { final ScimUser user = mock(ScimUser.class); when(scimUserAliasHandler.aliasPropertiesAreValid(user, existingUser)).thenReturn(false); - assertThatThrownBy(() -> scimUserService.updateUser(userId, user)) -.asInstanceOf(InstanceOfAssertFactories.throwable(AliasPropertiesInvalidException.class)); + assertThatThrownBy(() -> scimUserService.updateUser(userId, user)).isInstanceOf(AliasPropertiesInvalidException.class); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java index 5439fee0cac..322d86a1e5c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/scim/util/ScimUtilsTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.scim.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.codestore.ExpiringCode; import org.cloudfoundry.identity.uaa.codestore.ExpiringCodeStore; import org.cloudfoundry.identity.uaa.codestore.ExpiringCodeType; @@ -25,7 +26,7 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -135,7 +136,7 @@ void userWithEmptyandNonEmptyEmails() { emails.add(email2); user.setEmails(emails); - assertThatExceptionOfType(InvalidScimResourceException.class).isThrownBy(() -> ScimUtils.validate(user)); + assertThatThrownBy(() -> ScimUtils.validate(user)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidScimResourceException.class)); } @Test @@ -147,7 +148,7 @@ void userWithEmptyEmail() { emails.add(email); user.setEmails(emails); - assertThatExceptionOfType(InvalidScimResourceException.class).isThrownBy(() -> ScimUtils.validate(user)); + assertThatThrownBy(() -> ScimUtils.validate(user)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidScimResourceException.class)); } @Test @@ -156,6 +157,6 @@ void userWithNonAsciiUsername() { user.setOrigin(OriginKeys.UAA); user.addEmail("jo@blah.com"); - assertThatExceptionOfType(InvalidScimResourceException.class).isThrownBy(() -> ScimUtils.validate(user)); + assertThatThrownBy(() -> ScimUtils.validate(user)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidScimResourceException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java index 8ec8de47cd0..73bf42a72a4 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/security/CsrfAwareEntryPointAndDeniedHandlerTest.java @@ -13,7 +13,7 @@ */ package org.cloudfoundry.identity.uaa.security; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -28,7 +28,7 @@ import jakarta.servlet.http.HttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class CsrfAwareEntryPointAndDeniedHandlerTest { @@ -90,22 +90,22 @@ void handleWhenNotLoggedInJson() throws Exception { @Test void nullCsrfUrl() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler(null, "/login")); + assertThatThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler(null, "/login")).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test void invalidCsrfUrl() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler("csrf", "/login")); + assertThatThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler("csrf", "/login")).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test void nullLoginfUrl() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler("/csrf", null)); + assertThatThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler("/csrf", null)).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test void invalidLoginUrl() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler("/csrf", "login")); + assertThatThrownBy(() -> new CsrfAwareEntryPointAndDeniedHandler("/csrf", "login")).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } } \ No newline at end of file diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java index 209c942321e..2418eaa6b7d 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/InMemoryUaaUserDatabaseTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.user; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.zone.IdentityZoneHolder; import org.junit.jupiter.api.BeforeEach; @@ -10,7 +11,7 @@ import java.util.Date; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class InMemoryUaaUserDatabaseTests { @@ -34,14 +35,14 @@ void retrieveUserPrototypeByName() { @Test void retrieveUserByNameInvalidOrigin() { - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> - db.retrieveUserByName(user.getUsername(), OriginKeys.LDAP)); + assertThatThrownBy(() -> + db.retrieveUserByName(user.getUsername(), OriginKeys.LDAP)).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } @Test void retrieveUserByNameInvalidUsername() { - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> - db.retrieveUserByName(user.getUsername() + "1", OriginKeys.UAA)); + assertThatThrownBy(() -> + db.retrieveUserByName(user.getUsername() + "1", OriginKeys.UAA)).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } @Test @@ -56,8 +57,8 @@ void retrieveUserPrototypeById() { @Test void retrieveUserByInvalidId() { - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> - db.retrieveUserById(user.getId() + "1")); + assertThatThrownBy(() -> + db.retrieveUserById(user.getId() + "1")).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java index af65e6abd70..86db874c77c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/JdbcUaaUserDatabaseTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.user; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.db.beans.DatabaseProperties; @@ -134,7 +135,7 @@ void tearDown() { @Test void storeUserInfoWithoutId() { - assertThatExceptionOfType(NullPointerException.class).isThrownBy(() -> jdbcUaaUserDatabase.storeUserInfo(null, new UserInfo())); + assertThatThrownBy(() -> jdbcUaaUserDatabase.storeUserInfo(null, new UserInfo())).asInstanceOf(InstanceOfAssertFactories.throwable(NullPointerException.class)); } @Test @@ -277,7 +278,7 @@ private static void validateJoe(UaaUser joe) { @Test void getNonExistentUserRaisedNotFoundException() { - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> jdbcUaaUserDatabase.retrieveUserByName("jo", OriginKeys.UAA)); + assertThatThrownBy(() -> jdbcUaaUserDatabase.retrieveUserByName("jo", OriginKeys.UAA)).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } @Test @@ -343,7 +344,7 @@ void updatePreviousAndLastLogonTime() { void getValidUserInDefaultZoneFromOtherZoneFails() { when(mockIdentityZoneManager.getCurrentIdentityZoneId()).thenReturn("zone-the-second"); // TODO: One @Test should not call another @Test - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(this::getValidUserSucceeds); + assertThatThrownBy(this::getValidUserSucceeds).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } @Test @@ -354,7 +355,7 @@ void getValidUserInOtherZoneFromOtherZone() { @Test void getValidUserInOtherZoneFromDefaultZoneFails() { - assertThatExceptionOfType(UsernameNotFoundException.class).isThrownBy(() -> jdbcUaaUserDatabase.retrieveUserByName("alice", OriginKeys.UAA)); + assertThatThrownBy(() -> jdbcUaaUserDatabase.retrieveUserByName("alice", OriginKeys.UAA)).asInstanceOf(InstanceOfAssertFactories.throwable(UsernameNotFoundException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java index 7826aa8da83..18f8d217718 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/user/UaaUserEditorTests.java @@ -13,11 +13,12 @@ *******************************************************************************/ package org.cloudfoundry.identity.uaa.user; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.test.UaaTestAccounts; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class UaaUserEditorTests { private static final UaaTestAccounts testAccounts = UaaTestAccounts.standard(null); @@ -67,7 +68,7 @@ void longFormatWithAuthorities() { @Test void invalidFormat() { UaaUserEditor editor = new UaaUserEditor(); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> editor.setAsText("%s|%s|%s|%s".formatted(UNM, PWD, FNM, LNM))); + assertThatThrownBy(() -> editor.setAsText("%s|%s|%s|%s".formatted(UNM, PWD, FNM, LNM))).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java index b00eab6d9f8..9a2815a3317 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/JwtTokenSignedByThisUAATest.java @@ -20,6 +20,7 @@ import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.client.InMemoryClientDetailsService; import org.cloudfoundry.identity.uaa.client.UaaClientDetails; import org.cloudfoundry.identity.uaa.oauth.KeyInfo; @@ -65,7 +66,8 @@ import java.util.Map; import static java.util.Collections.emptyList; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.REQUIRED_USER_GROUPS; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.EMAIL; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.GRANTED_SCOPES; @@ -515,8 +517,8 @@ void buildIdTokenValidator_performsSignatureValidation() { @Test void idTokenValidator_rejectsTokensWithRefreshTokenSuffix() { content.put(JTI, "asdfsafsa-r"); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - buildIdTokenValidator(getToken(), mock(ChainedSignatureVerifier.class), new KeyInfoService("https://localhost")).checkJti()); + assertThatThrownBy(() -> + buildIdTokenValidator(getToken(), mock(ChainedSignatureVerifier.class), new KeyInfoService("https://localhost")).checkJti()).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -533,57 +535,57 @@ void idTokenValidator_findsScopesFromScopeClaim() { @Test void tokenSignedWithDifferentKey() { signer = new UaaMacSigner(new SecretKeySpec("some_other_key".getBytes(), "HS256")); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkSignature(verifier)); + .checkSignature(verifier)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void invalidJwt() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - buildAccessTokenValidator("invalid.jwt.token", new KeyInfoService("https://localhost"))); + assertThatThrownBy(() -> + buildAccessTokenValidator("invalid.jwt.token", new KeyInfoService("https://localhost"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void tokenWithInvalidIssuer() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")).checkIssuer("http://wrong.issuer/")); + assertThatThrownBy(() -> + buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")).checkIssuer("http://wrong.issuer/")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void emptyBodyJwt_failsCheckingIssuer() { content.remove("iss"); JwtTokenSignedByThisUAA jwtToken = buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - jwtToken.checkIssuer("http://localhost:8080/uaa/oauth/token")); + assertThatThrownBy(() -> + jwtToken.checkIssuer("http://localhost:8080/uaa/oauth/token")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void emptyBodyJwt_failsCheckingExpiry() { content.remove("exp"); JwtTokenSignedByThisUAA jwtToken = buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - jwtToken.checkExpiry(oneSecondBeforeTheTokenExpires)); + assertThatThrownBy(() -> + jwtToken.checkExpiry(oneSecondBeforeTheTokenExpires)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void expiredToken() { content.put("iat", 1458997132); content.put("exp", 1458997132); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkExpiry(oneSecondAfterTheTokenExpires)); + .checkExpiry(oneSecondAfterTheTokenExpires)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void nonExistentUser() { UaaUserDatabase userDb = new InMemoryUaaUserDatabase(Collections.emptySet()); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkUser(userDb::retrieveUserById)); + .checkUser(userDb::retrieveUserById)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -593,32 +595,32 @@ void userHadScopeRevoked() { .withId("a7f07bf6-e720-4652-8999-e980189cef54") .withEmail("marissa@test.org") .withAuthorities(Collections.singletonList(new SimpleGrantedAuthority("a.different.scope")))); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkUser(userDb::retrieveUserById)); + .checkUser(userDb::retrieveUserById)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void tokenHasInsufficientScope() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkRequestedScopesAreGranted("a.different.scope")); + .checkRequestedScopesAreGranted("a.different.scope")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void tokenContainsRevokedScope() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkRequestedScopesAreGranted("a.different.scope")); + .checkRequestedScopesAreGranted("a.different.scope")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void nonExistentClient() { InMemoryClientDetailsService clientDetailsService = new InMemoryClientDetailsService(); clientDetailsService.setClientDetailsStore(Collections.emptyMap()); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkClient(clientDetailsService::loadClientByClientId)); + .checkClient(clientDetailsService::loadClientByClientId)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -630,16 +632,16 @@ void clientHasScopeRevoked() { new UaaClientDetails("app", "acme", "a.different.scope", GRANT_TYPE_AUTHORIZATION_CODE, "") ) ); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkClient(clientDetailsService::loadClientByClientId)); + .checkClient(clientDetailsService::loadClientByClientId)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void clientRevocationHashChanged() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkRevocationSignature(Collections.singletonList("New-Hash"))); + .checkRevocationSignature(Collections.singletonList("New-Hash"))).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -653,16 +655,16 @@ void clientRevocationHashChanged_and_Should_Pass() { @Test void incorrectAudience() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkAudience("app", "somethingelse")); + .checkAudience("app", "somethingelse")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test void emptyAudience() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkAudience("")); + .checkAudience("")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -673,9 +675,9 @@ void tokenIsRevoked() { IdentityZoneHolder.get().getId() )).thenThrow(new EmptyResultDataAccessException(1)); - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkRevocableTokenStore(revocableTokenProvisioning)); + .checkRevocableTokenStore(revocableTokenProvisioning)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test @@ -783,8 +785,8 @@ void readScopesFromClaim_rejects_non_string_scopes() { @Test void nullUserIsCaught() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> + assertThatThrownBy(() -> buildAccessTokenValidator(getToken(), new KeyInfoService("https://localhost")) - .checkUser(_ -> null)); + .checkUser(_ -> null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java index ec3f7ddc1aa..7b4e0f618aa 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/SessionUtilsTest.java @@ -1,11 +1,12 @@ package org.cloudfoundry.identity.uaa.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpSession; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class SessionUtilsTest { private MockHttpSession mockHttpSession; @@ -35,6 +36,6 @@ void isPasswordChangeRequiredIfSetTrue() { @Test void isPasswordChangeRequiredIfSetNotBoolean() { mockHttpSession.setAttribute(SessionUtils.PASSWORD_CHANGE_REQUIRED, "true"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> SessionUtils.isPasswordChangeRequired(mockHttpSession)); + assertThatThrownBy(() -> SessionUtils.isPasswordChangeRequired(mockHttpSession)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } \ No newline at end of file diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java index 392ff4c0613..50afbdc8acf 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/TestUaaUrlBuilderTest.java @@ -1,11 +1,12 @@ package org.cloudfoundry.identity.uaa.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.test.util.ReflectionTestUtils; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class TestUaaUrlBuilderTest { private TestUaaUrlBuilder builder; @@ -19,7 +20,7 @@ void setup() { @Test void informativeError_whenNoSystemDomain() { ReflectionTestUtils.setField(builder, "systemDomain", ""); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> builder.build()); + assertThatThrownBy(() -> builder.build()).asInstanceOf(InstanceOfAssertFactories.throwable(RuntimeException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java index b3a9c51cc52..b3edecb6cac 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaRandomStringUtilImplTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -9,7 +10,7 @@ import java.security.NoSuchProviderException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class UaaRandomStringUtilImplTest { @@ -32,7 +33,7 @@ void secureRandom(final int length) { @Test void invalidLength() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> uaaRandomStringUtil.getSecureRandom(-1)); + assertThatThrownBy(() -> uaaRandomStringUtil.getSecureRandom(-1)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java index 004a19e6f0d..4a7cb7765af 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaTokenUtilsTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.util; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.oauth.common.exceptions.InvalidTokenException; import org.cloudfoundry.identity.uaa.oauth.jwt.UaaMacSigner; import org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants; @@ -16,7 +17,7 @@ import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.cloudfoundry.identity.uaa.oauth.common.util.OAuth2Utils.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.CID; import static org.cloudfoundry.identity.uaa.oauth.token.ClaimConstants.SUB; @@ -149,8 +150,8 @@ void getClaims() { @Test void getClaims_throwsExceptionWhenJwtIsMalformed() { - assertThatExceptionOfType(InvalidTokenException.class).isThrownBy(() -> - UaaTokenUtils.getClaims("not.a.jwt", Map.class)); + assertThatThrownBy(() -> + UaaTokenUtils.getClaims("not.a.jwt", Map.class)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidTokenException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java index dd66b04024b..968e613343c 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/UaaUrlUtilsTest.java @@ -1,5 +1,5 @@ package org.cloudfoundry.identity.uaa.util; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.extensions.PollutionPreventionExtension; import org.cloudfoundry.identity.uaa.zone.IdentityZone; import org.cloudfoundry.identity.uaa.zone.MultitenancyFixture; @@ -533,7 +533,7 @@ void uriHasMatchingHost() { void getHostForURI() { assertThat(UaaUrlUtils.getHostForURI("http://google.com")).isEqualTo("google.com"); assertThat(UaaUrlUtils.getHostForURI("http://subdomain.uaa.com/nowhere")).isEqualTo("subdomain.uaa.com"); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> UaaUrlUtils.getHostForURI(UaaStringUtils.EMPTY_STRING)); + assertThatThrownBy(() -> UaaUrlUtils.getHostForURI(UaaStringUtils.EMPTY_STRING)).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -594,13 +594,13 @@ void validateUriPathDecodingDoesNotAffectFragments() { @Test void validateUriPathDecodingLimit() { // URI path encoded more than MAX_URI_DECODES times - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> UaaUrlUtils.normalizeUri("https://example.com/test1/%25252525252e")); + assertThatThrownBy(() -> UaaUrlUtils.normalizeUri("https://example.com/test1/%25252525252e")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test void validateNormalizeUriIfNull() { - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> UaaUrlUtils.normalizeUri("nohost")); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> UaaUrlUtils.normalizeUri(" ://host/path")); + assertThatThrownBy(() -> UaaUrlUtils.normalizeUri("nohost")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); + assertThatThrownBy(() -> UaaUrlUtils.normalizeUri(" ://host/path")).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -669,9 +669,7 @@ void isValidRegisteredRedirectUrlRejectsOverlongInputQuickly() { @Test void invalidUrlExceptionIsThrown() { - assertThatExceptionOfType(InvalidUrlException.class).isThrownBy( - () -> UaaUrlUtils.fromUriString("invalid-url") - ); + assertThatThrownBy(() -> UaaUrlUtils.fromUriString("invalid-url")).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidUrlException.class)); } private static void validateRedirectUri(List urls, boolean result) { diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java index 0c783b1c562..26948bdb3bf 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/util/beans/DbUtilsTest.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.util.beans; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -14,7 +15,7 @@ import java.sql.SQLException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -92,13 +93,13 @@ void canCache() throws Exception { @NullSource void rejectsInvalidQuoteStrings(String quoteString) throws Exception { when(databaseMetaData.getIdentifierQuoteString()).thenReturn(quoteString); - assertThatExceptionOfType(Throwable.class).isThrownBy(() -> dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate)); + assertThatThrownBy(() -> dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate)).asInstanceOf(InstanceOfAssertFactories.throwable(Throwable.class)); } @Test void abortsWhenCannotGetMetaData() throws Exception { when(metaDataExtractor.extractDatabaseMetaData(any())).thenThrow(MetaDataAccessException.class); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate)); + assertThatThrownBy(() -> dbUtils.getQuotedIdentifier(IDENTIFIER_NAME, jdbcTemplate)).asInstanceOf(InstanceOfAssertFactories.throwable(RuntimeException.class)); } } } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java index e0d8f7ff3e4..4d274e24d98 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/web/tomcat/UaaStartupFailureListenerTest.java @@ -8,11 +8,12 @@ import org.apache.catalina.LifecycleState; import org.apache.catalina.Server; import org.apache.catalina.Service; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -60,7 +61,7 @@ void stopsTheServer() throws Exception { @Test void rethrowsAnyExceptions() throws Exception { doThrow(new LifecycleException()).when(server).stop(); - assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> listener.lifecycleEvent(mockLifecycleEvent(server, Lifecycle.AFTER_START_EVENT))); + assertThatThrownBy(() -> listener.lifecycleEvent(mockLifecycleEvent(server, Lifecycle.AFTER_START_EVENT))).asInstanceOf(InstanceOfAssertFactories.throwable(RuntimeException.class)); verify(server, times(1)).stop(); verify(server, times(0)).destroy(); } diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java index 0fcf612ed89..2bd8aaf96b0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/JdbcIdentityZoneProvisioningTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.zone; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.oauth.common.util.RandomValueStringGenerator; @@ -82,7 +83,7 @@ void createIdentityZoneSubdomainBecomesLowerCase() { @Test void null_subdomain() { - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> jdbcIdentityZoneProvisioning.retrieveBySubdomain(null)); + assertThatThrownBy(() -> jdbcIdentityZoneProvisioning.retrieveBySubdomain(null)).asInstanceOf(InstanceOfAssertFactories.throwable(EmptyResultDataAccessException.class)); } @Test @@ -176,7 +177,7 @@ void deleteInactiveIdentityZone() { void updateNonExistentIdentityZone() { IdentityZone identityZone = MultitenancyFixture.identityZone(randomValueStringGenerator.generate(), randomValueStringGenerator.generate()); identityZone.setId(randomValueStringGenerator.generate()); - assertThatExceptionOfType(ZoneDoesNotExistsException.class).isThrownBy(() -> jdbcIdentityZoneProvisioning.update(identityZone)); + assertThatThrownBy(() -> jdbcIdentityZoneProvisioning.update(identityZone)).asInstanceOf(InstanceOfAssertFactories.throwable(ZoneDoesNotExistsException.class)); } @Test @@ -282,8 +283,8 @@ void getInactiveIdentityZoneIgnoringActiveFlag() { @Test void identityZoneRetrieveZoneIdNull() { - assertThatExceptionOfType(ZoneDoesNotExistsException.class).isThrownBy(() -> jdbcIdentityZoneProvisioning.retrieve(null)); - assertThatExceptionOfType(ZoneDoesNotExistsException.class).isThrownBy(() -> jdbcIdentityZoneProvisioning.retrieveIgnoreActiveFlag(null)); + assertThatThrownBy(() -> jdbcIdentityZoneProvisioning.retrieve(null)).asInstanceOf(InstanceOfAssertFactories.throwable(ZoneDoesNotExistsException.class)); + assertThatThrownBy(() -> jdbcIdentityZoneProvisioning.retrieveIgnoreActiveFlag(null)).asInstanceOf(InstanceOfAssertFactories.throwable(ZoneDoesNotExistsException.class)); } @Test @@ -299,7 +300,7 @@ void identityZoneUpdateSubDomainSame() { assertThat(createdIdZone2.getSubdomain()).isNotEqualTo(createdIdZone.getSubdomain()); createdIdZone2.setConfig(null); createdIdZone2.setSubdomain(subDomain); - assertThatExceptionOfType(ZoneAlreadyExistsException.class).isThrownBy(() -> jdbcIdentityZoneProvisioning.update(createdIdZone2)); + assertThatThrownBy(() -> jdbcIdentityZoneProvisioning.update(createdIdZone2)).asInstanceOf(InstanceOfAssertFactories.throwable(ZoneAlreadyExistsException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java index 05a75cebb14..997d7c10357 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/MultitenantJdbcClientDetailsServiceTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.zone; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.annotations.WithDatabaseContext; import org.cloudfoundry.identity.uaa.audit.event.EntityDeletedEvent; import org.cloudfoundry.identity.uaa.authentication.UaaAuthentication; @@ -39,7 +40,8 @@ import java.util.List; import java.util.Map; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.cloudfoundry.identity.uaa.oauth.client.ClientConstants.REQUIRED_USER_GROUPS; import static org.cloudfoundry.identity.uaa.oauth.client.ClientDetailsModification.SECRET; import static org.cloudfoundry.identity.uaa.zone.MultitenantJdbcClientDetailsService.DEFAULT_DELETE_STATEMENT; @@ -200,7 +202,7 @@ void cannotDeleteUaaZoneClients() { @Test void loadingClientForNonExistingClientId() { - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> service.loadClientByClientId("nonExistingClientId")); + assertThatThrownBy(() -> service.loadClientByClientId("nonExistingClientId")).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } @Test @@ -477,7 +479,7 @@ void insertDuplicateClient() { clientDetails.setClientId("duplicateClientIdWithNoDetails"); service.addClientDetails(clientDetails); - assertThatExceptionOfType(ClientAlreadyExistsException.class).isThrownBy(() -> service.addClientDetails(clientDetails)); + assertThatThrownBy(() -> service.addClientDetails(clientDetails)).asInstanceOf(InstanceOfAssertFactories.throwable(ClientAlreadyExistsException.class)); } @Test @@ -624,7 +626,7 @@ void updateNonExistentClient() { UaaClientDetails clientDetails = new UaaClientDetails(); clientDetails.setClientId("nosuchClientIdWithNoDetails"); - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> service.updateClientDetails(clientDetails)); + assertThatThrownBy(() -> service.updateClientDetails(clientDetails)).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } @Test @@ -648,7 +650,7 @@ void removeNonExistentClient() { UaaClientDetails clientDetails = new UaaClientDetails(); clientDetails.setClientId("nosuchClientIdWithNoDetails"); - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> service.removeClientDetails(clientDetails.getClientId())); + assertThatThrownBy(() -> service.removeClientDetails(clientDetails.getClientId())).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } @Test @@ -679,7 +681,7 @@ void loadingClientInOtherZoneFromDefaultZoneFails() { clientDetails.setClientId("clientInOtherZone"); service.addClientDetails(clientDetails); when(mockIdentityZoneManager.getCurrentIdentityZoneId()).thenReturn(IdentityZone.getUaaZoneId()); - assertThatExceptionOfType(NoSuchClientException.class).isThrownBy(() -> service.loadClientByClientId("clientInOtherZone")); + assertThatThrownBy(() -> service.loadClientByClientId("clientInOtherZone")).asInstanceOf(InstanceOfAssertFactories.throwable(NoSuchClientException.class)); } @Test diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java index 0e433fef90e..3e3b20404a7 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/UserConfigValidatorTest.java @@ -1,10 +1,11 @@ package org.cloudfoundry.identity.uaa.zone; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; class UserConfigValidatorTest { @@ -31,15 +32,15 @@ void noGroupsAllowed() { UserConfig userConfig = new UserConfig(); userConfig.setDefaultGroups(Collections.emptyList()); userConfig.setAllowedGroups(Collections.emptyList()); - assertThatExceptionOfType(InvalidIdentityZoneConfigurationException.class).isThrownBy(() -> // no groups allowed - UserConfigValidator.validate(userConfig)); + assertThatThrownBy(() -> // no groups allowed + UserConfigValidator.validate(userConfig)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidIdentityZoneConfigurationException.class)); } @Test void noUsersAllowed() { UserConfig userConfig = new UserConfig(); userConfig.setMaxUsers(0); - assertThatExceptionOfType(InvalidIdentityZoneConfigurationException.class).isThrownBy(() -> - UserConfigValidator.validate(userConfig)); + assertThatThrownBy(() -> + UserConfigValidator.validate(userConfig)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidIdentityZoneConfigurationException.class)); } } \ No newline at end of file diff --git a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java index 6dac42cc8e7..00030bb1be0 100644 --- a/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java +++ b/server/src/test/java/org/cloudfoundry/identity/uaa/zone/ZoneAwareClientSecretPolicyValidatorTests.java @@ -1,11 +1,12 @@ package org.cloudfoundry.identity.uaa.zone; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.extensions.PollutionPreventionExtension; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; @ExtendWith(PollutionPreventionExtension.class) class ZoneAwareClientSecretPolicyValidatorTests { @@ -45,7 +46,7 @@ void emptyClientSecret() { @Test void default_policy_too_long_secret() { zone.getConfig().setClientSecretPolicy(defaultPolicy); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> validator.validate(TEST_SECRET_3)); + assertThatThrownBy(() -> validator.validate(TEST_SECRET_3)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test @@ -64,24 +65,24 @@ void secretConformingToPolicy() { @Test void secretMissingSpecialCharacter() { zone.getConfig().setClientSecretPolicy(strictPolicy); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> validator.validate(TEST_SECRET_5)); + assertThatThrownBy(() -> validator.validate(TEST_SECRET_5)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test void secretMissingDigit() { zone.getConfig().setClientSecretPolicy(strictPolicy); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> validator.validate(TEST_SECRET_6)); + assertThatThrownBy(() -> validator.validate(TEST_SECRET_6)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test void secretMissingUpperCaseCharacter() { zone.getConfig().setClientSecretPolicy(strictPolicy); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> validator.validate(TEST_SECRET_7)); + assertThatThrownBy(() -> validator.validate(TEST_SECRET_7)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } @Test void secretMissingLowerCaseCharacter() { zone.getConfig().setClientSecretPolicy(strictPolicy); - assertThatExceptionOfType(InvalidClientSecretException.class).isThrownBy(() -> validator.validate(TEST_SECRET_8)); + assertThatThrownBy(() -> validator.validate(TEST_SECRET_8)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidClientSecretException.class)); } } \ No newline at end of file diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java index a44ea42d9d3..f1e80526b79 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/UaaConfigurationTests.java @@ -12,7 +12,7 @@ * subcomponent's license, as noted in the LICENSE file. *******************************************************************************/ package org.cloudfoundry.identity.uaa; - +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.impl.config.UaaConfiguration; import org.cloudfoundry.identity.uaa.impl.config.YamlConfigurationValidator; import org.junit.jupiter.api.Test; @@ -20,7 +20,7 @@ import jakarta.validation.ConstraintViolationException; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Luke Taylor @@ -71,7 +71,7 @@ void validClientIsOk() { @Test void invalidIssuerUriCausesException() { - assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> - createValidator("name: uaa\nissuer.uri: notauri\n")); + assertThatThrownBy(() -> + createValidator("name: uaa\nissuer.uri: notauri\n")).asInstanceOf(InstanceOfAssertFactories.throwable(ConstraintViolationException.class)); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java index 3e42790a47d..bc10f570614 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/mock/providers/IdentityProviderEndpointsAliasMockMvcTests.java @@ -355,7 +355,7 @@ private void shouldRejectCreation(final IdentityZone zone, final IdentityProvide // after the failed creation, the IdP must not exist final List> idpsInZoneAfterFailedCreation = readAllIdpsInZone(zone); - assertThat(idpsInZoneAfterFailedCreation.stream().map(IdentityProvider::getOriginKey)).doesNotContain(idp.getOriginKey()); + assertThat(idpsInZoneAfterFailedCreation).extracting(IdentityProvider::getOriginKey).doesNotContain(idp.getOriginKey()); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java index 566a3d40e7c..0a028c1eaa4 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/oauth/UaaTokenServicesTests.java @@ -10,6 +10,7 @@ import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.Configurator; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.DefaultTestContext; import org.cloudfoundry.identity.uaa.approval.Approval; import org.cloudfoundry.identity.uaa.approval.JdbcApprovalStore; @@ -68,7 +69,7 @@ import static org.apache.logging.log4j.Level.DEBUG; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.HamcrestCondition.matching; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.GRANT_TYPE; import static org.cloudfoundry.identity.uaa.oauth.TokenTestSupport.ISSUER_URI; @@ -803,9 +804,9 @@ void invalidExpClaim(int validitySeconds) { // Verifying with generic Exception instead of specific type because // refreshAccessToken() throws an Exception of which type is // different from the one that is declared in its method signature - assertThatExceptionOfType(Exception.class).isThrownBy(() -> + assertThatThrownBy(() -> tokenServices.refreshAccessToken(refreshToken.getValue(), - tokenRequest)); + tokenRequest)).asInstanceOf(InstanceOfAssertFactories.throwable(Exception.class)); } private RefreshTokenCreator createRefreshTokenCreator( diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java index a9c14f12ab2..14b2e1af702 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimGroupEndpointsTests.java @@ -1,5 +1,6 @@ package org.cloudfoundry.identity.uaa.scim.endpoints; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.DefaultTestContext; import org.cloudfoundry.identity.uaa.constants.OriginKeys; import org.cloudfoundry.identity.uaa.resources.SearchResults; @@ -266,7 +267,7 @@ void listExternalGroups() { "displayName eq \"test\"" }) void listExternalGroupsInvalidFilter(final String filter) { - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> scimGroupEndpoints.getExternalGroups(1, 100, filter, null, null)); + assertThatThrownBy(() -> scimGroupEndpoints.getExternalGroups(1, 100, filter, null, null)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test @@ -393,7 +394,7 @@ void getGroup() { @Test void getNonExistentGroupFails() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> scimGroupEndpoints.getGroup("wrongid", new MockHttpServletResponse())); + assertThatThrownBy(() -> scimGroupEndpoints.getGroup("wrongid", new MockHttpServletResponse())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -486,7 +487,7 @@ void updateGroupNullEtag() { scimGroup.setDisplayName("superadmin"); MockHttpServletResponse httpServletResponse = new MockHttpServletResponse(); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> scimGroupEndpoints.updateGroup(createdScimGroup, createdScimGroup.getId(), null, httpServletResponse)); + assertThatThrownBy(() -> scimGroupEndpoints.updateGroup(createdScimGroup, createdScimGroup.getId(), null, httpServletResponse)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test @@ -498,7 +499,7 @@ void updateGroupNoEtag() { scimGroup.setDisplayName("superadmin"); MockHttpServletResponse httpServletResponse = new MockHttpServletResponse(); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> scimGroupEndpoints.updateGroup(createdScimGroup, createdScimGroup.getId(), "", httpServletResponse)); + assertThatThrownBy(() -> scimGroupEndpoints.updateGroup(createdScimGroup, createdScimGroup.getId(), "", httpServletResponse)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test @@ -510,7 +511,7 @@ void updateGroupInvalidEtag() { scimGroup.setDisplayName("superadmin"); MockHttpServletResponse httpServletResponse = new MockHttpServletResponse(); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> scimGroupEndpoints.updateGroup(createdScimGroup, createdScimGroup.getId(), "abc", httpServletResponse)); + assertThatThrownBy(() -> scimGroupEndpoints.updateGroup(createdScimGroup, createdScimGroup.getId(), "abc", httpServletResponse)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test @@ -687,7 +688,7 @@ void deleteWrongVersionFails() { @Test void deleteNonExistentGroupFails() { - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> scimGroupEndpoints.deleteGroup("some id", "*", new MockHttpServletResponse())); + assertThatThrownBy(() -> scimGroupEndpoints.deleteGroup("some id", "*", new MockHttpServletResponse())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -741,7 +742,7 @@ void patchInvalidResourceFails() { ScimGroup g1 = new ScimGroup(null, "name", identityZoneManager.getCurrentIdentityZoneId()); g1.setDescription("description"); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> scimGroupEndpoints.patchGroup(g1, "id", "0", new MockHttpServletResponse())); + assertThatThrownBy(() -> scimGroupEndpoints.patchGroup(g1, "id", "0", new MockHttpServletResponse())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } @Test @@ -774,6 +775,6 @@ void patchIncorrectEtagFails() { ScimGroup patch = new ScimGroup("NewName"); patch.setId(scimGroup.getId()); - assertThatExceptionOfType(ScimException.class).isThrownBy(() -> scimGroupEndpoints.patchGroup(patch, patch.getId(), Integer.toString(createdScimGroup.getVersion() + 1), new MockHttpServletResponse())); + assertThatThrownBy(() -> scimGroupEndpoints.patchGroup(patch, patch.getId(), Integer.toString(createdScimGroup.getVersion() + 1), new MockHttpServletResponse())).asInstanceOf(InstanceOfAssertFactories.throwable(ScimException.class)); } } diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java index 3f13b46ef78..6eee89882b0 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/scim/endpoints/ScimUserEndpointsTests.java @@ -2,6 +2,7 @@ import com.unboundid.scim.sdk.AttributePath; import com.unboundid.scim.sdk.SCIMFilter; +import org.assertj.core.api.InstanceOfAssertFactories; import org.cloudfoundry.identity.uaa.DefaultTestContext; import org.cloudfoundry.identity.uaa.account.UserAccountStatus; import org.cloudfoundry.identity.uaa.approval.Approval; @@ -78,7 +79,8 @@ import java.util.UUID; import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; @@ -407,7 +409,7 @@ void userWithNoEmailNotAllowed() { @Test void create_uaa_user_when_internal_user_management_is_disabled() { - assertThatExceptionOfType(InternalUserManagementDisabledException.class).isThrownBy(() -> createUserWhenInternalUserManagementIsDisabled(OriginKeys.UAA)); + assertThatThrownBy(() -> createUserWhenInternalUserManagementIsDisabled(OriginKeys.UAA)).asInstanceOf(InstanceOfAssertFactories.throwable(InternalUserManagementDisabledException.class)); } @Test @@ -503,7 +505,7 @@ void deleteIsAllowedWithQuotedEtag() { @Test void deleteIs_Not_Allowed_For_UAA_When_InternalUserManagement_Is_Disabled() { - assertThatExceptionOfType(InternalUserManagementDisabledException.class).isThrownBy(() -> deleteWhenInternalUserManagementIsDisabled(OriginKeys.UAA)); + assertThatThrownBy(() -> deleteWhenInternalUserManagementIsDisabled(OriginKeys.UAA)).asInstanceOf(InstanceOfAssertFactories.throwable(InternalUserManagementDisabledException.class)); } @Test @@ -518,12 +520,12 @@ void deleteIsNotAllowedWithWrongVersionInEtag() { exGuy = jdbcScimUserProvisioning.createUser(exGuy, "exguyspassword", identityZone.getId()); final String exGuyId = exGuy.getId(); final ScimMeta exGuyMeta = exGuy.getMeta(); - assertThatExceptionOfType(OptimisticLockingFailureException.class).isThrownBy(() -> + assertThatThrownBy(() -> scimUserEndpoints.deleteUser( exGuyId, Integer.toString(exGuyMeta.getVersion() + 1), new MockHttpServletRequest(), - new MockHttpServletResponse())); + new MockHttpServletResponse())).asInstanceOf(InstanceOfAssertFactories.throwable(OptimisticLockingFailureException.class)); } @Test @@ -877,7 +879,7 @@ void updateIncludesETagHeader() { @Test void updateWhenInternalUserManagementIsDisabledForUaa() { - assertThatExceptionOfType(InternalUserManagementDisabledException.class).isThrownBy(() -> updateWhenInternalUserManagementIsDisabled(OriginKeys.UAA)); + assertThatThrownBy(() -> updateWhenInternalUserManagementIsDisabled(OriginKeys.UAA)).asInstanceOf(InstanceOfAssertFactories.throwable(InternalUserManagementDisabledException.class)); } @Test @@ -1000,13 +1002,13 @@ void patchUser() { void patchUnknownUserFails() { ScimUser user = new ScimUser(null, "uname", "gname", "fname"); user.addEmail("test@example.org"); - assertThatExceptionOfType(ScimResourceNotFoundException.class).isThrownBy(() -> scimUserEndpoints.patchUser( + assertThatThrownBy(() -> scimUserEndpoints.patchUser( user, UUID.randomUUID().toString(), "0", new MockHttpServletRequest(), new MockHttpServletResponse(), - null)); + null)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceNotFoundException.class)); } @Test @@ -1032,7 +1034,7 @@ void patchDropUnknownAttributeFails() { user.addEmail("test@example.org"); ScimUser createdUser = scimUserEndpoints.createUser(user, new MockHttpServletRequest(), new MockHttpServletResponse()); createdUser.getMeta().setAttributes(new String[]{"attributeName"}); - assertThatExceptionOfType(InvalidScimResourceException.class).isThrownBy(() -> scimUserEndpoints.patchUser(createdUser, createdUser.getId(), Integer.toString(createdUser.getVersion()), new MockHttpServletRequest(), new MockHttpServletResponse(), null)); + assertThatThrownBy(() -> scimUserEndpoints.patchUser(createdUser, createdUser.getId(), Integer.toString(createdUser.getVersion()), new MockHttpServletRequest(), new MockHttpServletResponse(), null)).asInstanceOf(InstanceOfAssertFactories.throwable(InvalidScimResourceException.class)); } @Test @@ -1041,7 +1043,7 @@ void patchIncorrectVersionFails() { user.setPassword("password"); user.addEmail("test@example.org"); ScimUser createdUser = scimUserEndpoints.createUser(user, new MockHttpServletRequest(), new MockHttpServletResponse()); - assertThatExceptionOfType(ScimResourceConflictException.class).isThrownBy(() -> scimUserEndpoints.patchUser(createdUser, createdUser.getId(), Integer.toString(createdUser.getVersion() + 1), new MockHttpServletRequest(), new MockHttpServletResponse(), null)); + assertThatThrownBy(() -> scimUserEndpoints.patchUser(createdUser, createdUser.getId(), Integer.toString(createdUser.getVersion() + 1), new MockHttpServletRequest(), new MockHttpServletResponse(), null)).asInstanceOf(InstanceOfAssertFactories.throwable(ScimResourceConflictException.class)); } @Test @@ -1064,7 +1066,7 @@ void patchUserInvalidStatus() { ScimUser createdUser = scimUserEndpoints.createUser(user, new MockHttpServletRequest(), new MockHttpServletResponse()); UserAccountStatus userAccountStatus = new UserAccountStatus(); userAccountStatus.setLocked(true); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> scimUserEndpoints.updateAccountStatus(userAccountStatus, createdUser.getId())); + assertThatThrownBy(() -> scimUserEndpoints.updateAccountStatus(userAccountStatus, createdUser.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -1075,7 +1077,7 @@ void patchUserStatusWithPasswordExpiryFalse() { ScimUser createdUser = scimUserEndpoints.createUser(user, new MockHttpServletRequest(), new MockHttpServletResponse()); UserAccountStatus userAccountStatus = new UserAccountStatus(); userAccountStatus.setPasswordChangeRequired(false); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> scimUserEndpoints.updateAccountStatus(userAccountStatus, createdUser.getId())); + assertThatThrownBy(() -> scimUserEndpoints.updateAccountStatus(userAccountStatus, createdUser.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test @@ -1086,7 +1088,7 @@ void patchUserStatusWithPasswordExpiryExternalUser() { ScimUser createdUser = scimUserEndpoints.createUser(user, new MockHttpServletRequest(), new MockHttpServletResponse()); UserAccountStatus userAccountStatus = new UserAccountStatus(); userAccountStatus.setPasswordChangeRequired(true); - assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> scimUserEndpoints.updateAccountStatus(userAccountStatus, createdUser.getId())); + assertThatThrownBy(() -> scimUserEndpoints.updateAccountStatus(userAccountStatus, createdUser.getId())).asInstanceOf(InstanceOfAssertFactories.throwable(IllegalArgumentException.class)); } @Test From fd8a97b3cc6e5524e276c3a6fdee761661344306 Mon Sep 17 00:00:00 2001 From: Duane May Date: Thu, 4 Jun 2026 09:37:39 -0400 Subject: [PATCH 7/7] Adjust visibility for testing --- .../identity/uaa/integration/feature/ImplicitGrantIT.java | 2 +- .../identity/uaa/login/LoginMockMvcZonePathTests.java | 2 +- .../org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java | 3 +-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java index ed81cefb0bd..4bb05b99c31 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/integration/feature/ImplicitGrantIT.java @@ -48,7 +48,7 @@ // public for YamlProcessorTest @SpringJUnitConfig(classes = DefaultIntegrationTestConfig.class) -class ImplicitGrantIT { +public class ImplicitGrantIT { @Autowired TestAccounts testAccounts; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java index 5944468e5f5..ceb93eabc09 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/login/LoginMockMvcZonePathTests.java @@ -154,7 +154,7 @@ @DirtiesContext // public for LimitedModeLoginMockMvcTests @EnabledIfZonePathsEnabled -class LoginMockMvcZonePathTests { +public class LoginMockMvcZonePathTests { @Autowired private WebApplicationContext webApplicationContext; diff --git a/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java b/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java index c933a59858b..50e27c0e8be 100644 --- a/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java +++ b/uaa/src/test/java/org/cloudfoundry/identity/uaa/yml/YamlProcessorTest.java @@ -1,6 +1,5 @@ package org.cloudfoundry.identity.uaa.yml; -import org.cloudfoundry.identity.uaa.integration.feature.ImplicitGrantIT; import org.junit.jupiter.api.Test; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; @@ -13,7 +12,7 @@ class YamlProcessorTest { /** - * Integration tests using spring, such as {@link ImplicitGrantIT}, have been taking around 20 seconds to start up. + * Integration tests using spring, such as {@link org.cloudfoundry.identity.uaa.integration.feature.ImplicitGrantIT}, have been taking around 20 seconds to start up. * This is due to the {@link Yaml} parser having a hard time parsing uaa.yml, which contains very long comments. * This test ensures that the parser will parse swiftly. */