Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable compiler warnings in x-pack security #75473

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

<!-- Use our fork of this Checkstyle rule, so that we can ignore test classes -->
<module name="org.elasticsearch.gradle.internal.checkstyle.MissingJavadocTypeCheck">
<property name="ignorePattern" value="^.*(Tests?|IT)$"/>
<property name="ignorePattern" value="^.*(Tests?|IT|TestCase)$"/>
<property name="severity" value="warning"/>
<message key="javadoc.missing" value="Types should explain their purpose" />
</module>
Expand Down
Original file line number Diff line number Diff line change
@@ -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 <T> ActionListener<T> anyActionListener() {
return any(ActionListener.class);
}
}
4 changes: 0 additions & 4 deletions x-pack/plugin/security/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Object> tokenMeta = (Map<String, Object>) result.getMetadata().get(SamlRealm.CONTEXT_TOKEN_DATA);
tokenService.createOAuth2Tokens(authentication, originatingAuthentication,
tokenMeta, true, ActionListener.wrap(tokenResult -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ private void invalidateTokenPair(Tuple<UserToken, String> tokenPair, ActionListe

private Predicate<Map<String, Object>> containsMetadata(Map<String, Object> requiredMetadata) {
return source -> {
@SuppressWarnings("unchecked")
Map<String, Object> actualMetadata = (Map<String, Object>) source.get("metadata");
return requiredMetadata.entrySet().stream().allMatch(e -> Objects.equals(actualMetadata.get(e.getKey()), e.getValue()));
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,26 +34,21 @@
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;
import org.elasticsearch.common.settings.SecureString;
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;
Expand All @@ -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;
Expand All @@ -91,13 +91,12 @@
import org.elasticsearch.xpack.core.security.authc.support.Hasher;
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;
import org.elasticsearch.xpack.core.security.user.User;
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;
Expand Down Expand Up @@ -125,10 +124,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;
Expand Down Expand Up @@ -485,7 +485,9 @@ public void getRoleForApiKey(Authentication authentication, ActionListener<ApiKe

final Map<String, Object> metadata = authentication.getMetadata();
final String apiKeyId = (String) metadata.get(API_KEY_ID_KEY);
@SuppressWarnings("unchecked")
final Map<String, Object> roleDescriptors = (Map<String, Object>) metadata.get(API_KEY_ROLE_DESCRIPTORS_KEY);
@SuppressWarnings("unchecked")
final Map<String, Object> authnRoleDescriptors = (Map<String, Object>) metadata.get(API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY);

if (roleDescriptors == null && authnRoleDescriptors == null) {
Expand Down Expand Up @@ -545,6 +547,7 @@ private List<RoleDescriptor> parseRoleDescriptors(final String apiKeyId, final M
return roleDescriptors.entrySet().stream()
.map(entry -> {
final String name = entry.getKey();
@SuppressWarnings("unchecked")
final Map<String, Object> rdMap = (Map<String, Object>) entry.getValue();
try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) {
builder.map(rdMap);
Expand Down Expand Up @@ -694,6 +697,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<String, Object> metadata = (Map<String, Object>) apiKeyDoc.creator.get("metadata");
final User apiKeyUser = new User(principal, Strings.EMPTY_ARRAY, fullName, email, metadata, true);
final Map<String, Object> authResultMetadata = new HashMap<>();
Expand Down Expand Up @@ -917,8 +921,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<String, Object>) source.get("creator")).get("principal");
@SuppressWarnings("unchecked")
String realm = (String) ((Map<String, Object>) source.get("creator")).get("realm");
@SuppressWarnings("unchecked")
Map<String, Object> metadata = (Map<String, Object>) source.get("metadata_flattened");
return new ApiKey(name, id, Instant.ofEpochMilli(creation),
(expiration != null) ? Instant.ofEpochMilli(expiration) : null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,7 @@ protected List<Realm> initRealms(List<RealmConfig> realmConfigs) throws Exceptio
return Collections.unmodifiableList(realms);
}

@SuppressWarnings("unchecked")
public void usageStats(ActionListener<Map<String, Object>> listener) {
final XPackLicenseState licenseStateSnapshot = licenseState.copyCurrentLicenseState();
Map<String, Object> realmMap = new HashMap<>();
Expand All @@ -231,6 +232,7 @@ public void usageStats(ActionListener<Map<String, Object>> listener) {
}

assert value instanceof Map;
@SuppressWarnings("unchecked")
Map<String, Object> realmTypeUsage = (Map<String, Object>) value;
realmTypeUsage.put("enabled", true);
realmTypeUsage.put("available", true);
Expand Down Expand Up @@ -358,6 +360,7 @@ private void logDeprecationForReservedPrefixedRealmNames(List<RealmConfig.RealmI
}
}

@SuppressWarnings({"unchecked", "rawtypes"})
private static void combineMaps(Map<String, Object> mapA, Map<String, Object> mapB) {
for (Entry<String, Object> entry : mapB.entrySet()) {
mapA.compute(entry.getKey(), (key, value) -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -446,6 +446,7 @@ private void getUserTokenFromId(String userTokenId, Version tokenVersion, Action
() -> executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, getRequest,
ActionListener.<GetResponse>wrap(response -> {
if (response.isExists()) {
@SuppressWarnings("unchecked")
Map<String, Object> accessTokenSource =
(Map<String, Object>) response.getSource().get("access_token");
if (accessTokenSource == null) {
Expand All @@ -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<String, Object> userTokenSource =
(Map<String, Object>) accessTokenSource.get("user_token");
listener.onResponse(UserToken.fromSourceMap(userTokenSource));
Expand Down Expand Up @@ -687,7 +689,7 @@ public void invalidateActiveTokensForRealmAndUser(@Nullable String realmName, @N
}
}, listener::onFailure));
} else {
Predicate filter = null;
Predicate<Map<String, Object>> filter = null;
if (Strings.hasText(username)) {
filter = isOfUser(username);
}
Expand Down Expand Up @@ -1291,6 +1293,7 @@ private static Optional<ElasticsearchSecurityException> checkClientCanRefresh(Re
}

private static Map<String, Object> getRefreshTokenSourceMap(Map<String, Object> source) {
@SuppressWarnings("unchecked")
final Map<String, Object> refreshTokenSource = (Map<String, Object>) source.get("refresh_token");
if (refreshTokenSource == null || refreshTokenSource.isEmpty()) {
throw new IllegalStateException("token document is missing the refresh_token object");
Expand All @@ -1299,10 +1302,12 @@ private static Map<String, Object> getRefreshTokenSourceMap(Map<String, Object>
}

private static Map<String, Object> getUserTokenSourceMap(Map<String, Object> source) {
@SuppressWarnings("unchecked")
final Map<String, Object> accessTokenSource = (Map<String, Object>) source.get("access_token");
if (accessTokenSource == null || accessTokenSource.isEmpty()) {
throw new IllegalStateException("token document is missing the access_token object");
}
@SuppressWarnings("unchecked")
final Map<String, Object> userTokenSource = (Map<String, Object>) accessTokenSource.get("user_token");
if (userTokenSource == null || userTokenSource.isEmpty()) {
throw new IllegalStateException("token document is missing the user token info");
Expand Down Expand Up @@ -1552,7 +1557,9 @@ private Tuple<UserToken, String> filterAndParseHit(SearchHit hit, @Nullable Pred
*/
private Tuple<UserToken, String> parseTokensFromDocument(Map<String, Object> source, @Nullable Predicate<Map<String, Object>> filter)
throws IllegalStateException, DateTimeException {
@SuppressWarnings("unchecked")
final String hashedRefreshToken = (String) ((Map<String, Object>) source.get("refresh_token")).get("token");
@SuppressWarnings("unchecked")
final Map<String, Object> userTokenSource = (Map<String, Object>)
((Map<String, Object>) source.get("access_token")).get("user_token");
if (null != filter && filter.test(userTokenSource) == false) {
Expand Down Expand Up @@ -1630,6 +1637,7 @@ private void checkIfTokenIsValid(UserToken userToken, ActionListener<UserToken>
ActionListener.<GetResponse>wrap(response -> {
if (response.isExists()) {
Map<String, Object> source = response.getSource();
@SuppressWarnings("unchecked")
Map<String, Object> accessTokenSource = (Map<String, Object>) source.get("access_token");
if (accessTokenSource == null) {
onFailure.accept(new IllegalStateException("token document is missing access_token field"));
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -2402,6 +2411,7 @@ static RefreshTokenStatus fromSourceMap(Map<String, Object> refreshTokenSource)
if (invalidated == null) {
throw new IllegalStateException("token document is missing the \"invalidated\" field");
}
@SuppressWarnings("unchecked")
final Map<String, Object> clientInfo = (Map<String, Object>) refreshTokenSource.get("client");
if (clientInfo == null) {
throw new IllegalStateException("token document is missing the \"client\" field");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ static UserToken fromSourceMap(Map<String, Object> source) throws IllegalStateEx
if (versionId == null) {
throw new IllegalStateException("user token source document does not have the \"version\" field");
}
@SuppressWarnings("unchecked")
final Map<String, Object> metadata = (Map<String, Object>) source.get("metadata");
final String authString = (String) source.get("authentication");
if (authString == null) {
Expand Down
Loading