Remove doPrivileged uses from server (#127781)

Now that SecurityManager is no longer used, doPrivileged is no longer
necessary. This commit removes uses of it from core and server
This commit is contained in:
Ryan Ernst 2025-05-07 07:24:53 -07:00 committed by GitHub
parent afbd3319c1
commit 9537388897
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 109 additions and 275 deletions

View file

@ -23,10 +23,8 @@ import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.CodeSigner;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.SecureClassLoader;
import java.util.ArrayList;
import java.util.Collections;
@ -96,8 +94,7 @@ public final class EmbeddedImplClassLoader extends SecureClassLoader {
private final ClassLoader parent;
static EmbeddedImplClassLoader getInstance(ClassLoader parent, String providerName) {
PrivilegedAction<EmbeddedImplClassLoader> pa = () -> new EmbeddedImplClassLoader(parent, getProviderPrefixes(parent, providerName));
return AccessController.doPrivileged(pa);
return new EmbeddedImplClassLoader(parent, getProviderPrefixes(parent, providerName));
}
private EmbeddedImplClassLoader(ClassLoader parent, Map<JarMeta, CodeSource> prefixToCodeBase) {
@ -120,14 +117,12 @@ public final class EmbeddedImplClassLoader extends SecureClassLoader {
record Resource(InputStream inputStream, CodeSource codeSource) {}
/** Searches for the named resource. Iterates over all prefixes. */
private Resource privilegedGetResourceOrNull(JarMeta jarMeta, String pkg, String filepath) {
return AccessController.doPrivileged((PrivilegedAction<Resource>) () -> {
InputStream is = findResourceInLoaderPkgOrNull(jarMeta, pkg, filepath, parent::getResourceAsStream);
if (is != null) {
return new Resource(is, prefixToCodeBase.get(jarMeta.prefix()));
}
return null;
});
private Resource getResourceOrNull(JarMeta jarMeta, String pkg, String filepath) {
InputStream is = findResourceInLoaderPkgOrNull(jarMeta, pkg, filepath, parent::getResourceAsStream);
if (is != null) {
return new Resource(is, prefixToCodeBase.get(jarMeta.prefix()));
}
return null;
}
@Override
@ -148,7 +143,7 @@ public final class EmbeddedImplClassLoader extends SecureClassLoader {
String pkg = toPackageName(filepath);
JarMeta jarMeta = packageToJarMeta.get(pkg);
if (jarMeta != null) {
Resource res = privilegedGetResourceOrNull(jarMeta, pkg, filepath);
Resource res = getResourceOrNull(jarMeta, pkg, filepath);
if (res != null) {
try (InputStream in = res.inputStream()) {
byte[] bytes = in.readAllBytes();

View file

@ -15,9 +15,6 @@ import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.module.Configuration;
import java.lang.module.ModuleFinder;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Locale;
import java.util.Objects;
import java.util.ServiceConfigurationError;
@ -97,10 +94,9 @@ public final class ProviderLocator<T> implements Supplier<T> {
@Override
public T get() {
try {
PrivilegedExceptionAction<T> pa = this::load;
return AccessController.doPrivileged(pa);
} catch (PrivilegedActionException e) {
throw new UncheckedIOException((IOException) e.getCause());
return load();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}

View file

@ -174,7 +174,7 @@ public class EvilLoggerTests extends ESTestCase {
assertLogLine(
deprecationEvents.get(i),
DeprecationLogger.CRITICAL,
"org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0",
"org.elasticsearch.common.logging.DeprecationLogger.logDeprecation",
".*This is a maybe logged deprecation message" + i + ".*"
);
}
@ -207,7 +207,7 @@ public class EvilLoggerTests extends ESTestCase {
assertLogLine(
deprecationEvents.get(0),
DeprecationLogger.CRITICAL,
"org.elasticsearch.common.logging.DeprecationLogger.lambda\\$doPrivilegedLog\\$0",
"org.elasticsearch.common.logging.DeprecationLogger.logDeprecation",
".*\\[deprecated.foo\\] setting was deprecated in Elasticsearch and will be removed in a future release..*"
);
}

View file

@ -14,8 +14,6 @@ import org.apache.logging.log4j.Logger;
import org.elasticsearch.core.SuppressForbidden;
import java.io.IOError;
import java.security.AccessController;
import java.security.PrivilegedAction;
class ElasticsearchUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
private static final Logger logger = LogManager.getLogger(ElasticsearchUncaughtExceptionHandler.class);
@ -53,41 +51,17 @@ class ElasticsearchUncaughtExceptionHandler implements Thread.UncaughtExceptionH
void onFatalUncaught(final String threadName, final Throwable t) {
final String message = "fatal error in thread [" + threadName + "], exiting";
logErrorMessage(t, message);
logger.error(message, t);
}
void onNonFatalUncaught(final String threadName, final Throwable t) {
final String message = "uncaught exception in thread [" + threadName + "]";
logErrorMessage(t, message);
}
private static void logErrorMessage(Throwable t, String message) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
logger.error(message, t);
return null;
});
logger.error(message, t);
}
@SuppressForbidden(reason = "intentionally halting")
void halt(int status) {
AccessController.doPrivileged(new PrivilegedHaltAction(status));
// we halt to prevent shutdown hooks from running
Runtime.getRuntime().halt(status);
}
static class PrivilegedHaltAction implements PrivilegedAction<Void> {
private final int status;
private PrivilegedHaltAction(final int status) {
this.status = status;
}
@SuppressForbidden(reason = "halt")
@Override
public Void run() {
// we halt to prevent shutdown hooks from running
Runtime.getRuntime().halt(status);
return null;
}
}
}

View file

@ -18,8 +18,6 @@ import org.elasticsearch.core.IOUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Iterator;
import java.util.List;
@ -57,14 +55,11 @@ public class FsBlobStore implements BlobStore {
public BlobContainer blobContainer(BlobPath path) {
Path f = buildPath(path);
if (readOnly == false) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
try {
Files.createDirectories(f);
} catch (IOException ex) {
throw new ElasticsearchException("failed to create blob container", ex);
}
return null;
});
try {
Files.createDirectories(f);
} catch (IOException ex) {
throw new ElasticsearchException("failed to create blob container", ex);
}
}
return new FsBlobContainer(this, path, f);
}

View file

@ -15,8 +15,6 @@ import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.regex.Regex;
import org.elasticsearch.common.settings.Settings;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.List;
@ -119,18 +117,11 @@ public class DeprecationLogger {
String opaqueId = HeaderWarning.getXOpaqueId();
String productOrigin = HeaderWarning.getProductOrigin();
ESLogMessage deprecationMessage = DeprecatedMessage.of(category, key, opaqueId, productOrigin, msg, params);
doPrivilegedLog(level, deprecationMessage);
logger.log(level, deprecationMessage);
}
return this;
}
private void doPrivilegedLog(Level level, ESLogMessage deprecationMessage) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
logger.log(level, deprecationMessage);
return null;
});
}
/**
* Used for handling previous version RestApiCompatible logic.
* Logs a message at the {@link DeprecationLogger#CRITICAL} level

View file

@ -17,8 +17,6 @@ import org.elasticsearch.common.unit.Processors;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.node.Node;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.AbstractExecutorService;
@ -393,11 +391,9 @@ public class EsExecutors {
@Override
public Thread newThread(Runnable r) {
return AccessController.doPrivileged((PrivilegedAction<Thread>) () -> {
Thread t = new EsThread(group, r, namePrefix + "[T#" + threadNumber.getAndIncrement() + "]", 0, isSystem);
t.setDaemon(true);
return t;
});
Thread t = new EsThread(group, r, namePrefix + "[T#" + threadNumber.getAndIncrement() + "]", 0, isSystem);
t.setDaemon(true);
return t;
}
}

View file

@ -14,8 +14,6 @@ import org.elasticsearch.core.SuppressForbidden;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
* Reflective access to unwrap non-accessible delegate in AssertingKnnVectorsReader.
@ -52,25 +50,13 @@ public class AssertingKnnVectorsReaderReflect {
if (cls == null) {
return MethodHandles.throwException(KnnVectorsReader.class, AssertionError.class);
}
var lookup = privilegedPrivateLookupIn(cls, MethodHandles.lookup());
var lookup = MethodHandles.privateLookupIn(cls, MethodHandles.lookup());
return lookup.findGetter(cls, "delegate", KnnVectorsReader.class);
} catch (ReflectiveOperationException e) {
throw new AssertionError(e);
}
}
@SuppressWarnings("removal")
static MethodHandles.Lookup privilegedPrivateLookupIn(Class<?> cls, MethodHandles.Lookup lookup) throws IllegalAccessException {
PrivilegedAction<MethodHandles.Lookup> pa = () -> {
try {
return MethodHandles.privateLookupIn(cls, lookup);
} catch (IllegalAccessException e) {
throw new AssertionError("should not happen, check opens", e);
}
};
return AccessController.doPrivileged(pa);
}
static void handleThrowable(Throwable t) {
if (t instanceof Error error) {
throw error;

View file

@ -26,8 +26,6 @@ import org.elasticsearch.index.codec.vectors.es818.DirectIOLucene99FlatVectorsRe
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import static java.lang.invoke.MethodType.methodType;
@ -91,62 +89,62 @@ public class OffHeapReflectionUtils {
try {
// Lucene99ScalarQuantizedVectorsReader
var cls = Class.forName("org.apache.lucene.codecs.lucene99.Lucene99ScalarQuantizedVectorsReader$FieldEntry");
var lookup = privilegedPrivateLookupIn(L99_SQ_VR_CLS, MethodHandles.lookup());
var lookup = MethodHandles.privateLookupIn(L99_SQ_VR_CLS, MethodHandles.lookup());
var mt = methodType(cls, String.class);
GET_FIELD_ENTRY_HNDL_SQ = lookup.findVirtual(L99_SQ_VR_CLS, "getFieldEntry", mt);
GET_VECTOR_DATA_LENGTH_HANDLE_SQ = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class));
RAW_VECTORS_READER_HNDL_SQ = lookup.findVarHandle(L99_SQ_VR_CLS, "rawVectorsReader", FlatVectorsReader.class);
// Lucene99FlatVectorsReader
cls = Class.forName("org.apache.lucene.codecs.lucene99.Lucene99FlatVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(L99_FLT_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L99_FLT_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class, VectorEncoding.class);
GET_FIELD_ENTRY_HANDLE_L99FLT = lookup.findVirtual(L99_FLT_VR_CLS, "getFieldEntry", mt);
VECTOR_DATA_LENGTH_HANDLE_L99FLT = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class));
// DirectIOLucene99FlatVectorsReader
cls = Class.forName("org.elasticsearch.index.codec.vectors.es818.DirectIOLucene99FlatVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(DIOL99_FLT_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(DIOL99_FLT_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class, VectorEncoding.class);
GET_FIELD_ENTRY_HANDLE_DIOL99FLT = lookup.findVirtual(DIOL99_FLT_VR_CLS, "getFieldEntry", mt);
VECTOR_DATA_LENGTH_HANDLE_DIOL99FLT = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class));
// Lucene99HnswVectorsReader
cls = Class.forName("org.apache.lucene.codecs.lucene99.Lucene99HnswVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class, VectorEncoding.class);
GET_FIELD_ENTRY_HANDLE_L99HNSW = lookup.findVirtual(L99_HNSW_VR_CLS, "getFieldEntry", mt);
GET_VECTOR_INDEX_LENGTH_HANDLE_L99HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class));
lookup = privilegedPrivateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L99_HNSW_VR_CLS, MethodHandles.lookup());
FLAT_VECTORS_READER_HNDL_L99HNSW = lookup.findVarHandle(L99_HNSW_VR_CLS, "flatVectorsReader", FlatVectorsReader.class);
// Lucene90HnswVectorsReader
cls = Class.forName("org.apache.lucene.backward_codecs.lucene90.Lucene90HnswVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(L90_HNSW_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L90_HNSW_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class);
GET_FIELD_ENTRY_HANDLE_L90HNSW = lookup.findVirtual(L90_HNSW_VR_CLS, "getFieldEntry", mt);
GET_VECTOR_INDEX_LENGTH_HANDLE_L90HNSW = lookup.findVirtual(cls, "indexDataLength", methodType(long.class));
GET_VECTOR_DATA_LENGTH_HANDLE_L90HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class));
// Lucene91HnswVectorsReader
cls = Class.forName("org.apache.lucene.backward_codecs.lucene91.Lucene91HnswVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(L91_HNSW_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L91_HNSW_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class);
GET_FIELD_ENTRY_HANDLE_L91HNSW = lookup.findVirtual(L91_HNSW_VR_CLS, "getFieldEntry", mt);
GET_VECTOR_INDEX_LENGTH_HANDLE_L91HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class));
GET_VECTOR_DATA_LENGTH_HANDLE_L91HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class));
// Lucene92HnswVectorsReader
cls = Class.forName("org.apache.lucene.backward_codecs.lucene92.Lucene92HnswVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(L92_HNSW_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L92_HNSW_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class);
GET_FIELD_ENTRY_HANDLE_L92HNSW = lookup.findVirtual(L92_HNSW_VR_CLS, "getFieldEntry", mt);
GET_VECTOR_INDEX_LENGTH_HANDLE_L92HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class));
GET_VECTOR_DATA_LENGTH_HANDLE_L92HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class));
// Lucene94HnswVectorsReader
cls = Class.forName("org.apache.lucene.backward_codecs.lucene94.Lucene94HnswVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(L94_HNSW_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L94_HNSW_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class, VectorEncoding.class);
GET_FIELD_ENTRY_HANDLE_L94HNSW = lookup.findVirtual(L94_HNSW_VR_CLS, "getFieldEntry", mt);
GET_VECTOR_INDEX_LENGTH_HANDLE_L94HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class));
GET_VECTOR_DATA_LENGTH_HANDLE_L94HNSW = lookup.findVirtual(cls, "vectorDataLength", methodType(long.class));
// Lucene95HnswVectorsReader
cls = Class.forName("org.apache.lucene.backward_codecs.lucene95.Lucene95HnswVectorsReader$FieldEntry");
lookup = privilegedPrivateLookupIn(L95_HNSW_VR_CLS, MethodHandles.lookup());
lookup = MethodHandles.privateLookupIn(L95_HNSW_VR_CLS, MethodHandles.lookup());
mt = methodType(cls, String.class, VectorEncoding.class);
GET_FIELD_ENTRY_HANDLE_L95HNSW = lookup.findVirtual(L95_HNSW_VR_CLS, "getFieldEntry", mt);
GET_VECTOR_INDEX_LENGTH_HANDLE_L95HNSW = lookup.findVirtual(cls, "vectorIndexLength", methodType(long.class));
@ -278,18 +276,6 @@ public class OffHeapReflectionUtils {
throw new AssertionError("should not reach here");
}
@SuppressWarnings("removal")
private static MethodHandles.Lookup privilegedPrivateLookupIn(Class<?> cls, MethodHandles.Lookup lookup) {
PrivilegedAction<MethodHandles.Lookup> pa = () -> {
try {
return MethodHandles.privateLookupIn(cls, lookup);
} catch (IllegalAccessException e) {
throw new AssertionError("should not happen, check opens", e);
}
};
return AccessController.doPrivileged(pa);
}
private static void handleThrowable(Throwable t) {
if (t instanceof Error error) {
throw error;

View file

@ -9,8 +9,6 @@
package org.elasticsearch.plugins;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.List;
@ -43,8 +41,6 @@ class ExtendedPluginsClassLoader extends ClassLoader {
* Return a new classloader across the parent and extended loaders.
*/
public static ExtendedPluginsClassLoader create(ClassLoader parent, List<ClassLoader> extendedLoaders) {
return AccessController.doPrivileged(
(PrivilegedAction<ExtendedPluginsClassLoader>) () -> new ExtendedPluginsClassLoader(parent, extendedLoaders)
);
return new ExtendedPluginsClassLoader(parent, extendedLoaders);
}
}

View file

@ -27,8 +27,6 @@ import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@ -423,7 +421,7 @@ public class PluginsLoader {
finder,
Set.of(moduleName)
);
var controller = privilegedDefineModulesWithOneLoader(configuration, parentLayersOrBoot(parentLayers), parentLoader);
var controller = ModuleLayer.defineModulesWithOneLoader(configuration, parentLayersOrBoot(parentLayers), parentLoader);
var pluginModule = controller.layer().findModule(moduleName).get();
ensureEntryPointAccessible(controller, pluginModule, className);
// export/open upstream modules to this plugin module
@ -432,7 +430,7 @@ public class PluginsLoader {
addPluginExportsServices(qualifiedExports, controller);
enableNativeAccess(moduleName, modulesWithNativeAccess, controller);
logger.debug(() -> "Loading bundle: created module layer and loader for module " + moduleName);
return new LayerAndLoader(controller.layer(), privilegedFindLoader(controller.layer(), moduleName));
return new LayerAndLoader(controller.layer(), controller.layer().findLoader(moduleName));
}
/** Determines the module name of the SPI module, given its URL. */
@ -490,18 +488,6 @@ public class PluginsLoader {
}
}
@SuppressWarnings("removal")
static Controller privilegedDefineModulesWithOneLoader(Configuration cf, List<ModuleLayer> parentLayers, ClassLoader parentLoader) {
return AccessController.doPrivileged(
(PrivilegedAction<Controller>) () -> ModuleLayer.defineModulesWithOneLoader(cf, parentLayers, parentLoader)
);
}
@SuppressWarnings("removal")
static ClassLoader privilegedFindLoader(ModuleLayer layer, String name) {
return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> layer.findLoader(name));
}
private static List<ModuleLayer> parentLayersOrBoot(List<ModuleLayer> parentLayers) {
if (parentLayers == null || parentLayers.isEmpty()) {
return List.of(ModuleLayer.boot());

View file

@ -32,8 +32,6 @@ import org.elasticsearch.plugins.spi.SPIClassIterator;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@ -395,7 +393,7 @@ public class PluginsService implements ReportingService<PluginsAndModules> {
// Set context class loader to plugin's class loader so that plugins
// that have dependencies with their own SPI endpoints have a chance to load
// and initialize them appropriately.
privilegedSetContextClassLoader(pluginLayer.pluginClassLoader());
Thread.currentThread().setContextClassLoader(pluginLayer.pluginClassLoader());
Plugin plugin;
if (pluginBundle.pluginDescriptor().isStable()) {
@ -428,7 +426,7 @@ public class PluginsService implements ReportingService<PluginsAndModules> {
}
loadedPlugins.put(name, new LoadedPlugin(pluginBundle.plugin, plugin, pluginLayer.pluginClassLoader()));
} finally {
privilegedSetContextClassLoader(cl);
Thread.currentThread().setContextClassLoader(cl);
}
}
@ -537,12 +535,4 @@ public class PluginsService implements ReportingService<PluginsAndModules> {
public final <T> Stream<T> filterPlugins(Class<T> type) {
return plugins().stream().filter(x -> type.isAssignableFrom(x.instance().getClass())).map(p -> ((T) p.instance()));
}
@SuppressWarnings("removal")
private static void privilegedSetContextClassLoader(ClassLoader loader) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
Thread.currentThread().setContextClassLoader(loader);
return null;
});
}
}

View file

@ -23,10 +23,8 @@ import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.CodeSigner;
import java.security.CodeSource;
import java.security.PrivilegedAction;
import java.security.SecureClassLoader;
import java.util.Enumeration;
import java.util.List;
@ -119,7 +117,7 @@ public class UberModuleClassLoader extends SecureClassLoader implements AutoClos
Set<String> packageNames = finder.find(moduleName).map(ModuleReference::descriptor).map(ModuleDescriptor::packages).orElseThrow();
PrivilegedAction<UberModuleClassLoader> pa = () -> new UberModuleClassLoader(
return new UberModuleClassLoader(
parent,
moduleName,
jarUrls.toArray(new URL[0]),
@ -128,7 +126,6 @@ public class UberModuleClassLoader extends SecureClassLoader implements AutoClos
packageNames,
modulesWithNativeAccess
);
return AccessController.doPrivileged(pa);
}
private static boolean isPackageInLayers(String packageName, ModuleLayer moduleLayer) {
@ -312,17 +309,12 @@ public class UberModuleClassLoader extends SecureClassLoader implements AutoClos
}
@Override
@SuppressWarnings("removal")
public void close() throws Exception {
PrivilegedAction<Void> pa = () -> {
try {
internalLoader.close();
} catch (IOException e) {
throw new IllegalStateException("Could not close internal URLClassLoader");
}
return null;
};
AccessController.doPrivileged(pa);
try {
internalLoader.close();
} catch (IOException e) {
throw new IllegalStateException("Could not close internal URLClassLoader");
}
}
// visible for testing

View file

@ -32,8 +32,6 @@ import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
@ -122,25 +120,20 @@ public class ReadinessService extends AbstractLifecycleComponent implements Clus
int portNumber = PORT.get(settings);
assert portNumber >= 0;
var socketAddress = AccessController.doPrivileged((PrivilegedAction<InetSocketAddress>) () -> {
try {
return socketAddress(InetAddress.getByName("0"), portNumber);
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve readiness host address", e);
}
});
InetSocketAddress socketAddress;
try {
socketAddress = socketAddress(InetAddress.getByName("0"), portNumber);
} catch (IOException e) {
throw new IllegalArgumentException("Failed to resolve readiness host address", e);
}
try {
serverChannel = socketChannelFactory.get();
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
try {
serverChannel.bind(socketAddress);
} catch (IOException e) {
throw new BindTransportException("Failed to bind to " + NetworkAddress.format(socketAddress), e);
}
return null;
});
try {
serverChannel.bind(socketAddress);
} catch (IOException e) {
throw new BindTransportException("Failed to bind to " + NetworkAddress.format(socketAddress), e);
}
// First time bounding the socket, we notify any listeners
if (boundSocket.get() == null) {
@ -180,14 +173,11 @@ public class ReadinessService extends AbstractLifecycleComponent implements Clus
assert serverChannel != null;
try {
while (serverChannel.isOpen()) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
try (SocketChannel channel = serverChannel.accept()) {} catch (IOException e) {
logger.debug("encountered exception while responding to readiness check request", e);
} catch (Exception other) {
logger.warn("encountered unknown exception while responding to readiness check request", other);
}
return null;
});
try (SocketChannel channel = serverChannel.accept()) {} catch (IOException e) {
logger.debug("encountered exception while responding to readiness check request", e);
} catch (Exception other) {
logger.warn("encountered unknown exception while responding to readiness check request", other);
}
}
} finally {
listenerThreadLatch.countDown();

View file

@ -19,8 +19,6 @@ import org.elasticsearch.script.field.DocValuesScriptFieldFactory;
import org.elasticsearch.script.field.Field;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
@ -42,23 +40,18 @@ public class LeafDocLookup implements Map<String, ScriptDocValues<?>> {
*/
class FieldFactoryWrapper {
final DocValuesScriptFieldFactory factory;
private final PrivilegedAction<Void> advancer;
FieldFactoryWrapper(DocValuesScriptFieldFactory factory) {
this.factory = factory;
this.advancer = () -> {
try {
factory.setNextDocId(docId);
} catch (IOException ioe) {
throw ExceptionsHelper.convertToElastic(ioe);
}
return null;
};
}
// advances the factory to the current docid for the enclosing LeafDocLookup
void advanceToDoc() {
AccessController.doPrivileged(this.advancer);
try {
factory.setNextDocId(docId);
} catch (IOException ioe) {
throw ExceptionsHelper.convertToElastic(ioe);
}
}
}
@ -101,30 +94,26 @@ public class LeafDocLookup implements Map<String, ScriptDocValues<?>> {
throw new IllegalArgumentException("No field found for [" + fieldName + "] in mapping");
}
// Load the field data on behalf of the script. Otherwise, it would require
// additional permissions to deal with pagedbytes/ramusagestimator/etc.
return AccessController.doPrivileged((PrivilegedAction<FieldFactoryWrapper>) () -> {
IndexFieldData<?> indexFieldData = fieldDataLookup.apply(fieldType, SCRIPT);
IndexFieldData<?> indexFieldData = fieldDataLookup.apply(fieldType, SCRIPT);
FieldFactoryWrapper docFactory = null;
FieldFactoryWrapper docFactory = null;
if (docFactoryCache.isEmpty() == false) {
docFactory = docFactoryCache.get(fieldName);
}
if (docFactoryCache.isEmpty() == false) {
docFactory = docFactoryCache.get(fieldName);
}
// if this field has already been accessed via the doc-access API and the field-access API
// uses doc values then we share to avoid double-loading
FieldFactoryWrapper fieldFactory;
if (docFactory != null && indexFieldData instanceof SourceValueFetcherIndexFieldData == false) {
fieldFactory = docFactory;
} else {
fieldFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName));
}
// if this field has already been accessed via the doc-access API and the field-access API
// uses doc values then we share to avoid double-loading
FieldFactoryWrapper fieldFactory;
if (docFactory != null && indexFieldData instanceof SourceValueFetcherIndexFieldData == false) {
fieldFactory = docFactory;
} else {
fieldFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName));
}
fieldFactoryCache.put(fieldName, fieldFactory);
fieldFactoryCache.put(fieldName, fieldFactory);
return fieldFactory;
});
return fieldFactory;
}
public Field<?> getScriptField(String fieldName) {
@ -146,35 +135,31 @@ public class LeafDocLookup implements Map<String, ScriptDocValues<?>> {
throw new IllegalArgumentException("No field found for [" + fieldName + "] in mapping");
}
// Load the field data on behalf of the script. Otherwise, it would require
// additional permissions to deal with pagedbytes/ramusagestimator/etc.
return AccessController.doPrivileged((PrivilegedAction<FieldFactoryWrapper>) () -> {
FieldFactoryWrapper docFactory = null;
FieldFactoryWrapper fieldFactory = null;
FieldFactoryWrapper docFactory = null;
FieldFactoryWrapper fieldFactory = null;
if (fieldFactoryCache.isEmpty() == false) {
fieldFactory = fieldFactoryCache.get(fieldName);
if (fieldFactoryCache.isEmpty() == false) {
fieldFactory = fieldFactoryCache.get(fieldName);
}
if (fieldFactory != null) {
IndexFieldData<?> fieldIndexFieldData = fieldDataLookup.apply(fieldType, SCRIPT);
// if this field has already been accessed via the field-access API and the field-access API
// uses doc values then we share to avoid double-loading
if (fieldIndexFieldData instanceof SourceValueFetcherIndexFieldData == false) {
docFactory = fieldFactory;
}
}
if (fieldFactory != null) {
IndexFieldData<?> fieldIndexFieldData = fieldDataLookup.apply(fieldType, SCRIPT);
if (docFactory == null) {
IndexFieldData<?> indexFieldData = fieldDataLookup.apply(fieldType, SEARCH);
docFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName));
}
// if this field has already been accessed via the field-access API and the field-access API
// uses doc values then we share to avoid double-loading
if (fieldIndexFieldData instanceof SourceValueFetcherIndexFieldData == false) {
docFactory = fieldFactory;
}
}
docFactoryCache.put(fieldName, docFactory);
if (docFactory == null) {
IndexFieldData<?> indexFieldData = fieldDataLookup.apply(fieldType, SEARCH);
docFactory = new FieldFactoryWrapper(indexFieldData.load(reader).getScriptFieldFactory(fieldName));
}
docFactoryCache.put(fieldName, docFactory);
return docFactory;
});
return docFactory;
}
@Override

View file

@ -17,11 +17,6 @@ import org.apache.logging.log4j.spi.LoggerContextFactory;
import org.elasticsearch.test.ESTestCase;
import org.mockito.Mockito;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.hamcrest.Matchers.equalTo;
@ -75,13 +70,7 @@ public class DeprecationLoggerTests extends ESTestCase {
DeprecationLogger deprecationLogger = DeprecationLogger.getLogger("name");
AccessControlContext noPermissionsAcc = new AccessControlContext(
new ProtectionDomain[] { new ProtectionDomain(null, new Permissions()) }
);
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
deprecationLogger.warn(DeprecationCategory.API, "key", "foo", "bar");
return null;
}, noPermissionsAcc);
deprecationLogger.warn(DeprecationCategory.API, "key", "foo", "bar");
assertThat("supplier called", supplierCalled.get(), is(true));
} finally {
LogManager.setFactory(originalFactory);

View file

@ -24,10 +24,6 @@ import org.elasticsearch.test.ESTestCase;
import org.junit.Before;
import java.io.IOException;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Consumer;
@ -427,12 +423,7 @@ public class LeafDocLookupTests extends ESTestCase {
public void testLookupPrivilegesAdvanceDoc() {
nextDocCallback = i -> SpecialPermission.check();
// mimic the untrusted codebase, which gets no permissions
var restrictedContext = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, null) });
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
ScriptDocValues<?> fetchedDocValues = docLookup.get("field");
assertEquals(docValues, fetchedDocValues);
return null;
}, restrictedContext);
ScriptDocValues<?> fetchedDocValues = docLookup.get("field");
assertEquals(docValues, fetchedDocValues);
}
}

View file

@ -27,8 +27,6 @@ import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThan;
@ -193,8 +191,6 @@ public class TransportHandshakerRawMessageTests extends ESSingleNodeTestCase {
private Socket openTransportConnection() throws Exception {
final var transportAddress = randomFrom(getInstanceFromNode(TransportService.class).boundAddress().boundAddresses()).address();
return AccessController.doPrivileged(
(PrivilegedExceptionAction<Socket>) (() -> new Socket(transportAddress.getAddress(), transportAddress.getPort()))
);
return new Socket(transportAddress.getAddress(), transportAddress.getPort());
}
}