Skip to content

Support entitlements in internal cluster tests #130710

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

Merged
merged 24 commits into from
Jul 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9597586
Support entitlements in internal cluster tests
mosche Jul 7, 2025
ac4503a
[CI] Auto commit changes from spotless
elasticsearchmachine Jul 7, 2025
4c7f662
fix
mosche Jul 7, 2025
305c576
revert to previous approach enabling entitlements for tests
mosche Jul 8, 2025
45ea516
Merge branch 'main' into entitlements/integtestSupport
mosche Jul 14, 2025
debfcd9
Use separate temp folder for nodes to properly enforce file entitlements
mosche Jul 14, 2025
9258e17
Merge branch 'main' into entitlements/integtestSupport
mosche Jul 14, 2025
9575646
Merge branch 'main' into entitlements/integtestSupport
mosche Jul 14, 2025
8989582
skip configuring node dirs if no policyManager
mosche Jul 14, 2025
3a086de
Trivially allow test utility classes if annotated with @WithoutEntitl…
mosche Jul 15, 2025
12aab4e
Move ReloadingDatabasesWhilePerformingGeoLookupsIT from internalClust…
mosche Jul 15, 2025
ea9650a
@WithoutEntitlements // CLI tools don't run with entitlements enforced
mosche Jul 15, 2025
ce4d075
Merge branch 'main' into entitlements/integtestSupport
mosche Jul 15, 2025
d301ede
[CI] Auto commit changes from spotless
elasticsearchmachine Jul 15, 2025
e8be979
fix forbidden
mosche Jul 15, 2025
4b919cf
Merge branch 'main' into entitlements/integtestSupport
mosche Jul 15, 2025
bbfb065
move notEntitled into policManager to possibly ignore in tests
mosche Jul 15, 2025
affbb7f
fix compile
mosche Jul 15, 2025
c94bf75
Revert "fix compile"
mosche Jul 16, 2025
fcd1dd0
Revert "move notEntitled into policManager to possibly ignore in tests"
mosche Jul 16, 2025
c400748
Revert "[CI] Auto commit changes from spotless"
mosche Jul 16, 2025
998c62c
Revert "Trivially allow test utility classes if annotated with @Witho…
mosche Jul 16, 2025
c9608ef
disable entitlement checks for SecuritySingleNodeTestCase and Securit…
mosche Jul 16, 2025
f18747a
Merge branch 'main' into entitlements/integtestSupport
mosche Jul 16, 2025
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
Expand Up @@ -34,6 +34,7 @@
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

import javax.inject.Inject;
Expand All @@ -50,6 +51,8 @@ public abstract class ElasticsearchTestBasePlugin implements Plugin<Project> {

public static final String DUMP_OUTPUT_ON_FAILURE_PROP_NAME = "dumpOutputOnFailure";

public static final Set<String> TEST_TASKS_WITH_ENTITLEMENTS = Set.of("test", "internalClusterTest");

@Inject
protected abstract ProviderFactory getProviderFactory();

Expand Down Expand Up @@ -174,14 +177,23 @@ public void execute(Task t) {
nonInputProperties.systemProperty("workspace.dir", Util.locateElasticsearchWorkspace(project.getGradle()));
// we use 'temp' relative to CWD since this is per JVM and tests are forbidden from writing to CWD
nonInputProperties.systemProperty("java.io.tmpdir", test.getWorkingDir().toPath().resolve("temp"));
if (test.getName().equals("internalClusterTest")) {
// configure a node home directory independent of the Java temp dir so that entitlements can be properly enforced
nonInputProperties.systemProperty("tempDir", test.getWorkingDir().toPath().resolve("nodesTemp"));
}

SourceSetContainer sourceSets = project.getExtensions().getByType(SourceSetContainer.class);
SourceSet mainSourceSet = sourceSets.findByName(SourceSet.MAIN_SOURCE_SET_NAME);
SourceSet testSourceSet = sourceSets.findByName(SourceSet.TEST_SOURCE_SET_NAME);
if ("test".equals(test.getName()) && mainSourceSet != null && testSourceSet != null) {
SourceSet internalClusterTestSourceSet = sourceSets.findByName("internalClusterTest");

if (TEST_TASKS_WITH_ENTITLEMENTS.contains(test.getName()) && mainSourceSet != null && testSourceSet != null) {
FileCollection mainRuntime = mainSourceSet.getRuntimeClasspath();
FileCollection testRuntime = testSourceSet.getRuntimeClasspath();
FileCollection testOnlyFiles = testRuntime.minus(mainRuntime);
FileCollection internalClusterTestRuntime = ("internalClusterTest".equals(test.getName())
&& internalClusterTestSourceSet != null) ? internalClusterTestSourceSet.getRuntimeClasspath() : project.files();
FileCollection testOnlyFiles = testRuntime.plus(internalClusterTestRuntime).minus(mainRuntime);

test.doFirst(task -> test.environment("es.entitlement.testOnlyPath", testOnlyFiles.getAsPath()));
}

Expand Down Expand Up @@ -241,14 +253,15 @@ public void execute(Task t) {
* Computes and sets the {@code --patch-module=java.base} and {@code --add-opens=java.base} JVM command line options.
*/
private void configureJavaBaseModuleOptions(Project project) {
project.getTasks().withType(Test.class).matching(task -> task.getName().equals("test")).configureEach(test -> {
FileCollection patchedImmutableCollections = patchedImmutableCollections(project);
project.getTasks().withType(Test.class).configureEach(test -> {
// patch immutable collections only for "test" task
FileCollection patchedImmutableCollections = test.getName().equals("test") ? patchedImmutableCollections(project) : null;
if (patchedImmutableCollections != null) {
test.getInputs().files(patchedImmutableCollections);
test.systemProperty("tests.hackImmutableCollections", "true");
}

FileCollection entitlementBridge = entitlementBridge(project);
FileCollection entitlementBridge = TEST_TASKS_WITH_ENTITLEMENTS.contains(test.getName()) ? entitlementBridge(project) : null;
if (entitlementBridge != null) {
test.getInputs().files(entitlementBridge);
}
Expand Down Expand Up @@ -312,27 +325,30 @@ private static void configureEntitlements(Project project) {
}
FileCollection bridgeFiles = bridgeConfig;

project.getTasks().withType(Test.class).configureEach(test -> {
// See also SystemJvmOptions.maybeAttachEntitlementAgent.

// Agent
if (agentFiles.isEmpty() == false) {
test.getInputs().files(agentFiles);
test.systemProperty("es.entitlement.agentJar", agentFiles.getAsPath());
test.systemProperty("jdk.attach.allowAttachSelf", true);
}
project.getTasks()
.withType(Test.class)
.matching(test -> TEST_TASKS_WITH_ENTITLEMENTS.contains(test.getName()))
.configureEach(test -> {
// See also SystemJvmOptions.maybeAttachEntitlementAgent.

// Agent
if (agentFiles.isEmpty() == false) {
test.getInputs().files(agentFiles);
test.systemProperty("es.entitlement.agentJar", agentFiles.getAsPath());
test.systemProperty("jdk.attach.allowAttachSelf", true);
}

// Bridge
if (bridgeFiles.isEmpty() == false) {
String modulesContainingEntitlementInstrumentation = "java.logging,java.net.http,java.naming,jdk.net";
test.getInputs().files(bridgeFiles);
// Tests may not be modular, but the JDK still is
test.jvmArgs(
"--add-exports=java.base/org.elasticsearch.entitlement.bridge=ALL-UNNAMED,"
+ modulesContainingEntitlementInstrumentation
);
}
});
// Bridge
if (bridgeFiles.isEmpty() == false) {
String modulesContainingEntitlementInstrumentation = "java.logging,java.net.http,java.naming,jdk.net";
test.getInputs().files(bridgeFiles);
// Tests may not be modular, but the JDK still is
test.jvmArgs(
"--add-exports=java.base/org.elasticsearch.entitlement.bridge=ALL-UNNAMED,"
+ modulesContainingEntitlementInstrumentation
);
}
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,12 @@ public void apply(Project project) {
});

if (project.getRootProject().getName().equals("elasticsearch")) {
project.getTasks().withType(Test.class).matching(test -> List.of("test").contains(test.getName())).configureEach(test -> {
test.systemProperty("es.entitlement.enableForTests", "true");
});
project.getTasks()
.withType(Test.class)
.matching(test -> List.of("test", "internalClusterTest").contains(test.getName()))
.configureEach(test -> {
test.systemProperty("es.entitlement.enableForTests", "true");
});
}
}
}
2 changes: 1 addition & 1 deletion libs/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ configure(childProjects.values()) {
// Omit oddball libraries that aren't in server.
def nonServerLibs = ['plugin-scanner']
if (false == nonServerLibs.contains(project.name)) {
project.getTasks().withType(Test.class).matching(test -> ['test'].contains(test.name)).configureEach(test -> {
project.getTasks().withType(Test.class).matching(test -> ['test', 'internalClusterTest'].contains(test.name)).configureEach(test -> {
Copy link
Contributor

Choose a reason for hiding this comment

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

🎉

test.systemProperty('es.entitlement.enableForTests', 'true')
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
// 'WindowsFS.checkDeleteAccess(...)').
}
)
public class ReloadingDatabasesWhilePerformingGeoLookupsIT extends ESTestCase {
public class ReloadingDatabasesWhilePerformingGeoLookupsTests extends ESTestCase {

/**
* This tests essentially verifies that a Maxmind database reader doesn't fail with:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.elasticsearch.gateway.PersistedClusterStateService;
import org.elasticsearch.node.Node;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.InternalTestCluster;

import java.io.IOException;
Expand All @@ -39,6 +40,7 @@
import static org.hamcrest.Matchers.notNullValue;

@ESIntegTestCase.ClusterScope(scope = ESIntegTestCase.Scope.TEST, numDataNodes = 0, autoManageMasterNodes = false)
@ESTestCase.WithoutEntitlements // CLI tools don't run with entitlements enforced
public class UnsafeBootstrapAndDetachCommandIT extends ESIntegTestCase {

private MockTerminal executeCommand(ElasticsearchNodeCommand command, Environment environment, boolean abort) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
import org.elasticsearch.common.network.IfConfig;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.PathUtils;
import org.elasticsearch.entitlement.bootstrap.TestEntitlementBootstrap;
import org.elasticsearch.jdk.JarHell;
Expand Down Expand Up @@ -76,20 +75,12 @@ public class BootstrapForTesting {

// Fire up entitlements
try {
TestEntitlementBootstrap.bootstrap(javaTmpDir, maybePath(System.getProperty("tests.config")));
TestEntitlementBootstrap.bootstrap(javaTmpDir);
} catch (IOException e) {
throw new IllegalStateException(e.getClass().getSimpleName() + " while initializing entitlements for tests", e);
}
}

private static @Nullable Path maybePath(String str) {
if (str == null) {
return null;
} else {
return PathUtils.get(str);
}
}

// does nothing, just easy way to make sure the class is loaded.
public static void ensureInitialized() {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,15 @@
import org.elasticsearch.bootstrap.TestBuildInfo;
import org.elasticsearch.bootstrap.TestBuildInfoParser;
import org.elasticsearch.bootstrap.TestScopeResolver;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.core.PathUtils;
import org.elasticsearch.core.Strings;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.entitlement.initialization.EntitlementInitialization;
import org.elasticsearch.entitlement.runtime.policy.PathLookup;
import org.elasticsearch.entitlement.runtime.policy.PathLookup.BaseDir;
import org.elasticsearch.entitlement.runtime.policy.Policy;
import org.elasticsearch.entitlement.runtime.policy.PolicyParser;
import org.elasticsearch.entitlement.runtime.policy.TestPathLookup;
Expand All @@ -32,39 +34,106 @@
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Consumer;

import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toSet;
import static org.elasticsearch.entitlement.runtime.policy.PathLookup.BaseDir.CONFIG;
import static org.elasticsearch.entitlement.runtime.policy.PathLookup.BaseDir.TEMP;
import static org.elasticsearch.env.Environment.PATH_DATA_SETTING;
import static org.elasticsearch.env.Environment.PATH_HOME_SETTING;
import static org.elasticsearch.env.Environment.PATH_REPO_SETTING;

public class TestEntitlementBootstrap {

private static final Logger logger = LogManager.getLogger(TestEntitlementBootstrap.class);

private static Map<BaseDir, Collection<Path>> baseDirPaths = new ConcurrentHashMap<>();
private static TestPolicyManager policyManager;

/**
* Activates entitlement checking in tests.
*/
public static void bootstrap(@Nullable Path tempDir, @Nullable Path configDir) throws IOException {
public static void bootstrap(@Nullable Path tempDir) throws IOException {
if (isEnabledForTest() == false) {
return;
}
TestPathLookup pathLookup = new TestPathLookup(Map.of(TEMP, zeroOrOne(tempDir), CONFIG, zeroOrOne(configDir)));
var previousTempDir = baseDirPaths.put(TEMP, zeroOrOne(tempDir));
assert previousTempDir == null : "Test entitlement bootstrap called multiple times";
TestPathLookup pathLookup = new TestPathLookup(baseDirPaths);
policyManager = createPolicyManager(pathLookup);
EntitlementInitialization.initializeArgs = new EntitlementInitialization.InitializeArgs(pathLookup, Set.of(), policyManager);
logger.debug("Loading entitlement agent");
EntitlementBootstrap.loadAgent(EntitlementBootstrap.findAgentJar(), EntitlementInitialization.class.getName());
}

public static void registerNodeBaseDirs(Settings settings, Path configPath) {
if (policyManager == null) {
return;
}
Path homeDir = absolutePath(PATH_HOME_SETTING.get(settings));
Path configDir = configPath != null ? configPath : homeDir.resolve("config");
Collection<Path> dataDirs = dataDirs(settings, homeDir);
Collection<Path> repoDirs = repoDirs(settings);
logger.debug("Registering node dirs: config [{}], dataDirs [{}], repoDirs [{}]", configDir, dataDirs, repoDirs);
baseDirPaths.compute(BaseDir.CONFIG, baseDirModifier(paths -> paths.add(configDir)));
baseDirPaths.compute(BaseDir.DATA, baseDirModifier(paths -> paths.addAll(dataDirs)));
baseDirPaths.compute(BaseDir.SHARED_REPO, baseDirModifier(paths -> paths.addAll(repoDirs)));
policyManager.reset();
}

public static void unregisterNodeBaseDirs(Settings settings, Path configPath) {
if (policyManager == null) {
return;
}
Path homeDir = absolutePath(PATH_HOME_SETTING.get(settings));
Path configDir = configPath != null ? configPath : homeDir.resolve("config");
Collection<Path> dataDirs = dataDirs(settings, homeDir);
Collection<Path> repoDirs = repoDirs(settings);
logger.debug("Unregistering node dirs: config [{}], dataDirs [{}], repoDirs [{}]", configDir, dataDirs, repoDirs);
baseDirPaths.compute(BaseDir.CONFIG, baseDirModifier(paths -> paths.remove(configDir)));
baseDirPaths.compute(BaseDir.DATA, baseDirModifier(paths -> paths.removeAll(dataDirs)));
baseDirPaths.compute(BaseDir.SHARED_REPO, baseDirModifier(paths -> paths.removeAll(repoDirs)));
Copy link
Contributor

Choose a reason for hiding this comment

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

Huh, this baseDirModifier pattern is kind of neat. The code ends up quite readable.

policyManager.reset();
}

private static Collection<Path> dataDirs(Settings settings, Path homeDir) {
List<String> dataDirs = PATH_DATA_SETTING.get(settings);
return dataDirs.isEmpty()
? List.of(homeDir.resolve("data"))
: dataDirs.stream().map(TestEntitlementBootstrap::absolutePath).toList();
}

private static Collection<Path> repoDirs(Settings settings) {
return PATH_REPO_SETTING.get(settings).stream().map(TestEntitlementBootstrap::absolutePath).toList();
}

private static BiFunction<BaseDir, Collection<Path>, Collection<Path>> baseDirModifier(Consumer<Collection<Path>> consumer) {
return (BaseDir baseDir, Collection<Path> paths) -> {
if (paths == null) {
paths = new HashSet<>();
}
consumer.accept(paths);
return paths;
};
}

@SuppressForbidden(reason = "must be resolved using the default file system, rather then the mocked test file system")
private static Path absolutePath(String path) {
return Paths.get(path).toAbsolutePath().normalize();
}

private static <T> List<T> zeroOrOne(T item) {
if (item == null) {
return List.of();
Expand Down
32 changes: 22 additions & 10 deletions test/framework/src/main/java/org/elasticsearch/node/MockNode.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.elasticsearch.common.util.MockBigArrays;
import org.elasticsearch.common.util.MockPageCacheRecycler;
import org.elasticsearch.common.util.PageCacheRecycler;
import org.elasticsearch.entitlement.bootstrap.TestEntitlementBootstrap;
import org.elasticsearch.env.Environment;
import org.elasticsearch.http.HttpServerTransport;
import org.elasticsearch.indices.ExecutorSelector;
Expand Down Expand Up @@ -53,6 +54,7 @@
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.transport.TransportSettings;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -254,16 +256,7 @@ public MockNode(
final Path configPath,
final boolean forbidPrivateIndexSettings
) {
this(
InternalSettingsPreparer.prepareEnvironment(
Settings.builder().put(TransportSettings.PORT.getKey(), ESTestCase.getPortRange()).put(settings).build(),
Collections.emptyMap(),
configPath,
() -> "mock_ node"
),
classpathPlugins,
forbidPrivateIndexSettings
);
this(prepareEnvironment(settings, configPath), classpathPlugins, forbidPrivateIndexSettings);
}

private MockNode(
Expand All @@ -282,6 +275,25 @@ PluginsService newPluginService(Environment environment, PluginsLoader pluginsLo
this.classpathPlugins = classpathPlugins;
}

private static Environment prepareEnvironment(final Settings settings, final Path configPath) {
TestEntitlementBootstrap.registerNodeBaseDirs(settings, configPath);
return InternalSettingsPreparer.prepareEnvironment(
Settings.builder().put(TransportSettings.PORT.getKey(), ESTestCase.getPortRange()).put(settings).build(),
Collections.emptyMap(),
configPath,
() -> "mock_ node"
);
}

@Override
public synchronized void close() throws IOException {
try {
super.close();
} finally {
TestEntitlementBootstrap.unregisterNodeBaseDirs(getEnvironment().settings(), getEnvironment().configDir());
}
}

/**
* The classpath plugins this node was constructed with.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -286,7 +286,6 @@
* </ul>
*/
@LuceneTestCase.SuppressFileSystems("ExtrasFS") // doesn't work with potential multi data path from test cluster yet
@ESTestCase.WithoutEntitlements // ES-12042
public abstract class ESIntegTestCase extends ESTestCase {

/** node names of the corresponding clusters will start with these prefixes */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@
* A test that keep a singleton node started for all tests that can be used to get
* references to Guice injectors in unit tests.
*/
@ESTestCase.WithoutEntitlements // ES-12042
public abstract class ESSingleNodeTestCase extends ESTestCase {

private static Node NODE = null;
Expand Down
Loading