Skip to content

Commit 547cd73

Browse files
committed
Enable compiler warnings in x-pack security (#75473)
Part of #40366.
1 parent bb2125f commit 547cd73

76 files changed

Lines changed: 871 additions & 660 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

build-tools-internal/src/main/resources/checkstyle_ide_fragment.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929

3030
<!-- Use our fork of this Checkstyle rule, so that we can ignore test classes -->
3131
<module name="org.elasticsearch.gradle.internal.checkstyle.MissingJavadocTypeCheck">
32-
<property name="ignorePattern" value="^.*(Tests?|IT)$"/>
32+
<property name="ignorePattern" value="^.*(Tests?|IT|TestCase)$"/>
3333
<property name="severity" value="warning"/>
3434
<message key="javadoc.missing" value="Types should explain their purpose" />
3535
</module>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License
4+
* 2.0 and the Server Side Public License, v 1; you may not use this file except
5+
* in compliance with, at your election, the Elastic License 2.0 or the Server
6+
* Side Public License, v 1.
7+
*/
8+
9+
package org.elasticsearch.test;
10+
11+
import org.elasticsearch.action.ActionListener;
12+
13+
import static org.mockito.Matchers.any;
14+
15+
public abstract class ActionListenerUtils {
16+
17+
@SuppressWarnings("unchecked")
18+
public static <T> ActionListener<T> anyActionListener() {
19+
return any(ActionListener.class);
20+
}
21+
}

x-pack/plugin/security/build.gradle

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,10 +136,6 @@ dependencies {
136136
testImplementation('org.apache.directory.mavibot:mavibot:1.0.0-M8')
137137
}
138138

139-
tasks.withType(JavaCompile).configureEach {
140-
options.compilerArgs << "-Xlint:-rawtypes,-unchecked"
141-
}
142-
143139
tasks.named("processInternalClusterTestResources").configure {
144140
from(project(xpackModule('core')).file('src/main/config'))
145141
from(project(xpackModule('core')).file('src/test/resources'))

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlAuthenticateAction.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ protected void doExecute(Task task, SamlAuthenticateRequest request, ActionListe
6464
return;
6565
}
6666
assert authentication != null : "authentication should never be null at this point";
67+
@SuppressWarnings("unchecked")
6768
final Map<String, Object> tokenMeta = (Map<String, Object>) result.getMetadata().get(SamlRealm.CONTEXT_TOKEN_DATA);
6869
tokenService.createOAuth2Tokens(authentication, originatingAuthentication,
6970
tokenMeta, true, ActionListener.wrap(tokenResult -> {

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/action/saml/TransportSamlInvalidateSessionAction.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@ private void invalidateTokenPair(Tuple<UserToken, String> tokenPair, ActionListe
118118

119119
private Predicate<Map<String, Object>> containsMetadata(Map<String, Object> requiredMetadata) {
120120
return source -> {
121+
@SuppressWarnings("unchecked")
121122
Map<String, Object> actualMetadata = (Map<String, Object>) source.get("metadata");
122123
return requiredMetadata.entrySet().stream().allMatch(e -> Objects.equals(actualMetadata.get(e.getKey()), e.getValue()));
123124
};

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/ApiKeyService.java

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,26 +34,21 @@
3434
import org.elasticsearch.action.update.UpdateResponse;
3535
import org.elasticsearch.client.Client;
3636
import org.elasticsearch.cluster.service.ClusterService;
37-
import org.elasticsearch.common.cache.RemovalListener;
38-
import org.elasticsearch.common.cache.RemovalNotification.RemovalReason;
39-
import org.elasticsearch.core.CharArrays;
40-
import org.elasticsearch.core.Nullable;
41-
import org.elasticsearch.common.xcontent.ParseField;
4237
import org.elasticsearch.common.Strings;
4338
import org.elasticsearch.common.UUIDs;
4439
import org.elasticsearch.common.bytes.BytesArray;
4540
import org.elasticsearch.common.bytes.BytesReference;
4641
import org.elasticsearch.common.cache.Cache;
4742
import org.elasticsearch.common.cache.CacheBuilder;
48-
import org.elasticsearch.core.Tuple;
43+
import org.elasticsearch.common.cache.RemovalListener;
44+
import org.elasticsearch.common.cache.RemovalNotification.RemovalReason;
4945
import org.elasticsearch.common.hash.MessageDigests;
5046
import org.elasticsearch.common.logging.DeprecationCategory;
5147
import org.elasticsearch.common.logging.DeprecationLogger;
5248
import org.elasticsearch.common.settings.SecureString;
5349
import org.elasticsearch.common.settings.Setting;
5450
import org.elasticsearch.common.settings.Setting.Property;
5551
import org.elasticsearch.common.settings.Settings;
56-
import org.elasticsearch.core.TimeValue;
5752
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
5853
import org.elasticsearch.common.util.concurrent.FutureUtils;
5954
import org.elasticsearch.common.util.concurrent.ListenableFuture;
@@ -63,12 +58,17 @@
6358
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
6459
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
6560
import org.elasticsearch.common.xcontent.ObjectParserHelper;
61+
import org.elasticsearch.common.xcontent.ParseField;
6662
import org.elasticsearch.common.xcontent.XContentBuilder;
6763
import org.elasticsearch.common.xcontent.XContentFactory;
6864
import org.elasticsearch.common.xcontent.XContentHelper;
6965
import org.elasticsearch.common.xcontent.XContentLocation;
7066
import org.elasticsearch.common.xcontent.XContentParser;
7167
import org.elasticsearch.common.xcontent.XContentType;
68+
import org.elasticsearch.core.CharArrays;
69+
import org.elasticsearch.core.Nullable;
70+
import org.elasticsearch.core.TimeValue;
71+
import org.elasticsearch.core.Tuple;
7272
import org.elasticsearch.index.query.BoolQueryBuilder;
7373
import org.elasticsearch.index.query.QueryBuilders;
7474
import org.elasticsearch.license.LicenseUtils;
@@ -91,13 +91,12 @@
9191
import org.elasticsearch.xpack.core.security.authc.support.Hasher;
9292
import org.elasticsearch.xpack.core.security.authz.RoleDescriptor;
9393
import org.elasticsearch.xpack.core.security.user.User;
94-
import org.elasticsearch.xpack.security.support.LockingAtomicCounter;
9594
import org.elasticsearch.xpack.security.support.CacheInvalidatorRegistry;
9695
import org.elasticsearch.xpack.security.support.FeatureNotEnabledException;
9796
import org.elasticsearch.xpack.security.support.FeatureNotEnabledException.Feature;
97+
import org.elasticsearch.xpack.security.support.LockingAtomicCounter;
9898
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
9999

100-
import javax.crypto.SecretKeyFactory;
101100
import java.io.Closeable;
102101
import java.io.IOException;
103102
import java.io.UncheckedIOException;
@@ -125,6 +124,7 @@
125124
import java.util.function.Function;
126125
import java.util.function.Supplier;
127126
import java.util.stream.Collectors;
127+
import javax.crypto.SecretKeyFactory;
128128

129129
import static org.elasticsearch.action.bulk.TransportSingleItemBulkWriteAction.toSingleItemBulkRequest;
130130
import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;
@@ -513,7 +513,9 @@ public void getRoleForApiKey(Authentication authentication, ActionListener<ApiKe
513513

514514
final Map<String, Object> metadata = authentication.getMetadata();
515515
final String apiKeyId = (String) metadata.get(API_KEY_ID_KEY);
516+
@SuppressWarnings("unchecked")
516517
final Map<String, Object> roleDescriptors = (Map<String, Object>) metadata.get(API_KEY_ROLE_DESCRIPTORS_KEY);
518+
@SuppressWarnings("unchecked")
517519
final Map<String, Object> authnRoleDescriptors = (Map<String, Object>) metadata.get(API_KEY_LIMITED_ROLE_DESCRIPTORS_KEY);
518520

519521
if (roleDescriptors == null && authnRoleDescriptors == null) {
@@ -573,6 +575,7 @@ private List<RoleDescriptor> parseRoleDescriptors(final String apiKeyId, final M
573575
return roleDescriptors.entrySet().stream()
574576
.map(entry -> {
575577
final String name = entry.getKey();
578+
@SuppressWarnings("unchecked")
576579
final Map<String, Object> rdMap = (Map<String, Object>) entry.getValue();
577580
try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) {
578581
builder.map(rdMap);
@@ -722,6 +725,7 @@ void validateApiKeyExpiration(ApiKeyDoc apiKeyDoc, ApiKeyCredentials credentials
722725
final String principal = Objects.requireNonNull((String) apiKeyDoc.creator.get("principal"));
723726
final String fullName = (String) apiKeyDoc.creator.get("full_name");
724727
final String email = (String) apiKeyDoc.creator.get("email");
728+
@SuppressWarnings("unchecked")
725729
Map<String, Object> metadata = (Map<String, Object>) apiKeyDoc.creator.get("metadata");
726730
final User apiKeyUser = new User(principal, Strings.EMPTY_ARRAY, fullName, email, metadata, true);
727731
final Map<String, Object> authResultMetadata = new HashMap<>();
@@ -944,8 +948,11 @@ private void findApiKeys(final BoolQueryBuilder boolQuery, boolean filterOutInva
944948
Long creation = (Long) source.get("creation_time");
945949
Long expiration = (Long) source.get("expiration_time");
946950
Boolean invalidated = (Boolean) source.get("api_key_invalidated");
951+
@SuppressWarnings("unchecked")
947952
String username = (String) ((Map<String, Object>) source.get("creator")).get("principal");
953+
@SuppressWarnings("unchecked")
948954
String realm = (String) ((Map<String, Object>) source.get("creator")).get("realm");
955+
@SuppressWarnings("unchecked")
949956
Map<String, Object> metadata = (Map<String, Object>) source.get("metadata_flattened");
950957
return new ApiKey(name, id, Instant.ofEpochMilli(creation),
951958
(expiration != null) ? Instant.ofEpochMilli(expiration) : null,

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/Realms.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ protected List<Realm> initRealms() throws Exception {
253253
return Collections.unmodifiableList(realms);
254254
}
255255

256+
@SuppressWarnings("unchecked")
256257
public void usageStats(ActionListener<Map<String, Object>> listener) {
257258
final XPackLicenseState licenseStateSnapshot = licenseState.copyCurrentLicenseState();
258259
Map<String, Object> realmMap = new HashMap<>();
@@ -276,6 +277,7 @@ public void usageStats(ActionListener<Map<String, Object>> listener) {
276277
}
277278

278279
assert value instanceof Map;
280+
@SuppressWarnings("unchecked")
279281
Map<String, Object> realmTypeUsage = (Map<String, Object>) value;
280282
realmTypeUsage.put("enabled", true);
281283
realmTypeUsage.put("available", true);
@@ -330,6 +332,7 @@ private void addNativeRealms(List<Realm> realms) throws Exception {
330332
}
331333
}
332334

335+
@SuppressWarnings({"unchecked", "rawtypes"})
333336
private static void combineMaps(Map<String, Object> mapA, Map<String, Object> mapB) {
334337
for (Entry<String, Object> entry : mapB.entrySet()) {
335338
mapA.compute(entry.getKey(), (key, value) -> {

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/TokenService.java

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -45,14 +45,12 @@
4545
import org.elasticsearch.cluster.ClusterStateUpdateTask;
4646
import org.elasticsearch.cluster.ack.AckedRequest;
4747
import org.elasticsearch.cluster.service.ClusterService;
48-
import org.elasticsearch.core.Nullable;
4948
import org.elasticsearch.common.Priority;
5049
import org.elasticsearch.common.Strings;
5150
import org.elasticsearch.common.UUIDs;
5251
import org.elasticsearch.common.bytes.BytesReference;
5352
import org.elasticsearch.common.cache.Cache;
5453
import org.elasticsearch.common.cache.CacheBuilder;
55-
import org.elasticsearch.core.Tuple;
5654
import org.elasticsearch.common.hash.MessageDigests;
5755
import org.elasticsearch.common.io.stream.BytesStreamOutput;
5856
import org.elasticsearch.common.io.stream.InputStreamStreamInput;
@@ -63,13 +61,15 @@
6361
import org.elasticsearch.common.settings.Setting;
6462
import org.elasticsearch.common.settings.Setting.Property;
6563
import org.elasticsearch.common.settings.Settings;
66-
import org.elasticsearch.core.TimeValue;
6764
import org.elasticsearch.common.util.concurrent.AbstractRunnable;
6865
import org.elasticsearch.common.util.concurrent.ThreadContext;
6966
import org.elasticsearch.common.util.iterable.Iterables;
7067
import org.elasticsearch.common.xcontent.XContentBuilder;
7168
import org.elasticsearch.common.xcontent.XContentFactory;
7269
import org.elasticsearch.common.xcontent.XContentType;
70+
import org.elasticsearch.core.Nullable;
71+
import org.elasticsearch.core.TimeValue;
72+
import org.elasticsearch.core.Tuple;
7373
import org.elasticsearch.core.internal.io.Streams;
7474
import org.elasticsearch.index.IndexNotFoundException;
7575
import org.elasticsearch.index.engine.VersionConflictEngineException;
@@ -97,15 +97,6 @@
9797
import org.elasticsearch.xpack.security.support.FeatureNotEnabledException.Feature;
9898
import org.elasticsearch.xpack.security.support.SecurityIndexManager;
9999

100-
import javax.crypto.Cipher;
101-
import javax.crypto.CipherInputStream;
102-
import javax.crypto.CipherOutputStream;
103-
import javax.crypto.NoSuchPaddingException;
104-
import javax.crypto.SecretKey;
105-
import javax.crypto.SecretKeyFactory;
106-
import javax.crypto.spec.GCMParameterSpec;
107-
import javax.crypto.spec.PBEKeySpec;
108-
import javax.crypto.spec.SecretKeySpec;
109100
import java.io.ByteArrayInputStream;
110101
import java.io.ByteArrayOutputStream;
111102
import java.io.Closeable;
@@ -144,6 +135,15 @@
144135
import java.util.function.Predicate;
145136
import java.util.function.Supplier;
146137
import java.util.stream.Collectors;
138+
import javax.crypto.Cipher;
139+
import javax.crypto.CipherInputStream;
140+
import javax.crypto.CipherOutputStream;
141+
import javax.crypto.NoSuchPaddingException;
142+
import javax.crypto.SecretKey;
143+
import javax.crypto.SecretKeyFactory;
144+
import javax.crypto.spec.GCMParameterSpec;
145+
import javax.crypto.spec.PBEKeySpec;
146+
import javax.crypto.spec.SecretKeySpec;
147147

148148
import static java.util.Collections.emptyList;
149149
import static java.util.Collections.singletonList;
@@ -449,6 +449,7 @@ private void getUserTokenFromId(String userTokenId, Version tokenVersion, Action
449449
() -> executeAsyncWithOrigin(client.threadPool().getThreadContext(), SECURITY_ORIGIN, getRequest,
450450
ActionListener.<GetResponse>wrap(response -> {
451451
if (response.isExists()) {
452+
@SuppressWarnings("unchecked")
452453
Map<String, Object> accessTokenSource =
453454
(Map<String, Object>) response.getSource().get("access_token");
454455
if (accessTokenSource == null) {
@@ -458,6 +459,7 @@ private void getUserTokenFromId(String userTokenId, Version tokenVersion, Action
458459
onFailure.accept(new IllegalStateException(
459460
"token document is missing the user_token field"));
460461
} else {
462+
@SuppressWarnings("unchecked")
461463
Map<String, Object> userTokenSource =
462464
(Map<String, Object>) accessTokenSource.get("user_token");
463465
listener.onResponse(UserToken.fromSourceMap(userTokenSource));
@@ -691,7 +693,7 @@ public void invalidateActiveTokensForRealmAndUser(@Nullable String realmName, @N
691693
}
692694
}, listener::onFailure));
693695
} else {
694-
Predicate filter = null;
696+
Predicate<Map<String, Object>> filter = null;
695697
if (Strings.hasText(username)) {
696698
filter = isOfUser(username);
697699
}
@@ -1295,6 +1297,7 @@ private static Optional<ElasticsearchSecurityException> checkClientCanRefresh(Re
12951297
}
12961298

12971299
private static Map<String, Object> getRefreshTokenSourceMap(Map<String, Object> source) {
1300+
@SuppressWarnings("unchecked")
12981301
final Map<String, Object> refreshTokenSource = (Map<String, Object>) source.get("refresh_token");
12991302
if (refreshTokenSource == null || refreshTokenSource.isEmpty()) {
13001303
throw new IllegalStateException("token document is missing the refresh_token object");
@@ -1303,10 +1306,12 @@ private static Map<String, Object> getRefreshTokenSourceMap(Map<String, Object>
13031306
}
13041307

13051308
private static Map<String, Object> getUserTokenSourceMap(Map<String, Object> source) {
1309+
@SuppressWarnings("unchecked")
13061310
final Map<String, Object> accessTokenSource = (Map<String, Object>) source.get("access_token");
13071311
if (accessTokenSource == null || accessTokenSource.isEmpty()) {
13081312
throw new IllegalStateException("token document is missing the access_token object");
13091313
}
1314+
@SuppressWarnings("unchecked")
13101315
final Map<String, Object> userTokenSource = (Map<String, Object>) accessTokenSource.get("user_token");
13111316
if (userTokenSource == null || userTokenSource.isEmpty()) {
13121317
throw new IllegalStateException("token document is missing the user token info");
@@ -1556,7 +1561,9 @@ private Tuple<UserToken, String> filterAndParseHit(SearchHit hit, @Nullable Pred
15561561
*/
15571562
private Tuple<UserToken, String> parseTokensFromDocument(Map<String, Object> source, @Nullable Predicate<Map<String, Object>> filter)
15581563
throws IllegalStateException, DateTimeException {
1564+
@SuppressWarnings("unchecked")
15591565
final String hashedRefreshToken = (String) ((Map<String, Object>) source.get("refresh_token")).get("token");
1566+
@SuppressWarnings("unchecked")
15601567
final Map<String, Object> userTokenSource = (Map<String, Object>)
15611568
((Map<String, Object>) source.get("access_token")).get("user_token");
15621569
if (null != filter && filter.test(userTokenSource) == false) {
@@ -1634,6 +1641,7 @@ private void checkIfTokenIsValid(UserToken userToken, ActionListener<UserToken>
16341641
ActionListener.<GetResponse>wrap(response -> {
16351642
if (response.isExists()) {
16361643
Map<String, Object> source = response.getSource();
1644+
@SuppressWarnings("unchecked")
16371645
Map<String, Object> accessTokenSource = (Map<String, Object>) source.get("access_token");
16381646
if (accessTokenSource == null) {
16391647
onFailure.accept(new IllegalStateException("token document is missing access_token field"));
@@ -2002,6 +2010,7 @@ public void onFailure(Exception e) {
20022010
* Creates a new key unless present that is newer than the current active key and returns the corresponding metadata. Note:
20032011
* this method doesn't modify the metadata used in this token service. See {@link #refreshMetadata(TokenMetadata)}
20042012
*/
2013+
@SuppressWarnings("unchecked")
20052014
synchronized TokenMetadata generateSpareKey() {
20062015
KeyAndCache maxKey = keyCache.cache.values().stream().max(Comparator.comparingLong(v -> v.keyAndTimestamp.getTimestamp())).get();
20072016
KeyAndCache currentKey = keyCache.activeKeyCache;
@@ -2406,6 +2415,7 @@ static RefreshTokenStatus fromSourceMap(Map<String, Object> refreshTokenSource)
24062415
if (invalidated == null) {
24072416
throw new IllegalStateException("token document is missing the \"invalidated\" field");
24082417
}
2418+
@SuppressWarnings("unchecked")
24092419
final Map<String, Object> clientInfo = (Map<String, Object>) refreshTokenSource.get("client");
24102420
if (clientInfo == null) {
24112421
throw new IllegalStateException("token document is missing the \"client\" field");

x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authc/UserToken.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ static UserToken fromSourceMap(Map<String, Object> source) throws IllegalStateEx
155155
if (versionId == null) {
156156
throw new IllegalStateException("user token source document does not have the \"version\" field");
157157
}
158+
@SuppressWarnings("unchecked")
158159
final Map<String, Object> metadata = (Map<String, Object>) source.get("metadata");
159160
final String authString = (String) source.get("authentication");
160161
if (authString == null) {

0 commit comments

Comments
 (0)