diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ab256c30bc94..c3f2365b8afd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,7 +32,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Refactor the ThreadPoolStats.Stats class to use the Builder pattern instead of constructors ([#19317](https://github.com/opensearch-project/OpenSearch/pull/19317)) - Refactor the IndexingStats.Stats class to use the Builder pattern instead of constructors ([#19306](https://github.com/opensearch-project/OpenSearch/pull/19306)) - Remove FeatureFlag.MERGED_SEGMENT_WARMER_EXPERIMENTAL_FLAG. ([#19715](https://github.com/opensearch-project/OpenSearch/pull/19715)) -- +- Replace java.security.AccessController with org.opensearch.secure_sm.AccessController in discovery plugins ([#19802](https://github.com/opensearch-project/OpenSearch/pull/19802)) + ### Fixed - Fix Allocation and Rebalance Constraints of WeightFunction are incorrectly reset ([#19012](https://github.com/opensearch-project/OpenSearch/pull/19012)) - Fix flaky test FieldDataLoadingIT.testIndicesFieldDataCacheSizeSetting ([#19571](https://github.com/opensearch-project/OpenSearch/pull/19571)) diff --git a/plugins/discovery-azure-classic/src/internalClusterTest/java/org/opensearch/discovery/azure/classic/AzureDiscoveryClusterFormationTests.java b/plugins/discovery-azure-classic/src/internalClusterTest/java/org/opensearch/discovery/azure/classic/AzureDiscoveryClusterFormationTests.java index a4a2e672f3afe..c42635807f10f 100644 --- a/plugins/discovery-azure-classic/src/internalClusterTest/java/org/opensearch/discovery/azure/classic/AzureDiscoveryClusterFormationTests.java +++ b/plugins/discovery-azure-classic/src/internalClusterTest/java/org/opensearch/discovery/azure/classic/AzureDiscoveryClusterFormationTests.java @@ -49,6 +49,7 @@ import org.opensearch.node.Node; import org.opensearch.plugin.discovery.azure.classic.AzureDiscoveryPlugin; import org.opensearch.plugins.Plugin; +import org.opensearch.secure_sm.AccessController; import org.opensearch.test.OpenSearchIntegTestCase; import org.opensearch.transport.TransportSettings; import org.junit.AfterClass; @@ -74,9 +75,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.AccessController; import java.security.KeyStore; -import java.security.PrivilegedAction; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -296,14 +295,11 @@ private static SSLContext getSSLContext() throws Exception { * The {@link HttpsServer} in the JDK has issues with TLSv1.3 when running in a JDK prior to * 12.0.1 so we pin to TLSv1.2 when running on an earlier JDK */ - @SuppressWarnings("removal") private static String getProtocol() { if (Runtime.version().compareTo(Version.parse("12")) < 0) { return "TLSv1.2"; } else { - Version full = AccessController.doPrivileged( - (PrivilegedAction) () -> Version.parse(System.getProperty("java.version")) - ); + Version full = AccessController.doPrivileged(() -> Version.parse(System.getProperty("java.version"))); if (full.compareTo(Version.parse("12.0.1")) < 0) { return "TLSv1.2"; } diff --git a/plugins/discovery-azure-classic/src/main/java/org/opensearch/cloud/azure/classic/management/AzureComputeServiceImpl.java b/plugins/discovery-azure-classic/src/main/java/org/opensearch/cloud/azure/classic/management/AzureComputeServiceImpl.java index 6e21feca7f5fb..182b978ca0f91 100644 --- a/plugins/discovery-azure-classic/src/main/java/org/opensearch/cloud/azure/classic/management/AzureComputeServiceImpl.java +++ b/plugins/discovery-azure-classic/src/main/java/org/opensearch/cloud/azure/classic/management/AzureComputeServiceImpl.java @@ -49,11 +49,9 @@ import org.opensearch.common.settings.Setting; import org.opensearch.common.settings.Settings; import org.opensearch.core.common.Strings; +import org.opensearch.secure_sm.AccessController; import java.io.IOException; -import java.security.AccessController; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; import java.util.ServiceLoader; public class AzureComputeServiceImpl extends AbstractLifecycleComponent implements AzureComputeService { @@ -112,17 +110,13 @@ private static String getRequiredSetting(Settings settings, Setting sett return value; } - @SuppressWarnings("removal") @Override public HostedServiceGetDetailedResponse getServiceDetails() { SpecialPermission.check(); try { - return AccessController.doPrivileged( - (PrivilegedExceptionAction) () -> client.getHostedServicesOperations() - .getDetailed(serviceName) - ); - } catch (PrivilegedActionException e) { - throw new AzureServiceRemoteException("can not get list of azure nodes", e.getCause()); + return AccessController.doPrivilegedChecked(() -> client.getHostedServicesOperations().getDetailed(serviceName)); + } catch (Exception e) { + throw new AzureServiceRemoteException("can not get list of azure nodes", e); } } diff --git a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2SeedHostsProvider.java b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2SeedHostsProvider.java index fb46b82065fd1..8573a8426106e 100644 --- a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2SeedHostsProvider.java +++ b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2SeedHostsProvider.java @@ -50,6 +50,7 @@ import org.opensearch.common.util.SingleObjectCache; import org.opensearch.core.common.transport.TransportAddress; import org.opensearch.discovery.SeedHostsProvider; +import org.opensearch.secure_sm.AccessController; import org.opensearch.transport.TransportService; import java.util.ArrayList; @@ -142,7 +143,7 @@ protected List fetchDynamicNodes() { // 1. differences in VPCs require different parameters during query (ID vs Name) // 2. We want to use two different strategies: (all security groups vs. any security groups) DescribeInstancesRequest instancesRequest = buildDescribeInstancesRequest(); - descInstances = SocketAccess.doPrivileged(() -> clientReference.get().describeInstances(instancesRequest)); + descInstances = AccessController.doPrivileged(() -> clientReference.get().describeInstances(instancesRequest)); } catch (final SdkException e) { logger.warn("error retrieving instance list from IMDS", e); return dynamicHosts; diff --git a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2ServiceImpl.java b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2ServiceImpl.java index a2e920761b655..bf7775283227d 100644 --- a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2ServiceImpl.java +++ b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/AwsEc2ServiceImpl.java @@ -52,6 +52,7 @@ import org.opensearch.common.SuppressForbidden; import org.opensearch.common.util.LazyInitializable; import org.opensearch.core.common.Strings; +import org.opensearch.secure_sm.AccessController; import java.net.URI; import java.net.URISyntaxException; @@ -65,10 +66,10 @@ class AwsEc2ServiceImpl implements AwsEc2Service { new AtomicReference<>(); private Ec2Client buildClient(Ec2ClientSettings clientSettings) { - SocketAccess.doPrivilegedVoid(AwsEc2ServiceImpl::setDefaultAwsProfilePath); + AccessController.doPrivileged(AwsEc2ServiceImpl::setDefaultAwsProfilePath); final AwsCredentialsProvider awsCredentialsProvider = buildCredentials(logger, clientSettings); final ClientOverrideConfiguration overrideConfiguration = buildOverrideConfiguration(logger, clientSettings); - final ProxyConfiguration proxyConfiguration = SocketAccess.doPrivileged(() -> buildProxyConfiguration(logger, clientSettings)); + final ProxyConfiguration proxyConfiguration = AccessController.doPrivileged(() -> buildProxyConfiguration(logger, clientSettings)); return buildClient( awsCredentialsProvider, proxyConfiguration, @@ -107,7 +108,7 @@ protected Ec2Client buildClient( builder.region(Region.of(region)); } - return SocketAccess.doPrivileged(builder::build); + return AccessController.doPrivileged(builder::build); } protected String getFullEndpoint(String endpoint) { diff --git a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java index eb02e99582f93..bd1b91bfa4793 100644 --- a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java +++ b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2DiscoveryPlugin.java @@ -46,6 +46,7 @@ import org.opensearch.plugins.DiscoveryPlugin; import org.opensearch.plugins.Plugin; import org.opensearch.plugins.ReloadablePlugin; +import org.opensearch.secure_sm.AccessController; import org.opensearch.transport.TransportService; import java.io.BufferedReader; @@ -157,15 +158,15 @@ static Settings getAvailabilityZoneNodeAttributes(Settings settings, String azMe // Same as curl http://169.254.169.254/latest/meta-data/placement/availability-zone/. // TODO: use EC2MetadataUtils::getAvailabilityZone that was added in AWS SDK v2 instead of rolling our own logger.debug("obtaining ec2 [placement/availability-zone] from ec2 meta-data url {}", url); - urlConnection = SocketAccess.doPrivilegedIOException(url::openConnection); + urlConnection = AccessController.doPrivilegedChecked(() -> url.openConnection()); urlConnection.setConnectTimeout(2000); - } catch (final IOException e) { + } catch (final Exception e) { // should not happen, we know the url is not malformed, and openConnection does not actually hit network - throw new UncheckedIOException(e); + throw new UncheckedIOException((IOException) e); } try ( - InputStream in = SocketAccess.doPrivilegedIOException(urlConnection::getInputStream); + InputStream in = AccessController.doPrivilegedChecked(urlConnection::getInputStream); BufferedReader urlReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)) ) { @@ -175,7 +176,10 @@ static Settings getAvailabilityZoneNodeAttributes(Settings settings, String azMe } else { attrs.put(Node.NODE_ATTRIBUTES.getKey() + "aws_availability_zone", metadataResult); } - } catch (final IOException e) { + } catch (final Exception e) { + if (e instanceof IllegalStateException) { + throw (IllegalStateException) e; + } // this is lenient so the plugin does not fail when installed outside of ec2 logger.error("failed to get metadata for [placement/availability-zone]", e); } diff --git a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2NameResolver.java b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2NameResolver.java index 7efaf41bc3133..f93d853bf16b6 100644 --- a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2NameResolver.java +++ b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/Ec2NameResolver.java @@ -39,6 +39,7 @@ import org.opensearch.common.SuppressForbidden; import org.opensearch.common.network.NetworkService.CustomNameResolver; import org.opensearch.common.util.io.IOUtils; +import org.opensearch.secure_sm.AccessController; import java.io.BufferedReader; import java.io.IOException; @@ -111,9 +112,9 @@ public InetAddress[] resolve(Ec2HostnameType type) throws IOException { try { URL url = new URL(metadataUrl); logger.debug("obtaining ec2 hostname from ec2 meta-data url {}", url); - URLConnection urlConnection = SocketAccess.doPrivilegedIOException(url::openConnection); + URLConnection urlConnection = AccessController.doPrivilegedChecked(() -> url.openConnection()); urlConnection.setConnectTimeout(2000); - in = SocketAccess.doPrivilegedIOException(urlConnection::getInputStream); + in = AccessController.doPrivilegedChecked(urlConnection::getInputStream); BufferedReader urlReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); String metadataResult = urlReader.readLine(); @@ -123,7 +124,7 @@ public InetAddress[] resolve(Ec2HostnameType type) throws IOException { logger.debug("obtained ec2 hostname from ec2 meta-data url {}: {}", url, metadataResult); // only one address: because we explicitly ask for only one via the Ec2HostnameType return new InetAddress[] { InetAddress.getByName(metadataResult) }; - } catch (IOException e) { + } catch (Exception e) { throw new IOException("IOException caught when fetching InetAddress from [" + metadataUrl + "]", e); } finally { IOUtils.closeWhileHandlingException(in); diff --git a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/SocketAccess.java b/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/SocketAccess.java deleted file mode 100644 index 0125ae4d19c3e..0000000000000 --- a/plugins/discovery-ec2/src/main/java/org/opensearch/discovery/ec2/SocketAccess.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - */ - -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * Modifications Copyright OpenSearch Contributors. See - * GitHub history for details. - */ - -package org.opensearch.discovery.ec2; - -import org.opensearch.SpecialPermission; - -import java.io.IOException; -import java.net.SocketPermission; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; - -/** - * This plugin uses aws libraries to connect to aws services. For these remote calls the plugin needs - * {@link SocketPermission} 'connect' to establish connections. This class wraps the operations requiring access in - * {@link AccessController#doPrivileged(PrivilegedAction)} blocks. - */ -@SuppressWarnings("removal") -final class SocketAccess { - - private SocketAccess() {} - - public static void doPrivilegedVoid(Runnable action) { - SpecialPermission.check(); - AccessController.doPrivileged((PrivilegedAction) () -> { - action.run(); - return null; - }); - } - - public static T doPrivileged(PrivilegedAction operation) { - SpecialPermission.check(); - return AccessController.doPrivileged(operation); - } - - public static T doPrivilegedIOException(PrivilegedExceptionAction operation) throws IOException { - SpecialPermission.check(); - try { - return AccessController.doPrivileged(operation); - } catch (PrivilegedActionException e) { - throw (IOException) e.getCause(); - } - } - -} diff --git a/plugins/discovery-ec2/src/test/java/org/opensearch/discovery/ec2/AbstractEc2DiscoveryTestCase.java b/plugins/discovery-ec2/src/test/java/org/opensearch/discovery/ec2/AbstractEc2DiscoveryTestCase.java index 5250f8d88855e..10db761a2f628 100644 --- a/plugins/discovery-ec2/src/test/java/org/opensearch/discovery/ec2/AbstractEc2DiscoveryTestCase.java +++ b/plugins/discovery-ec2/src/test/java/org/opensearch/discovery/ec2/AbstractEc2DiscoveryTestCase.java @@ -12,6 +12,7 @@ import org.opensearch.common.SuppressForbidden; import org.opensearch.common.io.PathUtils; +import org.opensearch.secure_sm.AccessController; import org.opensearch.test.OpenSearchTestCase; import java.nio.file.Path; @@ -42,13 +43,15 @@ private Path configPath() { @SuppressForbidden(reason = "set predictable aws defaults") private void setUpAwsProfile() throws Exception { - previousOpenSearchPathConf = SocketAccess.doPrivileged(() -> System.setProperty("opensearch.path.conf", configPath().toString())); - awsRegion = SocketAccess.doPrivileged(() -> System.setProperty("aws.region", "us-west-2")); - awsAccessKeyId = SocketAccess.doPrivileged(() -> System.setProperty("aws.accessKeyId", "aws-access-key-id")); - awsSecretAccessKey = SocketAccess.doPrivileged(() -> System.setProperty("aws.secretAccessKey", "aws-secret-access-key")); + previousOpenSearchPathConf = AccessController.doPrivileged( + () -> System.setProperty("opensearch.path.conf", configPath().toString()) + ); + awsRegion = AccessController.doPrivileged(() -> System.setProperty("aws.region", "us-west-2")); + awsAccessKeyId = AccessController.doPrivileged(() -> System.setProperty("aws.accessKeyId", "aws-access-key-id")); + awsSecretAccessKey = AccessController.doPrivileged(() -> System.setProperty("aws.secretAccessKey", "aws-secret-access-key")); awsSharedCredentialsFile = System.getProperty(ProfileFileSystemSetting.AWS_SHARED_CREDENTIALS_FILE.property()); awsConfigFile = System.getProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property()); - SocketAccess.doPrivilegedVoid(AwsEc2ServiceImpl::setDefaultAwsProfilePath); + AccessController.doPrivileged(AwsEc2ServiceImpl::setDefaultAwsProfilePath); } @SuppressForbidden(reason = "reset aws settings") @@ -64,9 +67,9 @@ private void resetAwsProfile() throws Exception { @SuppressForbidden(reason = "reset aws settings") private void resetPropertyValue(String key, String value) { if (value != null) { - SocketAccess.doPrivileged(() -> System.setProperty(key, value)); + AccessController.doPrivileged(() -> System.setProperty(key, value)); } else { - SocketAccess.doPrivileged(() -> System.clearProperty(key)); + AccessController.doPrivileged(() -> System.clearProperty(key)); } } } diff --git a/plugins/discovery-gce/src/internalClusterTest/java/org/opensearch/discovery/gce/GceDiscoverTests.java b/plugins/discovery-gce/src/internalClusterTest/java/org/opensearch/discovery/gce/GceDiscoverTests.java index e97a4650ca8ae..f62424607a7fe 100644 --- a/plugins/discovery-gce/src/internalClusterTest/java/org/opensearch/discovery/gce/GceDiscoverTests.java +++ b/plugins/discovery-gce/src/internalClusterTest/java/org/opensearch/discovery/gce/GceDiscoverTests.java @@ -36,11 +36,11 @@ import com.google.api.services.compute.model.NetworkInterface; import org.opensearch.action.admin.cluster.state.ClusterStateResponse; import org.opensearch.cloud.gce.GceInstancesService; -import org.opensearch.cloud.gce.util.Access; import org.opensearch.cluster.node.DiscoveryNode; import org.opensearch.common.settings.Settings; import org.opensearch.plugin.discovery.gce.GceDiscoveryPlugin; import org.opensearch.plugins.Plugin; +import org.opensearch.secure_sm.AccessController; import org.opensearch.test.OpenSearchIntegTestCase; import org.opensearch.transport.TransportService; import org.junit.After; @@ -159,7 +159,7 @@ protected GceInstancesService createGceInstancesService() { return new GceInstancesService() { @Override public Collection instances() { - return Access.doPrivileged(() -> { + return AccessController.doPrivileged(() -> { final List instances = new ArrayList<>(); for (DiscoveryNode discoveryNode : nodes.values()) { diff --git a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceInstancesServiceImpl.java b/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceInstancesServiceImpl.java index 46cc1c8eab537..c3eb8a08ef212 100644 --- a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceInstancesServiceImpl.java +++ b/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceInstancesServiceImpl.java @@ -50,12 +50,12 @@ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; -import org.opensearch.cloud.gce.util.Access; import org.opensearch.common.settings.Setting; import org.opensearch.common.settings.Setting.Property; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; import org.opensearch.discovery.gce.RetryHttpInitializerWrapper; +import org.opensearch.secure_sm.AccessController; import java.io.IOException; import java.security.GeneralSecurityException; @@ -92,7 +92,7 @@ public Collection instances() { try { // hack around code messiness in GCE code // TODO: get this fixed - InstanceList instanceList = Access.doPrivilegedIOException(() -> { + InstanceList instanceList = AccessController.doPrivilegedChecked(() -> { Compute.Instances.List list = client().instances().list(project, zoneId); return list.execute(); }); @@ -100,7 +100,7 @@ public Collection instances() { return instanceList.isEmpty() || instanceList.getItems() == null ? Collections.emptyList() : instanceList.getItems(); - } catch (IOException e) { + } catch (Exception e) { logger.warn((Supplier) () -> new ParameterizedMessage("Problem fetching instance list for zone {}", zoneId), e); logger.debug("Full exception:", e); // assist type inference @@ -170,7 +170,7 @@ private List resolveZones() { String getAppEngineValueFromMetadataServer(String serviceURL) throws GeneralSecurityException, IOException { String metadata = GceMetadataService.GCE_HOST.get(settings); - GenericUrl url = Access.doPrivileged(() -> new GenericUrl(metadata + serviceURL)); + GenericUrl url = AccessController.doPrivileged(() -> new GenericUrl(metadata + serviceURL)); HttpTransport httpTransport = getGceHttpTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); @@ -178,7 +178,12 @@ String getAppEngineValueFromMetadataServer(String serviceURL) throws GeneralSecu .setConnectTimeout(500) .setReadTimeout(500) .setHeaders(new HttpHeaders().set("Metadata-Flavor", "Google")); - HttpResponse response = Access.doPrivilegedIOException(() -> request.execute()); + HttpResponse response; + try { + response = AccessController.doPrivilegedChecked(request::execute); + } catch (Exception e) { + throw (IOException) e; + } return headerContainsMetadataFlavor(response) ? response.parseAsString() : null; } @@ -224,7 +229,7 @@ public synchronized Compute client() { // hack around code messiness in GCE code // TODO: get this fixed - Access.doPrivilegedIOException(credential::refreshToken); + AccessController.doPrivilegedChecked(credential::refreshToken); logger.debug("token [{}] will expire in [{}] s", credential.getAccessToken(), credential.getExpiresInSeconds()); if (credential.getExpiresInSeconds() != null) { diff --git a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceMetadataService.java b/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceMetadataService.java index ef73f741ad20c..08c73d8081ba1 100644 --- a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceMetadataService.java +++ b/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/GceMetadataService.java @@ -39,10 +39,10 @@ import com.google.api.client.http.HttpTransport; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.opensearch.cloud.gce.util.Access; import org.opensearch.common.lifecycle.AbstractLifecycleComponent; import org.opensearch.common.settings.Setting; import org.opensearch.common.settings.Settings; +import org.opensearch.secure_sm.AccessController; import java.io.IOException; import java.net.URI; @@ -90,12 +90,12 @@ public String metadata(String metadataPath) throws IOException, URISyntaxExcepti try { // hack around code messiness in GCE code // TODO: get this fixed - headers = Access.doPrivileged(HttpHeaders::new); - GenericUrl genericUrl = Access.doPrivileged(() -> new GenericUrl(urlMetadataNetwork)); + headers = AccessController.doPrivileged(HttpHeaders::new); + GenericUrl genericUrl = AccessController.doPrivileged(() -> new GenericUrl(urlMetadataNetwork)); // This is needed to query meta data: https://cloud.google.com/compute/docs/metadata headers.put("Metadata-Flavor", "Google"); - HttpResponse response = Access.doPrivilegedIOException( + HttpResponse response = AccessController.doPrivilegedChecked( () -> getGceHttpTransport().createRequestFactory().buildGetRequest(genericUrl).setHeaders(headers).execute() ); String metadata = response.parseAsString(); diff --git a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/network/GceNameResolver.java b/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/network/GceNameResolver.java index 28e41963de489..c377b91754c75 100644 --- a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/network/GceNameResolver.java +++ b/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/network/GceNameResolver.java @@ -33,9 +33,9 @@ package org.opensearch.cloud.gce.network; import org.opensearch.cloud.gce.GceMetadataService; -import org.opensearch.cloud.gce.util.Access; import org.opensearch.common.network.NetworkService.CustomNameResolver; import org.opensearch.core.common.Strings; +import org.opensearch.secure_sm.AccessController; import java.io.IOException; import java.net.InetAddress; @@ -120,13 +120,13 @@ private InetAddress[] resolve(String value) throws IOException { } try { - String metadataResult = Access.doPrivilegedIOException(() -> gceMetadataService.metadata(gceMetadataPath)); + String metadataResult = AccessController.doPrivilegedChecked(() -> gceMetadataService.metadata(gceMetadataPath)); if (metadataResult == null || metadataResult.length() == 0) { throw new IOException("no gce metadata returned from [" + gceMetadataPath + "] for [" + value + "]"); } // only one address: because we explicitly ask for only one via the GceHostnameType return new InetAddress[] { InetAddress.getByName(metadataResult) }; - } catch (IOException e) { + } catch (Exception e) { throw new IOException("IOException caught when fetching InetAddress from [" + gceMetadataPath + "]", e); } } diff --git a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/util/Access.java b/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/util/Access.java deleted file mode 100644 index c46bfedbd8507..0000000000000 --- a/plugins/discovery-gce/src/main/java/org/opensearch/cloud/gce/util/Access.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * SPDX-License-Identifier: Apache-2.0 - * - * The OpenSearch Contributors require contributions made to - * this file be licensed under the Apache-2.0 license or a - * compatible open source license. - */ - -/* - * Licensed to Elasticsearch under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* - * Modifications Copyright OpenSearch Contributors. See - * GitHub history for details. - */ - -package org.opensearch.cloud.gce.util; - -import org.opensearch.SpecialPermission; - -import java.io.IOException; -import java.net.SocketPermission; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; - -/** - * GCE's HTTP client changes access levels. Specifically it needs {@link RuntimePermission} {@code - * accessDeclaredMembers} and {@code setFactory}, and {@link java.lang.reflect.ReflectPermission} - * {@code suppressAccessChecks}. For remote calls, the plugin needs {@link SocketPermission} for - * {@code connect}. This class wraps the operations requiring access in - * {@link AccessController#doPrivileged(PrivilegedAction)} blocks. - */ -@SuppressWarnings("removal") -public final class Access { - - private Access() {} - - public static T doPrivileged(final PrivilegedAction operation) { - SpecialPermission.check(); - return AccessController.doPrivileged(operation); - } - - public static void doPrivilegedVoid(final Runnable action) { - SpecialPermission.check(); - AccessController.doPrivileged((PrivilegedAction) () -> { - action.run(); - return null; - }); - } - - public static T doPrivilegedIOException(final PrivilegedExceptionAction operation) throws IOException { - SpecialPermission.check(); - try { - return AccessController.doPrivileged(operation); - } catch (final PrivilegedActionException e) { - throw (IOException) e.getCause(); - } - } - -} diff --git a/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/RetryHttpInitializerWrapper.java b/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/RetryHttpInitializerWrapper.java index 6e5372cad0a4b..084499e998c51 100644 --- a/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/RetryHttpInitializerWrapper.java +++ b/plugins/discovery-gce/src/main/java/org/opensearch/discovery/gce/RetryHttpInitializerWrapper.java @@ -44,8 +44,8 @@ import com.google.api.client.util.Sleeper; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.opensearch.cloud.gce.util.Access; import org.opensearch.common.unit.TimeValue; +import org.opensearch.secure_sm.AccessController; import java.io.IOException; import java.util.Objects; @@ -82,7 +82,7 @@ public RetryHttpInitializerWrapper(Credential wrappedCredential, TimeValue maxWa // Use only for testing static MockGoogleCredential.Builder newMockCredentialBuilder() { // TODO: figure out why GCE is so bad like this - return Access.doPrivileged(MockGoogleCredential.Builder::new); + return AccessController.doPrivileged(MockGoogleCredential.Builder::new); } @Override diff --git a/plugins/discovery-gce/src/main/java/org/opensearch/plugin/discovery/gce/GceDiscoveryPlugin.java b/plugins/discovery-gce/src/main/java/org/opensearch/plugin/discovery/gce/GceDiscoveryPlugin.java index d4df6d94c061b..494cbe9e74854 100644 --- a/plugins/discovery-gce/src/main/java/org/opensearch/plugin/discovery/gce/GceDiscoveryPlugin.java +++ b/plugins/discovery-gce/src/main/java/org/opensearch/plugin/discovery/gce/GceDiscoveryPlugin.java @@ -40,7 +40,6 @@ import org.opensearch.cloud.gce.GceInstancesServiceImpl; import org.opensearch.cloud.gce.GceMetadataService; import org.opensearch.cloud.gce.network.GceNameResolver; -import org.opensearch.cloud.gce.util.Access; import org.opensearch.common.Booleans; import org.opensearch.common.SetOnce; import org.opensearch.common.network.NetworkService; @@ -51,6 +50,7 @@ import org.opensearch.discovery.gce.GceSeedHostsProvider; import org.opensearch.plugins.DiscoveryPlugin; import org.opensearch.plugins.Plugin; +import org.opensearch.secure_sm.AccessController; import org.opensearch.transport.TransportService; import java.io.Closeable; @@ -84,7 +84,7 @@ public class GceDiscoveryPlugin extends Plugin implements DiscoveryPlugin, Close * our plugin permissions don't allow core to "reach through" plugins to * change the permission. Because that'd be silly. */ - Access.doPrivilegedVoid(() -> ClassInfo.of(HttpHeaders.class, true)); + AccessController.doPrivileged(() -> ClassInfo.of(HttpHeaders.class, true)); } public GceDiscoveryPlugin(Settings settings) {