Skip to content

Remove all security manager and java security references #14801

New issue

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

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

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import com.diffplug.gradle.spotless.SpotlessApply

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
Expand Down Expand Up @@ -74,6 +76,8 @@ def lintTasks = sourceSets.collect { SourceSet sourceSet ->
dependsOn sourceSet.compileClasspath
dependsOn ecjConfiguration

mustRunAfter tasks.withType(SpotlessApply)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

piggybacking this so that 'gradlew tidy check' works properly...


// The inputs are all source files from the sourceSet.
inputs.files sourceSet.allSource.asFileTree

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ configure(allprojects) { prj ->
lineEndings = LineEnding.UNIX
endWithNewline()
googleJavaFormat(deps.versions.googleJavaFormat.get())
removeUnusedImports()

// Apply to all Java sources
target("src/**/*.java")
Expand Down
2 changes: 1 addition & 1 deletion dev-tools/scripts/addBackcompatIndexes.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def create_and_add_index(source: str, indextype: str, index_version: scriptutil.
"dvupdates": "testCreateIndexWithDocValuesUpdates",
"emptyIndex": "testCreateEmptyIndex",
}[indextype]
gradle_args = " ".join(["-Ptests.useSecurityManager=false", "-p lucene/%s" % module, "test", "--tests TestGenerateBwcIndices.%s" % test, "-Dtests.bwcdir=%s" % temp_dir, "-Dtests.codec=default"])
gradle_args = " ".join(["-p lucene/%s" % module, "test", "--tests TestGenerateBwcIndices.%s" % test, "-Dtests.bwcdir=%s" % temp_dir, "-Dtests.codec=default"])
base_dir = os.getcwd()
bc_index_file = os.path.join(temp_dir, filename)

Expand Down
3 changes: 3 additions & 0 deletions lucene/CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ Changes in Runtime Behavior
Other
---------------------

* GITHUB#14801: Removed all security manager and java.security-related code, which is effectively dead
in Java 24+. (Dawid Weiss)

* GITHUB#14229: Bump minimum required Java version to 25

* GITHUB#14564: Remove abstractions from MMapDirectory as we need no MR-JAR anymore. (Uwe Schindler)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public class TestGenerateBwcIndices extends LuceneTestCase {
// To generate backcompat indexes with the current default codec, run the following gradle
// command:
// gradlew test -Ptests.bwcdir=/path/to/store/indexes -Ptests.codec=default
// -Ptests.useSecurityManager=false --tests TestGenerateBwcIndices --max-workers=1
// --tests TestGenerateBwcIndices --max-workers=1
//
// Also add testmethod with one of the index creation methods below, for example:
// -Ptestmethod=testCreateCFS
Expand Down
33 changes: 2 additions & 31 deletions lucene/core/src/java/org/apache/lucene/util/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,8 @@
*/
package org.apache.lucene.util;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Locale;
import java.util.Optional;
import java.util.logging.Logger;
import org.apache.lucene.store.ReadAdvice;

/** Some useful constants. */
Expand Down Expand Up @@ -166,36 +163,10 @@ private static boolean hasFastScalarFMA() {
.orElse(ReadAdvice.RANDOM);

private static String getSysProp(String property) {
try {
return doPrivileged(() -> System.getProperty(property));
} catch (
@SuppressWarnings("unused")
SecurityException se) {
logSecurityWarning(property);
return null;
}
return System.getProperty(property);
}

private static String getSysProp(String property, String def) {
try {
return doPrivileged(() -> System.getProperty(property, def));
} catch (
@SuppressWarnings("unused")
SecurityException se) {
logSecurityWarning(property);
return def;
}
}

private static void logSecurityWarning(String property) {
var log = Logger.getLogger(Constants.class.getName());
log.warning("SecurityManager prevented access to system property: " + property);
}

// Extracted to a method to be able to apply the SuppressForbidden annotation
@SuppressWarnings("removal")
@SuppressForbidden(reason = "security manager")
private static <T> T doPrivileged(PrivilegedAction<T> action) {
return AccessController.doPrivileged(action);
return System.getProperty(property, def);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,8 @@ public NamedThreadFactory(String threadNamePrefix) {
threadPoolNumber.getAndIncrement());
}

@SuppressWarnings("removal")
@SuppressForbidden(reason = "security manager")
private static ThreadGroup getThreadGroup() {
final SecurityManager s = System.getSecurityManager();
if (s != null) {
return s.getThreadGroup();
} else {
return Thread.currentThread().getThreadGroup();
}
return Thread.currentThread().getThreadGroup();
}

private static String checkPrefix(String prefix) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.AccessControlException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Collection;
Expand Down Expand Up @@ -541,15 +538,7 @@ public static long shallowSizeOfInstance(Class<?> clazz) {

// Walk type hierarchy
for (; clazz != null; clazz = clazz.getSuperclass()) {
final Class<?> target = clazz;
final Field[] fields;
try {
fields = doPrivileged((PrivilegedAction<Field[]>) target::getDeclaredFields);
} catch (
@SuppressWarnings("removal")
AccessControlException e) {
throw new RuntimeException("Can't access fields of class: " + target, e);
}
final Field[] fields = clazz.getDeclaredFields();

for (Field f : fields) {
if (!Modifier.isStatic(f.getModifiers())) {
Expand All @@ -560,13 +549,6 @@ public static long shallowSizeOfInstance(Class<?> clazz) {
return alignObjectSize(size);
}

// Extracted to a method to give the SuppressForbidden annotation the smallest possible scope
@SuppressWarnings("removal")
@SuppressForbidden(reason = "security manager")
private static <T> T doPrivileged(PrivilegedAction<T> action) {
return AccessController.doPrivileged(action);
}

/** Return shallow size of any <code>array</code>. */
private static long shallowSizeOfArray(Object array) {
long size = NUM_BYTES_ARRAY_HEADER;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
package org.apache.lucene.util;

import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
Expand Down Expand Up @@ -60,11 +58,6 @@
* VirtualMethod.compareImplementationDistance(this.getClass(), oldMethod, newMethod) &gt; 0);
* </pre>
*
* <p>It is important to use {@link AccessController#doPrivileged(PrivilegedAction)} for the actual
* call to get the implementation distance because the subclass may be in a different package. The
* static constructors do not need to use {@code AccessController} because it just initializes our
* own method reference. The caller should have access to all declared members in its own class.
*
* <p>{@link #getImplementationDistance} returns the distance of the subclass that overrides this
* method. The one with the larger distance should be used preferable. This way also more
* complicated method rename scenarios can be handled (think of 2.9 {@code TokenStream}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,13 @@

import java.io.IOException;
import java.lang.foreign.MemorySegment;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Locale;
import java.util.logging.Logger;
import jdk.incubator.vector.FloatVector;
import org.apache.lucene.codecs.hnsw.FlatVectorsScorer;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.MemorySegmentAccessInput;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.SuppressForbidden;

/** A vectorization provider that leverages the Panama Vector API. */
final class PanamaVectorizationProvider extends VectorizationProvider {
Expand All @@ -36,28 +33,12 @@ final class PanamaVectorizationProvider extends VectorizationProvider {
// would get called before we have a chance to perform sanity checks around the vector API in the
// constructor of this class. Put them in PanamaVectorConstants instead.

// Extracted to a method to be able to apply the SuppressForbidden annotation
@SuppressWarnings("removal")
@SuppressForbidden(reason = "security manager")
private static <T> T doPrivileged(PrivilegedAction<T> action) {
return AccessController.doPrivileged(action);
}

private final VectorUtilSupport vectorUtilSupport;

PanamaVectorizationProvider() {
// hack to work around for JDK-8309727:
try {
doPrivileged(
() ->
FloatVector.fromArray(
FloatVector.SPECIES_PREFERRED,
new float[FloatVector.SPECIES_PREFERRED.length()],
0));
} catch (SecurityException se) {
throw new UnsupportedOperationException(
"We hit initialization failure described in JDK-8309727: " + se);
}
FloatVector.fromArray(
FloatVector.SPECIES_PREFERRED, new float[FloatVector.SPECIES_PREFERRED.length()], 0);

if (PanamaVectorConstants.PREFERRED_VECTOR_BITSIZE < 128) {
throw new UnsupportedOperationException(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@
*/
package org.apache.lucene.index;

import java.io.FilePermission;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.PropertyPermission;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
Expand Down Expand Up @@ -66,18 +64,6 @@ public static void afterClass() throws Exception {
}

public void testReadOnlyIndex() throws Exception {
runWithRestrictedPermissions(
this::doTestReadOnlyIndex,
// add some basic permissions (because we are limited already - so we grant all important
// ones):
new RuntimePermission("*"),
new PropertyPermission("*", "read"),
// only allow read to the given index dir, nothing else:
new FilePermission(indexPath.toString(), "read"),
new FilePermission(indexPath.resolve("-").toString(), "read"));
}

private Void doTestReadOnlyIndex() throws Exception {
Directory dir = FSDirectory.open(indexPath);
IndexReader ireader = DirectoryReader.open(dir);
IndexSearcher isearcher = newSearcher(ireader);
Expand All @@ -100,6 +86,5 @@ private Void doTestReadOnlyIndex() throws Exception {
assertEquals(1, isearcher.count(phraseQuery));

ireader.close();
return null; // void
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

public class TestClassLoaderUtils extends LuceneTestCase {

public void testParentChild() throws Exception {
public void testParentChild() {
final ClassLoader parent = getClass().getClassLoader();
final ClassLoader child = URLClassLoader.newInstance(new URL[0], parent);
assertTrue(checkNoPerms(parent, parent));
Expand All @@ -31,7 +31,7 @@ public void testParentChild() throws Exception {
assertFalse(checkNoPerms(child, parent));
}

private boolean checkNoPerms(ClassLoader parent, ClassLoader child) throws Exception {
return runWithRestrictedPermissions(() -> ClassLoaderUtils.isParentClassLoader(parent, child));
private boolean checkNoPerms(ClassLoader parent, ClassLoader child) {
return ClassLoaderUtils.isParentClassLoader(parent, child);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,10 @@
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.FilterDirectory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.util.SuppressForbidden;

/**
* This directory wrapper overrides {@link Directory#copyFrom(Directory, String, String, IOContext)}
Expand Down Expand Up @@ -66,27 +63,22 @@ public void copyFrom(Directory from, String srcFile, String destFile, IOContext
if (Files.isReadable(fromPath.resolve(srcFile)) && Files.isWritable(toPath)) {
// only try hardlinks if we have permission to access the files
// if not super.copyFrom() will give us the right exceptions
suppressedException =
doPrivileged(
() -> {
try {
Files.createLink(toPath.resolve(destFile), fromPath.resolve(srcFile));
} catch (FileNotFoundException
| NoSuchFileException
| FileAlreadyExistsException ex) {
return ex; // in these cases we bubble up since it's a true error condition.
} catch (IOException
// if the FS doesn't support hard-links
| UnsupportedOperationException
// we don't have permission to use hard-links just fall back to byte copy
| SecurityException ex) {
// hard-links are not supported or the files are on different filesystems
// we could go deeper and check if their filesstores are the same and opt
// out earlier but for now we just fall back to normal file-copy
return ex;
}
return null;
});
try {
Files.createLink(toPath.resolve(destFile), fromPath.resolve(srcFile));
} catch (FileNotFoundException | NoSuchFileException | FileAlreadyExistsException ex) {
suppressedException =
ex; // in these cases we bubble up since it's a true error condition.
} catch (IOException
// if the FS doesn't support hard-links
| UnsupportedOperationException
// we don't have permission to use hard-links just fall back to byte copy
| SecurityException ex) {
// hard-links are not supported or the files are on different filesystems
// we could go deeper and check if their filesstores are the same and opt
// out earlier but for now we just fall back to normal file-copy
suppressedException = ex;
}

tryCopy = suppressedException != null;
}
}
Expand All @@ -101,11 +93,4 @@ public void copyFrom(Directory from, String srcFile, String destFile, IOContext
}
}
}

// Extracted to a method to give the SuppressForbidden annotation the smallest possible scope
@SuppressWarnings("removal")
@SuppressForbidden(reason = "security manager")
private static <T> T doPrivileged(PrivilegedAction<T> action) {
return AccessController.doPrivileged(action);
}
}
Loading