From 5718d497bc83d08f353df2ecc43dd6fc5e9e14e5 Mon Sep 17 00:00:00 2001 From: Rory Hunter Date: Wed, 21 Jul 2021 19:58:39 +0100 Subject: [PATCH] Enable compiler warnings in x-pack security (#75473) Part of #40366. --- .../resources/checkstyle_ide_fragment.xml | 2 +- .../test/ActionListenerUtils.java | 21 ++ x-pack/plugin/security/build.gradle | 4 - .../saml/TransportSamlAuthenticateAction.java | 1 + .../TransportSamlInvalidateSessionAction.java | 1 + .../xpack/security/authc/ApiKeyService.java | 27 ++- .../xpack/security/authc/Realms.java | 3 + .../xpack/security/authc/TokenService.java | 36 +-- .../xpack/security/authc/UserToken.java | 1 + .../authc/esnative/NativeUsersStore.java | 2 + .../oidc/OpenIdConnectAuthenticator.java | 19 +- .../authc/oidc/OpenIdConnectRealm.java | 5 +- .../authz/store/CompositeRolesStore.java | 2 +- .../enrollment/CreateEnrollmentToken.java | 1 + .../apikey/RestInvalidateApiKeyAction.java | 1 + .../support/SecurityIndexManager.java | 1 + .../test/SettingsFilterTests.java | 11 +- .../SecurityInfoTransportActionTests.java | 16 +- .../TransportGrantApiKeyActionTests.java | 10 +- .../TransportKibanaEnrollmentActionTests.java | 3 +- .../filter/SecurityActionFilterTests.java | 28 +-- ...ansportOpenIdConnectLogoutActionTests.java | 19 +- .../role/TransportDeleteRoleActionTests.java | 44 ++-- .../role/TransportGetRolesActionTests.java | 19 +- .../role/TransportPutRoleActionTests.java | 45 ++-- .../TransportGetRoleMappingsActionTests.java | 3 +- .../TransportPutRoleMappingActionTests.java | 3 +- ...sportSamlInvalidateSessionActionTests.java | 12 +- .../saml/TransportSamlLogoutActionTests.java | 1 + ...tDeleteServiceAccountTokenActionTests.java | 7 +- ...tServiceAccountCredentialsActionTests.java | 7 +- .../TransportCreateTokenActionTests.java | 17 +- .../TransportChangePasswordActionTests.java | 28 ++- .../user/TransportDeleteUserActionTests.java | 42 ++-- .../user/TransportGetUsersActionTests.java | 35 ++- .../user/TransportPutUserActionTests.java | 42 ++-- .../user/TransportSetEnabledActionTests.java | 42 ++-- .../security/authc/ApiKeyServiceTests.java | 11 +- .../authc/AuthenticationServiceTests.java | 61 +++-- .../security/authc/InternalRealmsTests.java | 1 + .../xpack/security/authc/RealmsTests.java | 1 + .../security/authc/TokenServiceTests.java | 31 ++- .../authc/esnative/NativeUsersStoreTests.java | 2 + .../authc/esnative/ReservedRealmTests.java | 53 +++-- .../esnative/tool/SetupPasswordToolTests.java | 103 ++++---- .../security/authc/file/FileRealmTests.java | 14 +- .../KerberosRealmAuthenticateFailedTests.java | 11 +- .../kerberos/KerberosRealmCacheTests.java | 24 +- .../authc/kerberos/KerberosRealmTestCase.java | 1 + .../authc/kerberos/KerberosRealmTests.java | 17 +- .../authc/ldap/ActiveDirectoryRealmTests.java | 9 +- .../ldap/CancellableLdapRunnableTests.java | 14 +- .../security/authc/ldap/LdapRealmTests.java | 9 +- .../oidc/OpenIdConnectAuthenticatorTests.java | 50 ++-- .../authc/oidc/OpenIdConnectRealmTests.java | 49 ++-- .../security/authc/pki/PkiRealmTests.java | 17 +- .../security/authc/saml/SamlRealmTests.java | 7 +- .../saml/SamlSpMetadataBuilderTests.java | 2 +- .../IndexServiceAccountTokenStoreTests.java | 10 +- .../authc/support/ApiKeyGeneratorTests.java | 1 + .../mapper/NativeRoleMappingStoreTests.java | 4 +- .../authz/AuthorizationServiceTests.java | 8 +- .../authz/IndicesAndAliasesResolverTests.java | 16 +- ...ldDataCacheWithFieldSubsetReaderTests.java | 1 + ...IndicesAliasesRequestInterceptorTests.java | 12 +- .../ResizeRequestInterceptorTests.java | 12 +- .../authz/store/CompositeRolesStoreTests.java | 220 ++++++++++-------- .../store/NativePrivilegeStoreTests.java | 18 +- .../authz/store/NativeRolesStoreTests.java | 1 + .../CreateEnrollmentTokenTests.java | 74 +++--- .../ingest/SetSecurityUserProcessorTests.java | 21 +- .../security/rest/RestRequestFilterTests.java | 6 + .../rest/SecurityRestFilterTests.java | 28 +-- .../RestInvalidateApiKeyActionTests.java | 1 + .../oauth2/RestGetTokenActionTests.java | 5 +- .../xpack/security/test/SecurityMocks.java | 19 +- ...curityServerTransportInterceptorTests.java | 15 +- .../transport/ServerTransportFilterTests.java | 77 +++--- .../transport/nio/SSLChannelContextTests.java | 10 +- 79 files changed, 911 insertions(+), 696 deletions(-) create mode 100644 test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java diff --git a/build-tools-internal/src/main/resources/checkstyle_ide_fragment.xml b/build-tools-internal/src/main/resources/checkstyle_ide_fragment.xml index 9441fa9cd77c3..6aeae3712aaf9 100644 --- a/build-tools-internal/src/main/resources/checkstyle_ide_fragment.xml +++ b/build-tools-internal/src/main/resources/checkstyle_ide_fragment.xml @@ -29,7 +29,7 @@ - + diff --git a/test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java b/test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java new file mode 100644 index 0000000000000..292e1fbef4a03 --- /dev/null +++ b/test/framework/src/main/java/org/elasticsearch/test/ActionListenerUtils.java @@ -0,0 +1,21 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License + * 2.0 and the Server Side Public License, v 1; you may not use this file except + * in compliance with, at your election, the Elastic License 2.0 or the Server + * Side Public License, v 1. + */ + +package org.elasticsearch.test; + +import org.elasticsearch.action.ActionListener; + +import static org.mockito.Matchers.any; + +public abstract class ActionListenerUtils { + + @SuppressWarnings("unchecked") + public static ActionListener anyActionListener() { + return any(ActionListener.class); + } +} diff --git a/x-pack/plugin/security/build.gradle b/x-pack/plugin/security/build.gradle index 57d2db2f046b6..7f23ab4e82548 100644 --- a/x-pack/plugin/security/build.gradle +++ b/x-pack/plugin/security/build.gradle @@ -134,10 +134,6 @@ dependencies { testImplementation('org.apache.directory.mavibot:mavibot:1.0.0-M8') } -tasks.withType(JavaCompile).configureEach { - options.compilerArgs << "-Xlint:-rawtypes,-unchecked" -} - tasks.named("processInternalClusterTestResources").configure { from(project(xpackModule('core')).file('src/main/config')) from(project(xpackModule('core')).file('src/test/resources')) diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlAuthenticateAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlAuthenticateAction.java index 6f4543cc5ce81..a223b259689b3 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlAuthenticateAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlAuthenticateAction.java @@ -64,6 +64,7 @@ protected void doExecute(Task task, SamlAuthenticateRequest request, ActionListe return; } assert authentication != null : "authentication should never be null at this point"; + @SuppressWarnings("unchecked") final Map tokenMeta = (Map) result.getMetadata().get(SamlRealm.CONTEXT_TOKEN_DATA); tokenService.createOAuth2Tokens(authentication, originatingAuthentication, tokenMeta, true, ActionListener.wrap(tokenResult -> { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionAction.java index 123ab949127b6..c4402bb85b453 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionAction.java @@ -118,6 +118,7 @@ private void invalidateTokenPair(Tuple tokenPair, ActionListe private Predicate> containsMetadata(Map requiredMetadata) { return source -> { + @SuppressWarnings("unchecked") Map actualMetadata = (Map) source.get("metadata"); return requiredMetadata.entrySet().stream().allMatch(e -> Objects.equals(actualMetadata.get(e.getKey()), e.getValue())); }; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ApiKeyService.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ApiKeyService.java index e275ea1a30904..a77dfbb1bf088 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ApiKeyService.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ApiKeyService.java @@ -34,18 +34,14 @@ import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.common.cache.RemovalListener; -import org.elasticsearch.common.cache.RemovalNotification.RemovalReason; -import org.elasticsearch.core.CharArrays; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.common.xcontent.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; -import org.elasticsearch.core.Tuple; +import org.elasticsearch.common.cache.RemovalListener; +import org.elasticsearch.common.cache.RemovalNotification.RemovalReason; import org.elasticsearch.common.hash.MessageDigests; import org.elasticsearch.common.logging.DeprecationCategory; import org.elasticsearch.common.logging.DeprecationLogger; @@ -53,7 +49,6 @@ import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException; import org.elasticsearch.common.util.concurrent.FutureUtils; import org.elasticsearch.common.util.concurrent.ListenableFuture; @@ -63,12 +58,17 @@ import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.ObjectParserHelper; +import org.elasticsearch.common.xcontent.ParseField; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentLocation; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.core.CharArrays; +import org.elasticsearch.core.Nullable; +import org.elasticsearch.core.TimeValue; +import org.elasticsearch.core.Tuple; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.license.LicenseUtils; @@ -93,13 +93,12 @@ import org.elasticsearch.xpack.core.security.authz.RoleDescriptor; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.security.support.ApiKeyBoolQueryBuilder; -import org.elasticsearch.xpack.security.support.LockingAtomicCounter; import org.elasticsearch.xpack.security.support.CacheInvalidatorRegistry; import org.elasticsearch.xpack.security.support.FeatureNotEnabledException; import org.elasticsearch.xpack.security.support.FeatureNotEnabledException.Feature; +import org.elasticsearch.xpack.security.support.LockingAtomicCounter; import org.elasticsearch.xpack.security.support.SecurityIndexManager; -import javax.crypto.SecretKeyFactory; import java.io.Closeable; import java.io.IOException; import java.io.UncheckedIOException; @@ -127,10 +126,11 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; +import javax.crypto.SecretKeyFactory; +import static org.elasticsearch.action.bulk.TransportSingleItemBulkWriteAction.toSingleItemBulkRequest; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg; -import static org.elasticsearch.action.bulk.TransportSingleItemBulkWriteAction.toSingleItemBulkRequest; import static org.elasticsearch.search.SearchService.DEFAULT_KEEPALIVE_SETTING; import static org.elasticsearch.xpack.core.ClientHelper.SECURITY_ORIGIN; import static org.elasticsearch.xpack.core.ClientHelper.executeAsyncWithOrigin; @@ -487,7 +487,9 @@ public void getRoleForApiKey(Authentication authentication, ActionListener metadata = authentication.getMetadata(); final String apiKeyId = (String) metadata.get(API_KEY_ID_KEY); + @SuppressWarnings("unchecked") final Map roleDescriptors = (Map) metadata.get(API_KEY_ROLE_DESCRIPTORS_KEY); + @SuppressWarnings("unchecked") final Map authnRoleDescriptors = (Map) metadata.get(API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY); if (roleDescriptors == null && authnRoleDescriptors == null) { @@ -547,6 +549,7 @@ private List parseRoleDescriptors(final String apiKeyId, final M return roleDescriptors.entrySet().stream() .map(entry -> { final String name = entry.getKey(); + @SuppressWarnings("unchecked") final Map rdMap = (Map) entry.getValue(); try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) { builder.map(rdMap); @@ -696,6 +699,7 @@ void validateApiKeyExpiration(ApiKeyDoc apiKeyDoc, ApiKeyCredentials credentials final String principal = Objects.requireNonNull((String) apiKeyDoc.creator.get("principal")); final String fullName = (String) apiKeyDoc.creator.get("full_name"); final String email = (String) apiKeyDoc.creator.get("email"); + @SuppressWarnings("unchecked") Map metadata = (Map) apiKeyDoc.creator.get("metadata"); final User apiKeyUser = new User(principal, Strings.EMPTY_ARRAY, fullName, email, metadata, true); final Map authResultMetadata = new HashMap<>(); @@ -919,8 +923,11 @@ private void findApiKeys(final BoolQueryBuilder boolQuery, boolean filterOutInva Long creation = (Long) source.get("creation_time"); Long expiration = (Long) source.get("expiration_time"); Boolean invalidated = (Boolean) source.get("api_key_invalidated"); + @SuppressWarnings("unchecked") String username = (String) ((Map) source.get("creator")).get("principal"); + @SuppressWarnings("unchecked") String realm = (String) ((Map) source.get("creator")).get("realm"); + @SuppressWarnings("unchecked") Map metadata = (Map) source.get("metadata_flattened"); return new ApiKey(name, id, Instant.ofEpochMilli(creation), (expiration != null) ? Instant.ofEpochMilli(expiration) : null, diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/Realms.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/Realms.java index 0db95c1b2436c..86aa688aa7a7b 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/Realms.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/Realms.java @@ -208,6 +208,7 @@ protected List initRealms(List realmConfigs) throws Exceptio return Collections.unmodifiableList(realms); } + @SuppressWarnings("unchecked") public void usageStats(ActionListener> listener) { final XPackLicenseState licenseStateSnapshot = licenseState.copyCurrentLicenseState(); Map realmMap = new HashMap<>(); @@ -231,6 +232,7 @@ public void usageStats(ActionListener> listener) { } assert value instanceof Map; + @SuppressWarnings("unchecked") Map realmTypeUsage = (Map) value; realmTypeUsage.put("enabled", true); realmTypeUsage.put("available", true); @@ -358,6 +360,7 @@ private void logDeprecationForReservedPrefixedRealmNames(List mapA, Map mapB) { for (Entry entry : mapB.entrySet()) { mapA.compute(entry.getKey(), (key, value) -> { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java index f1fdb937dc74f..4648e80c9714e 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java @@ -45,14 +45,12 @@ import org.elasticsearch.cluster.ClusterStateUpdateTask; import org.elasticsearch.cluster.ack.AckedRequest; import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.core.Nullable; import org.elasticsearch.common.Priority; import org.elasticsearch.common.Strings; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.hash.MessageDigests; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.InputStreamStreamInput; @@ -63,13 +61,15 @@ import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.util.concurrent.AbstractRunnable; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.util.iterable.Iterables; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.core.Nullable; +import org.elasticsearch.core.TimeValue; +import org.elasticsearch.core.Tuple; import org.elasticsearch.core.internal.io.Streams; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.index.engine.VersionConflictEngineException; @@ -97,15 +97,6 @@ import org.elasticsearch.xpack.security.support.FeatureNotEnabledException.Feature; import org.elasticsearch.xpack.security.support.SecurityIndexManager; -import javax.crypto.Cipher; -import javax.crypto.CipherInputStream; -import javax.crypto.CipherOutputStream; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.SecretKey; -import javax.crypto.SecretKeyFactory; -import javax.crypto.spec.GCMParameterSpec; -import javax.crypto.spec.PBEKeySpec; -import javax.crypto.spec.SecretKeySpec; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; @@ -144,6 +135,15 @@ import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collectors; +import javax.crypto.Cipher; +import javax.crypto.CipherInputStream; +import javax.crypto.CipherOutputStream; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; import static org.elasticsearch.action.support.TransportActions.isShardNotAvailableException; import static org.elasticsearch.gateway.GatewayService.STATE_NOT_RECOVERED_BLOCK; @@ -446,6 +446,7 @@ private void getUserTokenFromId(String userTokenId, Version tokenVersion, Action () -> executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, getRequest, ActionListener.wrap(response -> { if (response.isExists()) { + @SuppressWarnings("unchecked") Map accessTokenSource = (Map) response.getSource().get("access_token"); if (accessTokenSource == null) { @@ -455,6 +456,7 @@ private void getUserTokenFromId(String userTokenId, Version tokenVersion, Action onFailure.accept(new IllegalStateException( "token document is missing the user_token field")); } else { + @SuppressWarnings("unchecked") Map userTokenSource = (Map) accessTokenSource.get("user_token"); listener.onResponse(UserToken.fromSourceMap(userTokenSource)); @@ -687,7 +689,7 @@ public void invalidateActiveTokensForRealmAndUser(@Nullable String realmName, @N } }, listener::onFailure)); } else { - Predicate filter = null; + Predicate> filter = null; if (Strings.hasText(username)) { filter = isOfUser(username); } @@ -1291,6 +1293,7 @@ private static Optional checkClientCanRefresh(Re } private static Map getRefreshTokenSourceMap(Map source) { + @SuppressWarnings("unchecked") final Map refreshTokenSource = (Map) source.get("refresh_token"); if (refreshTokenSource == null || refreshTokenSource.isEmpty()) { throw new IllegalStateException("token document is missing the refresh_token object"); @@ -1299,10 +1302,12 @@ private static Map getRefreshTokenSourceMap(Map } private static Map getUserTokenSourceMap(Map source) { + @SuppressWarnings("unchecked") final Map accessTokenSource = (Map) source.get("access_token"); if (accessTokenSource == null || accessTokenSource.isEmpty()) { throw new IllegalStateException("token document is missing the access_token object"); } + @SuppressWarnings("unchecked") final Map userTokenSource = (Map) accessTokenSource.get("user_token"); if (userTokenSource == null || userTokenSource.isEmpty()) { throw new IllegalStateException("token document is missing the user token info"); @@ -1552,7 +1557,9 @@ private Tuple filterAndParseHit(SearchHit hit, @Nullable Pred */ private Tuple parseTokensFromDocument(Map source, @Nullable Predicate> filter) throws IllegalStateException, DateTimeException { + @SuppressWarnings("unchecked") final String hashedRefreshToken = (String) ((Map) source.get("refresh_token")).get("token"); + @SuppressWarnings("unchecked") final Map userTokenSource = (Map) ((Map) source.get("access_token")).get("user_token"); if (null != filter && filter.test(userTokenSource) == false) { @@ -1630,6 +1637,7 @@ private void checkIfTokenIsValid(UserToken userToken, ActionListener ActionListener.wrap(response -> { if (response.isExists()) { Map source = response.getSource(); + @SuppressWarnings("unchecked") Map accessTokenSource = (Map) source.get("access_token"); if (accessTokenSource == null) { onFailure.accept(new IllegalStateException("token document is missing access_token field")); @@ -1998,6 +2006,7 @@ public void onFailure(Exception e) { * Creates a new key unless present that is newer than the current active key and returns the corresponding metadata. Note: * this method doesn't modify the metadata used in this token service. See {@link #refreshMetadata(TokenMetadata)} */ + @SuppressWarnings("unchecked") synchronized TokenMetadata generateSpareKey() { KeyAndCache maxKey = keyCache.cache.values().stream().max(Comparator.comparingLong(v -> v.keyAndTimestamp.getTimestamp())).get(); KeyAndCache currentKey = keyCache.activeKeyCache; @@ -2402,6 +2411,7 @@ static RefreshTokenStatus fromSourceMap(Map refreshTokenSource) if (invalidated == null) { throw new IllegalStateException("token document is missing the \"invalidated\" field"); } + @SuppressWarnings("unchecked") final Map clientInfo = (Map) refreshTokenSource.get("client"); if (clientInfo == null) { throw new IllegalStateException("token document is missing the \"client\" field"); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/UserToken.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/UserToken.java index a1d31dd47d529..63241ed7a5206 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/UserToken.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/UserToken.java @@ -149,6 +149,7 @@ static UserToken fromSourceMap(Map source) throws IllegalStateEx if (versionId == null) { throw new IllegalStateException("user token source document does not have the \"version\" field"); } + @SuppressWarnings("unchecked") final Map metadata = (Map) source.get("metadata"); final String authString = (String) source.get("authentication"); if (authString == null) { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java index 6aaa3c14dbf98..0d9c68f32d62b 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStore.java @@ -611,6 +611,7 @@ private UserAndPassword transformUser(final String id, final Map final String username = id.substring(USER_DOC_TYPE.length() + 1); try { String password = (String) sourceMap.get(Fields.PASSWORD.getPreferredName()); + @SuppressWarnings("unchecked") String[] roles = ((List) sourceMap.get(Fields.ROLES.getPreferredName())).toArray(Strings.EMPTY_ARRAY); String fullName = (String) sourceMap.get(Fields.FULL_NAME.getPreferredName()); String email = (String) sourceMap.get(Fields.EMAIL.getPreferredName()); @@ -619,6 +620,7 @@ private UserAndPassword transformUser(final String id, final Map // fallback mechanism as a user from 2.x may not have the enabled field enabled = Boolean.TRUE; } + @SuppressWarnings("unchecked") Map metadata = (Map) sourceMap.get(Fields.METADATA.getPreferredName()); return new UserAndPassword(new User(username, roles, fullName, email, metadata, enabled), password.toCharArray()); } catch (Exception e) { diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java index 91a2930fcdd05..84d76ea11aef6 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticator.java @@ -6,6 +6,8 @@ */ package org.elasticsearch.xpack.security.authc.oidc; +import net.minidev.json.JSONArray; + import com.nimbusds.jose.JOSEException; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.jwk.JWK; @@ -40,7 +42,7 @@ import com.nimbusds.openid.connect.sdk.token.OIDCTokens; import com.nimbusds.openid.connect.sdk.validators.AccessTokenValidator; import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; -import net.minidev.json.JSONArray; + import org.apache.commons.codec.Charsets; import org.apache.http.Header; import org.apache.http.HttpEntity; @@ -75,11 +77,11 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.SpecialPermission; import org.elasticsearch.action.ActionListener; +import org.elasticsearch.common.Strings; +import org.elasticsearch.common.util.concurrent.ListenableFuture; import org.elasticsearch.core.CheckedRunnable; import org.elasticsearch.core.Nullable; -import org.elasticsearch.common.Strings; import org.elasticsearch.core.Tuple; -import org.elasticsearch.common.util.concurrent.ListenableFuture; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.watcher.FileChangesListener; import org.elasticsearch.watcher.FileWatcher; @@ -90,8 +92,6 @@ import org.elasticsearch.xpack.core.ssl.SSLConfiguration; import org.elasticsearch.xpack.core.ssl.SSLService; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; @@ -110,6 +110,8 @@ import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.ALLOWED_CLOCK_SKEW; import static org.elasticsearch.xpack.core.security.authc.oidc.OpenIdConnectRealmSettings.HTTP_CONNECTION_READ_TIMEOUT; @@ -224,6 +226,7 @@ public void authenticate(OpenIdConnectToken token, final ActionListener claimsListener) { try { @@ -636,8 +639,8 @@ IDTokenValidator createIdTokenValidator(boolean addFileWatcherIfRequired) { if (jwkSetPath.startsWith("http://")) { throw new IllegalArgumentException("The [http] protocol is not supported as it is insecure. Use [https] instead"); } else if (jwkSetPath.startsWith("https://")) { - final JWSVerificationKeySelector keySelector = new JWSVerificationKeySelector(requestedAlgorithm, - new ReloadableJWKSource(new URL(jwkSetPath))); + final JWSVerificationKeySelector keySelector = new JWSVerificationKeySelector<>(requestedAlgorithm, + new ReloadableJWKSource<>(new URL(jwkSetPath))); idTokenValidator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), keySelector, null); } else { if (addFileWatcherIfRequired) { @@ -676,6 +679,7 @@ private void setMetadataFileWatcher(String jwkSetPath) throws IOException { * @return the merged Map */ // pkg protected for testing + @SuppressWarnings("unchecked") static Map mergeObjects(Map idToken, Map userInfo) { for (Map.Entry entry : idToken.entrySet()) { Object value1 = entry.getValue(); @@ -707,6 +711,7 @@ static Map mergeObjects(Map idToken, Map mergeObjects(Map jsonObject1, Object jsonObject2) { if (jsonObject2 == null) { return jsonObject1; diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java index e7a42fc53b339..d7134b2ad8881 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealm.java @@ -392,7 +392,7 @@ public void close() { */ private static boolean isAllowedTypeForClaim(Object o) { return (o instanceof String || o instanceof Boolean || o instanceof Number - || (o instanceof Collection && ((Collection) o).stream() + || (o instanceof Collection && ((Collection) o).stream() .allMatch(c -> c instanceof String || c instanceof Boolean || c instanceof Number))); } @@ -423,6 +423,7 @@ public String toString() { return name; } + @SuppressWarnings("unchecked") private static Collection parseClaimValues(JWTClaimsSet claimsSet, String claimName, String settingKey) { Collection values; final Object claimValueObject = claimsSet.getClaim(claimName); @@ -431,7 +432,7 @@ private static Collection parseClaimValues(JWTClaimsSet claimsSet, Strin } else if (claimValueObject instanceof String) { values = List.of((String) claimValueObject); } else if (claimValueObject instanceof Collection && - ((Collection) claimValueObject).stream().allMatch(c -> c instanceof String)) { + ((Collection) claimValueObject).stream().allMatch(c -> c instanceof String)) { values = (Collection) claimValueObject; } else { throw new SettingsException("Setting [ " + settingKey + " expects a claim with String or a String Array value"); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java index f2de500a6cb8a..9d16bef2c682d 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStore.java @@ -137,7 +137,7 @@ public CompositeRolesStore(Settings settings, FileRolesStore fileRolesStore, Nat builder.setMaximumWeight(cacheSize); } this.roleCache = builder.build(); - this.roleCacheHelper = new CacheIteratorHelper(roleCache); + this.roleCacheHelper = new CacheIteratorHelper<>(roleCache); this.threadContext = threadContext; CacheBuilder nlcBuilder = CacheBuilder.builder(); final int nlcCacheSize = NEGATIVE_LOOKUP_CACHE_SIZE_SETTING.get(settings); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentToken.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentToken.java index 2e385b416fc65..e046f71be09d6 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentToken.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentToken.java @@ -123,6 +123,7 @@ protected URL getHttpInfoUrl() throws MalformedURLException, URISyntaxException return new URL(defaultUrl, (defaultUrl.toURI().getPath() + "/_nodes/_local/http").replaceAll("/+", "/")); } + @SuppressWarnings("unchecked") protected static List getBoundAddresses(Map nodesInfo) { nodesInfo = (Map) nodesInfo.get("nodes"); Map nodeInfo = (Map) nodesInfo.values().iterator().next(); diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyAction.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyAction.java index 50e53a82e86a9..a035abd8b680f 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyAction.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyAction.java @@ -33,6 +33,7 @@ * Rest action to invalidate one or more API keys */ public final class RestInvalidateApiKeyAction extends SecurityBaseRestHandler { + @SuppressWarnings("unchecked") static final ConstructingObjectParser PARSER = new ConstructingObjectParser<>("invalidate_api_key", a -> { return new InvalidateApiKeyRequest((String) a[0], (String) a[1], (String) a[2], diff --git a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/SecurityIndexManager.java b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/SecurityIndexManager.java index 0ccce4c0efcb7..1b5ecdba005f3 100644 --- a/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/SecurityIndexManager.java +++ b/x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/support/SecurityIndexManager.java @@ -283,6 +283,7 @@ private static IndexMetadata resolveConcreteIndex(final String indexOrAliasName, private static Version readMappingVersion(String indexName, MappingMetadata mappingMetadata, Logger logger) { try { + @SuppressWarnings("unchecked") Map meta = (Map) mappingMetadata.sourceAsMap().get("_meta"); if (meta == null) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/test/SettingsFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/test/SettingsFilterTests.java index 5723c40fc39bc..91fef098424d3 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/test/SettingsFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/test/SettingsFilterTests.java @@ -20,14 +20,13 @@ import org.elasticsearch.xpack.security.LocalStateSecurity; import org.hamcrest.Matcher; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.TrustManagerFactory; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.TrustManagerFactory; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.is; @@ -35,7 +34,7 @@ public class SettingsFilterTests extends ESTestCase { private Settings.Builder configuredSettingsBuilder = Settings.builder(); - private Map settingsMatcherMap = new HashMap<>(); + private Map> settingsMatcherMap = new HashMap<>(); private MockSecureSettings mockSecureSettings = new MockSecureSettings(); public void testFiltering() throws Exception { @@ -130,7 +129,7 @@ public void testFiltering() throws Exception { SettingsFilter settingsFilter = injector.getInstance(SettingsFilter.class); Settings filteredSettings = settingsFilter.filter(settings); - for (Map.Entry entry : settingsMatcherMap.entrySet()) { + for (Map.Entry> entry : settingsMatcherMap.entrySet()) { assertThat(filteredSettings.get(entry.getKey()), entry.getValue()); } @@ -154,7 +153,7 @@ private void configureSecureSetting(String settingName, String value) { settingsMatcherMap.put(settingName, is(nullValue())); } - private void configureSetting(String settingName, String value, Matcher expectedMatcher) { + private void configureSetting(String settingName, String value, Matcher expectedMatcher) { configuredSettingsBuilder.put(settingName, value); settingsMatcherMap.put(settingName, expectedMatcher); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityInfoTransportActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityInfoTransportActionTests.java index 4855306acbe69..2a46d58823454 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityInfoTransportActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/SecurityInfoTransportActionTests.java @@ -38,12 +38,12 @@ import java.util.HashMap; import java.util.Map; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; -import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -87,6 +87,7 @@ public void testEnabled() { assertThat(featureSet.enabled(), is(false)); } + @SuppressWarnings("rawtypes") public void testUsage() throws Exception { final boolean explicitlyDisabled = randomBoolean(); final boolean enabled = explicitlyDisabled == false && randomBoolean(); @@ -312,14 +313,16 @@ private XContentSource getXContentSource(XPackFeatureSet.Usage usage) throws IOE private void configureRealmsUsage(Map realmsUsageStats) { doAnswer(invocationOnMock -> { - ActionListener> listener = (ActionListener) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") + ActionListener> listener = (ActionListener>) invocationOnMock.getArguments()[0]; listener.onResponse(realmsUsageStats); return Void.TYPE; - }).when(realms).usageStats(any(ActionListener.class)); + }).when(realms).usageStats(anyActionListener()); } private void configureRoleStoreUsage(boolean rolesStoreEnabled) { doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocationOnMock.getArguments()[0]; if (rolesStoreEnabled) { listener.onResponse(Collections.singletonMap("count", 1)); @@ -327,12 +330,13 @@ private void configureRoleStoreUsage(boolean rolesStoreEnabled) { listener.onResponse(Collections.emptyMap()); } return Void.TYPE; - }).when(rolesStore).usageStats(any(ActionListener.class)); + }).when(rolesStore).usageStats(anyActionListener()); } private void configureRoleMappingStoreUsage(boolean roleMappingStoreEnabled) { doAnswer(invocationOnMock -> { - ActionListener> listener = (ActionListener) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") + ActionListener> listener = (ActionListener>) invocationOnMock.getArguments()[0]; if (roleMappingStoreEnabled) { final Map map = new HashMap<>(); map.put("size", 12L); @@ -342,7 +346,7 @@ private void configureRoleMappingStoreUsage(boolean roleMappingStoreEnabled) { listener.onResponse(Collections.emptyMap()); } return Void.TYPE; - }).when(roleMappingStore).usageStats(any(ActionListener.class)); + }).when(roleMappingStore).usageStats(anyActionListener()); } private SecurityUsageTransportAction newUsageAction(Settings settings) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/TransportGrantApiKeyActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/TransportGrantApiKeyActionTests.java index 5faf19dca2f98..eb421dd0e1dc8 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/TransportGrantApiKeyActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/TransportGrantApiKeyActionTests.java @@ -34,6 +34,7 @@ import java.util.List; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.TestMatchers.throwableWithMessage; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.equalTo; @@ -95,12 +96,13 @@ public void testGrantApiKeyWithUsernamePassword() throws Exception { assertThat(token.principal(), equalTo(username)); assertThat(token.credentials(), equalTo(password)); + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[args.length - 1]; listener.onResponse(authentication); return null; }).when(authenticationService) - .authenticate(eq(GrantApiKeyAction.NAME), same(request), any(UsernamePasswordToken.class), any(ActionListener.class)); + .authenticate(eq(GrantApiKeyAction.NAME), same(request), any(UsernamePasswordToken.class), anyActionListener()); setupApiKeyGenerator(authentication, request, response); @@ -133,12 +135,13 @@ public void testGrantApiKeyWithInvalidUsernamePassword() throws Exception { assertThat(token.principal(), equalTo(username)); assertThat(token.credentials(), equalTo(password)); + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[args.length - 1]; listener.onFailure(new ElasticsearchSecurityException("authentication failed for testing")); return null; }).when(authenticationService) - .authenticate(eq(GrantApiKeyAction.NAME), same(request), any(UsernamePasswordToken.class), any(ActionListener.class)); + .authenticate(eq(GrantApiKeyAction.NAME), same(request), any(UsernamePasswordToken.class), anyActionListener()); setupApiKeyGenerator(authentication, request, response); @@ -221,11 +224,12 @@ private void setupApiKeyGenerator(Authentication authentication, GrantApiKeyRequ assertThat(args[0], equalTo(authentication)); assertThat(args[1], sameInstance(request.getApiKeyRequest())); + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[args.length - 1]; listener.onResponse(response); return null; - }).when(apiKeyGenerator).generateApiKey(any(Authentication.class), any(CreateApiKeyRequest.class), any(ActionListener.class)); + }).when(apiKeyGenerator).generateApiKey(any(Authentication.class), any(CreateApiKeyRequest.class), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentActionTests.java index edefcc4899749..a107188dbe32e 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/enrollment/TransportKibanaEnrollmentActionTests.java @@ -112,7 +112,8 @@ public void testKibanaEnrollment() { public void testKibanaEnrollmentFailedPasswordChange() { // Override change password mock doAnswer(invocation -> { - ActionListener listener = (ActionListener) invocation.getArguments()[2]; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) invocation.getArguments()[2]; listener.onFailure(new ValidationException()); return null; }).when(client).execute(eq(ChangePasswordAction.INSTANCE), any(), any()); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java index 2f5620e787375..37dfe654a7f2d 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/filter/SecurityActionFilterTests.java @@ -47,6 +47,7 @@ import java.util.Collections; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.authz.AuthorizationServiceField.INDICES_PERMISSIONS_KEY; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.is; @@ -62,6 +63,7 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; +@SuppressWarnings({"unchecked", "rawtypes"}) public class SecurityActionFilterTests extends ESTestCase { private AuthenticationService authcService; private AuthorizationService authzService; @@ -115,7 +117,7 @@ public void testApply() throws Exception { ActionResponse actionResponse = mock(ActionResponse.class); mockChain(task, "_action", request, actionResponse); filter.apply(task, "_action", request, listener, chain); - verify(authzService).authorize(eq(authentication), eq("_action"), eq(request), any(ActionListener.class)); + verify(authzService).authorize(eq(authentication), eq("_action"), eq(request), anyActionListener()); verify(auditTrail).coordinatingActionResponse(eq(requestId), eq(authentication), eq("_action"), eq(request), eq(actionResponse)); } @@ -137,7 +139,7 @@ public void testApplyRestoresThreadContext() throws Exception { assertNull(threadContext.getTransient(AuthenticationField.AUTHENTICATION_KEY)); assertNull(threadContext.getTransient(INDICES_PERMISSIONS_KEY)); - verify(authzService).authorize(eq(authentication), eq("_action"), eq(request), any(ActionListener.class)); + verify(authzService).authorize(eq(authentication), eq("_action"), eq(request), anyActionListener()); verify(auditTrail).coordinatingActionResponse(eq(requestId), eq(authentication), eq("_action"), eq(request), eq(actionResponse)); } @@ -178,7 +180,7 @@ public void testApplyAsSystemUser() throws Exception { requestIdFromAuthn.set(AuditUtil.generateRequestId(threadContext)); callback.onResponse(threadContext.getTransient(AuthenticationField.AUTHENTICATION_KEY)); return Void.TYPE; - }).when(authcService).authenticate(eq(action), eq(request), eq(SystemUser.INSTANCE), any(ActionListener.class)); + }).when(authcService).authenticate(eq(action), eq(request), eq(SystemUser.INSTANCE), anyActionListener()); IndicesAccessControl authzAccessControl = mock(IndicesAccessControl.class); mockAuthorize(authzAccessControl); @@ -220,20 +222,20 @@ public void testApplyDestructiveOperations() throws Exception { threadContext.putHeader(AuthenticationField.AUTHENTICATION_KEY, authentication.encode()); callback.onResponse(authentication); return Void.TYPE; - }).when(authcService).authenticate(eq(action), eq(request), eq(SystemUser.INSTANCE), any(ActionListener.class)); + }).when(authcService).authenticate(eq(action), eq(request), eq(SystemUser.INSTANCE), anyActionListener()); doAnswer((i) -> { ActionListener callback = (ActionListener) i.getArguments()[3]; callback.onResponse(null); return Void.TYPE; }).when(authzService) - .authorize(any(Authentication.class), any(String.class), any(TransportRequest.class), any(ActionListener.class)); + .authorize(any(Authentication.class), any(String.class), any(TransportRequest.class), anyActionListener()); filter.apply(task, action, request, listener, chain); if (failDestructiveOperations) { verify(listener).onFailure(isA(IllegalArgumentException.class)); verifyNoMoreInteractions(authzService, chain, auditTrailService, auditTrail); } else { - verify(authzService).authorize(eq(authentication), eq(action), eq(request), any(ActionListener.class)); - verify(chain).proceed(eq(task), eq(action), eq(request), any(ActionListener.class)); + verify(authzService).authorize(eq(authentication), eq(action), eq(request), anyActionListener()); + verify(chain).proceed(eq(task), eq(action), eq(request), anyActionListener()); verify(auditTrail).coordinatingActionResponse(eq(requestIdFromAuthn.get()), eq(authentication), eq(action), eq(request), eq(actionResponse)); } @@ -255,16 +257,16 @@ public void testActionProcessException() throws Exception { AuditUtil.generateRequestId(threadContext); callback.onResponse(authentication); return Void.TYPE; - }).when(authcService).authenticate(eq("_action"), eq(request), eq(SystemUser.INSTANCE), any(ActionListener.class)); + }).when(authcService).authenticate(eq("_action"), eq(request), eq(SystemUser.INSTANCE), anyActionListener()); if (randomBoolean()) { - doThrow(exception).when(authzService).authorize(eq(authentication), eq("_action"), eq(request), any(ActionListener.class)); + doThrow(exception).when(authzService).authorize(eq(authentication), eq("_action"), eq(request), anyActionListener()); } else { doAnswer((i) -> { ActionListener callback = (ActionListener) i.getArguments()[3]; callback.onFailure(exception); return Void.TYPE; }).when(authzService) - .authorize(eq(authentication), eq("_action"), eq(request), any(ActionListener.class)); + .authorize(eq(authentication), eq("_action"), eq(request), anyActionListener()); } filter.apply(task, "_action", request, listener, chain); verify(listener).onFailure(exception); @@ -294,7 +296,7 @@ private void mockAuthentication(ActionRequest request, Authentication authentica threadContext.putHeader("_xpack_audit_request_id", requestId); callback.onResponse(authentication); return Void.TYPE; - }).when(authcService).authenticate(eq("_action"), eq(request), eq(SystemUser.INSTANCE), any(ActionListener.class)); + }).when(authcService).authenticate(eq("_action"), eq(request), eq(SystemUser.INSTANCE), anyActionListener()); } private void mockAuthorize() { @@ -311,7 +313,7 @@ private void mockAuthorize(IndicesAccessControl indicesAccessControl) { callback.onResponse(null); return Void.TYPE; }).when(authzService) - .authorize(any(Authentication.class), any(String.class), any(TransportRequest.class), any(ActionListener.class)); + .authorize(any(Authentication.class), any(String.class), any(TransportRequest.class), anyActionListener()); } private void mockChain(Task task, String action, ActionRequest request, ActionResponse actionResponse) { @@ -321,6 +323,6 @@ private void mockChain(Task task, String action, ActionRequest request, ActionRe ActionListener callback = (ActionListener) args[args.length - 1]; callback.onResponse(actionResponse); return Void.TYPE; - }).when(chain).proceed(eq(task), eq(action), eq(request), any(ActionListener.class)); + }).when(chain).proceed(eq(task), eq(action), eq(request), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java index 0e582f5bee390..f04c451e22d86 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/oidc/TransportOpenIdConnectLogoutActionTests.java @@ -67,6 +67,7 @@ import java.util.Map; import java.util.function.Consumer; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.security.authc.TokenServiceTests.mockGetTokenFromId; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -133,40 +134,43 @@ public void setup() throws Exception { }).when(client).prepareBulk(); doAnswer(invocationOnMock -> { IndexRequest indexRequest = (IndexRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; indexRequests.add(indexRequest); final IndexResponse response = new IndexResponse( indexRequest.shardId(), indexRequest.id(), 1, 1, 1, true); listener.onResponse(response); return Void.TYPE; - }).when(client).index(any(IndexRequest.class), any(ActionListener.class)); + }).when(client).index(any(IndexRequest.class), anyActionListener()); doAnswer(invocationOnMock -> { IndexRequest indexRequest = (IndexRequest) invocationOnMock.getArguments()[1]; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[2]; indexRequests.add(indexRequest); final IndexResponse response = new IndexResponse( new ShardId("test", "test", 0), indexRequest.id(), 1, 1, 1, true); listener.onResponse(response); return Void.TYPE; - }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), any(ActionListener.class)); + }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), anyActionListener()); doAnswer(invocationOnMock -> { BulkRequest bulkRequest = (BulkRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; bulkRequests.add(bulkRequest); final BulkResponse response = new BulkResponse(new BulkItemResponse[0], 1); listener.onResponse(response); return Void.TYPE; - }).when(client).bulk(any(BulkRequest.class), any(ActionListener.class)); + }).when(client).bulk(any(BulkRequest.class), anyActionListener()); final SecurityIndexManager securityIndex = mock(SecurityIndexManager.class); doAnswer(inv -> { ((Runnable) inv.getArguments()[1]).run(); return null; - }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).prepareIndexIfNeededThenExecute(anyConsumer(), any(Runnable.class)); doAnswer(inv -> { ((Runnable) inv.getArguments()[1]).run(); return null; - }).when(securityIndex).checkIndexVersionThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).checkIndexVersionThenExecute(anyConsumer(), any(Runnable.class)); when(securityIndex.isAvailable()).thenReturn(true); when(securityIndex.freeze()).thenReturn(securityIndex); @@ -236,4 +240,9 @@ public void testLogoutInvalidatesTokens() throws Exception { public void cleanup() { oidcRealm.close(); } + + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java index 2d0f833da02d5..1dfa1425ce4b2 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java @@ -18,20 +18,18 @@ import org.elasticsearch.xpack.core.security.action.role.DeleteRoleResponse; import org.elasticsearch.xpack.core.security.authz.store.ReservedRolesStore; import org.elasticsearch.xpack.security.authz.store.NativeRolesStore; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -84,16 +82,14 @@ public void testValidRole() { request.name(roleName); final boolean found = randomBoolean(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onResponse(found); - return null; - } - }).when(rolesStore).deleteRole(eq(request), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[1]; + listener.onResponse(found); + return null; + }).when(rolesStore).deleteRole(eq(request), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -112,7 +108,7 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().found(), is(found)); assertThat(throwableRef.get(), is(nullValue())); - verify(rolesStore, times(1)).deleteRole(eq(request), any(ActionListener.class)); + verify(rolesStore, times(1)).deleteRole(eq(request), anyActionListener()); } public void testException() { @@ -126,16 +122,14 @@ public void testException() { DeleteRoleRequest request = new DeleteRoleRequest(); request.name(roleName); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onFailure(e); - return null; - } - }).when(rolesStore).deleteRole(eq(request), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[1]; + listener.onFailure(e); + return null; + }).when(rolesStore).deleteRole(eq(request), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -154,6 +148,6 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(nullValue())); assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), is(sameInstance(e))); - verify(rolesStore, times(1)).deleteRole(eq(request), any(ActionListener.class)); + verify(rolesStore, times(1)).deleteRole(eq(request), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportGetRolesActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportGetRolesActionTests.java index 2241bb9b27b39..8c3e34ad50566 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportGetRolesActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportGetRolesActionTests.java @@ -31,11 +31,11 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -60,10 +60,11 @@ public void testReservedRoles() { doAnswer(invocation -> { Object[] args = invocation.getArguments(); assert args.length == 2; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[1]; listener.onResponse(RoleRetrievalResult.success(Collections.emptySet())); return null; - }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>()), any(ActionListener.class)); + }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>()), anyActionListener()); GetRolesRequest request = new GetRolesRequest(); request.names(names.toArray(Strings.EMPTY_ARRAY)); @@ -104,10 +105,11 @@ public void testStoreRoles() { doAnswer(invocation -> { Object[] args = invocation.getArguments(); assert args.length == 2; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[1]; listener.onResponse(RoleRetrievalResult.success(new HashSet<>(storeRoleDescriptors))); return null; - }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>(Arrays.asList(request.names()))), any(ActionListener.class)); + }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>(Arrays.asList(request.names()))), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -164,7 +166,9 @@ public void testGetAllOrMix() { doAnswer(invocation -> { Object[] args = invocation.getArguments(); assert args.length == 2; + @SuppressWarnings("unchecked") Set requestedNames1 = (Set) args[0]; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[1]; if (requestedNames1.size() == 0) { listener.onResponse(RoleRetrievalResult.success(new HashSet<>(storeRoleDescriptors))); @@ -174,7 +178,7 @@ public void testGetAllOrMix() { .collect(Collectors.toSet()))); } return null; - }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>(specificStoreNames)), any(ActionListener.class)); + }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>(specificStoreNames)), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -197,10 +201,10 @@ public void onFailure(Exception e) { assertThat(retrievedRoleNames, containsInAnyOrder(expectedNames.toArray(Strings.EMPTY_ARRAY))); if (all) { - verify(rolesStore, times(1)).getRoleDescriptors(eq(new HashSet<>()), any(ActionListener.class)); + verify(rolesStore, times(1)).getRoleDescriptors(eq(new HashSet<>()), anyActionListener()); } else { verify(rolesStore, times(1)) - .getRoleDescriptors(eq(new HashSet<>(specificStoreNames)), any(ActionListener.class)); + .getRoleDescriptors(eq(new HashSet<>(specificStoreNames)), anyActionListener()); } } @@ -219,10 +223,11 @@ public void testException() { doAnswer(invocation -> { Object[] args = invocation.getArguments(); assert args.length == 2; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[1]; listener.onFailure(e); return null; - }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>(Arrays.asList(request.names()))), any(ActionListener.class)); + }).when(rolesStore).getRoleDescriptors(eq(new HashSet<>(Arrays.asList(request.names()))), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportPutRoleActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportPutRoleActionTests.java index c922b1dfbd625..f4f3019d4ba5c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportPutRoleActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportPutRoleActionTests.java @@ -10,12 +10,12 @@ import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; -import org.elasticsearch.common.xcontent.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.NamedXContentRegistry; +import org.elasticsearch.common.xcontent.ParseField; import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.TermQueryBuilder; @@ -30,14 +30,13 @@ import org.elasticsearch.xpack.core.security.authz.RoleDescriptor; import org.elasticsearch.xpack.core.security.authz.store.ReservedRolesStore; import org.elasticsearch.xpack.security.authz.store.NativeRolesStore; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; @@ -110,16 +109,14 @@ public void testValidRole() { PutRoleRequest request = new PutRoleRequest(); request.name(roleName); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - assert args.length == 3; - ActionListener listener = (ActionListener) args[2]; - listener.onResponse(created); - return null; - } - }).when(rolesStore).putRole(eq(request), any(RoleDescriptor.class), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 3; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[2]; + listener.onResponse(created); + return null; + }).when(rolesStore).putRole(eq(request), any(RoleDescriptor.class), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -138,7 +135,7 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().isCreated(), is(created)); assertThat(throwableRef.get(), is(nullValue())); - verify(rolesStore, times(1)).putRole(eq(request), any(RoleDescriptor.class), any(ActionListener.class)); + verify(rolesStore, times(1)).putRole(eq(request), any(RoleDescriptor.class), anyActionListener()); } public void testException() { @@ -153,16 +150,14 @@ public void testException() { PutRoleRequest request = new PutRoleRequest(); request.name(roleName); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - assert args.length == 3; - ActionListener listener = (ActionListener) args[2]; - listener.onFailure(e); - return null; - } - }).when(rolesStore).putRole(eq(request), any(RoleDescriptor.class), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 3; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[2]; + listener.onFailure(e); + return null; + }).when(rolesStore).putRole(eq(request), any(RoleDescriptor.class), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -181,7 +176,7 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(nullValue())); assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), is(sameInstance(e))); - verify(rolesStore, times(1)).putRole(eq(request), any(RoleDescriptor.class), any(ActionListener.class)); + verify(rolesStore, times(1)).putRole(eq(request), any(RoleDescriptor.class), anyActionListener()); } public void testCreationOfRoleWithMalformedQueryJsonFails() { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java index 3f0485adbf7c1..4a455d7349fff 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportGetRoleMappingsActionTests.java @@ -43,6 +43,7 @@ public class TransportGetRoleMappingsActionTests extends ESTestCase { private AtomicReference> namesRef; private List result; + @SuppressWarnings("unchecked") @Before public void setupMocks() { store = mock(NativeRoleMappingStore.class); @@ -57,7 +58,7 @@ public void setupMocks() { Object[] args = invocation.getArguments(); assert args.length == 2; namesRef.set((Set) args[0]); - ActionListener> listener = (ActionListener) args[1]; + ActionListener> listener = (ActionListener>) args[1]; listener.onResponse(result); return null; }).when(store).getRoleMappings(any(Set.class), any(ActionListener.class)); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportPutRoleMappingActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportPutRoleMappingActionTests.java index 2cdcd9fef564d..0a4e3b17876d9 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportPutRoleMappingActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/rolemapping/TransportPutRoleMappingActionTests.java @@ -40,6 +40,7 @@ public class TransportPutRoleMappingActionTests extends ESTestCase { private TransportPutRoleMappingAction action; private AtomicReference requestRef; + @SuppressWarnings("unchecked") @Before public void setupMocks() { store = mock(NativeRoleMappingStore.class); @@ -53,7 +54,7 @@ public void setupMocks() { Object[] args = invocation.getArguments(); assert args.length == 2; requestRef.set((PutRoleMappingRequest) args[0]); - ActionListener listener = (ActionListener) args[1]; + ActionListener listener = (ActionListener) args[1]; listener.onResponse(true); return null; }).when(store).putRoleMapping(any(PutRoleMappingRequest.class), any(ActionListener.class) diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionActionTests.java index e9d8ec836f8c9..9d2276c89dd12 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionActionTests.java @@ -148,6 +148,7 @@ public void setup() throws Exception { bulkRequests = new ArrayList<>(); final Client client = new NoOpClient(threadPool) { @Override + @SuppressWarnings("unchecked") protected void doExecute(ActionType action, Request request, ActionListener listener) { if (IndexAction.NAME.equals(action.name())) { @@ -195,11 +196,11 @@ void doExecute(ActionType action, Request request, ActionListener { ((Runnable) inv.getArguments()[1]).run(); return null; - }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).prepareIndexIfNeededThenExecute(anyConsumer(), any(Runnable.class)); doAnswer(inv -> { ((Runnable) inv.getArguments()[1]).run(); return null; - }).when(securityIndex).checkIndexVersionThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).checkIndexVersionThenExecute(anyConsumer(), any(Runnable.class)); when(securityIndex.isAvailable()).thenReturn(true); when(securityIndex.indexExists()).thenReturn(true); when(securityIndex.isIndexUpToDate()).thenReturn(true); @@ -244,7 +245,9 @@ private SearchHit tokenHit(int idx, BytesReference source) { try { final Map sourceMap = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, source.streamInput()).map(); + @SuppressWarnings("unchecked") final Map accessToken = (Map) sourceMap.get("access_token"); + @SuppressWarnings("unchecked") final Map userToken = (Map) accessToken.get("user_token"); final SearchHit hit = new SearchHit(idx, "token_" + userToken.get("id"), null, null); hit.sourceRef(source); @@ -366,6 +369,7 @@ private Function findTokenByRefreshToken(SearchHit[] final TermQueryBuilder termQuery = (TermQueryBuilder) filters.get(1); assertThat(termQuery.fieldName(), equalTo("refresh_token.token")); for (SearchHit hit : searchHits) { + @SuppressWarnings("unchecked") final Map refreshToken = (Map) hit.getSourceAsMap().get("refresh_token"); if (termQuery.value().equals(refreshToken.get("token"))) { return new SearchHit[]{hit}; @@ -390,4 +394,8 @@ private TokenService.CreateTokenResult storeToken(SamlNameId nameId, String sess return storeToken(userTokenId, refreshToken, nameId, session); } + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java index 05ff6a0e70fd8..9d1691971f9e9 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/saml/TransportSamlLogoutActionTests.java @@ -104,6 +104,7 @@ public class TransportSamlLogoutActionTests extends SamlTestCase { private TransportSamlLogoutAction action; private Client client; + @SuppressWarnings("unchecked") @Before public void setup() throws Exception { final RealmIdentifier realmIdentifier = new RealmIdentifier("saml", REALM_NAME); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportDeleteServiceAccountTokenActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportDeleteServiceAccountTokenActionTests.java index 641a50c42ceb3..3c191514be1a5 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportDeleteServiceAccountTokenActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportDeleteServiceAccountTokenActionTests.java @@ -13,12 +13,14 @@ import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.TransportService; import org.elasticsearch.xpack.core.security.action.service.DeleteServiceAccountTokenRequest; +import org.elasticsearch.xpack.core.security.action.service.DeleteServiceAccountTokenResponse; import org.elasticsearch.xpack.security.authc.service.IndexServiceAccountTokenStore; import org.elasticsearch.xpack.security.authc.support.HttpTlsRuntimeCheck; import org.junit.Before; import java.util.Collections; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; @@ -45,13 +47,12 @@ public void init() { }).when(httpTlsRuntimeCheck).checkTlsThenExecute(any(), any(), any()); } - @SuppressWarnings("rawtypes") public void testDoExecuteWillDelegate() { final DeleteServiceAccountTokenRequest request = new DeleteServiceAccountTokenRequest( randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8)); - final ActionListener listener = mock(ActionListener.class); + @SuppressWarnings("unchecked") final ActionListener listener = mock(ActionListener.class); transportDeleteServiceAccountTokenAction.doExecute(mock(Task.class), request, listener); - verify(indexServiceAccountTokenStore).deleteToken(eq(request), any(ActionListener.class)); + verify(indexServiceAccountTokenStore).deleteToken(eq(request), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportGetServiceAccountCredentialsActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportGetServiceAccountCredentialsActionTests.java index 8bdd72676075a..4122ff6072200 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportGetServiceAccountCredentialsActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/service/TransportGetServiceAccountCredentialsActionTests.java @@ -12,10 +12,10 @@ import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.PlainActionFuture; -import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.TransportAddress; +import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.tasks.Task; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.transport.Transport; @@ -74,9 +74,8 @@ public void init() throws UnknownHostException { public void testDoExecuteWillDelegate() { final GetServiceAccountCredentialsRequest request = new GetServiceAccountCredentialsRequest(randomAlphaOfLengthBetween(3, 8), randomAlphaOfLengthBetween(3, 8)); - @SuppressWarnings("rawtypes") - final ActionListener listener = mock(ActionListener.class); - //noinspection unchecked + @SuppressWarnings("unchecked") + final ActionListener listener = mock(ActionListener.class); transportGetServiceAccountCredentialsAction.doExecute(mock(Task.class), request, listener); verify(serviceAccountService).findTokensFor( eq(new ServiceAccount.ServiceAccountId(request.getNamespace(), request.getServiceName())), diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java index 0d2ef10fa1278..73b0a0082ffd1 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/token/TransportCreateTokenActionTests.java @@ -68,6 +68,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.mockito.Matchers.any; @@ -107,6 +108,7 @@ public void setupClient() { }).when(client).prepareGet(anyString(), anyString()); when(client.prepareMultiGet()).thenReturn(new MultiGetRequestBuilder(client, MultiGetAction.INSTANCE)); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; MultiGetResponse response = mock(MultiGetResponse.class); MultiGetItemResponse[] responses = new MultiGetItemResponse[2]; @@ -121,18 +123,19 @@ public void setupClient() { when(getResponse.isExists()).thenReturn(false); listener.onResponse(response); return Void.TYPE; - }).when(client).multiGet(any(MultiGetRequest.class), any(ActionListener.class)); + }).when(client).multiGet(any(MultiGetRequest.class), anyActionListener()); when(client.prepareIndex(any(String.class))) .thenReturn(new IndexRequestBuilder(client, IndexAction.INSTANCE)); when(client.prepareUpdate(any(String.class), any(String.class))) .thenReturn(new UpdateRequestBuilder(client, UpdateAction.INSTANCE)); doAnswer(invocationOnMock -> { idxReqReference.set((IndexRequest) invocationOnMock.getArguments()[1]); + @SuppressWarnings("unchecked") ActionListener responseActionListener = (ActionListener) invocationOnMock.getArguments()[2]; responseActionListener.onResponse(new IndexResponse(new ShardId(".security", UUIDs.randomBase64UUID(), randomInt()), randomAlphaOfLength(4), randomNonNegativeLong(), randomNonNegativeLong(), randomNonNegativeLong(), true)); return null; - }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), any(ActionListener.class)); + }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), anyActionListener()); securityContext = new SecurityContext(Settings.EMPTY, threadPool.getThreadContext()); @@ -142,10 +145,11 @@ public void setupClient() { Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; runnable.run(); return null; - }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).prepareIndexIfNeededThenExecute(anyConsumer(), any(Runnable.class)); doAnswer(invocationOnMock -> { AuthenticationToken authToken = (AuthenticationToken) invocationOnMock.getArguments()[2]; + @SuppressWarnings("unchecked") ActionListener authListener = (ActionListener) invocationOnMock.getArguments()[3]; User user = null; if (authToken instanceof UsernamePasswordToken) { @@ -169,7 +173,7 @@ && new String((byte[]) token.credentials(), StandardCharsets.UTF_8).equals("fail authListener.onResponse(authentication); return Void.TYPE; }).when(authenticationService).authenticate(eq(CreateTokenAction.NAME), any(CreateTokenRequest.class), - any(AuthenticationToken.class), any(ActionListener.class)); + any(AuthenticationToken.class), anyActionListener()); this.clusterService = ClusterServiceUtils.createClusterService(threadPool); @@ -327,4 +331,9 @@ private static ActionListener assertListenerIsOnlyCalledOnce(ActionListen } }); } + + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java index 6a4a7aecfdb7b..3a8f55f68de22 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportChangePasswordActionTests.java @@ -28,13 +28,12 @@ import org.elasticsearch.xpack.core.security.user.XPackSecurityUser; import org.elasticsearch.xpack.core.security.user.XPackUser; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.Collections; import java.util.Locale; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.SecurityIntegTestCase.getFastStoredHashAlgoForTests; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; @@ -42,7 +41,6 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -132,10 +130,11 @@ public void testValidUser() { doAnswer(invocation -> { Object[] args = invocation.getArguments(); assert args.length == 2; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) args[1]; listener.onResponse(null); return null; - }).when(usersStore).changePassword(eq(request), any(ActionListener.class)); + }).when(usersStore).changePassword(eq(request), anyActionListener()); TransportService transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet()); Settings passwordHashingSettings = Settings.builder(). @@ -159,7 +158,7 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(notNullValue())); assertSame(responseRef.get(), ActionResponse.Empty.INSTANCE); assertThat(throwableRef.get(), is(nullValue())); - verify(usersStore, times(1)).changePassword(eq(request), any(ActionListener.class)); + verify(usersStore, times(1)).changePassword(eq(request), anyActionListener()); } public void testIncorrectPasswordHashingAlgorithm() { @@ -205,15 +204,14 @@ public void testException() { request.username(user.principal()); request.passwordHash(hasher.hash(SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)); final Exception e = randomFrom(new ElasticsearchSecurityException(""), new IllegalStateException(), new RuntimeException()); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onFailure(e); - return null; - } - }).when(usersStore).changePassword(eq(request), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[1]; + listener.onFailure(e); + return null; + }).when(usersStore).changePassword(eq(request), anyActionListener()); TransportService transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet()); Settings passwordHashingSettings = Settings.builder(). @@ -237,6 +235,6 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(nullValue())); assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), sameInstance(e)); - verify(usersStore, times(1)).changePassword(eq(request), any(ActionListener.class)); + verify(usersStore, times(1)).changePassword(eq(request), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportDeleteUserActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportDeleteUserActionTests.java index d865dc558c025..daa2ab5b7241f 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportDeleteUserActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportDeleteUserActionTests.java @@ -25,19 +25,17 @@ import org.elasticsearch.xpack.core.security.user.XPackSecurityUser; import org.elasticsearch.xpack.core.security.user.XPackUser; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -146,15 +144,14 @@ public void testValidUser() { final boolean found = randomBoolean(); final DeleteUserRequest request = new DeleteUserRequest(user.principal()); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onResponse(found); - return null; - } - }).when(usersStore).deleteUser(eq(request), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[1]; + listener.onResponse(found); + return null; + }).when(usersStore).deleteUser(eq(request), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -173,7 +170,7 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().found(), is(found)); assertThat(throwableRef.get(), is(nullValue())); - verify(usersStore, times(1)).deleteUser(eq(request), any(ActionListener.class)); + verify(usersStore, times(1)).deleteUser(eq(request), anyActionListener()); } public void testException() { @@ -186,15 +183,14 @@ public void testException() { usersStore, transportService); final DeleteUserRequest request = new DeleteUserRequest(user.principal()); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onFailure(e); - return null; - } - }).when(usersStore).deleteUser(eq(request), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[1]; + listener.onFailure(e); + return null; + }).when(usersStore).deleteUser(eq(request), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -213,6 +209,6 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(nullValue())); assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), sameInstance(e)); - verify(usersStore, times(1)).deleteUser(eq(request), any(ActionListener.class)); + verify(usersStore, times(1)).deleteUser(eq(request), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportGetUsersActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportGetUsersActionTests.java index 25589e6f1b58c..ea97f4bd26755 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportGetUsersActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportGetUsersActionTests.java @@ -34,8 +34,6 @@ import org.elasticsearch.xpack.security.support.SecurityIndexManager; import org.junit.After; import org.junit.Before; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.ArrayList; import java.util.Arrays; @@ -45,6 +43,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.emptyArray; @@ -54,7 +53,6 @@ import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; import static org.mockito.AdditionalMatchers.aryEq; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -218,15 +216,14 @@ public void testGetAllUsers() { usersStore, transportService, reservedRealm); GetUsersRequest request = new GetUsersRequest(); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener> listener = (ActionListener>) args[1]; - listener.onResponse(storeUsers); - return null; - } - }).when(usersStore).getUsers(eq(Strings.EMPTY_ARRAY), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener> listener = (ActionListener>) args[1]; + listener.onResponse(storeUsers); + return null; + }).when(usersStore).getUsers(eq(Strings.EMPTY_ARRAY), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -251,7 +248,7 @@ public void onFailure(Exception e) { assertThat(throwableRef.get(), is(nullValue())); assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().users(), arrayContaining(expectedList.toArray(new User[expectedList.size()]))); - verify(usersStore, times(1)).getUsers(aryEq(Strings.EMPTY_ARRAY), any(ActionListener.class)); + verify(usersStore, times(1)).getUsers(aryEq(Strings.EMPTY_ARRAY), anyActionListener()); } public void testGetStoreOnlyUsers() { @@ -269,10 +266,11 @@ public void testGetStoreOnlyUsers() { doAnswer(invocation -> { Object[] args = invocation.getArguments(); assert args.length == 2; + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) args[1]; listener.onResponse(storeUsers); return null; - }).when(usersStore).getUsers(aryEq(storeUsernames), any(ActionListener.class)); + }).when(usersStore).getUsers(aryEq(storeUsernames), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -295,9 +293,9 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().users(), arrayContaining(expectedList.toArray(new User[expectedList.size()]))); if (storeUsers.size() > 1) { - verify(usersStore, times(1)).getUsers(aryEq(storeUsernames), any(ActionListener.class)); + verify(usersStore, times(1)).getUsers(aryEq(storeUsernames), anyActionListener()); } else { - verify(usersStore, times(1)).getUsers(aryEq(new String[] {storeUsernames[0]}), any(ActionListener.class)); + verify(usersStore, times(1)).getUsers(aryEq(new String[] {storeUsernames[0]}), anyActionListener()); } } @@ -317,10 +315,11 @@ public void testException() { doAnswer(invocation -> { Object[] args = invocation.getArguments(); assert args.length == 2; + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) args[1]; listener.onFailure(e); return null; - }).when(usersStore).getUsers(aryEq(storeUsernames), any(ActionListener.class)); + }).when(usersStore).getUsers(aryEq(storeUsernames), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -339,7 +338,7 @@ public void onFailure(Exception e) { assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), is(sameInstance(e))); assertThat(responseRef.get(), is(nullValue())); - verify(usersStore, times(1)).getUsers(aryEq(storeUsernames), any(ActionListener.class)); + verify(usersStore, times(1)).getUsers(aryEq(storeUsernames), anyActionListener()); } private List randomUsers() { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java index 51884da6590ea..e489d36c7c544 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportPutUserActionTests.java @@ -34,13 +34,12 @@ import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealmTests; import org.elasticsearch.xpack.security.support.SecurityIndexManager; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.Collection; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.SecurityIntegTestCase.getFastStoredHashAlgoForTests; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; @@ -49,7 +48,6 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -177,15 +175,14 @@ public void testValidUser() { request.passwordHash(hasher.hash(SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING)); } final boolean created = isCreate ? randomBoolean() : false; // updates should always return false for create - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onResponse(created); - return null; - } - }).when(usersStore).putUser(eq(request), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[1]; + listener.onResponse(created); + return null; + }).when(usersStore).putUser(eq(request), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -204,7 +201,7 @@ public void onFailure(Exception e) { assertThat(throwableRef.get(), is(nullValue())); assertThat(responseRef.get(), is(notNullValue())); assertThat(responseRef.get().created(), is(created)); - verify(usersStore, times(1)).putUser(eq(request), any(ActionListener.class)); + verify(usersStore, times(1)).putUser(eq(request), anyActionListener()); } public void testInvalidUser() { @@ -238,15 +235,14 @@ public void testException() { final PutUserRequest request = new PutUserRequest(); request.username(user.principal()); - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 2; - ActionListener listener = (ActionListener) args[1]; - listener.onFailure(e); - return null; - } - }).when(usersStore).putUser(eq(request), any(ActionListener.class)); + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 2; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[1]; + listener.onFailure(e); + return null; + }).when(usersStore).putUser(eq(request), anyActionListener()); final AtomicReference throwableRef = new AtomicReference<>(); final AtomicReference responseRef = new AtomicReference<>(); @@ -265,6 +261,6 @@ public void onFailure(Exception e) { assertThat(responseRef.get(), is(nullValue())); assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), sameInstance(e)); - verify(usersStore, times(1)).putUser(eq(request), any(ActionListener.class)); + verify(usersStore, times(1)).putUser(eq(request), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportSetEnabledActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportSetEnabledActionTests.java index 3aef0d7ada90e..de2f597a8f940 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportSetEnabledActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/user/TransportSetEnabledActionTests.java @@ -31,19 +31,17 @@ import org.elasticsearch.xpack.core.security.user.XPackSecurityUser; import org.elasticsearch.xpack.core.security.user.XPackUser; import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.sameInstance; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -159,16 +157,15 @@ public void testValidUser() throws Exception { request.enabled(randomBoolean()); request.setRefreshPolicy(randomFrom(RefreshPolicy.values())); // mock the setEnabled call on the native users store so that it will invoke the action listener with a response - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 4; - ActionListener listener = (ActionListener) args[3]; - listener.onResponse(null); - return null; - } + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 4; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[3]; + listener.onResponse(null); + return null; }).when(usersStore) - .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), any(ActionListener.class)); + .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), anyActionListener()); TransportService transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet()); final SecurityContext securityContext = new SecurityContext(Settings.EMPTY, threadContext); @@ -193,7 +190,7 @@ public void onFailure(Exception e) { assertSame(responseRef.get(), ActionResponse.Empty.INSTANCE); assertThat(throwableRef.get(), is(nullValue())); verify(usersStore, times(1)) - .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), any(ActionListener.class)); + .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), anyActionListener()); } public void testException() throws Exception { @@ -214,16 +211,15 @@ public void testException() throws Exception { request.setRefreshPolicy(randomFrom(RefreshPolicy.values())); final Exception e = randomFrom(new ElasticsearchSecurityException(""), new IllegalStateException(), new RuntimeException()); // we're mocking the setEnabled call on the native users store so that it will invoke the action listener with an exception - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) { - Object[] args = invocation.getArguments(); - assert args.length == 4; - ActionListener listener = (ActionListener) args[3]; - listener.onFailure(e); - return null; - } + doAnswer(invocation -> { + Object[] args = invocation.getArguments(); + assert args.length == 4; + @SuppressWarnings("unchecked") + ActionListener listener = (ActionListener) args[3]; + listener.onFailure(e); + return null; }).when(usersStore) - .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), any(ActionListener.class)); + .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), anyActionListener()); TransportService transportService = new TransportService(Settings.EMPTY, mock(Transport.class), null, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null, Collections.emptySet()); final SecurityContext securityContext = new SecurityContext(Settings.EMPTY, threadContext); @@ -248,7 +244,7 @@ public void onFailure(Exception e) { assertThat(throwableRef.get(), is(notNullValue())); assertThat(throwableRef.get(), sameInstance(e)); verify(usersStore, times(1)) - .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), any(ActionListener.class)); + .setEnabled(eq(user.principal()), eq(request.enabled()), eq(request.getRefreshPolicy()), anyActionListener()); } public void testUserModifyingThemselves() throws Exception { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java index 042f2ba71cccd..ab57c6fc497b3 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ApiKeyServiceTests.java @@ -107,6 +107,7 @@ import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.SecurityIntegTestCase.getFastStoredHashAlgoForTests; import static org.elasticsearch.test.TestMatchers.throwableWithMessage; import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY; @@ -519,6 +520,7 @@ public void testGetRolesForApiKeyNotInContext() throws Exception { assertThat(result.getRoleDescriptors().get(0).getName(), is("superuser")); } + @SuppressWarnings("unchecked") public void testGetRolesForApiKey() throws Exception { Map authMetadata = new HashMap<>(); authMetadata.put(ApiKeyService.API_KEY_ID_KEY, randomAlphaOfLength(12)); @@ -563,7 +565,7 @@ public void testGetRolesForApiKey() throws Exception { listener.onResponse(Collections.emptyList()); return null; } - ).when(privilegesStore).getPrivileges(any(Collection.class), any(Collection.class), any(ActionListener.class)); + ).when(privilegesStore).getPrivileges(any(Collection.class), any(Collection.class), anyActionListener()); ApiKeyService service = createApiKeyService(Settings.EMPTY); PlainActionFuture roleFuture = new PlainActionFuture<>(); @@ -857,7 +859,7 @@ public void testAuthenticateWhileCacheBeingPopulated() throws Exception { hashCounter.incrementAndGet(); hashWait.acquire(); return invocationOnMock.callRealMethod(); - }).when(service).verifyKeyAgainstHash(any(String.class), any(ApiKeyCredentials.class), any(ActionListener.class)); + }).when(service).verifyKeyAgainstHash(any(String.class), any(ApiKeyCredentials.class), anyActionListener()); final ApiKeyCredentials creds = new ApiKeyCredentials(randomAlphaOfLength(12), new SecureString(apiKey.toCharArray())); final PlainActionFuture future1 = new PlainActionFuture<>(); @@ -1036,7 +1038,7 @@ public void testApiKeyDocCache() throws IOException, ExecutionException, Interru mockKeyDocument(service, docId, apiKey, new User("hulk", "superuser"), false, Duration.ofSeconds(3600)); PlainActionFuture future4 = new PlainActionFuture<>(); service.loadApiKeyAndValidateCredentials(threadContext, apiKeyCredentials, future4); - verify(client, times(4)).get(any(GetRequest.class), any(ActionListener.class)); + verify(client, times(4)).get(any(GetRequest.class), anyActionListener()); assertEquals(2, service.getRoleDescriptorsBytesCache().count()); final AuthenticationResult authResult4 = future4.get(); assertSame(AuthenticationResult.Status.SUCCESS, authResult4.getStatus()); @@ -1190,6 +1192,7 @@ public void testCachedApiKeyValidationWillNotBeBlockedByUnCachedApiKey() throws checkAuthApiKeyMetadata(metadata, authenticationResult3); } + @SuppressWarnings("unchecked") public void testApiKeyDocDeserialization() throws IOException { final String apiKeyDocumentSource = "{\"doc_type\":\"api_key\",\"creation_time\":1591919944598,\"expiration_time\":1591919944599,\"api_key_invalidated\":false," + @@ -1399,11 +1402,11 @@ private ApiKeyDoc buildApiKeyDoc(char[] hash, long expirationTime, boolean inval ); } + @SuppressWarnings("unchecked") private void checkAuthApiKeyMetadata(Object metadata, AuthenticationResult authResult1) throws IOException { if (metadata == null) { assertThat(authResult1.getMetadata().containsKey(API_KEY_METADATA_KEY), is(false)); } else { - //noinspection unchecked assertThat( authResult1.getMetadata().get(API_KEY_METADATA_KEY), equalTo(XContentTestUtils.convertToXContent((Map) metadata, XContentType.JSON))); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java index a467828d8d7bc..12eab49f80369 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/AuthenticationServiceTests.java @@ -124,6 +124,7 @@ import java.util.function.Consumer; import static org.elasticsearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.SecurityTestsUtils.assertAuthenticationException; import static org.elasticsearch.test.TestMatchers.throwableWithMessage; import static org.elasticsearch.xpack.core.security.support.Exceptions.authenticationError; @@ -245,11 +246,12 @@ public void init() throws Exception { when(client.prepareUpdate(any(String.class), any(String.class))) .thenReturn(new UpdateRequestBuilder(client, UpdateAction.INSTANCE)); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener responseActionListener = (ActionListener) invocationOnMock.getArguments()[2]; responseActionListener.onResponse(new IndexResponse(new ShardId(".security", UUIDs.randomBase64UUID(), randomInt()), randomAlphaOfLength(4), randomNonNegativeLong(), randomNonNegativeLong(), randomNonNegativeLong(), true)); return null; - }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), any(ActionListener.class)); + }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), anyActionListener()); doAnswer(invocationOnMock -> { GetRequestBuilder builder = new GetRequestBuilder(client, GetAction.INSTANCE); builder.setIndex((String) invocationOnMock.getArguments()[0]) @@ -261,12 +263,12 @@ public void init() throws Exception { Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; runnable.run(); return null; - }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).prepareIndexIfNeededThenExecute(anyConsumer(), any(Runnable.class)); doAnswer(invocationOnMock -> { Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; runnable.run(); return null; - }).when(securityIndex).checkIndexVersionThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).checkIndexVersionThenExecute(anyConsumer(), any(Runnable.class)); ClusterService clusterService = ClusterServiceUtils.createClusterService(threadPool); final SecurityContext securityContext = new SecurityContext(settings, threadContext); apiKeyService = new ApiKeyService(settings, Clock.systemUTC(), client, licenseState, securityIndex, clusterService, @@ -451,8 +453,8 @@ public void testAuthenticateSmartRealmOrdering() { verify(secondRealm, times(2)).token(threadContext); verify(firstRealm).supports(token); verify(secondRealm, times(2)).supports(token); - verify(firstRealm).authenticate(eq(token), any(ActionListener.class)); - verify(secondRealm, times(2)).authenticate(eq(token), any(ActionListener.class)); + verify(firstRealm).authenticate(eq(token), anyActionListener()); + verify(secondRealm, times(2)).authenticate(eq(token), anyActionListener()); verifyNoMoreInteractions(auditTrail, firstRealm, secondRealm); // Now assume some change in the backend system so that 2nd realm no longer has the user, but the 1st realm does. @@ -478,8 +480,8 @@ public void testAuthenticateSmartRealmOrdering() { }, this::logAndFail)); verify(auditTrail).authenticationFailed(reqId.get(), SECOND_REALM_NAME, token, "_action", transportRequest); - verify(secondRealm, times(3)).authenticate(eq(token), any(ActionListener.class)); // 2 from above + 1 more - verify(firstRealm, times(2)).authenticate(eq(token), any(ActionListener.class)); // 1 from above + 1 more + verify(secondRealm, times(3)).authenticate(eq(token), anyActionListener()); // 2 from above + 1 more + verify(firstRealm, times(2)).authenticate(eq(token), anyActionListener()); // 1 from above + 1 more } public void testCacheClearOnSecurityIndexChange() { @@ -576,8 +578,8 @@ public void testAuthenticateSmartRealmOrderingDisabled() { verify(secondRealm, times(2)).token(threadContext); verify(firstRealm, times(2)).supports(token); verify(secondRealm, times(2)).supports(token); - verify(firstRealm, times(2)).authenticate(eq(token), any(ActionListener.class)); - verify(secondRealm, times(2)).authenticate(eq(token), any(ActionListener.class)); + verify(firstRealm, times(2)).authenticate(eq(token), anyActionListener()); + verify(secondRealm, times(2)).authenticate(eq(token), anyActionListener()); verifyNoMoreInteractions(auditTrail, firstRealm, secondRealm); } @@ -611,7 +613,7 @@ public void testAuthenticateFirstNotSupportingSecondSucceeds() throws Exception verify(operatorPrivilegesService).maybeMarkOperatorUser(eq(result), eq(threadContext)); }, this::logAndFail)); verifyNoMoreInteractions(auditTrail); - verify(firstRealm, never()).authenticate(eq(token), any(ActionListener.class)); + verify(firstRealm, never()).authenticate(eq(token), anyActionListener()); assertTrue(completed.get()); } @@ -656,6 +658,7 @@ public void testTokenRestMissing() throws Exception { when(firstRealm.token(threadContext)).thenReturn(null); when(secondRealm.token(threadContext)).thenReturn(null); + @SuppressWarnings("unchecked") Authenticator authenticator = service.createAuthenticator(restRequest, true, mock(ActionListener.class)); authenticator.extractToken((token) -> { expectAuditRequestId(threadContext); @@ -1039,12 +1042,13 @@ public void testWrongApiKeyDoesNotFallbackToAnonymous() { tokenService, apiKeyService, serviceAccountService, operatorPrivilegesService); doAnswer(invocationOnMock -> { final GetRequest request = (GetRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") final ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; listener.onResponse(new GetResponse(new GetResult(request.index(), request.id(), SequenceNumbers.UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1L, false, null, Collections.emptyMap(), Collections.emptyMap()))); return Void.TYPE; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { boolean requestIdAlreadyPresent = randomBoolean(); SetOnce reqId = new SetOnce<>(); @@ -1330,7 +1334,7 @@ public void testRealmAuthenticateThrowingException() throws Exception { when(secondRealm.token(threadContext)).thenReturn(token); when(secondRealm.supports(token)).thenReturn(true); doThrow(authenticationError("realm doesn't like authenticate")) - .when(secondRealm).authenticate(eq(token), any(ActionListener.class)); + .when(secondRealm).authenticate(eq(token), anyActionListener()); boolean requestIdAlreadyPresent = randomBoolean(); SetOnce reqId = new SetOnce<>(); if (requestIdAlreadyPresent) { @@ -1357,7 +1361,7 @@ public void testRealmAuthenticateThrowingExceptionRest() throws Exception { when(secondRealm.token(threadContext)).thenReturn(token); when(secondRealm.supports(token)).thenReturn(true); doThrow(authenticationError("realm doesn't like authenticate")) - .when(secondRealm).authenticate(eq(token), any(ActionListener.class)); + .when(secondRealm).authenticate(eq(token), anyActionListener()); try { authenticateBlocking(restRequest); fail("exception should bubble out"); @@ -1378,7 +1382,7 @@ public void testRealmLookupThrowingException() throws Exception { mockAuthenticate(secondRealm, token, new User("lookup user", new String[]{"user"})); mockRealmLookupReturnsNull(firstRealm, "run_as"); doThrow(authenticationError("realm doesn't want to lookup")) - .when(secondRealm).lookupUser(eq("run_as"), any(ActionListener.class)); + .when(secondRealm).lookupUser(eq("run_as"), anyActionListener()); boolean requestIdAlreadyPresent = randomBoolean(); SetOnce reqId = new SetOnce<>(); if (requestIdAlreadyPresent) { @@ -1408,7 +1412,7 @@ public void testRealmLookupThrowingExceptionRest() throws Exception { mockAuthenticate(secondRealm, token, new User("lookup user", new String[]{"user"})); mockRealmLookupReturnsNull(firstRealm, "run_as"); doThrow(authenticationError("realm doesn't want to lookup")) - .when(secondRealm).lookupUser(eq("run_as"), any(ActionListener.class)); + .when(secondRealm).lookupUser(eq("run_as"), anyActionListener()); try { authenticateBlocking(restRequest); fail("exception should bubble out"); @@ -1437,10 +1441,11 @@ public void testRunAsLookupSameRealm() throws Exception { mockAuthenticate(secondRealm, token, user); mockRealmLookupReturnsNull(firstRealm, "run_as"); doAnswer((i) -> { + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) i.getArguments()[1]; listener.onResponse(new User("looked up user", new String[]{"some role"})); return null; - }).when(secondRealm).lookupUser(eq("run_as"), any(ActionListener.class)); + }).when(secondRealm).lookupUser(eq("run_as"), anyActionListener()); final AtomicBoolean completed = new AtomicBoolean(false); ActionListener listener = ActionListener.wrap(result -> { @@ -1497,7 +1502,7 @@ public void testRunAsLookupDifferentRealm() throws Exception { ActionListener listener = (ActionListener) i.getArguments()[1]; listener.onResponse(new User("looked up user", new String[]{"some role"})); return null; - }).when(firstRealm).lookupUser(eq("run_as"), any(ActionListener.class)); + }).when(firstRealm).lookupUser(eq("run_as"), anyActionListener()); final AtomicBoolean completed = new AtomicBoolean(false); ActionListener listener = ActionListener.wrap(result -> { @@ -1598,7 +1603,7 @@ public void testAuthenticateTransportDisabledRunAsUser() throws Exception { ActionListener listener = (ActionListener) i.getArguments()[1]; listener.onResponse(new User("looked up user", new String[]{"some role"}, null, null, Map.of(), false)); return null; - }).when(secondRealm).lookupUser(eq("run_as"), any(ActionListener.class)); + }).when(secondRealm).lookupUser(eq("run_as"), anyActionListener()); User fallback = randomBoolean() ? SystemUser.INSTANCE : null; ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticateBlocking("_action", transportRequest, fallback)); @@ -1626,7 +1631,7 @@ public void testAuthenticateRestDisabledRunAsUser() throws Exception { ActionListener listener = (ActionListener) i.getArguments()[1]; listener.onResponse(new User("looked up user", new String[]{"some role"}, null, null, Map.of(), false)); return null; - }).when(secondRealm).lookupUser(eq("run_as"), any(ActionListener.class)); + }).when(secondRealm).lookupUser(eq("run_as"), anyActionListener()); ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> authenticateBlocking(restRequest)); @@ -1769,7 +1774,7 @@ public void testExpiredToken() throws Exception { doAnswer(invocationOnMock -> { ((Runnable) invocationOnMock.getArguments()[1]).run(); return null; - }).when(securityIndex).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).prepareIndexIfNeededThenExecute(anyConsumer(), any(Runnable.class)); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { boolean requestIdAlreadyPresent = randomBoolean(); @@ -1845,7 +1850,7 @@ public void testApiKeyAuth() { Collections.emptyMap(), Collections.emptyMap()))); } return Void.TYPE; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { boolean requestIdAlreadyPresent = randomBoolean(); @@ -1873,6 +1878,7 @@ public void testExpiredApiKey() { final String headerValue = "ApiKey " + Base64.getEncoder().encodeToString((id + ":" + key).getBytes(StandardCharsets.UTF_8)); doAnswer(invocationOnMock -> { final GetRequest request = (GetRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") final ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; if (request.id().equals(id)) { final Map source = new HashMap<>(); @@ -1897,7 +1903,7 @@ public void testExpiredApiKey() { Collections.emptyMap(), Collections.emptyMap()))); } return Void.TYPE; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); try (ThreadContext.StoredContext ignore = threadContext.stashContext()) { boolean requestIdAlreadyPresent = randomBoolean(); @@ -2012,7 +2018,7 @@ private void mockAuthenticate(Realm realm, AuthenticationToken token, User user) run.run(); } return null; - }).when(realm).authenticate(eq(token), any(ActionListener.class)); + }).when(realm).authenticate(eq(token), anyActionListener()); } @SuppressWarnings("unchecked") @@ -2025,7 +2031,7 @@ private void mockAuthenticate(Realm realm, AuthenticationToken token, Exception listener.onResponse(AuthenticationResult.unsuccessful("unsuccessful, but continue authc process", e)); } return null; - }).when(realm).authenticate(eq(token), any(ActionListener.class)); + }).when(realm).authenticate(eq(token), anyActionListener()); } private Tuple authenticateBlocking(RestRequest restRequest) { @@ -2088,7 +2094,7 @@ private static void mockRealmLookupReturnsNull(Realm realm, String username) { ActionListener listener = (ActionListener) i.getArguments()[1]; listener.onResponse(null); return null; - }).when(realm).lookupUser(eq(username), any(ActionListener.class)); + }).when(realm).lookupUser(eq(username), anyActionListener()); } static class TestRealms extends Realms { @@ -2115,4 +2121,9 @@ private SecurityIndexManager.State dummyState(ClusterHealthStatus indexStatus) { return new SecurityIndexManager.State( Instant.now(), true, true, true, null, concreteSecurityIndexName, indexStatus, IndexMetadata.State.OPEN, null, "my_uuid"); } + + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java index df49b5ac6a8aa..1d711287b2933 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/InternalRealmsTests.java @@ -42,6 +42,7 @@ public class InternalRealmsTests extends ESTestCase { + @SuppressWarnings("unchecked") public void testNativeRealmRegistersIndexHealthChangeListener() throws Exception { SecurityIndexManager securityIndex = mock(SecurityIndexManager.class); Map factories = InternalRealms.getFactories(mock(ThreadPool.class), mock(ResourceWatcherService.class), diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsTests.java index eef02cb9874f3..266a7439216ff 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/RealmsTests.java @@ -495,6 +495,7 @@ public void testAuthcAuthzDisabled() throws Exception { assertThat(realms.iterator().hasNext(), is(false)); } + @SuppressWarnings("unchecked") public void testUsageStats() throws Exception { // test realms with duplicate values Settings.Builder builder = Settings.builder() diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java index d8de31d5a8cd9..9ba40b9a44f4a 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/TokenServiceTests.java @@ -41,19 +41,19 @@ import org.elasticsearch.cluster.node.DiscoveryNodeRole; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.core.Nullable; import org.elasticsearch.common.Strings; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.bytes.BytesReference; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.core.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.core.Nullable; +import org.elasticsearch.core.TimeValue; +import org.elasticsearch.core.Tuple; import org.elasticsearch.index.Index; import org.elasticsearch.index.get.GetResult; import org.elasticsearch.index.query.BoolQueryBuilder; @@ -89,7 +89,6 @@ import org.junit.Before; import org.junit.BeforeClass; -import javax.crypto.SecretKey; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; @@ -101,9 +100,11 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import javax.crypto.SecretKey; import static java.time.Clock.systemUTC; import static org.elasticsearch.repositories.blobstore.ESBlobStoreRepositoryIntegTestCase.randomBytes; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.ClusterServiceUtils.setState; import static org.elasticsearch.test.TestMatchers.throwableWithMessage; import static org.hamcrest.CoreMatchers.is; @@ -162,13 +163,15 @@ public void setupClient() { when(client.prepareSearch(any(String.class))) .thenReturn(new SearchRequestBuilder(client, SearchAction.INSTANCE)); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener responseActionListener = (ActionListener) invocationOnMock.getArguments()[2]; responseActionListener.onResponse(new IndexResponse(new ShardId(".security", UUIDs.randomBase64UUID(), randomInt()), randomAlphaOfLength(4), randomNonNegativeLong(), randomNonNegativeLong(), randomNonNegativeLong(), true)); return null; - }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), any(ActionListener.class)); + }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), anyActionListener()); doAnswer(invocationOnMock -> { BulkRequest request = (BulkRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") ActionListener responseActionListener = (ActionListener) invocationOnMock.getArguments()[1]; BulkItemResponse[] responses = new BulkItemResponse[request.requests().size()]; final String indexUUID = randomAlphaOfLength(22); @@ -183,7 +186,7 @@ public void setupClient() { } responseActionListener.onResponse(new BulkResponse(responses, randomLongBetween(1, 500))); return null; - }).when(client).bulk(any(BulkRequest.class), any(ActionListener.class)); + }).when(client).bulk(any(BulkRequest.class), anyActionListener()); this.securityContext = new SecurityContext(settings, threadPool.getThreadContext()); // setup lifecycle service @@ -797,10 +800,11 @@ public void testIndexNotAvailable() throws Exception { storeTokenHeader(requestContext, accessToken); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; listener.onFailure(new NoShardAvailableActionException(new ShardId(new Index("foo", "uuid"), 0), "shard oh shard")); return Void.TYPE; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); final SecurityIndexManager tokensIndex; if (oldNode != null) { @@ -926,6 +930,7 @@ public static void mockGetTokenFromId(TokenService tokenService, String userToke Client client) { doAnswer(invocationOnMock -> { GetRequest request = (GetRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; GetResponse response = mock(GetResponse.class); Version tokenVersion = tokenService.getTokenVersionCompatibility(); @@ -951,7 +956,7 @@ public static void mockGetTokenFromId(TokenService tokenService, String userToke } listener.onResponse(response); return Void.TYPE; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); } protected static UserToken buildUserToken(TokenService tokenService, String userTokenId, Authentication authentication) { @@ -973,6 +978,7 @@ protected static UserToken buildUserToken(TokenService tokenService, String user private void mockGetTokenFromId(UserToken userToken, boolean isExpired) { doAnswer(invocationOnMock -> { GetRequest request = (GetRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; GetResponse response = mock(GetResponse.class); final String possiblyHashedUserTokenId; @@ -998,7 +1004,7 @@ private void mockGetTokenFromId(UserToken userToken, boolean isExpired) { } listener.onResponse(response); return Void.TYPE; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); } private void mockFindTokenFromRefreshToken(String refreshToken, UserToken userToken, @Nullable RefreshTokenStatus refreshTokenStatus) { @@ -1010,6 +1016,7 @@ private void mockFindTokenFromRefreshToken(String refreshToken, UserToken userTo } doAnswer(invocationOnMock -> { final SearchRequest request = (SearchRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") final ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; final SearchResponse response = mock(SearchResponse.class); @@ -1039,6 +1046,7 @@ private void mockFindTokenFromRefreshToken(String refreshToken, UserToken userTo BytesReference source = TokenService.createTokenDocument(userToken, storedRefreshToken, clientAuthentication, Instant.now()); if (refreshTokenStatus != null) { var sourceAsMap = XContentHelper.convertToMap(source, false, XContentType.JSON).v2(); + @SuppressWarnings("unchecked") var refreshTokenSource = (Map) sourceAsMap.get("refresh_token"); refreshTokenSource.put("invalidated", refreshTokenStatus.isInvalidated()); refreshTokenSource.put("refreshed", refreshTokenStatus.isRefreshed()); @@ -1050,12 +1058,13 @@ private void mockFindTokenFromRefreshToken(String refreshToken, UserToken userTo when(response.getHits()).thenReturn(hits); listener.onResponse(response); return Void.TYPE; - }).when(client).search(any(SearchRequest.class), any(ActionListener.class)); + }).when(client).search(any(SearchRequest.class), anyActionListener()); } private void mockGetTokenAsyncForDecryptedToken(String accessToken) { doAnswer(invocationOnMock -> { GetRequest request = (GetRequest) invocationOnMock.getArguments()[0]; + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[1]; GetResponse response = mock(GetResponse.class); if (request.id().replace("token_", "").equals(TokenService.hashTokenString(accessToken))) { @@ -1063,7 +1072,7 @@ private void mockGetTokenAsyncForDecryptedToken(String accessToken) { } listener.onResponse(response); return Void.TYPE; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); } public static void assertAuthentication(Authentication result, Authentication expected) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStoreTests.java index d00b77a563bba..f328ede14107f 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/NativeUsersStoreTests.java @@ -210,6 +210,7 @@ public void testDefaultReservedUserInfoPasswordEmpty() { assertThat(constructedUserInfo.hasEmptyPassword(), equalTo(false)); } + @SuppressWarnings("unchecked") private ARequest actionRespond(Class requestClass, AResponse response) { Tuple> tuple = findRequest(requestClass); @@ -246,6 +247,7 @@ private void respondToGetUserRequest(String username, SecureString password, Str actionRespond(GetRequest.class, new GetResponse(getResult)); } + @SuppressWarnings("unchecked") private NativeUsersStore startNativeUsersStore() { SecurityIndexManager securityIndex = mock(SecurityIndexManager.class); when(securityIndex.isAvailable()).thenReturn(true); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java index 2ae71e8076c32..5d3f2f518bb19 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/ReservedRealmTests.java @@ -34,6 +34,7 @@ import org.elasticsearch.xpack.security.authc.esnative.NativeUsersStore.ReservedUserInfo; import org.elasticsearch.xpack.security.support.SecurityIndexManager; import org.junit.Before; +import org.mockito.stubbing.Answer; import java.util.Collection; import java.util.Collections; @@ -42,6 +43,7 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.containsString; @@ -49,7 +51,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -138,11 +139,7 @@ private void verifySuccessfulAuthentication(boolean enabled) throws Exception { // Mocked users store is initiated with default hashing algorithm final Hasher hasher = Hasher.resolve("bcrypt"); when(securityIndex.indexExists()).thenReturn(true); - doAnswer((i) -> { - ActionListener callback = (ActionListener) i.getArguments()[1]; - callback.onResponse(new ReservedUserInfo(hasher.hash(newPassword), enabled)); - return null; - }).when(usersStore).getReservedUserInfo(eq(principal), any(ActionListener.class)); + doAnswer(getAnswer(enabled, newPassword, hasher)).when(usersStore).getReservedUserInfo(eq(principal), anyActionListener()); // test empty password final PlainActionFuture listener = new PlainActionFuture<>(); @@ -150,11 +147,7 @@ private void verifySuccessfulAuthentication(boolean enabled) throws Exception { assertFailedAuthentication(listener, expectedUser.principal()); // the realm assumes it owns the hashed password so it fills it with 0's - doAnswer((i) -> { - ActionListener callback = (ActionListener) i.getArguments()[1]; - callback.onResponse(new ReservedUserInfo(hasher.hash(newPassword), true)); - return null; - }).when(usersStore).getReservedUserInfo(eq(principal), any(ActionListener.class)); + doAnswer(getAnswer(true, newPassword, hasher)).when(usersStore).getReservedUserInfo(eq(principal), anyActionListener()); // test new password final PlainActionFuture authListener = new PlainActionFuture<>(); @@ -164,7 +157,7 @@ private void verifySuccessfulAuthentication(boolean enabled) throws Exception { assertThat(expectedUser.enabled(), is(enabled)); verify(securityIndex, times(2)).indexExists(); - verify(usersStore, times(2)).getReservedUserInfo(eq(principal), any(ActionListener.class)); + verify(usersStore, times(2)).getReservedUserInfo(eq(principal), anyActionListener()); verifyNoMoreInteractions(usersStore); if (new KibanaUser(enabled).equals(expectedUser)) { @@ -173,6 +166,15 @@ private void verifySuccessfulAuthentication(boolean enabled) throws Exception { } } + @SuppressWarnings("unchecked") + private Answer> getAnswer(boolean enabled, SecureString newPassword, Hasher hasher) { + return (i) -> { + ActionListener callback = (ActionListener) i.getArguments()[1]; + callback.onResponse(new ReservedUserInfo(hasher.hash(newPassword), enabled)); + return null; + }; + } + public void testLookup() throws Exception { final ReservedRealm reservedRealm = new ReservedRealm(mock(Environment.class), Settings.EMPTY, usersStore, @@ -234,10 +236,10 @@ public void testLookupThrows() throws Exception { when(securityIndex.indexExists()).thenReturn(true); final RuntimeException e = new RuntimeException("store threw"); doAnswer((i) -> { - ActionListener callback = (ActionListener) i.getArguments()[1]; + ActionListener callback = (ActionListener) i.getArguments()[1]; callback.onFailure(e); return null; - }).when(usersStore).getReservedUserInfo(eq(principal), any(ActionListener.class)); + }).when(usersStore).getReservedUserInfo(eq(principal), anyActionListener()); PlainActionFuture future = new PlainActionFuture<>(); reservedRealm.lookupUser(principal, future); @@ -245,7 +247,7 @@ public void testLookupThrows() throws Exception { assertThat(securityException.getMessage(), containsString("failed to lookup")); verify(securityIndex).indexExists(); - verify(usersStore).getReservedUserInfo(eq(principal), any(ActionListener.class)); + verify(usersStore).getReservedUserInfo(eq(principal), anyActionListener()); verifyNoMoreInteractions(usersStore); } @@ -342,10 +344,11 @@ public void testBootstrapElasticPasswordWorksOnceSecurityIndexExists() throws Ex PlainActionFuture listener = new PlainActionFuture<>(); doAnswer((i) -> { + @SuppressWarnings("rawtypes") ActionListener callback = (ActionListener) i.getArguments()[1]; callback.onResponse(null); return null; - }).when(usersStore).getReservedUserInfo(eq("elastic"), any(ActionListener.class)); + }).when(usersStore).getReservedUserInfo(eq("elastic"), anyActionListener()); reservedRealm.doAuthenticate(new UsernamePasswordToken(new ElasticUser(true).principal(), mockSecureSettings.getString("bootstrap.password")), listener); @@ -366,12 +369,13 @@ public void testBootstrapElasticPasswordFailsOnceElasticUserExists() throws Exce // Mocked users store is initiated with default hashing algorithm final Hasher hasher = Hasher.resolve("bcrypt"); doAnswer((i) -> { - ActionListener callback = (ActionListener) i.getArguments()[1]; + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) i.getArguments()[1]; char[] hash = hasher.hash(password); ReservedUserInfo userInfo = new ReservedUserInfo(hash, true); callback.onResponse(userInfo); return null; - }).when(usersStore).getReservedUserInfo(eq("elastic"), any(ActionListener.class)); + }).when(usersStore).getReservedUserInfo(eq("elastic"), anyActionListener()); reservedRealm.doAuthenticate(new UsernamePasswordToken(new ElasticUser(true).principal(), mockSecureSettings.getString("bootstrap.password")), listener); assertFailedAuthentication(listener, "elastic"); @@ -413,10 +417,10 @@ public void testNonElasticUsersCannotUseBootstrapPasswordWhenSecurityIndexExists final String principal = randomFrom(KibanaUser.NAME, KibanaSystemUser.NAME, LogstashSystemUser.NAME, BeatsSystemUser.NAME, APMSystemUser.NAME, RemoteMonitoringUser.NAME); doAnswer((i) -> { - ActionListener callback = (ActionListener) i.getArguments()[1]; + ActionListener callback = (ActionListener) i.getArguments()[1]; callback.onResponse(null); return null; - }).when(usersStore).getReservedUserInfo(eq(principal), any(ActionListener.class)); + }).when(usersStore).getReservedUserInfo(eq(principal), anyActionListener()); reservedRealm.doAuthenticate(new UsernamePasswordToken(principal, mockSecureSettings.getString("bootstrap.password")), listener); final AuthenticationResult result = listener.get(); assertThat(result.getStatus(), is(AuthenticationResult.Status.TERMINATE)); @@ -448,17 +452,18 @@ private User randomReservedUser(boolean enabled) { /* * NativeUserStore#getAllReservedUserInfo is pkg private we can't mock it otherwise */ + @SuppressWarnings("unchecked") public static void mockGetAllReservedUserInfo(NativeUsersStore usersStore, Map collection) { doAnswer((i) -> { - ((ActionListener) i.getArguments()[0]).onResponse(collection); + ((ActionListener>) i.getArguments()[0]).onResponse(collection); return null; - }).when(usersStore).getAllReservedUserInfo(any(ActionListener.class)); + }).when(usersStore).getAllReservedUserInfo(anyActionListener()); for (Entry entry : collection.entrySet()) { doAnswer((i) -> { - ((ActionListener) i.getArguments()[1]).onResponse(entry.getValue()); + ((ActionListener) i.getArguments()[1]).onResponse(entry.getValue()); return null; - }).when(usersStore).getReservedUserInfo(eq(entry.getKey()), any(ActionListener.class)); + }).when(usersStore).getReservedUserInfo(eq(entry.getKey()), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java index b377cbf2ef579..c1b48e74b26b4 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/esnative/tool/SetupPasswordToolTests.java @@ -11,7 +11,6 @@ import org.elasticsearch.cli.CommandTestCase; import org.elasticsearch.cli.ExitCodes; import org.elasticsearch.cli.UserException; -import org.elasticsearch.core.CheckedFunction; import org.elasticsearch.common.CheckedSupplier; import org.elasticsearch.common.Strings; import org.elasticsearch.common.collect.MapBuilder; @@ -22,6 +21,7 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.core.CheckedFunction; import org.elasticsearch.env.Environment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.protocol.xpack.XPackInfoResponse; @@ -31,9 +31,9 @@ import org.elasticsearch.xpack.core.security.support.Validation; import org.elasticsearch.xpack.core.security.user.ElasticUser; import org.elasticsearch.xpack.security.authc.esnative.ReservedRealm; +import org.elasticsearch.xpack.security.tool.CommandLineHttpClient; import org.elasticsearch.xpack.security.tool.HttpResponse; import org.elasticsearch.xpack.security.tool.HttpResponse.HttpResponseBuilder; -import org.elasticsearch.xpack.security.tool.CommandLineHttpClient; import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Rule; @@ -42,7 +42,6 @@ import org.mockito.InOrder; import org.mockito.Mockito; -import javax.net.ssl.SSLException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; @@ -56,6 +55,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import javax.net.ssl.SSLException; import static org.hamcrest.CoreMatchers.containsString; import static org.mockito.Matchers.any; @@ -97,19 +97,19 @@ public void setSecretsAndKeyStore() throws Exception { this.httpClient = mock(CommandLineHttpClient.class); when(httpClient.getDefaultURL()).thenReturn("http://localhost:9200"); - HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap()); - when(httpClient.execute(anyString(), any(URL.class), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponse); + HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap<>()); + when(httpClient.execute(anyString(), any(URL.class), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponse); URL url = new URL(httpClient.getDefaultURL()); httpResponse = new HttpResponse(HttpURLConnection.HTTP_OK, Collections.singletonMap("status", randomFrom("yellow", "green"))); - when(httpClient.execute(anyString(), eq(clusterHealthUrl(url)), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponse); + when(httpClient.execute(anyString(), eq(clusterHealthUrl(url)), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponse); URL xpackSecurityPluginQueryURL = queryXPackSecurityFeatureConfigURL(url); - HttpResponse queryXPackSecurityConfigHttpResponse = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap()); + HttpResponse queryXPackSecurityConfigHttpResponse = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap<>()); when(httpClient.execute(eq("GET"), eq(xpackSecurityPluginQueryURL), anyString(), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))).thenReturn(queryXPackSecurityConfigHttpResponse); + anyCheckedSupplier(), anyCheckedFunction())).thenReturn(queryXPackSecurityConfigHttpResponse); // elastic user is updated last usersInSetOrder = new ArrayList<>(SetupPasswordTool.USERS); @@ -183,14 +183,15 @@ public void testAutoSetup() throws Exception { InOrder inOrder = Mockito.inOrder(httpClient); URL checkUrl = authenticateUrl(url); - inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), any(CheckedSupplier.class), - any(CheckedFunction.class)); + inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), anyCheckedSupplier(), + anyCheckedFunction()); Map capturedPasswords = new HashMap<>(usersInSetOrder.size()); for (String user : usersInSetOrder) { URL urlWithRoute = passwordUrl(url, user); + @SuppressWarnings({"unchecked", "rawtypes"}) ArgumentCaptor> passwordCaptor = ArgumentCaptor.forClass((Class) CheckedSupplier.class); inOrder.verify(httpClient).execute(eq("PUT"), eq(urlWithRoute), eq(ElasticUser.NAME), eq(bootstrapPassword), - passwordCaptor.capture(), any(CheckedFunction.class)); + passwordCaptor.capture(), anyCheckedFunction()); String userPassword = passwordCaptor.getValue().get(); capturedPasswords.put(user, userPassword); @@ -211,10 +212,10 @@ public void testAuthnFail() throws Exception { URL url = new URL(httpClient.getDefaultURL()); URL authnURL = authenticateUrl(url); - HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_UNAUTHORIZED, new HashMap()); + HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_UNAUTHORIZED, new HashMap<>()); - when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponse); + when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponse); try { execute(randomBoolean() ? "auto" : "interactive", pathHomeParameter); @@ -228,9 +229,9 @@ public void testErrorMessagesWhenXPackIsNotAvailableOnNode() throws Exception { URL url = new URL(httpClient.getDefaultURL()); URL authnURL = authenticateUrl(url); - HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap()); - when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponse); + HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap<>()); + when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponse); URL xpackSecurityPluginQueryURL = queryXPackSecurityFeatureConfigURL(url); String securityPluginQueryResponseBody = null; @@ -244,7 +245,7 @@ public void testErrorMessagesWhenXPackIsNotAvailableOnNode() throws Exception { securityPluginQueryResponseBody = Strings.toString(builder); } when(httpClient.execute(eq("GET"), eq(xpackSecurityPluginQueryURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, securityPluginQueryResponseBody)); thrown.expect(UserException.class); @@ -256,9 +257,9 @@ public void testErrorMessagesWhenXPackIsAvailableWithCorrectLicenseAndIsEnabledB URL url = new URL(httpClient.getDefaultURL()); URL authnURL = authenticateUrl(url); - HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap()); - when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponse); + HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap<>()); + when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponse); URL xpackSecurityPluginQueryURL = queryXPackSecurityFeatureConfigURL(url); @@ -275,7 +276,7 @@ public void testErrorMessagesWhenXPackIsAvailableWithCorrectLicenseAndIsEnabledB securityPluginQueryResponseBody = Strings.toString(builder); } when(httpClient.execute(eq("GET"), eq(xpackSecurityPluginQueryURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, securityPluginQueryResponseBody)); thrown.expect(UserException.class); @@ -289,9 +290,9 @@ public void testErrorMessagesWhenXPackPluginIsAvailableButNoSecurityLicense() th URL authnURL = authenticateUrl(url); URL xpackSecurityPluginQueryURL = queryXPackSecurityFeatureConfigURL(url); - HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap()); - when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponse); + HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap<>()); + when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponse); Set featureSets = new HashSet<>(); featureSets.add(new FeatureSet("logstash", true, true)); @@ -306,7 +307,7 @@ public void testErrorMessagesWhenXPackPluginIsAvailableButNoSecurityLicense() th securityPluginQueryResponseBody = Strings.toString(builder); } when(httpClient.execute(eq("GET"), eq(xpackSecurityPluginQueryURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, securityPluginQueryResponseBody)); thrown.expect(UserException.class); @@ -320,9 +321,9 @@ public void testErrorMessagesWhenXPackPluginIsAvailableWithValidLicenseButDisabl URL authnURL = authenticateUrl(url); URL xpackSecurityPluginQueryURL = queryXPackSecurityFeatureConfigURL(url); - HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap()); - when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponse); + HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND, new HashMap<>()); + when(httpClient.execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponse); Set featureSets = new HashSet<>(); featureSets.add(new FeatureSet("logstash", true, true)); @@ -337,7 +338,7 @@ public void testErrorMessagesWhenXPackPluginIsAvailableWithValidLicenseButDisabl securityPluginQueryResponseBody = Strings.toString(builder); } when(httpClient.execute(eq("GET"), eq(xpackSecurityPluginQueryURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, securityPluginQueryResponseBody)); thrown.expect(UserException.class); @@ -349,7 +350,7 @@ public void testWrongServer() throws Exception { URL url = new URL(httpClient.getDefaultURL()); URL authnURL = authenticateUrl(url); doThrow(randomFrom(new IOException(), new SSLException(""))).when(httpClient).execute(eq("GET"), eq(authnURL), eq(ElasticUser.NAME), - any(SecureString.class), any(CheckedSupplier.class), any(CheckedFunction.class)); + any(SecureString.class), anyCheckedSupplier(), anyCheckedFunction()); try { execute(randomBoolean() ? "auto" : "interactive", pathHomeParameter); @@ -364,12 +365,12 @@ public void testRedCluster() throws Exception { HttpResponse httpResponse = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap<>()); when(httpClient.execute(eq("GET"), eq(authenticateUrl(url)), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))).thenReturn(httpResponse); + anyCheckedSupplier(), anyCheckedFunction())).thenReturn(httpResponse); httpResponse = new HttpResponse(HttpURLConnection.HTTP_OK, MapBuilder.newMapBuilder() .put("cluster_name", "elasticsearch").put("status", "red").put("number_of_nodes", 1).map()); when(httpClient.execute(eq("GET"), eq(clusterHealthUrl(url)), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))).thenReturn(httpResponse); + anyCheckedSupplier(), anyCheckedFunction())).thenReturn(httpResponse); terminal.addTextInput("n"); try { @@ -388,12 +389,12 @@ public void testUrlOption() throws Exception { InOrder inOrder = Mockito.inOrder(httpClient); URL checkUrl = authenticateUrl(url); - inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), any(CheckedSupplier.class), - any(CheckedFunction.class)); + inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), anyCheckedSupplier(), + anyCheckedFunction()); for (String user : usersInSetOrder) { URL urlWithRoute = passwordUrl(url, user); inOrder.verify(httpClient).execute(eq("PUT"), eq(urlWithRoute), eq(ElasticUser.NAME), eq(bootstrapPassword), - any(CheckedSupplier.class), any(CheckedFunction.class)); + anyCheckedSupplier(), anyCheckedFunction()); } } @@ -403,7 +404,7 @@ public void testSetUserPassFail() throws Exception { URL userToFailURL = passwordUrl(url, userToFail); doThrow(new IOException()).when(httpClient).execute(eq("PUT"), eq(userToFailURL), anyString(), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class)); + anyCheckedSupplier(), anyCheckedFunction()); try { execute(randomBoolean() ? "auto" : "interactive", pathHomeParameter, "-b"); fail("Should have thrown exception"); @@ -421,14 +422,15 @@ public void testInteractiveSetup() throws Exception { InOrder inOrder = Mockito.inOrder(httpClient); URL checkUrl = authenticateUrl(url); - inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), any(CheckedSupplier.class), - any(CheckedFunction.class)); + inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), anyCheckedSupplier(), + anyCheckedFunction()); for (String user : usersInSetOrder) { URL urlWithRoute = passwordUrl(url, user); + @SuppressWarnings("unchecked") ArgumentCaptor> passwordCaptor = ArgumentCaptor.forClass((Class) CheckedSupplier.class); inOrder.verify(httpClient).execute(eq("PUT"), eq(urlWithRoute), eq(ElasticUser.NAME), eq(bootstrapPassword), - passwordCaptor.capture(), any(CheckedFunction.class)); + passwordCaptor.capture(), anyCheckedFunction()); assertThat(passwordCaptor.getValue().get(), containsString(getExpectedPasswordForUser(user))); } } @@ -467,13 +469,14 @@ public void testInteractivePasswordsFatFingers() throws Exception { InOrder inOrder = Mockito.inOrder(httpClient); URL checkUrl = authenticateUrl(url); - inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), any(CheckedSupplier.class), - any(CheckedFunction.class)); + inOrder.verify(httpClient).execute(eq("GET"), eq(checkUrl), eq(ElasticUser.NAME), eq(bootstrapPassword), anyCheckedSupplier(), + anyCheckedFunction()); for (String user : usersInSetOrder) { URL urlWithRoute = passwordUrl(url, user); + @SuppressWarnings({"unchecked", "rawtypes"}) ArgumentCaptor> passwordCaptor = ArgumentCaptor.forClass((Class) CheckedSupplier.class); inOrder.verify(httpClient).execute(eq("PUT"), eq(urlWithRoute), eq(ElasticUser.NAME), eq(bootstrapPassword), - passwordCaptor.capture(), any(CheckedFunction.class)); + passwordCaptor.capture(), anyCheckedFunction()); assertThat(passwordCaptor.getValue().get(), containsString(getExpectedPasswordForUser(user))); } } @@ -558,5 +561,15 @@ private String getExpectedPasswordForUser(String user) throws Exception { throw new Exception("Expected to find corresponding user for " + user); } return user + "-password"; + } + + @SuppressWarnings("unchecked") + private static CheckedFunction anyCheckedFunction() { + return any(CheckedFunction.class); + } + + @SuppressWarnings("unchecked") + private static CheckedSupplier anyCheckedSupplier() { + return any(CheckedSupplier.class); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java index 155af0b301e3b..7074d9f499969 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/file/FileRealmTests.java @@ -48,6 +48,7 @@ public class FileRealmTests extends ESTestCase { private static final Answer VERIFY_PASSWORD_ANSWER = inv -> { assertThat(inv.getArguments().length, is(3)); + @SuppressWarnings("unchecked") Supplier supplier = (Supplier) inv.getArguments()[2]; return AuthenticationResult.success(supplier.get()); }; @@ -72,7 +73,7 @@ public void init() throws Exception { } public void testAuthenticate() throws Exception { - when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), any(Supplier.class))) + when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), anySupplier())) .thenAnswer(VERIFY_PASSWORD_ANSWER); when(userRolesStore.roles("user1")).thenReturn(new String[] { "role1", "role2" }); RealmConfig config = getRealmConfig(globalSettings); @@ -100,7 +101,7 @@ public void testAuthenticateCaching() throws Exception { .put(globalSettings) .build(); RealmConfig config = getRealmConfig(settings); - when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), any(Supplier.class))) + when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), anySupplier())) .thenAnswer(VERIFY_PASSWORD_ANSWER); when(userRolesStore.roles("user1")).thenReturn(new String[]{"role1", "role2"}); FileRealm realm = new FileRealm(config, userPasswdStore, userRolesStore, threadPool); @@ -117,7 +118,7 @@ public void testAuthenticateCachingRefresh() throws Exception { RealmConfig config = getRealmConfig(globalSettings); userPasswdStore = spy(new UserPasswdStore(config)); userRolesStore = spy(new UserRolesStore(config)); - when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), any(Supplier.class))) + when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), anySupplier())) .thenAnswer(VERIFY_PASSWORD_ANSWER); doReturn(new String[] { "role1", "role2" }).when(userRolesStore).roles("user1"); FileRealm realm = new FileRealm(config, userPasswdStore, userRolesStore, threadPool); @@ -154,7 +155,7 @@ public void testAuthenticateCachingRefresh() throws Exception { public void testToken() throws Exception { RealmConfig config = getRealmConfig(globalSettings); - when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), any(Supplier.class))) + when(userPasswdStore.verifyPassword(eq("user1"), eq(new SecureString("longtestpassword")), anySupplier())) .thenAnswer(VERIFY_PASSWORD_ANSWER); when(userRolesStore.roles("user1")).thenReturn(new String[]{"role1", "role2"}); FileRealm realm = new FileRealm(config, userPasswdStore, userRolesStore, threadPool); @@ -276,4 +277,9 @@ static class UserRolesStore extends FileUserRolesStore { } } + @SuppressWarnings("unchecked") + private static Supplier anySupplier() { + return any(Supplier.class); + } + } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmAuthenticateFailedTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmAuthenticateFailedTests.java index cfa578e407288..eb0a8a216bcd4 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmAuthenticateFailedTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmAuthenticateFailedTests.java @@ -8,12 +8,11 @@ package org.elasticsearch.xpack.security.authc.kerberos; import org.elasticsearch.ElasticsearchSecurityException; -import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.core.Tuple; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; import org.elasticsearch.xpack.core.security.authc.RealmConfig; @@ -24,20 +23,20 @@ import org.elasticsearch.xpack.security.authc.support.MockLookupRealm; import org.ietf.jgss.GSSException; -import javax.security.auth.login.LoginException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.security.auth.login.LoginException; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.mockito.AdditionalMatchers.aryEq; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -117,7 +116,7 @@ public void testAuthenticateDifferentFailureScenarios() throws LoginException, G } } verify(mockKerberosTicketValidator).validateTicket(aryEq(decodedTicket), eq(keytabPath), eq(krbDebug), - any(ActionListener.class)); + anyActionListener()); } } @@ -145,7 +144,7 @@ public void testDelegatedAuthorizationFailedToResolve() throws Exception { AuthenticationResult result = future.actionGet(); assertThat(result.getStatus(), is(equalTo(AuthenticationResult.Status.CONTINUE))); verify(mockKerberosTicketValidator, times(1)).validateTicket(aryEq(decodedTicket), eq(keytabPath), eq(krbDebug), - any(ActionListener.class)); + anyActionListener()); verify(mockNativeRoleMappingStore).refreshRealmOnChange(kerberosRealm); verifyNoMoreInteractions(mockKerberosTicketValidator, mockNativeRoleMappingStore); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmCacheTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmCacheTests.java index 794512be4b190..1fbba2e5c13ec 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmCacheTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmCacheTests.java @@ -7,23 +7,23 @@ package org.elasticsearch.xpack.security.authc.kerberos; -import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.core.Tuple; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; import org.elasticsearch.xpack.core.security.authc.kerberos.KerberosRealmSettings; -import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper.UserData; +import org.elasticsearch.xpack.core.security.user.User; import org.ietf.jgss.GSSException; -import javax.security.auth.login.LoginException; import java.io.IOException; import java.nio.file.Path; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.security.auth.login.LoginException; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; @@ -45,7 +45,7 @@ public void testAuthenticateWithCache() throws LoginException, GSSException { final Map metadata = new HashMap<>(); metadata.put(KerberosRealm.KRB_METADATA_REALM_NAME_KEY, realmName(username)); metadata.put(KerberosRealm.KRB_METADATA_UPN_KEY, username); - final User expectedUser = new User(expectedUsername, roles.toArray(new String[roles.size()]), null, null, metadata, true); + final User expectedUser = new User(expectedUsername, roles.toArray(new String[0]), null, null, metadata, true); final byte[] decodedTicket = randomByteArrayOfLength(10); final Path keytabPath = config.env().configFile().resolve(config.getSetting(KerberosRealmSettings.HTTP_SERVICE_KEYTAB_PATH)); final boolean krbDebug = config.getSetting(KerberosRealmSettings.SETTING_KRB_DEBUG_ENABLE); @@ -59,9 +59,9 @@ public void testAuthenticateWithCache() throws LoginException, GSSException { assertThat(user1, sameInstance(user2)); verify(mockKerberosTicketValidator, times(2)).validateTicket(aryEq(decodedTicket), eq(keytabPath), eq(krbDebug), - any(ActionListener.class)); + anyActionListener()); verify(mockNativeRoleMappingStore).refreshRealmOnChange(kerberosRealm); - verify(mockNativeRoleMappingStore).resolveRoles(any(UserData.class), any(ActionListener.class)); + verify(mockNativeRoleMappingStore).resolveRoles(any(UserData.class), anyActionListener()); verifyNoMoreInteractions(mockKerberosTicketValidator, mockNativeRoleMappingStore); } @@ -97,13 +97,13 @@ public void testCacheInvalidationScenarios() throws LoginException, GSSException if (expireAll || expireThisUser.equals(authNUsername)) { assertThat(user1, is(not(sameInstance(user2)))); - verify(mockNativeRoleMappingStore, times(2)).resolveRoles(any(UserData.class), any(ActionListener.class)); + verify(mockNativeRoleMappingStore, times(2)).resolveRoles(any(UserData.class), anyActionListener()); } else { assertThat(user1, sameInstance(user2)); - verify(mockNativeRoleMappingStore).resolveRoles(any(UserData.class), any(ActionListener.class)); + verify(mockNativeRoleMappingStore).resolveRoles(any(UserData.class), anyActionListener()); } verify(mockKerberosTicketValidator, times(2)).validateTicket(aryEq(decodedTicket), eq(keytabPath), eq(krbDebug), - any(ActionListener.class)); + anyActionListener()); verifyNoMoreInteractions(mockKerberosTicketValidator, mockNativeRoleMappingStore); } @@ -120,7 +120,7 @@ public void testAuthenticateWithValidTicketSucessAuthnWithUserDetailsWhenCacheDi final Map metadata = new HashMap<>(); metadata.put(KerberosRealm.KRB_METADATA_REALM_NAME_KEY, realmName(username)); metadata.put(KerberosRealm.KRB_METADATA_UPN_KEY, username); - final User expectedUser = new User(expectedUsername, roles.toArray(new String[roles.size()]), null, null, metadata, true); + final User expectedUser = new User(expectedUsername, roles.toArray(new String[0]), null, null, metadata, true); final byte[] decodedTicket = randomByteArrayOfLength(10); final Path keytabPath = config.env().configFile().resolve(config.getSetting(KerberosRealmSettings.HTTP_SERVICE_KEYTAB_PATH)); final boolean krbDebug = config.getSetting(KerberosRealmSettings.SETTING_KRB_DEBUG_ENABLE); @@ -134,9 +134,9 @@ public void testAuthenticateWithValidTicketSucessAuthnWithUserDetailsWhenCacheDi assertThat(user1, not(sameInstance(user2))); verify(mockKerberosTicketValidator, times(2)).validateTicket(aryEq(decodedTicket), eq(keytabPath), eq(krbDebug), - any(ActionListener.class)); + anyActionListener()); verify(mockNativeRoleMappingStore).refreshRealmOnChange(kerberosRealm); - verify(mockNativeRoleMappingStore, times(2)).resolveRoles(any(UserData.class), any(ActionListener.class)); + verify(mockNativeRoleMappingStore, times(2)).resolveRoles(any(UserData.class), anyActionListener()); verifyNoMoreInteractions(mockKerberosTicketValidator, mockNativeRoleMappingStore); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTestCase.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTestCase.java index f43d296cf8f23..831292a1a81c5 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTestCase.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTestCase.java @@ -95,6 +95,7 @@ public void shutdown() throws InterruptedException { terminate(threadPool); } + @SuppressWarnings("unchecked") protected void mockKerberosTicketValidator(final byte[] decodedTicket, final Path keytabPath, final boolean krbDebug, final Tuple value, final Exception e) { assert value != null || e != null; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTests.java index 45cd9bf4ea82a..9cea9f220888b 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/kerberos/KerberosRealmTests.java @@ -9,25 +9,23 @@ import org.apache.lucene.util.Constants; import org.elasticsearch.ElasticsearchSecurityException; -import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.core.Tuple; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; import org.elasticsearch.xpack.core.security.authc.kerberos.KerberosRealmSettings; +import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper.UserData; import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.security.authc.support.MockLookupRealm; -import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper.UserData; import org.ietf.jgss.GSSException; -import javax.security.auth.login.LoginException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.SeekableByteChannel; @@ -45,8 +43,9 @@ import java.util.Locale; import java.util.Map; import java.util.Set; +import javax.security.auth.login.LoginException; -import static org.elasticsearch.xpack.security.authc.kerberos.KerberosRealmTestCase.buildKerberosRealmSettings; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; @@ -90,9 +89,9 @@ public void testAuthenticateWithValidTicketSucessAuthnWithUserDetails() throws L assertSuccessAuthenticationResult(expectedUser, "out-token", future.actionGet()); verify(mockKerberosTicketValidator, times(1)).validateTicket(aryEq(decodedTicket), eq(keytabPath), eq(krbDebug), - any(ActionListener.class)); + anyActionListener()); verify(mockNativeRoleMappingStore).refreshRealmOnChange(kerberosRealm); - verify(mockNativeRoleMappingStore).resolveRoles(any(UserData.class), any(ActionListener.class)); + verify(mockNativeRoleMappingStore).resolveRoles(any(UserData.class), anyActionListener()); verifyNoMoreInteractions(mockKerberosTicketValidator, mockNativeRoleMappingStore); } @@ -204,10 +203,10 @@ public void testDelegatedAuthorization() throws Exception { assertSuccessAuthenticationResult(expectedUser, "out-token", future.actionGet()); verify(mockKerberosTicketValidator, times(2)).validateTicket(aryEq(decodedTicket), eq(keytabPath), eq(krbDebug), - any(ActionListener.class)); + anyActionListener()); verify(mockNativeRoleMappingStore).refreshRealmOnChange(kerberosRealm); verifyNoMoreInteractions(mockKerberosTicketValidator, mockNativeRoleMappingStore); - verify(otherRealm, times(2)).lookupUser(eq(expectedUsername), any(ActionListener.class)); + verify(otherRealm, times(2)).lookupUser(eq(expectedUsername), anyActionListener()); } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java index cf149727a79d5..c3e910b4b9b89 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/ActiveDirectoryRealmTests.java @@ -70,6 +70,7 @@ import java.util.Locale; import java.util.Map; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; import static org.elasticsearch.xpack.core.security.authc.ldap.support.SessionFactorySettings.URLS_SETTING; import static org.hamcrest.Matchers.arrayContaining; @@ -236,7 +237,7 @@ public void testAuthenticateCachesSuccessfulAuthentications() throws Exception { } // verify one and only one session as further attempts should be returned from cache - verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); + verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), anyActionListener()); } public void testAuthenticateCachingCanBeDisabled() throws Exception { @@ -258,7 +259,7 @@ public void testAuthenticateCachingCanBeDisabled() throws Exception { } // verify one and only one session as second attempt should be returned from cache - verify(sessionFactory, times(count)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); + verify(sessionFactory, times(count)).session(eq("CN=ironman"), any(SecureString.class), anyActionListener()); } public void testAuthenticateCachingClearsCacheOnRoleMapperRefresh() throws Exception { @@ -278,7 +279,7 @@ public void testAuthenticateCachingClearsCacheOnRoleMapperRefresh() throws Excep } // verify one and only one session as further attempts should be returned from cache - verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); + verify(sessionFactory, times(1)).session(eq("CN=ironman"), any(SecureString.class), anyActionListener()); // Refresh the role mappings roleMapper.notifyRefresh(); @@ -289,7 +290,7 @@ public void testAuthenticateCachingClearsCacheOnRoleMapperRefresh() throws Excep future.actionGet(); } - verify(sessionFactory, times(2)).session(eq("CN=ironman"), any(SecureString.class), any(ActionListener.class)); + verify(sessionFactory, times(2)).session(eq("CN=ironman"), any(SecureString.class), anyActionListener()); } public void testUnauthenticatedLookupWithConnectionPool() throws Exception { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/CancellableLdapRunnableTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/CancellableLdapRunnableTests.java index 611a6305474ba..9f8de13b9fac0 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/CancellableLdapRunnableTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/CancellableLdapRunnableTests.java @@ -25,8 +25,8 @@ public class CancellableLdapRunnableTests extends ESTestCase { public void testTimingOutARunnable() { AtomicReference exceptionAtomicReference = new AtomicReference<>(); - final CancellableLdapRunnable runnable = - new CancellableLdapRunnable(ActionListener.wrap(user -> { + final CancellableLdapRunnable runnable = + new CancellableLdapRunnable<>(ActionListener.wrap(user -> { throw new AssertionError("onResponse should not be called"); }, exceptionAtomicReference::set), e -> null, () -> { throw new AssertionError("runnable should not be executed"); @@ -43,8 +43,8 @@ public void testTimingOutARunnable() { public void testCallTimeOutAfterRunning() { final AtomicBoolean ran = new AtomicBoolean(false); final AtomicBoolean listenerCalled = new AtomicBoolean(false); - final CancellableLdapRunnable runnable = - new CancellableLdapRunnable(ActionListener.wrap(user -> { + final CancellableLdapRunnable runnable = + new CancellableLdapRunnable<>(ActionListener.wrap(user -> { listenerCalled.set(true); throw new AssertionError("onResponse should not be called"); }, e -> { @@ -63,8 +63,8 @@ public void testCallTimeOutAfterRunning() { public void testRejectingExecution() { AtomicReference exceptionAtomicReference = new AtomicReference<>(); - final CancellableLdapRunnable runnable = - new CancellableLdapRunnable(ActionListener.wrap(user -> { + final CancellableLdapRunnable runnable = + new CancellableLdapRunnable<>(ActionListener.wrap(user -> { throw new AssertionError("onResponse should not be called"); }, exceptionAtomicReference::set), e -> null, () -> { throw new AssertionError("runnable should not be executed"); @@ -86,7 +86,7 @@ public void testTimeoutDuringExecution() throws InterruptedException { }, e -> { throw new AssertionError("onFailure should not be executed"); }); - final CancellableLdapRunnable runnable = new CancellableLdapRunnable(listener, e -> null, () -> { + final CancellableLdapRunnable runnable = new CancellableLdapRunnable<>(listener, e -> null, () -> { runningLatch.countDown(); try { timeoutCalledLatch.await(); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java index 959a00c92ab2b..9abb5f17b9a6e 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/ldap/LdapRealmTests.java @@ -63,6 +63,7 @@ import java.util.Map; import java.util.function.Function; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; import static org.elasticsearch.xpack.core.security.authc.ldap.support.SessionFactorySettings.URLS_SETTING; import static org.hamcrest.Matchers.arrayContaining; @@ -198,7 +199,7 @@ public void testAuthenticateCaching() throws Exception { assertThat(future.actionGet().getStatus(), is(AuthenticationResult.Status.SUCCESS)); //verify one and only one session -> caching is working - verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), any(ActionListener.class)); + verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), anyActionListener()); } public void testAuthenticateCachingRefresh() throws Exception { @@ -225,7 +226,7 @@ public void testAuthenticateCachingRefresh() throws Exception { future.actionGet(); //verify one and only one session -> caching is working - verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), any(ActionListener.class)); + verify(ldapFactory, times(1)).session(anyString(), any(SecureString.class), anyActionListener()); roleMapper.notifyRefresh(); @@ -234,7 +235,7 @@ public void testAuthenticateCachingRefresh() throws Exception { future.actionGet(); //we need to session again - verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), any(ActionListener.class)); + verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), anyActionListener()); } public void testAuthenticateNoncaching() throws Exception { @@ -262,7 +263,7 @@ public void testAuthenticateNoncaching() throws Exception { future.actionGet(); //verify two and only two binds -> caching is disabled - verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), any(ActionListener.class)); + verify(ldapFactory, times(2)).session(anyString(), any(SecureString.class), anyActionListener()); } public void testDelegatedAuthorization() throws Exception { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java index 3db41d9636cbc..e6cfc5ed1de4b 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectAuthenticatorTests.java @@ -6,6 +6,8 @@ */ package org.elasticsearch.xpack.security.authc.oidc; +import net.minidev.json.JSONArray; + import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.JWSHeader; import com.nimbusds.jose.crypto.ECDSASigner; @@ -40,15 +42,15 @@ import com.nimbusds.openid.connect.sdk.claims.AccessTokenHash; import com.nimbusds.openid.connect.sdk.validators.IDTokenValidator; import com.nimbusds.openid.connect.sdk.validators.InvalidHashException; -import net.minidev.json.JSONArray; + import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.support.PlainActionFuture; -import org.elasticsearch.core.Nullable; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; +import org.elasticsearch.core.Nullable; +import org.elasticsearch.core.Tuple; import org.elasticsearch.env.Environment; import org.elasticsearch.env.TestEnvironment; import org.elasticsearch.xpack.core.security.authc.RealmConfig; @@ -57,8 +59,6 @@ import org.junit.Before; import org.mockito.Mockito; -import javax.crypto.SecretKey; -import javax.crypto.spec.SecretKeySpec; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; @@ -75,6 +75,8 @@ import java.util.Date; import java.util.Map; import java.util.UUID; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; import static java.time.Instant.now; import static org.hamcrest.Matchers.containsInAnyOrder; @@ -114,9 +116,9 @@ private OpenIdConnectAuthenticator buildAuthenticator() throws URISyntaxExceptio } private OpenIdConnectAuthenticator buildAuthenticator(OpenIdConnectProviderConfiguration opConfig, RelyingPartyConfiguration rpConfig, - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource) { + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource) { final RealmConfig config = buildConfig(getBasicRealmSettings().build(), threadContext); - final JWSVerificationKeySelector keySelector = new JWSVerificationKeySelector(rpConfig.getSignatureAlgorithm(), jwkSource); + final JWSVerificationKeySelector keySelector = new JWSVerificationKeySelector<>(rpConfig.getSignatureAlgorithm(), jwkSource); final IDTokenValidator validator = new IDTokenValidator(opConfig.getIssuer(), rpConfig.getClientId(), keySelector, null); return new OpenIdConnectAuthenticator(config, opConfig, rpConfig, new SSLService(env), validator, null); @@ -166,7 +168,7 @@ public void testInvalidNonceIsRejected() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } @@ -194,7 +196,7 @@ public void testAuthenticateImplicitFlowWithRsa() throws Exception { final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); final State state = new State(); @@ -216,7 +218,7 @@ public void testAuthenticateImplicitFlowWithEcdsa() throws Exception { final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); final State state = new State(); @@ -263,7 +265,7 @@ public void testClockSkewIsHonored() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -301,7 +303,7 @@ public void testImplicitFlowFailsWithExpiredToken() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -346,7 +348,7 @@ public void testImplicitFlowFailsNotYetIssuedToken() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -391,7 +393,7 @@ public void testImplicitFlowFailsInvalidIssuer() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -435,7 +437,7 @@ public void testImplicitFlowFailsInvalidAudience() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -476,7 +478,7 @@ public void testAuthenticateImplicitFlowFailsWithForgedRsaIdToken() throws Excep final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); final State state = new State(); @@ -502,7 +504,7 @@ public void testAuthenticateImplicitFlowFailsWithForgedEcsdsaIdToken() throws Ex final Key key = keyMaterial.v1(); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); final State state = new State(); @@ -556,7 +558,7 @@ public void testAuthenticateImplicitFlowFailsWithForgedAccessToken() throws Exce if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -587,7 +589,7 @@ public void testImplicitFlowFailsWithNoneAlgorithm() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -627,7 +629,7 @@ public void testImplicitFlowFailsWithAlgorithmMixupAttack() throws Exception { final JWK jwk = keyMaterial.v2().getKeys().get(0); RelyingPartyConfiguration rpConfig = getRpConfig(jwk.getAlgorithm().getName()); OpenIdConnectProviderConfiguration opConfig = getOpConfig(); - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); final State state = new State(); final Nonce nonce = new Nonce(); @@ -657,7 +659,7 @@ public void testImplicitFlowFailsWithUnsignedJwt() throws Exception { if (jwk.getAlgorithm().getName().startsWith("HS")) { authenticator = buildAuthenticator(opConfig, rpConfig); } else { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mockSource(jwk); authenticator = buildAuthenticator(opConfig, rpConfig, jwkSource); } final State state = new State(); @@ -816,6 +818,7 @@ public void testJsonObjectMerging() throws Exception { .toJSONObject(); OpenIdConnectAuthenticator.mergeObjects(idTokenObject, userInfoWithAddress); assertTrue(idTokenObject.containsKey("address")); + @SuppressWarnings("unchecked") Map combinedAddress = (Map) idTokenObject.get("address"); assertTrue(combinedAddress.containsKey("street_name")); assertTrue(combinedAddress.containsKey("locality")); @@ -931,8 +934,9 @@ private String buildAuthResponse(JWT idToken, @Nullable AccessToken accessToken, return response.toURI().toString(); } - private OpenIdConnectAuthenticator.ReloadableJWKSource mockSource(JWK jwk) { - OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = + @SuppressWarnings("unchecked") + private OpenIdConnectAuthenticator.ReloadableJWKSource mockSource(JWK jwk) { + OpenIdConnectAuthenticator.ReloadableJWKSource jwkSource = mock(OpenIdConnectAuthenticator.ReloadableJWKSource.class); when(jwkSource.get(any(), any())).thenReturn(Collections.singletonList(jwk)); Mockito.doAnswer(invocation -> { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java index 891817037cd00..a8747a8235e43 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/oidc/OpenIdConnectRealmTests.java @@ -33,6 +33,7 @@ import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper; import org.hamcrest.Matchers; import org.junit.Before; +import org.mockito.stubbing.Answer; import java.util.Arrays; import java.util.Collection; @@ -46,6 +47,7 @@ import java.util.concurrent.atomic.AtomicReference; import static java.time.Instant.now; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; import static org.elasticsearch.xpack.security.authc.oidc.OpenIdConnectRealm.CONTEXT_TOKEN_DATA; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; @@ -77,13 +79,7 @@ public void testAuthentication() throws Exception { final UserRoleMapper roleMapper = mock(UserRoleMapper.class); final String principal = randomAlphaOfLength(12); AtomicReference userData = new AtomicReference<>(); - doAnswer(invocation -> { - assert invocation.getArguments().length == 2; - userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]); - ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; - listener.onResponse(new HashSet<>(Arrays.asList("kibana_user", "role1"))); - return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + doAnswer(getAnswer(userData)).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); final boolean notPopulateMetadata = randomBoolean(); final String authenticatingRealm = randomBoolean() ? REALM_NAME : null; @@ -110,13 +106,7 @@ public void testClaimPropertyMapping() throws Exception { final UserRoleMapper roleMapper = mock(UserRoleMapper.class); final String principal = randomAlphaOfLength(12); AtomicReference userData = new AtomicReference<>(); - doAnswer(invocation -> { - assert invocation.getArguments().length == 2; - userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]); - ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; - listener.onResponse(new HashSet<>(Arrays.asList("kibana_user", "role1"))); - return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + doAnswer(getAnswer(userData)).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); Map claimsWithObject = Map.of( "groups", List.of(Map.of("key1", List.of("value1", "value2")), Map.of("key2", List.of("value1", "value2"))) ); @@ -134,13 +124,7 @@ public void testClaimMetadataMapping() throws Exception { final UserRoleMapper roleMapper = mock(UserRoleMapper.class); final String principal = randomAlphaOfLength(12); AtomicReference userData = new AtomicReference<>(); - doAnswer(invocation -> { - assert invocation.getArguments().length == 2; - userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]); - ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; - listener.onResponse(new HashSet<>(Arrays.asList("kibana_user", "role1"))); - return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + doAnswer(getAnswer(userData)).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); Map claims = Map.of( "string", "String", "number", 232, @@ -173,10 +157,11 @@ public void testWithAuthorizingRealm() throws Exception { final String principal = randomAlphaOfLength(12); doAnswer(invocation -> { assert invocation.getArguments().length == 2; + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; listener.onFailure(new RuntimeException("Role mapping should not be called")); return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); final String authenticatingRealm = randomBoolean() ? REALM_NAME : null; AuthenticationResult result = authenticateWithOidc(principal, roleMapper, randomBoolean(), true, authenticatingRealm, null); assertThat(result, notNullValue()); @@ -189,7 +174,8 @@ public void testWithAuthorizingRealm() throws Exception { assertThat(result.getUser().metadata().get("is_lookup"), Matchers.equalTo(true)); assertNotNull(result.getMetadata().get(CONTEXT_TOKEN_DATA)); assertThat(result.getMetadata().get(CONTEXT_TOKEN_DATA), instanceOf(Map.class)); - Map tokenMetadata = (Map) result.getMetadata().get(CONTEXT_TOKEN_DATA); + @SuppressWarnings("unchecked") + Map tokenMetadata = (Map) result.getMetadata().get(CONTEXT_TOKEN_DATA); assertThat(tokenMetadata.get("id_token_hint"), equalTo("thisis.aserialized.jwt")); } @@ -235,10 +221,11 @@ public void testInvalidPrincipalClaimPatternParsing() { .issuer("https://op.company.org") .build(); doAnswer((i) -> { + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) i.getArguments()[1]; listener.onResponse(claims); return null; - }).when(authenticator).authenticate(any(OpenIdConnectToken.class), any(ActionListener.class)); + }).when(authenticator).authenticate(any(OpenIdConnectToken.class), anyActionListener()); final PlainActionFuture future = new PlainActionFuture<>(); realm.authenticate(token, future); @@ -447,10 +434,11 @@ private AuthenticationResult authenticateWithOidc(String principal, UserRoleMapp } final JWTClaimsSet claims = claimsBuilder.build(); doAnswer((i) -> { + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) i.getArguments()[1]; listener.onResponse(claims); return null; - }).when(authenticator).authenticate(any(OpenIdConnectToken.class), any(ActionListener.class)); + }).when(authenticator).authenticate(any(OpenIdConnectToken.class), anyActionListener()); final PlainActionFuture future = new PlainActionFuture<>(); realm.authenticate(token, future); @@ -467,4 +455,15 @@ private void initializeRealms(Realm... realms) { realm.initialize(realmList, licenseState); } } + + private Answer> getAnswer(AtomicReference userData) { + return invocation -> { + assert invocation.getArguments().length == 2; + userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]); + @SuppressWarnings("unchecked") + ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; + listener.onResponse(new HashSet<>(Arrays.asList("kibana_user", "role1"))); + return null; + }; + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java index 6784d4358954b..34e807b2c6a56 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/pki/PkiRealmTests.java @@ -27,16 +27,15 @@ import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.RealmSettings; import org.elasticsearch.xpack.core.security.authc.pki.PkiRealmSettings; +import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper; import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.core.security.support.NoOpLogger; import org.elasticsearch.xpack.core.security.user.User; import org.elasticsearch.xpack.security.authc.BytesKey; import org.elasticsearch.xpack.security.authc.support.MockLookupRealm; -import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper; import org.junit.Before; import org.mockito.Mockito; -import javax.security.auth.x500.X500Principal; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; @@ -49,7 +48,9 @@ import java.util.Map; import java.util.Set; import java.util.regex.Pattern; +import javax.security.auth.x500.X500Principal; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; @@ -155,17 +156,18 @@ private void assertSuccessfulAuthentication(Set roles) throws Exception } final int numTimes = invalidate ? 2 : 1; - verify(roleMapper, times(numTimes)).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + verify(roleMapper, times(numTimes)).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); verifyNoMoreInteractions(roleMapper); } private UserRoleMapper buildRoleMapper() { UserRoleMapper roleMapper = mock(UserRoleMapper.class); Mockito.doAnswer(invocation -> { + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; listener.onResponse(Collections.emptySet()); return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); return roleMapper; } @@ -173,6 +175,7 @@ private UserRoleMapper buildRoleMapper(Set roles, String dn) { UserRoleMapper roleMapper = mock(UserRoleMapper.class); Mockito.doAnswer(invocation -> { final UserRoleMapper.UserData userData = (UserRoleMapper.UserData) invocation.getArguments()[0]; + @SuppressWarnings("unchecked") final ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; if (userData.getDn().equals(dn)) { listener.onResponse(roles); @@ -180,7 +183,7 @@ private UserRoleMapper buildRoleMapper(Set roles, String dn) { listener.onFailure(new IllegalArgumentException("Expected DN '" + dn + "' but was '" + userData + "'")); } return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); return roleMapper; } @@ -413,7 +416,7 @@ public void testTruststorePathWithLegacyPasswordDoesNotThrow() throws Exception .build(); new PkiRealm(new RealmConfig(new RealmConfig.RealmIdentifier(PkiRealmSettings.TYPE, REALM_NAME), settings, TestEnvironment.newEnvironment(settings), new ThreadContext(settings)), mock(UserRoleMapper.class)); - assertSettingDeprecationsAndWarnings(new Setting[]{ + assertSettingDeprecationsAndWarnings(new Setting[]{ PkiRealmSettings.LEGACY_TRUST_STORE_PASSWORD.getConcreteSettingForNamespace(REALM_NAME) }); } @@ -471,7 +474,7 @@ public void testPKIRealmSettingsPassValidation() throws Exception { ClusterSettings clusterSettings = new ClusterSettings(settings, new HashSet<>(settingList)); clusterSettings.validate(settings, true); - assertSettingDeprecationsAndWarnings(new Setting[]{ + assertSettingDeprecationsAndWarnings(new Setting[]{ PkiRealmSettings.LEGACY_TRUST_STORE_PASSWORD.getConcreteSettingForNamespace("pki1") }); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java index 4f39e44941a87..8314885fd3db6 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlRealmTests.java @@ -74,6 +74,7 @@ import java.util.function.Supplier; import java.util.stream.Stream; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.authc.RealmSettings.getFullSettingKey; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.hamcrest.Matchers.contains; @@ -174,10 +175,11 @@ public void testAuthenticateWithRoleMapping() throws Exception { Mockito.doAnswer(invocation -> { assert invocation.getArguments().length == 2; userData.set((UserRoleMapper.UserData) invocation.getArguments()[0]); + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; listener.onResponse(Collections.singleton("superuser")); return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); final boolean useNameId = randomBoolean(); final boolean principalIsEmailAddress = randomBoolean(); @@ -209,10 +211,11 @@ public void testAuthenticateWithAuthorizingRealm() throws Exception { final UserRoleMapper roleMapper = mock(UserRoleMapper.class); Mockito.doAnswer(invocation -> { assert invocation.getArguments().length == 2; + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocation.getArguments()[1]; listener.onFailure(new RuntimeException("Role mapping should not be called")); return null; - }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), any(ActionListener.class)); + }).when(roleMapper).resolveRoles(any(UserRoleMapper.UserData.class), anyActionListener()); final boolean useNameId = randomBoolean(); final boolean principalIsEmailAddress = randomBoolean(); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlSpMetadataBuilderTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlSpMetadataBuilderTests.java index 111e526c0916a..0b63d7a2bb624 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlSpMetadataBuilderTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlSpMetadataBuilderTests.java @@ -56,7 +56,7 @@ public void setup() throws Exception { if (threeCerts.length != 3) { fail("Expected exactly 3 certificate in " + certPath); } - List notX509Certificates = Arrays.stream(threeCerts).filter((cert) -> { + List> notX509Certificates = Arrays.stream(threeCerts).filter((cert) -> { return (cert instanceof X509Certificate) == false; }).map(cert -> cert.getClass()).collect(Collectors.toList()); if (notX509Certificates.isEmpty() == false) { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java index 76549d89e7edb..28af0118c7fe9 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/service/IndexServiceAccountTokenStoreTests.java @@ -112,6 +112,7 @@ public void init() { when(threadPool.getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY)); client = new FilterClient(mockClient) { @Override + @SuppressWarnings("unchecked") protected void doExecute(ActionType action, Request request, ActionListener listener) { requestHolder.set(request); @@ -135,12 +136,12 @@ void doExecute(ActionType action, Request request, ActionListener { Runnable action = (Runnable) i.getArguments()[1]; action.run(); return null; - }).when(securityIndex).checkIndexVersionThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).checkIndexVersionThenExecute(anyConsumer(), any(Runnable.class)); store = new IndexServiceAccountTokenStore(Settings.EMPTY, threadPool, Clock.systemUTC(), @@ -390,4 +391,9 @@ private BulkResponse createSingleBulkResponse() { )) }, randomLong()); } + + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/ApiKeyGeneratorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/ApiKeyGeneratorTests.java index 43cba1ff0d75b..4dc55f4ea23be 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/ApiKeyGeneratorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/ApiKeyGeneratorTests.java @@ -35,6 +35,7 @@ public class ApiKeyGeneratorTests extends ESTestCase { + @SuppressWarnings("unchecked") public void testGenerateApiKeySuccessfully() { final ApiKeyService apiKeyService = mock(ApiKeyService.class); final CompositeRolesStore rolesStore = mock(CompositeRolesStore.class); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/mapper/NativeRoleMappingStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/mapper/NativeRoleMappingStoreTests.java index ebdcfd6f2c399..2bea6f09aced0 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/mapper/NativeRoleMappingStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/support/mapper/NativeRoleMappingStoreTests.java @@ -51,6 +51,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; @@ -244,11 +245,12 @@ private NativeRoleMappingStore buildRoleMappingStoreForInvalidationTesting(Atomi final ClearRealmCacheRequest request = (ClearRealmCacheRequest) invocationOnMock.getArguments()[1]; assertThat(request.realms(), Matchers.arrayContaining(realmName)); + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) invocationOnMock.getArguments()[2]; invalidationCounter.incrementAndGet(); listener.onResponse(new ClearRealmCacheResponse(new ClusterName("cluster"), Collections.emptyList(), Collections.emptyList())); return null; - }).when(client).execute(eq(ClearRealmCacheAction.INSTANCE), any(ClearRealmCacheRequest.class), any(ActionListener.class)); + }).when(client).execute(eq(ClearRealmCacheAction.INSTANCE), any(ClearRealmCacheRequest.class), anyActionListener()); final NativeRoleMappingStore store = new NativeRoleMappingStore(Settings.EMPTY, client, mock(SecurityIndexManager.class), mock(ScriptService.class)); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java index eb35b5501439a..93ce00a40347b 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/AuthorizationServiceTests.java @@ -180,6 +180,7 @@ import java.util.function.Predicate; import static java.util.Arrays.asList; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.SecurityTestsUtils.assertAuthenticationException; import static org.elasticsearch.test.SecurityTestsUtils.assertThrowsAuthorizationException; import static org.elasticsearch.test.SecurityTestsUtils.assertThrowsAuthorizationExceptionRunAs; @@ -254,7 +255,7 @@ public void setup() { listener.onResponse(Collections.emptyList()); return null; } - ).when(privilegesStore).getPrivileges(any(Collection.class), any(Collection.class), any(ActionListener.class)); + ).when(privilegesStore).getPrivileges(any(Collection.class), any(Collection.class), anyActionListener()); doAnswer((i) -> { ActionListener callback = (ActionListener) i.getArguments()[2]; @@ -277,7 +278,7 @@ public void setup() { ); } return Void.TYPE; - }).when(rolesStore).getRoles(any(User.class), any(Authentication.class), any(ActionListener.class)); + }).when(rolesStore).getRoles(any(User.class), any(Authentication.class), anyActionListener()); roleMap.put(ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR.getName(), ReservedRolesStore.SUPERUSER_ROLE_DESCRIPTOR); operatorPrivilegesService = mock(OperatorPrivileges.OperatorPrivilegesService.class); authorizationService = new AuthorizationService(settings, rolesStore, clusterService, @@ -712,7 +713,7 @@ public void testServiceAccountDenial() { ActionListener listener = (ActionListener) invocationOnMock.getArguments()[2]; listener.onResponse(Role.EMPTY); return null; - }).when(rolesStore).getRoles(any(User.class), any(Authentication.class), any(ActionListener.class)); + }).when(rolesStore).getRoles(any(User.class), any(Authentication.class), anyActionListener()); ElasticsearchSecurityException securityException = expectThrows(ElasticsearchSecurityException.class, () -> authorize(authentication, action, request)); @@ -741,7 +742,6 @@ public void testThatNonIndicesAndNonClusterActionIsDenied() throws IOException { } public void testThatRoleWithNoIndicesIsDenied() throws IOException { - @SuppressWarnings("unchecked") Tuple tuple = randomFrom( new Tuple<>(SearchAction.NAME, new SearchRequest()), new Tuple<>(SqlQueryAction.NAME, new SqlQueryRequest())); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java index 3b791646a970c..261decc281834 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndicesAndAliasesResolverTests.java @@ -32,9 +32,9 @@ import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.action.support.PlainActionFuture; import org.elasticsearch.action.termvectors.MultiTermVectorsRequest; -import org.elasticsearch.cluster.metadata.DataStreamTestHelper; import org.elasticsearch.cluster.metadata.AliasMetadata; import org.elasticsearch.cluster.metadata.DataStream; +import org.elasticsearch.cluster.metadata.DataStreamTestHelper; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.IndexMetadata.State; import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver; @@ -42,11 +42,11 @@ import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.common.Strings; import org.elasticsearch.common.UUIDs; -import org.elasticsearch.core.Tuple; import org.elasticsearch.common.regex.Regex; import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.time.DateFormatter; +import org.elasticsearch.core.Tuple; import org.elasticsearch.index.Index; import org.elasticsearch.index.IndexNotFoundException; import org.elasticsearch.indices.TestIndexNameExpressionResolver; @@ -86,6 +86,7 @@ import java.util.Set; import static org.elasticsearch.cluster.metadata.DataStreamTestHelper.createTimestampField; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.test.TestMatchers.throwableWithMessage; import static org.elasticsearch.xpack.core.security.index.RestrictedIndicesNames.SECURITY_MAIN_ALIAS; import static org.elasticsearch.xpack.security.authz.AuthorizedIndicesTests.getRequestInfo; @@ -103,6 +104,7 @@ import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.oneOf; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anySetOf; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; @@ -122,6 +124,7 @@ public class IndicesAndAliasesResolverTests extends ESTestCase { private String tomorrowSuffix; @Before +// @SuppressWarnings("unchecked") public void setup() { Settings settings = Settings.builder() .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT) @@ -260,8 +263,9 @@ public void setup() { }, null)); final FieldPermissionsCache fieldPermissionsCache = new FieldPermissionsCache(Settings.EMPTY); doAnswer((i) -> { - ActionListener callback = - (ActionListener) i.getArguments()[1]; + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) i.getArguments()[1]; + @SuppressWarnings("unchecked") Set names = (Set) i.getArguments()[0]; assertNotNull(names); Set roleDescriptors = new HashSet<>(); @@ -280,8 +284,8 @@ public void setup() { ); } return Void.TYPE; - }).when(rolesStore).roles(any(Set.class), any(ActionListener.class)); - doCallRealMethod().when(rolesStore).getRoles(any(User.class), any(Authentication.class), any(ActionListener.class)); + }).when(rolesStore).roles(anySetOf(String.class), anyActionListener()); + doCallRealMethod().when(rolesStore).getRoles(any(User.class), any(Authentication.class), anyActionListener()); ClusterService clusterService = mock(ClusterService.class); when(clusterService.getClusterSettings()).thenReturn(new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/accesscontrol/FieldDataCacheWithFieldSubsetReaderTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/accesscontrol/FieldDataCacheWithFieldSubsetReaderTests.java index 9d36369d873b5..6b72a8bddbca9 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/accesscontrol/FieldDataCacheWithFieldSubsetReaderTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/accesscontrol/FieldDataCacheWithFieldSubsetReaderTests.java @@ -162,6 +162,7 @@ public > FD load(LeafRe } @Override + @SuppressWarnings("unchecked") public > IFD load(DirectoryReader indexReader, IFD indexFieldData) throws Exception { topLevelBuilds++; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/IndicesAliasesRequestInterceptorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/IndicesAliasesRequestInterceptorTests.java index fca94d3217719..28cbf2b6fbe55 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/IndicesAliasesRequestInterceptorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/IndicesAliasesRequestInterceptorTests.java @@ -36,7 +36,9 @@ import java.util.Map; import java.util.Set; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -44,6 +46,7 @@ public class IndicesAliasesRequestInterceptorTests extends ESTestCase { + @SuppressWarnings("unchecked") public void testInterceptorThrowsWhenFLSDLSEnabled() { XPackLicenseState licenseState = mock(XPackLicenseState.class); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState); @@ -92,8 +95,8 @@ public void testInterceptorThrowsWhenFLSDLSEnabled() { ActionListener listener = (ActionListener) invocationOnMock.getArguments()[3]; listener.onResponse(AuthorizationResult.deny()); return null; - }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), any(Map.class), - any(ActionListener.class)); + }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), anyMap(), + anyActionListener()); ElasticsearchSecurityException securityException = expectThrows(ElasticsearchSecurityException.class, () -> { interceptor.intercept(requestInfo, mockEngine, EmptyAuthorizationInfo.INSTANCE, plainActionFuture); @@ -103,6 +106,7 @@ public void testInterceptorThrowsWhenFLSDLSEnabled() { securityException.getMessage()); } + @SuppressWarnings("unchecked") public void testInterceptorThrowsWhenTargetHasGreaterPermissions() throws Exception { XPackLicenseState licenseState = mock(XPackLicenseState.class); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState); @@ -137,7 +141,7 @@ public void testInterceptorThrowsWhenTargetHasGreaterPermissions() throws Except listener.onResponse(AuthorizationResult.deny()); return null; }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), any(Map.class), - any(ActionListener.class)); + anyActionListener()); ElasticsearchSecurityException securityException = expectThrows(ElasticsearchSecurityException.class, () -> { interceptor.intercept(requestInfo, mockEngine, EmptyAuthorizationInfo.INSTANCE, plainActionFuture); @@ -165,7 +169,7 @@ public void testInterceptorThrowsWhenTargetHasGreaterPermissions() throws Except listener.onResponse(AuthorizationResult.granted()); return null; }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), any(Map.class), - any(ActionListener.class)); + anyActionListener()); interceptor.intercept(requestInfo, mockEngine, EmptyAuthorizationInfo.INSTANCE, plainActionFuture); plainActionFuture.actionGet(); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/ResizeRequestInterceptorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/ResizeRequestInterceptorTests.java index 518ad872577e0..43eb6b9301f81 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/ResizeRequestInterceptorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/interceptor/ResizeRequestInterceptorTests.java @@ -40,7 +40,9 @@ import java.util.Map; import java.util.Set; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMap; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -48,6 +50,7 @@ public class ResizeRequestInterceptorTests extends ESTestCase { + @SuppressWarnings("unchecked") public void testResizeRequestInterceptorThrowsWhenFLSDLSEnabled() { XPackLicenseState licenseState = mock(XPackLicenseState.class); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState); @@ -89,8 +92,8 @@ public void testResizeRequestInterceptorThrowsWhenFLSDLSEnabled() { ActionListener listener = (ActionListener) invocationOnMock.getArguments()[3]; listener.onResponse(AuthorizationResult.deny()); return null; - }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), any(Map.class), - any(ActionListener.class)); + }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), anyMap(), + anyActionListener()); ElasticsearchSecurityException securityException = expectThrows(ElasticsearchSecurityException.class, () -> { resizeRequestInterceptor.intercept(requestInfo, mockEngine, EmptyAuthorizationInfo.INSTANCE, plainActionFuture); @@ -100,6 +103,7 @@ public void testResizeRequestInterceptorThrowsWhenFLSDLSEnabled() { securityException.getMessage()); } + @SuppressWarnings("unchecked") public void testResizeRequestInterceptorThrowsWhenTargetHasGreaterPermissions() throws Exception { XPackLicenseState licenseState = mock(XPackLicenseState.class); when(licenseState.copyCurrentLicenseState()).thenReturn(licenseState); @@ -130,7 +134,7 @@ public void testResizeRequestInterceptorThrowsWhenTargetHasGreaterPermissions() listener.onResponse(AuthorizationResult.deny()); return null; }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), any(Map.class), - any(ActionListener.class)); + anyActionListener()); ElasticsearchSecurityException securityException = expectThrows(ElasticsearchSecurityException.class, () -> { resizeRequestInterceptor.intercept(requestInfo, mockEngine, EmptyAuthorizationInfo.INSTANCE, plainActionFuture); @@ -149,7 +153,7 @@ public void testResizeRequestInterceptorThrowsWhenTargetHasGreaterPermissions() listener.onResponse(AuthorizationResult.granted()); return null; }).when(mockEngine).validateIndexPermissionsAreSubset(eq(requestInfo), eq(EmptyAuthorizationInfo.INSTANCE), any(Map.class), - any(ActionListener.class)); + anyActionListener()); resizeRequestInterceptor.intercept(requestInfo, mockEngine, EmptyAuthorizationInfo.INSTANCE, plainActionFuture); plainActionFuture.actionGet(); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java index 8c2776b3bace6..c6e0793897c78 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/CompositeRolesStoreTests.java @@ -19,7 +19,6 @@ import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.service.ClusterService; -import org.elasticsearch.core.Nullable; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamOutput; @@ -29,6 +28,7 @@ import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.core.Nullable; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.license.License.OperationMode; import org.elasticsearch.license.TestUtils.UpdatableLicenseState; @@ -96,6 +96,7 @@ import static org.elasticsearch.mock.orig.Mockito.times; import static org.elasticsearch.mock.orig.Mockito.verifyNoMoreInteractions; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY; import static org.elasticsearch.xpack.core.security.authc.AuthenticationField.API_KEY_ROLE_DESCRIPTORS_KEY; import static org.elasticsearch.xpack.security.authc.ApiKeyService.API_KEY_ID_KEY; @@ -110,6 +111,7 @@ import static org.hamcrest.Matchers.nullValue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; +import static org.mockito.Matchers.anyCollectionOf; import static org.mockito.Matchers.anySetOf; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; @@ -167,7 +169,7 @@ public void testRolesWhenDlsFlsUnlicensed() throws IOException { .build() }, null); FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(Collections.singleton("fls"))).thenReturn(Collections.singleton(flsRole)); when(fileRolesStore.roleDescriptors(Collections.singleton("dls"))).thenReturn(Collections.singleton(dlsRole)); @@ -239,7 +241,7 @@ public void testRolesWhenDlsFlsLicensed() throws IOException { .build() }, null); FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(Collections.singleton("fls"))).thenReturn(Collections.singleton(flsRole)); when(fileRolesStore.roleDescriptors(Collections.singleton("dls"))).thenReturn(Collections.singleton(dlsRole)); when(fileRolesStore.roleDescriptors(Collections.singleton("fls_dls"))).thenReturn(Collections.singleton(flsDlsRole)); @@ -276,30 +278,32 @@ public void testRolesWhenDlsFlsLicensed() throws IOException { public void testNegativeLookupsAreCached() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.success(Collections.emptySet())); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final NativePrivilegeStore nativePrivilegeStore = mock(NativePrivilegeStore.class); doAnswer((invocationOnMock) -> { - ActionListener> callback = null; - callback = (ActionListener>) invocationOnMock.getArguments()[2]; + @SuppressWarnings("unchecked") + ActionListener> callback = + (ActionListener>) invocationOnMock.getArguments()[2]; callback.onResponse(Collections.emptyList()); return null; - }).when(nativePrivilegeStore).getPrivileges(isA(Set.class), isA(Set.class), any(ActionListener.class)); + }).when(nativePrivilegeStore).getPrivileges(anySetOf(String.class), anySetOf(String.class), anyActionListener()); final AtomicReference> effectiveRoleDescriptors = new AtomicReference>(); final CompositeRolesStore compositeRolesStore = buildCompositeRolesStore(SECURITY_ENABLED_SETTINGS, fileRolesStore, nativeRolesStore, reservedRolesStore, nativePrivilegeStore, null, null, null, null, rds -> effectiveRoleDescriptors.set(rds)); - verify(fileRolesStore).addListener(any(Consumer.class)); // adds a listener in ctor + verify(fileRolesStore).addListener(anyConsumer()); // adds a listener in ctor final String roleName = randomAlphaOfLengthBetween(1, 10); PlainActionFuture future = new PlainActionFuture<>(); @@ -308,11 +312,11 @@ public void testNegativeLookupsAreCached() { assertThat(effectiveRoleDescriptors.get().isEmpty(), is(true)); effectiveRoleDescriptors.set(null); assertEquals(Role.EMPTY, role); - verify(reservedRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); - verify(fileRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); + verify(reservedRolesStore).accept(anySetOf(String.class), anyActionListener()); + verify(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); verify(fileRolesStore).roleDescriptors(eq(Collections.singleton(roleName))); - verify(nativeRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); - verify(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + verify(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); + verify(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final int numberOfTimesToCall = scaledRandomIntBetween(0, 32); final boolean getSuperuserRole = randomBoolean() @@ -333,23 +337,24 @@ public void testNegativeLookupsAreCached() { if (getSuperuserRole && numberOfTimesToCall > 0) { // the superuser role was requested so we get the role descriptors again - verify(reservedRolesStore, times(2)).accept(anySetOf(String.class), any(ActionListener.class)); - verify(nativePrivilegeStore).getPrivileges(isA(Set.class), isA(Set.class), any(ActionListener.class)); + verify(reservedRolesStore, times(2)).accept(anySetOf(String.class), anyActionListener()); + verify(nativePrivilegeStore).getPrivileges(isASet(), isASet(), anyActionListener()); } verifyNoMoreInteractions(fileRolesStore, reservedRolesStore, nativeRolesStore, nativePrivilegeStore); } public void testNegativeLookupsCacheDisabled() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.success(Collections.emptySet())); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final Settings settings = Settings.builder().put(SECURITY_ENABLED_SETTINGS) @@ -362,7 +367,7 @@ reservedRolesStore, mock(NativePrivilegeStore.class), Collections.emptyList(), n new XPackLicenseState(settings, () -> 0), cache, mock(ApiKeyService.class), mock(ServiceAccountService.class), documentSubsetBitsetCache, rds -> effectiveRoleDescriptors.set(rds)); - verify(fileRolesStore).addListener(any(Consumer.class)); // adds a listener in ctor + verify(fileRolesStore).addListener(anyConsumer()); // adds a listener in ctor final String roleName = randomAlphaOfLengthBetween(1, 10); PlainActionFuture future = new PlainActionFuture<>(); @@ -371,11 +376,11 @@ reservedRolesStore, mock(NativePrivilegeStore.class), Collections.emptyList(), n assertThat(effectiveRoleDescriptors.get().isEmpty(), is(true)); effectiveRoleDescriptors.set(null); assertEquals(Role.EMPTY, role); - verify(reservedRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); - verify(fileRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); + verify(reservedRolesStore).accept(anySetOf(String.class), anyActionListener()); + verify(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); verify(fileRolesStore).roleDescriptors(eq(Collections.singleton(roleName))); - verify(nativeRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); - verify(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + verify(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); + verify(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); assertFalse(compositeRolesStore.isValueInNegativeLookupCache(roleName)); verifyNoMoreInteractions(fileRolesStore, reservedRolesStore, nativeRolesStore); @@ -383,15 +388,16 @@ reservedRolesStore, mock(NativePrivilegeStore.class), Collections.emptyList(), n public void testNegativeLookupsAreNotCachedWithFailures() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final AtomicReference> effectiveRoleDescriptors = new AtomicReference>(); @@ -402,7 +408,7 @@ public void testNegativeLookupsAreNotCachedWithFailures() { new XPackLicenseState(SECURITY_ENABLED_SETTINGS, () -> 0), cache, mock(ApiKeyService.class), mock(ServiceAccountService.class), documentSubsetBitsetCache, rds -> effectiveRoleDescriptors.set(rds)); - verify(fileRolesStore).addListener(any(Consumer.class)); // adds a listener in ctor + verify(fileRolesStore).addListener(anyConsumer()); // adds a listener in ctor final String roleName = randomAlphaOfLengthBetween(1, 10); PlainActionFuture future = new PlainActionFuture<>(); @@ -411,11 +417,11 @@ public void testNegativeLookupsAreNotCachedWithFailures() { assertThat(effectiveRoleDescriptors.get().isEmpty(), is(true)); effectiveRoleDescriptors.set(null); assertEquals(Role.EMPTY, role); - verify(reservedRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); - verify(fileRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); + verify(reservedRolesStore).accept(anySetOf(String.class), anyActionListener()); + verify(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); verify(fileRolesStore).roleDescriptors(eq(Collections.singleton(roleName))); - verify(nativeRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); - verify(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + verify(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); + verify(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final int numberOfTimesToCall = scaledRandomIntBetween(0, 32); final Set names = Collections.singleton(roleName); @@ -428,26 +434,27 @@ public void testNegativeLookupsAreNotCachedWithFailures() { } assertFalse(compositeRolesStore.isValueInNegativeLookupCache(roleName)); - verify(reservedRolesStore, times(numberOfTimesToCall + 1)).accept(anySetOf(String.class), any(ActionListener.class)); - verify(fileRolesStore, times(numberOfTimesToCall + 1)).accept(anySetOf(String.class), any(ActionListener.class)); + verify(reservedRolesStore, times(numberOfTimesToCall + 1)).accept(anySetOf(String.class), anyActionListener()); + verify(fileRolesStore, times(numberOfTimesToCall + 1)).accept(anySetOf(String.class), anyActionListener()); verify(fileRolesStore, times(numberOfTimesToCall + 1)).roleDescriptors(eq(Collections.singleton(roleName))); - verify(nativeRolesStore, times(numberOfTimesToCall + 1)).accept(anySetOf(String.class), any(ActionListener.class)); - verify(nativeRolesStore, times(numberOfTimesToCall + 1)).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + verify(nativeRolesStore, times(numberOfTimesToCall + 1)).accept(anySetOf(String.class), anyActionListener()); + verify(nativeRolesStore, times(numberOfTimesToCall + 1)).getRoleDescriptors(isASet(), anyActionListener()); verifyNoMoreInteractions(fileRolesStore, reservedRolesStore, nativeRolesStore); } public void testCustomRolesProviders() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.success(Collections.emptySet())); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final RoleDescriptor roleAProvider1 = new RoleDescriptor("roleA", null, @@ -506,8 +513,8 @@ cache, mock(ApiKeyService.class), mock(ServiceAccountService.class), documentSub assertThat(role.indices().groups()[1].indices()[0], anyOf(equalTo("foo"), equalTo("bar"))); // make sure negative lookups are cached - verify(inMemoryProvider1).accept(anySetOf(String.class), any(ActionListener.class)); - verify(inMemoryProvider2).accept(anySetOf(String.class), any(ActionListener.class)); + verify(inMemoryProvider1).accept(anySetOf(String.class), anyActionListener()); + verify(inMemoryProvider2).accept(anySetOf(String.class), anyActionListener()); final int numberOfTimesToCall = scaledRandomIntBetween(1, 8); for (int i = 0; i < numberOfTimesToCall; i++) { @@ -634,7 +641,8 @@ public ClusterPermission.Builder buildPermission(ClusterPermission.Builder build PlainActionFuture future = new PlainActionFuture<>(); final NativePrivilegeStore privilegeStore = mock(NativePrivilegeStore.class); doAnswer(inv -> { - assertTrue(inv.getArguments().length == 3); + assertEquals(3, inv.getArguments().length); + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) inv.getArguments()[2]; Set set = new HashSet<>(); @@ -645,7 +653,7 @@ public ClusterPermission.Builder buildPermission(ClusterPermission.Builder build ))); listener.onResponse(set); return null; - }).when(privilegeStore).getPrivileges(any(Collection.class), any(Collection.class), any(ActionListener.class)); + }).when(privilegeStore).getPrivileges(anyCollectionOf(String.class), anyCollectionOf(String.class), anyActionListener()); CompositeRolesStore.buildRoleFromDescriptors(Sets.newHashSet(role1, role2), cache, privilegeStore, future); Role role = future.actionGet(); @@ -686,15 +694,16 @@ public ClusterPermission.Builder buildPermission(ClusterPermission.Builder build public void testCustomRolesProviderFailures() throws Exception { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.success(Collections.emptySet())); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = new ReservedRolesStore(); final InMemoryRolesProvider inMemoryProvider1 = new InMemoryRolesProvider((roles) -> { @@ -734,15 +743,16 @@ cache, mock(ApiKeyService.class), mock(ServiceAccountService.class), public void testCustomRolesProvidersLicensing() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.success(Collections.emptySet())); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = new ReservedRolesStore(); final RoleDescriptor roleA = new RoleDescriptor("roleA", null, @@ -827,11 +837,11 @@ public void testCacheClearOnIndexHealthChange() { final AtomicInteger numInvalidation = new AtomicInteger(0); FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); ReservedRolesStore reservedRolesStore = mock(ReservedRolesStore.class); - doCallRealMethod().when(reservedRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(reservedRolesStore).accept(anySetOf(String.class), anyActionListener()); NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); CompositeRolesStore compositeRolesStore = new CompositeRolesStore( Settings.EMPTY, fileRolesStore, nativeRolesStore, reservedRolesStore, @@ -882,11 +892,11 @@ public void testCacheClearOnIndexOutOfDateChange() { final AtomicInteger numInvalidation = new AtomicInteger(0); FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); ReservedRolesStore reservedRolesStore = mock(ReservedRolesStore.class); - doCallRealMethod().when(reservedRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(reservedRolesStore).accept(anySetOf(String.class), anyActionListener()); NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); CompositeRolesStore compositeRolesStore = new CompositeRolesStore(SECURITY_ENABLED_SETTINGS, fileRolesStore, nativeRolesStore, reservedRolesStore, @@ -908,21 +918,22 @@ public void invalidateAll() { public void testDefaultRoleUserWithoutRoles() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final CompositeRolesStore compositeRolesStore = buildCompositeRolesStore(SECURITY_ENABLED_SETTINGS, fileRolesStore, nativeRolesStore, reservedRolesStore, mock(NativePrivilegeStore.class), null, mock(ApiKeyService.class), mock(ServiceAccountService.class), null, null); - verify(fileRolesStore).addListener(any(Consumer.class)); // adds a listener in ctor + verify(fileRolesStore).addListener(anyConsumer()); // adds a listener in ctor PlainActionFuture rolesFuture = new PlainActionFuture<>(); final User user = new User("no role user"); @@ -938,10 +949,11 @@ public void testAnonymousUserEnabledRoleAdded() { .put(AnonymousUser.ROLES_SETTING.getKey(), "anonymous_user_role") .build(); final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") Set names = (Set) invocationOnMock.getArguments()[0]; if (names.size() == 1 && names.contains("anonymous_user_role")) { RoleDescriptor rd = new RoleDescriptor("anonymous_user_role", null, null, null); @@ -951,16 +963,17 @@ public void testAnonymousUserEnabledRoleAdded() { }). when(fileRolesStore).roleDescriptors(anySetOf(String.class)); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final CompositeRolesStore compositeRolesStore = buildCompositeRolesStore(settings, fileRolesStore, nativeRolesStore, reservedRolesStore, mock(NativePrivilegeStore.class), null, mock(ApiKeyService.class), mock(ServiceAccountService.class), null, null); - verify(fileRolesStore).addListener(any(Consumer.class)); // adds a listener in ctor + verify(fileRolesStore).addListener(anyConsumer()); // adds a listener in ctor PlainActionFuture rolesFuture = new PlainActionFuture<>(); final User user = new User("no role user"); @@ -972,15 +985,16 @@ reservedRolesStore, mock(NativePrivilegeStore.class), null, mock(ApiKeyService.c public void testDoesNotUseRolesStoreForXPacAndAsyncSearchUser() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); @@ -991,7 +1005,7 @@ public void testDoesNotUseRolesStoreForXPacAndAsyncSearchUser() { new XPackLicenseState(SECURITY_ENABLED_SETTINGS, () -> 0), cache, mock(ApiKeyService.class), mock(ServiceAccountService.class), documentSubsetBitsetCache, rds -> effectiveRoleDescriptors.set(rds)); - verify(fileRolesStore).addListener(any(Consumer.class)); // adds a listener in ctor + verify(fileRolesStore).addListener(anyConsumer()); // adds a listener in ctor // test Xpack user short circuits to its own reserved role PlainActionFuture rolesFuture = new PlainActionFuture<>(); @@ -1014,15 +1028,16 @@ public void testDoesNotUseRolesStoreForXPacAndAsyncSearchUser() { public void testGetRolesForSystemUserThrowsException() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); @@ -1033,7 +1048,7 @@ public void testGetRolesForSystemUserThrowsException() { new XPackLicenseState(SECURITY_ENABLED_SETTINGS, () -> 0), cache, mock(ApiKeyService.class), mock(ServiceAccountService.class), documentSubsetBitsetCache, rds -> effectiveRoleDescriptors.set(rds)); - verify(fileRolesStore).addListener(any(Consumer.class)); // adds a listener in ctor + verify(fileRolesStore).addListener(anyConsumer()); // adds a listener in ctor IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> compositeRolesStore.getRoles(SystemUser.INSTANCE, null, null)); assertThat(effectiveRoleDescriptors.get(), is(nullValue())); @@ -1042,15 +1057,16 @@ public void testGetRolesForSystemUserThrowsException() { public void testApiKeyAuthUsesApiKeyService() throws Exception { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); ThreadContext threadContext = new ThreadContext(SECURITY_ENABLED_SETTINGS); ApiKeyService apiKeyService = spy(new ApiKeyService(SECURITY_ENABLED_SETTINGS, Clock.systemUTC(), mock(Client.class), @@ -1058,11 +1074,12 @@ public void testApiKeyAuthUsesApiKeyService() throws Exception { mock(CacheInvalidatorRegistry.class), mock(ThreadPool.class))); NativePrivilegeStore nativePrivStore = mock(NativePrivilegeStore.class); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocationOnMock.getArguments()[2]; listener.onResponse(Collections.emptyList()); return Void.TYPE; - }).when(nativePrivStore).getPrivileges(any(Collection.class), any(Collection.class), any(ActionListener.class)); + }).when(nativePrivStore).getPrivileges(anyCollectionOf(String.class), anyCollectionOf(String.class), anyActionListener()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); final AtomicReference> effectiveRoleDescriptors = new AtomicReference>(); @@ -1087,7 +1104,7 @@ public void testApiKeyAuthUsesApiKeyService() throws Exception { if (version == Version.CURRENT) { verify(apiKeyService, times(2)).getApiKeyIdAndRoleBytes(eq(authentication), anyBoolean()); } else { - verify(apiKeyService).getRoleForApiKey(eq(authentication), any(ActionListener.class)); + verify(apiKeyService).getRoleForApiKey(eq(authentication), anyActionListener()); } assertThat(role.names().length, is(1)); assertThat(role.names()[0], containsString("user_role_")); @@ -1095,15 +1112,16 @@ public void testApiKeyAuthUsesApiKeyService() throws Exception { public void testApiKeyAuthUsesApiKeyServiceWithScopedRole() throws Exception { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); ThreadContext threadContext = new ThreadContext(SECURITY_ENABLED_SETTINGS); @@ -1112,11 +1130,12 @@ public void testApiKeyAuthUsesApiKeyServiceWithScopedRole() throws Exception { mock(CacheInvalidatorRegistry.class), mock(ThreadPool.class))); NativePrivilegeStore nativePrivStore = mock(NativePrivilegeStore.class); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocationOnMock.getArguments()[2]; listener.onResponse(Collections.emptyList()); return Void.TYPE; - }).when(nativePrivStore).getPrivileges(any(Collection.class), any(Collection.class), any(ActionListener.class)); + }).when(nativePrivStore).getPrivileges(anyCollectionOf(String.class), anyCollectionOf(String.class), anyActionListener()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); final AtomicReference> effectiveRoleDescriptors = new AtomicReference>(); @@ -1142,7 +1161,7 @@ public void testApiKeyAuthUsesApiKeyServiceWithScopedRole() throws Exception { verify(apiKeyService).getApiKeyIdAndRoleBytes(eq(authentication), eq(false)); verify(apiKeyService).getApiKeyIdAndRoleBytes(eq(authentication), eq(true)); } else { - verify(apiKeyService).getRoleForApiKey(eq(authentication), any(ActionListener.class)); + verify(apiKeyService).getRoleForApiKey(eq(authentication), anyActionListener()); } assertThat(role.names().length, is(1)); assertThat(role.names()[0], containsString("user_role_")); @@ -1156,10 +1175,11 @@ public void testUsageStats() { final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); final Map nativeRolesStoreUsageStats = Map.of(); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener> usageStats = (ActionListener>) invocationOnMock.getArguments()[0]; usageStats.onResponse(nativeRolesStoreUsageStats); return Void.TYPE; - }).when(nativeRolesStore).usageStats(any(ActionListener.class)); + }).when(nativeRolesStore).usageStats(anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); @@ -1229,25 +1249,27 @@ public void testLoggingOfDeprecatedRoles() { public void testCacheEntryIsReusedForIdenticalApiKeyRoles() { final FileRolesStore fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); final NativeRolesStore nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(anySetOf(String.class), anyActionListener()); final ReservedRolesStore reservedRolesStore = spy(new ReservedRolesStore()); ThreadContext threadContext = new ThreadContext(SECURITY_ENABLED_SETTINGS); ApiKeyService apiKeyService = mock(ApiKeyService.class); NativePrivilegeStore nativePrivStore = mock(NativePrivilegeStore.class); doAnswer(invocationOnMock -> { + @SuppressWarnings("unchecked") ActionListener> listener = (ActionListener>) invocationOnMock.getArguments()[2]; listener.onResponse(Collections.emptyList()); return Void.TYPE; - }).when(nativePrivStore).getPrivileges(any(Collection.class), any(Collection.class), any(ActionListener.class)); + }).when(nativePrivStore).getPrivileges(anyCollectionOf(String.class), anyCollectionOf(String.class), anyActionListener()); final DocumentSubsetBitsetCache documentSubsetBitsetCache = buildBitsetCache(); final AtomicReference> effectiveRoleDescriptors = new AtomicReference>(); @@ -1360,30 +1382,32 @@ private CompositeRolesStore buildCompositeRolesStore(Settings settings, @Nullable Consumer> roleConsumer) { if (fileRolesStore == null) { fileRolesStore = mock(FileRolesStore.class); - doCallRealMethod().when(fileRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(fileRolesStore).accept(anySetOf(String.class), anyActionListener()); when(fileRolesStore.roleDescriptors(anySetOf(String.class))).thenReturn(Collections.emptySet()); } if (nativeRolesStore == null) { nativeRolesStore = mock(NativeRolesStore.class); - doCallRealMethod().when(nativeRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(nativeRolesStore).accept(anySetOf(String.class), anyActionListener()); doAnswer((invocationOnMock) -> { + @SuppressWarnings("unchecked") ActionListener callback = (ActionListener) invocationOnMock.getArguments()[1]; callback.onResponse(RoleRetrievalResult.failure(new RuntimeException("intentionally failed!"))); return null; - }).when(nativeRolesStore).getRoleDescriptors(isA(Set.class), any(ActionListener.class)); + }).when(nativeRolesStore).getRoleDescriptors(isASet(), anyActionListener()); } if (reservedRolesStore == null) { reservedRolesStore = mock(ReservedRolesStore.class); - doCallRealMethod().when(reservedRolesStore).accept(any(Set.class), any(ActionListener.class)); + doCallRealMethod().when(reservedRolesStore).accept(anySetOf(String.class), anyActionListener()); } if (privilegeStore == null) { privilegeStore = mock(NativePrivilegeStore.class); doAnswer((invocationOnMock) -> { - ActionListener> callback = null; - callback = (ActionListener>) invocationOnMock.getArguments()[2]; + @SuppressWarnings("unchecked") + ActionListener> callback = + (ActionListener>) invocationOnMock.getArguments()[2]; callback.onResponse(Collections.emptyList()); return null; - }).when(privilegeStore).getPrivileges(isA(Set.class), isA(Set.class), any(ActionListener.class)); + }).when(privilegeStore).getPrivileges(isASet(), isASet(), anyActionListener()); } if (licenseState == null) { licenseState = new XPackLicenseState(settings, () -> 0); @@ -1449,4 +1473,14 @@ private IndexAbstraction mockIndexAbstraction(String name) { IndexAbstraction.Type.ALIAS, IndexAbstraction.Type.DATA_STREAM)); return mock; } + + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } + + @SuppressWarnings("unchecked") + private static Set isASet() { + return isA(Set.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java index 040fea0871d35..a1ab0fff57587 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativePrivilegeStoreTests.java @@ -85,7 +85,7 @@ public class NativePrivilegeStoreTests extends ESTestCase { private NativePrivilegeStore store; private List requests; - private AtomicReference listener; + private AtomicReference> listener; private Client client; private SecurityIndexManager securityIndex; private CacheInvalidatorRegistry cacheInvalidatorRegistry; @@ -96,10 +96,11 @@ public void setup() { listener = new AtomicReference<>(); client = new NoOpClient(getTestName()) { @Override + @SuppressWarnings("unchecked") protected void doExecute(ActionType action, Request request, ActionListener listener) { NativePrivilegeStoreTests.this.requests.add(request); - NativePrivilegeStoreTests.this.listener.set(listener); + NativePrivilegeStoreTests.this.listener.set((ActionListener) listener); } }; securityIndex = mock(SecurityIndexManager.class); @@ -111,13 +112,13 @@ void doExecute(ActionType action, Request request, ActionListener { assertThat(invocationOnMock.getArguments().length, equalTo(2)); assertThat(invocationOnMock.getArguments()[1], instanceOf(Runnable.class)); ((Runnable) invocationOnMock.getArguments()[1]).run(); return null; - }).when(securityIndex).checkIndexVersionThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndex).checkIndexVersionThenExecute(anyConsumer(), any(Runnable.class)); cacheInvalidatorRegistry = new CacheInvalidatorRegistry(); store = new NativePrivilegeStore(Settings.EMPTY, client, securityIndex, cacheInvalidatorRegistry); } @@ -466,7 +467,7 @@ public void testPutPrivileges() throws Exception { requests.stream().map(IndexRequest.class::cast).forEach(indexRequests::add); requests.clear(); - final ActionListener indexListener = listener.get(); + final ActionListener indexListener = listener.get(); final String uuid = UUIDs.randomBase64UUID(random()); for (int i = 0; i < putPrivileges.size(); i++) { ApplicationPrivilegeDescriptor privilege = putPrivileges.get(i); @@ -510,7 +511,7 @@ public void testDeletePrivileges() throws Exception { requests.stream().map(DeleteRequest.class::cast).forEach(deletes::add); requests.clear(); - final ActionListener deleteListener = listener.get(); + final ActionListener deleteListener = listener.get(); final String uuid = UUIDs.randomBase64UUID(random()); for (int i = 0; i < privilegeNames.size(); i++) { String name = privilegeNames.get(i); @@ -634,4 +635,9 @@ private void assertResult(List sourcePrivileges, assertThat(getPrivileges, iterableWithSize(sourcePrivileges.size())); assertThat(new HashSet<>(getPrivileges), equalTo(new HashSet<>(sourcePrivileges))); } + + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativeRolesStoreTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativeRolesStoreTests.java index 796f0e7f145e2..cd86b6295a1d5 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativeRolesStoreTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/store/NativeRolesStoreTests.java @@ -92,6 +92,7 @@ public void testBWCFieldPermissions() throws IOException { assertNull(indicesPrivileges.getDeniedFields()); } + @SuppressWarnings("unchecked") public void testRoleDescriptorWithFlsDlsLicensing() throws IOException { XPackLicenseState licenseState = mock(XPackLicenseState.class); when(licenseState.isSecurityEnabled()).thenReturn(true); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentTokenTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentTokenTests.java index 0294e0261f6f5..8d63387497d2c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentTokenTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/enrollment/CreateEnrollmentTokenTests.java @@ -52,7 +52,7 @@ public class CreateEnrollmentTokenTests extends ESTestCase { private Environment environment; @BeforeClass - public static void muteInFips(){ + public static void muteInFips() { assumeFalse("Enrollment is not supported in FIPS 140-2 as we are using PKCS#12 keystores", inFipsJvm()); } @@ -86,9 +86,9 @@ public void testCreateSuccess() throws Exception { final URL createAPIKeyURL = createEnrollmentToken.createAPIKeyUrl(); final URL getHttpInfoURL = createEnrollmentToken.getHttpInfoUrl(); - final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap()); - when(client.execute(anyString(), any(URL.class), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseOK); + final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap<>()); + when(client.execute(anyString(), any(URL.class), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseOK); String createApiKeyResponseBody; try (XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON)) { @@ -101,7 +101,7 @@ public void testCreateSuccess() throws Exception { createApiKeyResponseBody = Strings.toString(builder); } when(client.execute(eq("POST"), eq(createAPIKeyURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, createApiKeyResponseBody)); String getHttpInfoResponseBody; @@ -126,7 +126,7 @@ public void testCreateSuccess() throws Exception { getHttpInfoResponseBody = Strings.toString(builder); } when(client.execute(eq("GET"), eq(getHttpInfoURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, getHttpInfoResponseBody)); final String tokenNode = createEnrollmentToken.createNodeEnrollmentToken("elastic", new SecureString("elastic")); @@ -152,9 +152,9 @@ public void testFailedCreateApiKey() throws Exception { final CreateEnrollmentToken createEnrollmentToken = new CreateEnrollmentToken(environment, client); final URL createAPIKeyURL = createEnrollmentToken.createAPIKeyUrl(); - final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap()); - when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseNotOK); + final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap<>()); + when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseNotOK); IllegalStateException ex = expectThrows(IllegalStateException.class, () -> createEnrollmentToken.createNodeEnrollmentToken("elastic", new SecureString("elastic"))); @@ -168,9 +168,9 @@ public void testFailedRetrieveHttpInfo() throws Exception { final URL createAPIKeyURL = createEnrollmentToken.createAPIKeyUrl(); final URL getHttpInfoURL = createEnrollmentToken.getHttpInfoUrl(); - final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap()); - when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseOK); + final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap<>()); + when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseOK); String createApiKeyResponseBody; try (XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON)) { @@ -183,12 +183,12 @@ public void testFailedRetrieveHttpInfo() throws Exception { createApiKeyResponseBody = Strings.toString(builder); } when(client.execute(eq("POST"), eq(createAPIKeyURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, createApiKeyResponseBody)); - final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap()); - when(client.execute(anyString(), eq(getHttpInfoURL), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseNotOK); + final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap<>()); + when(client.execute(anyString(), eq(getHttpInfoURL), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseNotOK); IllegalStateException ex = expectThrows(IllegalStateException.class, () -> createEnrollmentToken.createNodeEnrollmentToken("elastic", new SecureString("elastic"))); @@ -220,9 +220,9 @@ public void testFailedNoCaInKeystore() throws Exception { final URL createAPIKeyURL = createEnrollmentToken.createAPIKeyUrl(); final URL getHttpInfoURL = createEnrollmentToken.getHttpInfoUrl(); - final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap()); - when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseOK); + final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap<>()); + when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseOK); String createApiKeyResponseBody; try (XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON)) { @@ -235,12 +235,12 @@ public void testFailedNoCaInKeystore() throws Exception { createApiKeyResponseBody = Strings.toString(builder); } when(client.execute(eq("POST"), eq(createAPIKeyURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, createApiKeyResponseBody)); - final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap()); - when(client.execute(anyString(), eq(getHttpInfoURL), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseNotOK); + final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap<>()); + when(client.execute(anyString(), eq(getHttpInfoURL), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseNotOK); IllegalStateException ex = expectThrows(IllegalStateException.class, () -> createEnrollmentToken.createNodeEnrollmentToken("elastic", new SecureString("elastic"))); @@ -273,9 +273,9 @@ public void testFailedManyCaInKeystore() throws Exception { final URL createAPIKeyURL = createEnrollmentToken.createAPIKeyUrl(); final URL getHttpInfoURL = createEnrollmentToken.getHttpInfoUrl(); - final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap()); - when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseOK); + final HttpResponse httpResponseOK = new HttpResponse(HttpURLConnection.HTTP_OK, new HashMap<>()); + when(client.execute(anyString(), eq(createAPIKeyURL), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseOK); String createApiKeyResponseBody; try (XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON)) { @@ -288,12 +288,12 @@ public void testFailedManyCaInKeystore() throws Exception { createApiKeyResponseBody = Strings.toString(builder); } when(client.execute(eq("POST"), eq(createAPIKeyURL), eq(ElasticUser.NAME), any(SecureString.class), - any(CheckedSupplier.class), any(CheckedFunction.class))) + anyCheckedSupplier(), anyCheckedFunction())) .thenReturn(createHttpResponse(HttpURLConnection.HTTP_OK, createApiKeyResponseBody)); - final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap()); - when(client.execute(anyString(), eq(getHttpInfoURL), anyString(), any(SecureString.class), any(CheckedSupplier.class), - any(CheckedFunction.class))).thenReturn(httpResponseNotOK); + final HttpResponse httpResponseNotOK = new HttpResponse(HttpURLConnection.HTTP_BAD_REQUEST, new HashMap<>()); + when(client.execute(anyString(), eq(getHttpInfoURL), anyString(), any(SecureString.class), anyCheckedSupplier(), + anyCheckedFunction())).thenReturn(httpResponseNotOK); IllegalStateException ex = expectThrows(IllegalStateException.class, () -> createEnrollmentToken.createNodeEnrollmentToken("elastic", new SecureString("elastic"))); @@ -301,7 +301,7 @@ public void testFailedManyCaInKeystore() throws Exception { "configuration Keystore contains multiple PrivateKey entries where the associated certificate is a CA certificate")); } - public void testNoKeyStore() throws Exception{ + public void testNoKeyStore() throws Exception { final Path tempDir = createTempDir(); final Settings settings = Settings.builder() .put("xpack.security.enabled", true) @@ -347,7 +347,7 @@ public void testEnrollmentNotEnabled() throws Exception { "create an enrollment token")); } - public void testGetFilteredAddresses () throws Exception { + public void testGetFilteredAddresses() throws Exception { List addresses = Arrays.asList("[::1]:9200", "127.0.0.1:9200", "192.168.0.1:9201", "172.16.254.1:9202", "[2001:db8:0:1234:0:567:8:1]:9203"); List filteredAddresses = getFilteredAddresses(addresses); @@ -392,4 +392,14 @@ private HttpResponse createHttpResponse(final int httpStatus, final String respo builder.withResponseBody(responseJson); return builder.build(); } + + @SuppressWarnings("unchecked") + private static CheckedSupplier anyCheckedSupplier() { + return any(CheckedSupplier.class); + } + + @SuppressWarnings("unchecked") + private static CheckedFunction anyCheckedFunction() { + return any(CheckedFunction.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java index 0fa602e9e779c..1b1d527dc2e05 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/ingest/SetSecurityUserProcessorTests.java @@ -54,6 +54,7 @@ public void setupObjects() { when(licenseState.isSecurityEnabled()).thenReturn(true); } + @SuppressWarnings("unchecked") public void testProcessorWithData() throws Exception { final Authentication authentication = randomAuthentication(); authentication.writeToContext(threadContext); @@ -82,11 +83,12 @@ public void testProcessorWithData() throws Exception { } assertThat(result.get("username"), equalTo(authentication.getUser().principal())); assertThat(result.get("full_name"), equalTo(authentication.getUser().fullName())); - assertThat(((Map) result.get("realm")).get("name"), equalTo(authentication.getSourceRealm().getName())); - assertThat(((Map) result.get("realm")).get("type"), equalTo(authentication.getSourceRealm().getType())); + assertThat(((Map) result.get("realm")).get("name"), equalTo(authentication.getSourceRealm().getName())); + assertThat(((Map) result.get("realm")).get("type"), equalTo(authentication.getSourceRealm().getType())); assertThat(result.get("authentication_type"), equalTo(authentication.getAuthenticationType().toString())); } + @SuppressWarnings("unchecked") public void testProcessorWithEmptyUserData() throws Exception { // test when user returns null for all values (need a mock, because a real user cannot have a null username) User user = Mockito.mock(User.class); @@ -245,6 +247,7 @@ public void testOverwriteExistingField() throws Exception { assertThat(result2.get("other"), equalTo("test")); } + @SuppressWarnings("unchecked") public void testApiKeyPopulation() throws Exception { User user = new User(randomAlphaOfLengthBetween(4, 12), null, null); Authentication.RealmRef realmRef = new Authentication.RealmRef( @@ -280,11 +283,12 @@ public void testApiKeyPopulation() throws Exception { } else { assertThat(apiKeyMap.get("metadata"), equalTo(apiKeyMetadata)); } - assertThat(((Map) result.get("realm")).get("name"), equalTo("creator_realm_name")); - assertThat(((Map) result.get("realm")).get("type"), equalTo("creator_realm_type")); + assertThat(((Map) result.get("realm")).get("name"), equalTo("creator_realm_name")); + assertThat(((Map) result.get("realm")).get("type"), equalTo("creator_realm_type")); assertThat(result.get("authentication_type"), equalTo("API_KEY")); } + @SuppressWarnings("unchecked") public void testWillNotOverwriteExistingApiKeyAndRealm() throws Exception { User user = new User(randomAlphaOfLengthBetween(4, 12), null, null); Authentication.RealmRef realmRef = new Authentication.RealmRef( @@ -314,10 +318,11 @@ public void testWillNotOverwriteExistingApiKeyAndRealm() throws Exception { Map result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(4)); - assertThat(((Map) result.get("api_key")).get("version"), equalTo(42)); - assertThat(((Map) result.get("realm")).get("id"), equalTo(7)); + assertThat(((Map) result.get("api_key")).get("version"), equalTo(42)); + assertThat(((Map) result.get("realm")).get("id"), equalTo(7)); } + @SuppressWarnings("unchecked") public void testWillSetRunAsRealmForNonApiKeyAuth() throws Exception { User user = new User(randomAlphaOfLengthBetween(4, 12), null, null); Authentication.RealmRef authRealmRef = new Authentication.RealmRef( @@ -337,8 +342,8 @@ public void testWillSetRunAsRealmForNonApiKeyAuth() throws Exception { Map result = ingestDocument.getFieldValue("_field", Map.class); assertThat(result.size(), equalTo(3)); - assertThat(((Map) result.get("realm")).get("name"), equalTo(lookedUpRealmRef.getName())); - assertThat(((Map) result.get("realm")).get("type"), equalTo(lookedUpRealmRef.getType())); + assertThat(((Map) result.get("realm")).get("name"), equalTo(lookedUpRealmRef.getName())); + assertThat(((Map) result.get("realm")).get("type"), equalTo(lookedUpRealmRef.getType())); } private User randomUser() { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/RestRequestFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/RestRequestFilterTests.java index 3578bb05efa9a..2da7f263bcc9c 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/RestRequestFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/RestRequestFilterTests.java @@ -35,8 +35,10 @@ public void testFilteringItemsInSubLevels() throws IOException { Map map = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, filtered.content().streamInput()).map(); + @SuppressWarnings("unchecked") Map root = (Map) map.get("root"); assertNotNull(root); + @SuppressWarnings("unchecked") Map second = (Map) root.get("second"); assertNotNull(second); assertEquals("bar", second.get("foo")); @@ -54,8 +56,10 @@ public void testFilteringItemsInSubLevelsWithWildCard() throws IOException { Map map = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, filtered.content().streamInput()).map(); + @SuppressWarnings("unchecked") Map root = (Map) map.get("root"); assertNotNull(root); + @SuppressWarnings("unchecked") Map second = (Map) root.get("second"); assertNotNull(second); assertEquals("bar", second.get("foo")); @@ -73,8 +77,10 @@ public void testFilteringItemsInSubLevelsWithLeadingWildCard() throws IOExceptio Map map = XContentType.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, filtered.content().streamInput()).map(); + @SuppressWarnings("unchecked") Map root = (Map) map.get("root"); assertNotNull(root); + @SuppressWarnings("unchecked") Map second = (Map) root.get("second"); assertNotNull(second); assertEquals("bar", second.get("foo")); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/SecurityRestFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/SecurityRestFilterTests.java index cac1b0395d9f1..a5ce52669dd4e 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/SecurityRestFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/SecurityRestFilterTests.java @@ -46,6 +46,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicReference; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.support.Exceptions.authenticationError; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; @@ -87,11 +88,11 @@ public void testProcess() throws Exception { when(request.getHttpChannel()).thenReturn(mock(HttpChannel.class)); Authentication authentication = mock(Authentication.class); doAnswer((i) -> { - ActionListener callback = - (ActionListener) i.getArguments()[1]; + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) i.getArguments()[1]; callback.onResponse(authentication); return Void.TYPE; - }).when(authcService).authenticate(eq(request), any(ActionListener.class)); + }).when(authcService).authenticate(eq(request), anyActionListener()); filter.handleRequest(request, channel, null); verify(restHandler).handleRequest(request, channel, null); verifyZeroInteractions(channel); @@ -107,19 +108,21 @@ public void testProcessSecondaryAuthentication() throws Exception { when(primaryAuthentication.encode()).thenReturn(randomAlphaOfLengthBetween(12, 36)); doAnswer(i -> { final Object[] arguments = i.getArguments(); - ActionListener callback = (ActionListener) arguments[arguments.length - 1]; + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) arguments[arguments.length - 1]; callback.onResponse(primaryAuthentication); return null; - }).when(authcService).authenticate(eq(request), any(ActionListener.class)); + }).when(authcService).authenticate(eq(request), anyActionListener()); Authentication secondaryAuthentication = mock(Authentication.class); when(secondaryAuthentication.encode()).thenReturn(randomAlphaOfLengthBetween(12, 36)); doAnswer(i -> { final Object[] arguments = i.getArguments(); - ActionListener callback = (ActionListener) arguments[arguments.length - 1]; + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) arguments[arguments.length - 1]; callback.onResponse(secondaryAuthentication); return null; - }).when(authcService).authenticate(eq(request), eq(false), any(ActionListener.class)); + }).when(authcService).authenticate(eq(request), eq(false), anyActionListener()); SecurityContext securityContext = new SecurityContext(Settings.EMPTY, threadContext); AtomicReference secondaryAuthRef = new AtomicReference<>(); @@ -174,11 +177,10 @@ private void testProcessAuthenticationFailed(Exception authnException, RestStatu request = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).build(); } doAnswer((i) -> { - ActionListener callback = - (ActionListener) i.getArguments()[1]; + ActionListener callback = (ActionListener) i.getArguments()[1]; callback.onFailure(authnException); return Void.TYPE; - }).when(authcService).authenticate(eq(request), any(ActionListener.class)); + }).when(authcService).authenticate(eq(request), anyActionListener()); RestChannel channel = mock(RestChannel.class); when(channel.detailedErrorsEnabled()).thenReturn(detailedErrorsEnabled); when(channel.request()).thenReturn(request); @@ -224,12 +226,12 @@ public Set getFilteredFields() { }; SetOnce authcServiceRequest = new SetOnce<>(); doAnswer((i) -> { - ActionListener callback = - (ActionListener) i.getArguments()[1]; + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) i.getArguments()[1]; authcServiceRequest.set((RestRequest) i.getArguments()[0]); callback.onResponse(new Authentication(XPackUser.INSTANCE, new RealmRef("test", "test", "t"), null)); return Void.TYPE; - }).when(authcService).authenticate(any(RestRequest.class), any(ActionListener.class)); + }).when(authcService).authenticate(any(RestRequest.class), anyActionListener()); filter = new SecurityRestFilter(licenseState, threadContext, authcService, secondaryAuthenticator, restHandler, false); filter.handleRequest(restRequest, channel, null); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyActionTests.java index 501e3d4058aa1..9348c5f384960 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/apikey/RestInvalidateApiKeyActionTests.java @@ -87,6 +87,7 @@ public void sendResponse(RestResponse restResponse) { try (NodeClient client = new NodeClient(Settings.EMPTY, threadPool) { @Override + @SuppressWarnings("unchecked") public void doExecute(ActionType action, Request request, ActionListener listener) { InvalidateApiKeyRequest invalidateApiKeyRequest = (InvalidateApiKeyRequest) request; diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java index bf53469c19a4e..dd3d68bdbbaa9 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/rest/action/oauth2/RestGetTokenActionTests.java @@ -92,8 +92,9 @@ public void sendResponse(RestResponse restResponse) { assertThat(map, hasEntry("refresh_token", createTokenResponse.getRefreshToken())); assertThat(map, hasEntry("kerberos_authentication_response_token", createTokenResponse.getKerberosAuthenticationResponseToken())); assertThat(map, hasKey("authentication")); - assertThat((Map)(map.get("authentication")), - hasEntry("username", createTokenResponse.getAuthentication().getUser().principal())); + @SuppressWarnings("unchecked") + final Map authentication = (Map) (map.get("authentication")); + assertThat(authentication, hasEntry("username", createTokenResponse.getAuthentication().getUser().principal())); assertEquals(6, map.size()); } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/test/SecurityMocks.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/test/SecurityMocks.java index 71aa27416f796..7d987abb91399 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/test/SecurityMocks.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/test/SecurityMocks.java @@ -40,6 +40,7 @@ import java.util.function.Consumer; import static java.util.Collections.emptyMap; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.index.RestrictedIndicesNames.SECURITY_MAIN_ALIAS; import static org.elasticsearch.xpack.core.security.index.RestrictedIndicesNames.SECURITY_TOKENS_ALIAS; import static org.hamcrest.Matchers.arrayWithSize; @@ -79,12 +80,12 @@ public static SecurityIndexManager mockSecurityIndexManager(String alias, boolea Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; runnable.run(); return null; - }).when(securityIndexManager).prepareIndexIfNeededThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndexManager).prepareIndexIfNeededThenExecute(anyConsumer(), any(Runnable.class)); doAnswer(invocationOnMock -> { Runnable runnable = (Runnable) invocationOnMock.getArguments()[1]; runnable.run(); return null; - }).when(securityIndexManager).checkIndexVersionThenExecute(any(Consumer.class), any(Runnable.class)); + }).when(securityIndexManager).checkIndexVersionThenExecute(anyConsumer(), any(Runnable.class)); when(securityIndexManager.indexExists()).thenReturn(exists); when(securityIndexManager.isAvailable()).thenReturn(available); when(securityIndexManager.aliasName()).thenReturn(alias); @@ -116,20 +117,22 @@ public static void mockGetRequest(Client client, String indexAliasName, String d Assert.assertThat(request.index(), equalTo(indexAliasName)); Assert.assertThat(inv.getArguments()[1], instanceOf(ActionListener.class)); + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) inv.getArguments()[1]; listener.onResponse(new GetResponse(result)); return null; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); } public static void mockGetRequestException(Client client, Exception e) { when(client.prepareGet(anyString(), anyString())).thenReturn(new GetRequestBuilder(client, GetAction.INSTANCE)); doAnswer(inv -> { + @SuppressWarnings("unchecked") ActionListener listener = (ActionListener) inv.getArguments()[1]; listener.onFailure(e); return null; - }).when(client).get(any(GetRequest.class), any(ActionListener.class)); + }).when(client).get(any(GetRequest.class), anyActionListener()); } public static void mockIndexRequest(Client client, String indexAliasName, Consumer consumer) { @@ -147,11 +150,12 @@ public static void mockIndexRequest(Client client, String indexAliasName, Consum Assert.assertThat(request.index(), equalTo(indexAliasName)); consumer.accept(request); Assert.assertThat(inv.getArguments()[2], instanceOf(ActionListener.class)); + @SuppressWarnings("unchecked") final ActionListener listener = (ActionListener) inv.getArguments()[2]; final ShardId shardId = new ShardId(request.index(), ESTestCase.randomAlphaOfLength(12), 0); listener.onResponse(new IndexResponse(shardId, request.id(), 1, 1, 1, true)); return null; - }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), any(ActionListener.class)); + }).when(client).execute(eq(IndexAction.INSTANCE), any(IndexRequest.class), anyActionListener()); } public static TokenServiceMock tokenService(boolean enabled, ThreadPool threadPool) throws GeneralSecurityException { @@ -170,4 +174,9 @@ public static TokenServiceMock tokenService(boolean enabled, ThreadPool threadPo mockSecurityIndexManager(SECURITY_MAIN_ALIAS), mockSecurityIndexManager(SECURITY_TOKENS_ALIAS), clusterService); return new TokenServiceMock(service, client); } + + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java index eaed0bf9cd7ad..18ed70eef9c12 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/SecurityServerTransportInterceptorTests.java @@ -138,7 +138,7 @@ public void sendRequest(Transport.Connection conne assertTrue(calledWrappedSender.get()); assertThat(sendingUser.get(), is(SystemUser.INSTANCE)); verify(xPackLicenseState).isSecurityEnabled(); - verify(securityContext).executeAsUser(any(User.class), any(Consumer.class), eq(Version.CURRENT)); + verify(securityContext).executeAsUser(any(User.class), anyConsumer(), eq(Version.CURRENT)); verifyNoMoreInteractions(xPackLicenseState); } @@ -173,7 +173,7 @@ public void sendRequest(Transport.Connection conne assertTrue(calledWrappedSender.get()); assertEquals(SystemUser.INSTANCE, sendingUser.get()); verify(xPackLicenseState).isSecurityEnabled(); - verify(securityContext).executeAsUser(any(User.class), any(Consumer.class), eq(Version.CURRENT)); + verify(securityContext).executeAsUser(any(User.class), anyConsumer(), eq(Version.CURRENT)); verifyNoMoreInteractions(xPackLicenseState); } @@ -207,7 +207,7 @@ public void sendRequest(Transport.Connection conne assertEquals(user, sendingUser.get()); assertEquals(user, securityContext.getUser()); verify(xPackLicenseState).isSecurityEnabled(); - verify(securityContext, never()).executeAsUser(any(User.class), any(Consumer.class), any(Version.class)); + verify(securityContext, never()).executeAsUser(any(User.class), anyConsumer(), any(Version.class)); verifyNoMoreInteractions(xPackLicenseState); } @@ -244,7 +244,7 @@ public void sendRequest(Transport.Connection conne assertEquals(SystemUser.INSTANCE, sendingUser.get()); assertEquals(user, securityContext.getUser()); verify(xPackLicenseState).isSecurityEnabled(); - verify(securityContext).executeAsUser(any(User.class), any(Consumer.class), eq(Version.CURRENT)); + verify(securityContext).executeAsUser(any(User.class), anyConsumer(), eq(Version.CURRENT)); verifyNoMoreInteractions(xPackLicenseState); } @@ -274,7 +274,7 @@ public void sendRequest(Transport.Connection conne assertEquals("there should always be a user when sending a message for action [indices:foo]", e.getMessage()); assertNull(securityContext.getUser()); verify(xPackLicenseState).isSecurityEnabled(); - verify(securityContext, never()).executeAsUser(any(User.class), any(Consumer.class), any(Version.class)); + verify(securityContext, never()).executeAsUser(any(User.class), anyConsumer(), any(Version.class)); verifyNoMoreInteractions(xPackLicenseState); } @@ -428,5 +428,8 @@ private String[] randomRoles() { return generateRandomStringArray(3, 10, false, true); } - + @SuppressWarnings("unchecked") + private static Consumer anyConsumer() { + return any(Consumer.class); + } } diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ServerTransportFilterTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ServerTransportFilterTests.java index 1f064d40f30ac..3828e8f571c20 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ServerTransportFilterTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ServerTransportFilterTests.java @@ -33,14 +33,15 @@ import org.elasticsearch.xpack.security.authc.AuthenticationService; import org.elasticsearch.xpack.security.authz.AuthorizationService; import org.junit.Before; +import org.mockito.stubbing.Answer; import java.util.Collections; +import static org.elasticsearch.test.ActionListenerUtils.anyActionListener; import static org.elasticsearch.xpack.core.security.support.Exceptions.authenticationError; import static org.elasticsearch.xpack.core.security.support.Exceptions.authorizationError; import static org.hamcrest.Matchers.arrayWithSize; import static org.hamcrest.Matchers.equalTo; -import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.doAnswer; @@ -78,18 +79,12 @@ public void testInbound() throws Exception { Authentication authentication = mock(Authentication.class); when(authentication.getVersion()).thenReturn(Version.CURRENT); when(authentication.getUser()).thenReturn(SystemUser.INSTANCE); - doAnswer(i -> { - final Object[] args = i.getArguments(); - assertThat(args, arrayWithSize(4)); - ActionListener callback = (ActionListener) args[args.length - 1]; - callback.onResponse(authentication); - return Void.TYPE; - }).when(authcService).authenticate(eq("_action"), eq(request), eq(true), any(ActionListener.class)); + doAnswer(getAnswer(authentication)).when(authcService).authenticate(eq("_action"), eq(request), eq(true), anyActionListener()); ServerTransportFilter filter = getNodeFilter(); PlainActionFuture future = new PlainActionFuture<>(); filter.inbound("_action", request, channel, future); //future.get(); // don't block it's not called really just mocked - verify(authzService).authorize(eq(authentication), eq("_action"), eq(request), any(ActionListener.class)); + verify(authzService).authorize(eq(authentication), eq("_action"), eq(request), anyActionListener()); } public void testInboundDestructiveOperations() throws Exception { @@ -100,21 +95,16 @@ public void testInboundDestructiveOperations() throws Exception { Authentication authentication = mock(Authentication.class); when(authentication.getVersion()).thenReturn(Version.CURRENT); when(authentication.getUser()).thenReturn(SystemUser.INSTANCE); - doAnswer(i -> { - final Object[] args = i.getArguments(); - assertThat(args, arrayWithSize(4)); - ActionListener callback = (ActionListener) args[args.length - 1]; - callback.onResponse(authentication); - return Void.TYPE; - }).when(authcService).authenticate(eq(action), eq(request), eq(true), any(ActionListener.class)); + doAnswer(getAnswer(authentication)).when(authcService).authenticate(eq(action), eq(request), eq(true), anyActionListener()); ServerTransportFilter filter = getNodeFilter(); - PlainActionFuture listener = mock(PlainActionFuture.class); + @SuppressWarnings("unchecked") + PlainActionFuture listener = mock(PlainActionFuture.class); filter.inbound(action, request, channel, listener); if (failDestructiveOperations) { verify(listener).onFailure(isA(IllegalArgumentException.class)); verifyNoMoreInteractions(authzService); } else { - verify(authzService).authorize(eq(authentication), eq(action), eq(request), any(ActionListener.class)); + verify(authzService).authorize(eq(authentication), eq(action), eq(request), anyActionListener()); } } @@ -124,10 +114,11 @@ public void testInboundAuthenticationException() throws Exception { doAnswer(i -> { final Object[] args = i.getArguments(); assertThat(args, arrayWithSize(4)); - ActionListener callback = (ActionListener) args[args.length - 1]; + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) args[args.length - 1]; callback.onFailure(authE); return Void.TYPE; - }).when(authcService).authenticate(eq("_action"), eq(request), eq(true), any(ActionListener.class)); + }).when(authcService).authenticate(eq("_action"), eq(request), eq(true), anyActionListener()); ServerTransportFilter filter = getNodeFilter(); try { PlainActionFuture future = new PlainActionFuture<>(); @@ -144,18 +135,12 @@ public void testInboundAuthorizationException() throws Exception { ServerTransportFilter filter = getNodeFilter(); TransportRequest request = mock(TransportRequest.class); Authentication authentication = mock(Authentication.class); - doAnswer(i -> { - final Object[] args = i.getArguments(); - assertThat(args, arrayWithSize(4)); - ActionListener callback = (ActionListener) args[args.length - 1]; - callback.onResponse(authentication); - return Void.TYPE; - }).when(authcService).authenticate(eq("_action"), eq(request), eq(true), any(ActionListener.class)); + doAnswer(getAnswer(authentication)).when(authcService).authenticate(eq("_action"), eq(request), eq(true), anyActionListener()); when(authentication.getVersion()).thenReturn(Version.CURRENT); when(authentication.getUser()).thenReturn(XPackUser.INSTANCE); PlainActionFuture future = new PlainActionFuture<>(); doThrow(authorizationError("authz failed")) - .when(authzService).authorize(eq(authentication), eq("_action"), eq(request), any(ActionListener.class)); + .when(authzService).authorize(eq(authentication), eq("_action"), eq(request), anyActionListener()); ElasticsearchSecurityException e = expectThrows(ElasticsearchSecurityException.class, () -> { filter.inbound("_action", request, channel, future); future.actionGet(); @@ -169,31 +154,31 @@ public void testAllowsNodeActions() throws Exception { ServerTransportFilter filter = getNodeFilter(); TransportRequest request = mock(TransportRequest.class); Authentication authentication = new Authentication(new User("test", "superuser"), new RealmRef("test", "test", "node1"), null); - doAnswer(i -> { - final Object[] args = i.getArguments(); - assertThat(args, arrayWithSize(4)); - ActionListener callback = (ActionListener) args[args.length - 1]; - callback.onResponse(authentication); - return Void.TYPE; - }).when(authcService).authenticate(eq(internalAction), eq(request), eq(true), any(ActionListener.class)); - doAnswer((i) -> { - final Object[] args = i.getArguments(); - assertThat(args, arrayWithSize(4)); - ActionListener callback = (ActionListener) args[args.length - 1]; - callback.onResponse(authentication); - return Void.TYPE; - }).when(authcService).authenticate(eq(nodeOrShardAction), eq(request), eq(true), any(ActionListener.class)); + doAnswer(getAnswer(authentication)).when(authcService).authenticate(eq(internalAction), eq(request), eq(true), anyActionListener()); + doAnswer(getAnswer(authentication)).when(authcService) + .authenticate(eq(nodeOrShardAction), eq(request), eq(true), anyActionListener()); filter.inbound(internalAction, request, channel, new PlainActionFuture<>()); - verify(authcService).authenticate(eq(internalAction), eq(request), eq(true), any(ActionListener.class)); - verify(authzService).authorize(eq(authentication), eq(internalAction), eq(request), any(ActionListener.class)); + verify(authcService).authenticate(eq(internalAction), eq(request), eq(true), anyActionListener()); + verify(authzService).authorize(eq(authentication), eq(internalAction), eq(request), anyActionListener()); filter.inbound(nodeOrShardAction, request, channel, new PlainActionFuture<>()); - verify(authcService).authenticate(eq(nodeOrShardAction), eq(request), eq(true), any(ActionListener.class)); - verify(authzService).authorize(eq(authentication), eq(nodeOrShardAction), eq(request), any(ActionListener.class)); + verify(authcService).authenticate(eq(nodeOrShardAction), eq(request), eq(true), anyActionListener()); + verify(authzService).authorize(eq(authentication), eq(nodeOrShardAction), eq(request), anyActionListener()); verifyNoMoreInteractions(authcService, authzService); } + private static Answer> getAnswer(Authentication authentication) { + return i -> { + final Object[] args = i.getArguments(); + assertThat(args, arrayWithSize(4)); + @SuppressWarnings("unchecked") + ActionListener callback = (ActionListener) args[args.length - 1]; + callback.onResponse(authentication); + return Void.TYPE; + }; + } + private ServerTransportFilter getNodeFilter() { Settings settings = Settings.builder().put("path.home", createTempDir()).build(); ThreadContext threadContext = new ThreadContext(settings); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SSLChannelContextTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SSLChannelContextTests.java index 73986e4e56fed..2bef23bd7a0b8 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SSLChannelContextTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/nio/SSLChannelContextTests.java @@ -6,16 +6,16 @@ */ package org.elasticsearch.xpack.security.transport.nio; -import org.elasticsearch.core.CheckedFunction; import org.elasticsearch.common.util.PageCacheRecycler; +import org.elasticsearch.core.CheckedFunction; import org.elasticsearch.nio.BytesWriteHandler; +import org.elasticsearch.nio.Config; import org.elasticsearch.nio.FlushOperation; import org.elasticsearch.nio.FlushReadyWrite; import org.elasticsearch.nio.InboundChannelBuffer; import org.elasticsearch.nio.NioSelector; import org.elasticsearch.nio.NioSocketChannel; import org.elasticsearch.nio.Page; -import org.elasticsearch.nio.Config; import org.elasticsearch.nio.TaskScheduler; import org.elasticsearch.nio.WriteOperation; import org.elasticsearch.test.ESTestCase; @@ -23,7 +23,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.stubbing.Answer; -import javax.net.ssl.SSLException; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; @@ -32,6 +31,7 @@ import java.nio.channels.SocketChannel; import java.util.function.BiConsumer; import java.util.function.Consumer; +import javax.net.ssl.SSLException; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; @@ -55,7 +55,7 @@ public class SSLChannelContextTests extends ESTestCase { private NioSelector selector; private TaskScheduler nioTimer; private BiConsumer listener; - private Consumer exceptionHandler; + private Consumer exceptionHandler; private SSLDriver sslDriver; private int messageLength; private Config.Socket socketConfig; @@ -401,7 +401,7 @@ private Answer getWriteAnswer(int bytesToEncrypt, boolean isApp) { }; } - private Answer getReadAnswerForBytes(byte[] bytes) { + private Answer getReadAnswerForBytes(byte[] bytes) { return invocationOnMock -> { InboundChannelBuffer appBuffer = (InboundChannelBuffer) invocationOnMock.getArguments()[1]; appBuffer.ensureCapacity(appBuffer.getIndex() + bytes.length);