Skip to content

Commit 7129ae6

Browse files
cwperkskkewwei
authored andcommitted
Replace java.security.AccessController with org.opensearch.secure_sm.AccessController in sub projects with SocketAccess class (opensearch-project#19803)
* Replace AccessController in sub projects with SocketAccess class Signed-off-by: Craig Perkins <[email protected]> * Add to CHANGELOG Signed-off-by: Craig Perkins <[email protected]> * Add import Signed-off-by: Craig Perkins <[email protected]> * Address review comments Signed-off-by: Craig Perkins <[email protected]> * Address comments Signed-off-by: Craig Perkins <[email protected]> * Wrap exception Signed-off-by: Craig Perkins <[email protected]> * Wrap instead Signed-off-by: Craig Perkins <[email protected]> --------- Signed-off-by: Craig Perkins <[email protected]>
1 parent 7597a90 commit 7129ae6

File tree

40 files changed

+250
-519
lines changed

40 files changed

+250
-519
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
4646
- Refactor the ThreadPoolStats.Stats class to use the Builder pattern instead of constructors ([#19317](https://github.com/opensearch-project/OpenSearch/pull/19317))
4747
- Refactor the IndexingStats.Stats class to use the Builder pattern instead of constructors ([#19306](https://github.com/opensearch-project/OpenSearch/pull/19306))
4848
- Remove FeatureFlag.MERGED_SEGMENT_WARMER_EXPERIMENTAL_FLAG. ([#19715](https://github.com/opensearch-project/OpenSearch/pull/19715))
49+
- Replace java.security.AccessController with org.opensearch.secure_sm.AccessController in sub projects with SocketAccess class ([#19803](https://github.com/opensearch-project/OpenSearch/pull/19803))
4950
- Replace java.security.AccessController with org.opensearch.secure_sm.AccessController in discovery plugins ([#19802](https://github.com/opensearch-project/OpenSearch/pull/19802))
5051
- Change the default value of doc_values in WildcardFieldMapper to true. ([#19796](https://github.com/opensearch-project/OpenSearch/pull/19796))
5152
- Make Engine#loadHistoryUUID() protected and Origin#isFromTranslog() public ([#19753](https://github.com/opensearch-project/OpenSearch/pull/19752))

libs/agent-sm/agent-policy/src/main/java/org/opensearch/secure_sm/AccessController.java

Lines changed: 31 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
package org.opensearch.secure_sm;
1010

11-
import java.util.concurrent.Callable;
1211
import java.util.function.Supplier;
1312

1413
/**
@@ -78,38 +77,37 @@ public static <T> T doPrivileged(Supplier<T> action) {
7877
}
7978

8079
/**
81-
* Performs the specified action.
80+
* Performs the specified action in a privileged block.
8281
*
83-
* <p> If the action's {@code run} method throws an <i>unchecked</i>
82+
* <p> If the action's {@code run} method throws an (unchecked)
8483
* exception, it will propagate through this method.
8584
*
86-
* @param <T> the type of the value returned by the
87-
* PrivilegedExceptionAction's {@code run} method
88-
*
8985
* @param action the action to be performed
9086
*
91-
* @return the value returned by the action's {@code run} method
92-
*
93-
* @throws Exception if the specified action's
87+
* @throws T if the specified action's
9488
* {@code call} method threw a <i>checked</i> exception
9589
*/
96-
public static <T> T doPrivilegedChecked(Callable<T> action) throws Exception {
97-
return action.call();
90+
public static <T extends Exception> void doPrivilegedChecked(CheckedRunnable<T> action) throws T {
91+
action.run();
9892
}
9993

10094
/**
101-
* Performs the specified action in a privileged block.
95+
* Performs the specified action in a privileged block and returns a value.
10296
*
103-
* <p> If the action's {@code run} method throws an (unchecked)
104-
* exception, it will propagate through this method.
97+
* <p> If the action's {@code call} method throws an exception,
98+
* it will propagate through this method.
10599
*
100+
* @param <R> the type of the value returned by the action
101+
* @param <T> the type of the exception that can be thrown
106102
* @param action the action to be performed
107103
*
104+
* @return the value returned by the action's {@code call} method
105+
*
108106
* @throws T if the specified action's
109107
* {@code call} method threw a <i>checked</i> exception
110108
*/
111-
public static <T extends Exception> void doPrivilegedChecked(CheckedRunnable<T> action) throws T {
112-
action.run();
109+
public static <R, T extends Exception> R doPrivilegedChecked(CheckedSupplier<R, T> action) throws T {
110+
return action.get();
113111
}
114112

115113
/**
@@ -126,4 +124,21 @@ public interface CheckedRunnable<E extends Exception> {
126124
*/
127125
void run() throws E;
128126
}
127+
128+
/**
129+
* A functional interface that represents a supplier action that can throw a checked exception.
130+
*
131+
* @param <R> the type of the value returned
132+
* @param <E> the type of the exception that can be thrown
133+
*/
134+
public interface CheckedSupplier<R, E extends Exception> {
135+
136+
/**
137+
* Gets a result.
138+
*
139+
* @return a result
140+
* @throws E
141+
*/
142+
R get() throws E;
143+
}
129144
}

plugins/crypto-kms/src/main/java/org/opensearch/crypto/kms/CredentialProviderFactory.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
1616
import software.amazon.awssdk.core.SdkSystemSetting;
1717

18+
import org.opensearch.secure_sm.AccessController;
19+
1820
import java.util.function.Supplier;
1921

2022
/**
@@ -44,7 +46,7 @@ private AwsCredentialsProvider initializeProvider() {
4446

4547
@Override
4648
public AwsCredentials resolveCredentials() {
47-
return SocketAccess.doPrivileged(credentials::resolveCredentials);
49+
return AccessController.doPrivileged(credentials::resolveCredentials);
4850
}
4951
}
5052

plugins/crypto-kms/src/main/java/org/opensearch/crypto/kms/KmsMasterKeyProvider.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import org.apache.logging.log4j.Logger;
2020
import org.opensearch.common.crypto.DataKeyPair;
2121
import org.opensearch.common.crypto.MasterKeyProvider;
22+
import org.opensearch.secure_sm.AccessController;
2223

2324
import java.util.Map;
2425
import java.util.function.Supplier;
@@ -51,7 +52,7 @@ public DataKeyPair generateDataPair() {
5152
.keySpec(DataKeySpec.AES_256)
5253
.keyId(keyArn)
5354
.build();
54-
GenerateDataKeyResponse dataKeyPair = SocketAccess.doPrivileged(() -> clientReference.get().generateDataKey(request));
55+
GenerateDataKeyResponse dataKeyPair = AccessController.doPrivileged(() -> clientReference.get().generateDataKey(request));
5556
return new DataKeyPair(dataKeyPair.plaintext().asByteArray(), dataKeyPair.ciphertextBlob().asByteArray());
5657
}
5758
}
@@ -63,7 +64,7 @@ public byte[] decryptKey(byte[] encryptedKey) {
6364
.ciphertextBlob(SdkBytes.fromByteArray(encryptedKey))
6465
.encryptionContext(encryptionContext)
6566
.build();
66-
DecryptResponse decryptResponse = SocketAccess.doPrivileged(() -> clientReference.get().decrypt(decryptRequest));
67+
DecryptResponse decryptResponse = AccessController.doPrivileged(() -> clientReference.get().decrypt(decryptRequest));
6768
return decryptResponse.plaintext().asByteArray();
6869
}
6970
}

plugins/crypto-kms/src/main/java/org/opensearch/crypto/kms/KmsService.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import org.opensearch.common.settings.Setting;
3030
import org.opensearch.common.settings.Settings;
3131
import org.opensearch.core.common.Strings;
32+
import org.opensearch.secure_sm.AccessController;
3233

3334
import java.io.Closeable;
3435
import java.net.URI;
@@ -70,10 +71,10 @@ public KmsService() {
7071
}
7172

7273
private KmsClient buildClient(KmsClientSettings clientSettings) {
73-
SocketAccess.doPrivilegedVoid(KmsService::setDefaultAwsProfilePath);
74+
AccessController.doPrivileged(KmsService::setDefaultAwsProfilePath);
7475
final AwsCredentialsProvider awsCredentialsProvider = buildCredentials(clientSettings);
7576
final ClientOverrideConfiguration overrideConfiguration = buildOverrideConfiguration();
76-
final ProxyConfiguration proxyConfiguration = SocketAccess.doPrivileged(() -> buildProxyConfiguration(clientSettings));
77+
final ProxyConfiguration proxyConfiguration = AccessController.doPrivileged(() -> buildProxyConfiguration(clientSettings));
7778
return buildClient(
7879
awsCredentialsProvider,
7980
proxyConfiguration,
@@ -113,7 +114,7 @@ protected KmsClient buildClient(
113114
builder.region(Region.of(region));
114115
}
115116

116-
return SocketAccess.doPrivileged(builder::build);
117+
return AccessController.doPrivileged(builder::build);
117118
}
118119

119120
ProxyConfiguration buildProxyConfiguration(KmsClientSettings clientSettings) {
@@ -166,7 +167,7 @@ public AmazonKmsClientReference client(CryptoMetadata cryptoMetadata) {
166167
return existing;
167168
}
168169
final AmazonKmsClientReference clientReference = new AmazonKmsClientReference(
169-
SocketAccess.doPrivileged(() -> buildClient(clientSettings))
170+
AccessController.doPrivileged(() -> buildClient(clientSettings))
170171
);
171172
clientReference.incRef();
172173
clientsCache = MapBuilder.newMapBuilder(clientsCache).put(clientSettings, clientReference).immutableMap();

plugins/crypto-kms/src/main/java/org/opensearch/crypto/kms/SocketAccess.java

Lines changed: 0 additions & 39 deletions
This file was deleted.

plugins/crypto-kms/src/test/java/org/opensearch/crypto/kms/AbstractAwsTestCase.java

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212

1313
import org.opensearch.common.SuppressForbidden;
1414
import org.opensearch.common.io.PathUtils;
15+
import org.opensearch.secure_sm.AccessController;
1516
import org.opensearch.test.OpenSearchTestCase;
1617

1718
import java.nio.file.Path;
@@ -42,13 +43,15 @@ private Path configPath() {
4243

4344
@SuppressForbidden(reason = "set predictable aws defaults")
4445
private void setUpAwsProfile() throws Exception {
45-
previousOpenSearchPathConf = SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", configPath().toString()));
46-
awsRegion = SocketAccess.doPrivileged(() -> System.setProperty("aws.region", "us-west-2"));
47-
awsAccessKeyId = SocketAccess.doPrivileged(() -> System.setProperty("aws.accessKeyId", "aws-access-key-id"));
48-
awsSecretAccessKey = SocketAccess.doPrivileged(() -> System.setProperty("aws.secretAccessKey", "aws-secret-access-key"));
46+
previousOpenSearchPathConf = AccessController.doPrivileged(
47+
() -> System.setProperty("opensearch.path.conf", configPath().toString())
48+
);
49+
awsRegion = AccessController.doPrivileged(() -> System.setProperty("aws.region", "us-west-2"));
50+
awsAccessKeyId = AccessController.doPrivileged(() -> System.setProperty("aws.accessKeyId", "aws-access-key-id"));
51+
awsSecretAccessKey = AccessController.doPrivileged(() -> System.setProperty("aws.secretAccessKey", "aws-secret-access-key"));
4952
awsSharedCredentialsFile = System.getProperty(ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE.property());
5053
awsConfigFile = System.getProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property());
51-
SocketAccess.doPrivilegedVoid(KmsService::setDefaultAwsProfilePath);
54+
AccessController.doPrivileged(KmsService::setDefaultAwsProfilePath);
5255
}
5356

5457
@SuppressForbidden(reason = "reset aws settings")
@@ -64,9 +67,9 @@ private void resetAwsProfile() throws Exception {
6467
@SuppressForbidden(reason = "reset aws settings")
6568
private void resetPropertyValue(String key, String value) {
6669
if (value != null) {
67-
SocketAccess.doPrivileged(() -> System.setProperty(key, value));
70+
AccessController.doPrivileged(() -> System.setProperty(key, value));
6871
} else {
69-
SocketAccess.doPrivileged(() -> System.clearProperty(key));
72+
AccessController.doPrivileged(() -> System.clearProperty(key));
7073
}
7174
}
7275
}

plugins/crypto-kms/src/test/java/org/opensearch/crypto/kms/KmsServiceTests.java

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import org.opensearch.cluster.metadata.CryptoMetadata;
2121
import org.opensearch.common.settings.MockSecureSettings;
2222
import org.opensearch.common.settings.Settings;
23+
import org.opensearch.secure_sm.AccessController;
2324

2425
public class KmsServiceTests extends AbstractAwsTestCase {
2526
private final CryptoMetadata cryptoMetadata = new CryptoMetadata("kp1", "kp2", Settings.EMPTY);
@@ -38,11 +39,11 @@ public void testAWSDefaultConfiguration() {
3839
assertNull(proxyConfiguration.password());
3940

4041
// retry policy
41-
RetryPolicy retryPolicyConfiguration = SocketAccess.doPrivileged(kmsService::buildRetryPolicy);
42+
RetryPolicy retryPolicyConfiguration = AccessController.doPrivileged(kmsService::buildRetryPolicy);
4243

4344
assertEquals(retryPolicyConfiguration.numRetries().intValue(), 10);
4445

45-
ClientOverrideConfiguration clientOverrideConfiguration = SocketAccess.doPrivileged(kmsService::buildOverrideConfiguration);
46+
ClientOverrideConfiguration clientOverrideConfiguration = AccessController.doPrivileged(kmsService::buildOverrideConfiguration);
4647
assertTrue(clientOverrideConfiguration.retryPolicy().isPresent());
4748
assertEquals(clientOverrideConfiguration.retryPolicy().get().numRetries().intValue(), 10);
4849
}
@@ -63,7 +64,7 @@ public void testAWSConfigurationWithAwsSettings() {
6364

6465
try (KmsService kmsService = new KmsService()) {
6566
// proxy configuration
66-
final ProxyConfiguration proxyConfiguration = SocketAccess.doPrivileged(
67+
final ProxyConfiguration proxyConfiguration = AccessController.doPrivileged(
6768
() -> kmsService.buildProxyConfiguration(KmsClientSettings.getClientSettings(settings))
6869
);
6970

@@ -73,10 +74,10 @@ public void testAWSConfigurationWithAwsSettings() {
7374
assertEquals(proxyConfiguration.password(), "aws_proxy_password");
7475

7576
// retry policy
76-
RetryPolicy retryPolicyConfiguration = SocketAccess.doPrivileged(kmsService::buildRetryPolicy);
77+
RetryPolicy retryPolicyConfiguration = AccessController.doPrivileged(kmsService::buildRetryPolicy);
7778
assertEquals(retryPolicyConfiguration.numRetries().intValue(), 10);
7879

79-
ClientOverrideConfiguration clientOverrideConfiguration = SocketAccess.doPrivileged(kmsService::buildOverrideConfiguration);
80+
ClientOverrideConfiguration clientOverrideConfiguration = AccessController.doPrivileged(kmsService::buildOverrideConfiguration);
8081
assertTrue(clientOverrideConfiguration.retryPolicy().isPresent());
8182
assertEquals(clientOverrideConfiguration.retryPolicy().get().numRetries().intValue(), 10);
8283
}

plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,9 @@ static Settings getAvailabilityZoneNodeAttributes(Settings settings, String azMe
160160
logger.debug("obtaining ec2 [placement/availability-zone] from ec2 meta-data url {}", url);
161161
urlConnection = AccessController.doPrivilegedChecked(() -> url.openConnection());
162162
urlConnection.setConnectTimeout(2000);
163-
} catch (final Exception e) {
163+
} catch (final IOException e) {
164164
// should not happen, we know the url is not malformed, and openConnection does not actually hit network
165-
throw new UncheckedIOException((IOException) e);
165+
throw new UncheckedIOException(e);
166166
}
167167

168168
try (
@@ -176,10 +176,7 @@ static Settings getAvailabilityZoneNodeAttributes(Settings settings, String azMe
176176
} else {
177177
attrs.put(Node.NODE_ATTRIBUTES.getKey() + "aws_availability_zone", metadataResult);
178178
}
179-
} catch (final Exception e) {
180-
if (e instanceof IllegalStateException ise) {
181-
throw ise;
182-
}
179+
} catch (final IOException e) {
183180
// this is lenient so the plugin does not fail when installed outside of ec2
184181
logger.error("failed to get metadata for [placement/availability-zone]", e);
185182
}

plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2NameResolver.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ public InetAddress[] resolve(Ec2HostnameType type) throws IOException {
124124
logger.debug("obtained ec2 hostname from ec2 meta-data url {}: {}", url, metadataResult);
125125
// only one address: because we explicitly ask for only one via the Ec2HostnameType
126126
return new InetAddress[] { InetAddress.getByName(metadataResult) };
127-
} catch (Exception e) {
127+
} catch (IOException e) {
128128
throw new IOException("IOException caught when fetching InetAddress from [" + metadataUrl + "]", e);
129129
} finally {
130130
IOUtils.closeWhileHandlingException(in);

0 commit comments

Comments
 (0)