Skip to content

Create equivalents of JSM's AccessController in the java agent #18346

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 37 commits into from
Jun 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
5beafae
Create OpenSearch replacements for widely used methods in AccessContr…
cwperks Apr 22, 2025
e8248de
Fix javadoc
cwperks Apr 22, 2025
9afced3
Remove getException
cwperks Apr 22, 2025
a0a0d9f
Remove other instance of apiNote
cwperks Apr 22, 2025
cc5a240
Modify javadoc and restart stuck CI checks
cwperks Apr 22, 2025
a172f67
Remove mistakenly added line
cwperks May 20, 2025
366406f
Add to CHANGELOG
cwperks May 20, 2025
53be672
Address code review feedback
cwperks May 21, 2025
18ccef4
Use callable and runnable
cwperks May 22, 2025
44eb148
Use Callable
cwperks May 22, 2025
00c22c7
Merge branch 'main' into access-controller
cwperks May 22, 2025
3678956
Add checked equivalents to interface
cwperks May 23, 2025
0d6e1b3
Add throws IllegalArgumentException
cwperks May 23, 2025
d79bdc1
Merge branch 'main' into access-controller
cwperks May 23, 2025
71ba997
Fix precommit
cwperks May 23, 2025
9cfa314
Show example of replacement in a module
cwperks May 23, 2025
435fe93
Merge branch 'main' into access-controller
cwperks May 29, 2025
995c66c
Address code review comments
cwperks May 29, 2025
5b04b59
Fix precommit
cwperks May 29, 2025
f054131
Merge branch 'main' into access-controller
cwperks Jun 2, 2025
7e2a98d
Merge branch 'main' into access-controller
cwperks Jun 6, 2025
cca10f5
Merge branch 'main' into access-controller
cwperks Jun 10, 2025
1348eeb
Address code review comments
cwperks Jun 10, 2025
9c44efb
Merge branch 'access-controller' of https://github.com/cwperks/OpenSe…
cwperks Jun 10, 2025
e81fdf5
Merge branch 'main' into access-controller
cwperks Jun 10, 2025
e735773
Merge branch 'main' into access-controller
cwperks Jun 11, 2025
293fd83
Merge branch 'main' into access-controller
cwperks Jun 13, 2025
2c8e511
Merge branch 'main' into access-controller
cwperks Jun 17, 2025
9dc5780
Merge branch 'access-controller' of https://github.com/cwperks/OpenSe…
cwperks Jun 17, 2025
fc6a21b
Merge branch 'main' into access-controller
cwperks Jun 18, 2025
dc7eafd
Create separate agent-api lib and remove compileOnlyApi
cwperks Jun 19, 2025
9a3f3f2
Re-use agent-policy lib
cwperks Jun 19, 2025
8950858
Address review comments
cwperks Jun 20, 2025
c6a61fc
Move to secure_sm package
cwperks Jun 20, 2025
5c32ba2
Merge branch 'main' into access-controller
cwperks Jun 20, 2025
235bd69
Merge branch 'main' into access-controller
cwperks Jun 21, 2025
e7270f7
Fix conflicts in CHANGELOG
cwperks Jun 21, 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Add support for Warm Indices Write Block on Flood Watermark breach ([#18375](https://github.com/opensearch-project/OpenSearch/pull/18375))
- Ability to run Code Coverage with Gradle and produce the jacoco reports locally ([#18509](https://github.com/opensearch-project/OpenSearch/issues/18509))
- Introduce SecureHttpTransportParameters experimental API (to complement SecureTransportParameters counterpart) ([#18572](https://github.com/opensearch-project/OpenSearch/issues/18572))
- Create equivalents of JSM's AccessController in the java agent ([#18346](https://github.com/opensearch-project/OpenSearch/issues/18346))

### Changed
- Update Subject interface to use CheckedRunnable ([#18570](https://github.com/opensearch-project/OpenSearch/issues/18570))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
/*
* 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.
*/

package org.opensearch.secure_sm;

import java.util.concurrent.Callable;
import java.util.function.Supplier;

/**
* A utility class that provides methods to perform actions in a privileged context.
*
* This class is a replacement for Java's {@code java.security.AccessController} functionality which is marked for
* removal. All new code should use this class instead of the JDK's {@code AccessController}.
*
* Running code in a privileged context will ensure that the code has the necessary permissions
* without traversing through the entire call stack. See {@code org.opensearch.javaagent.StackCallerProtectionDomainChainExtractor}
*
* Example usages:
* <pre>
* {@code
* AccessController.doPrivileged(() -> {
* // code that requires privileges
* });
* }
* </pre>
*
* Example usage with a return value and checked exception:
*
* <pre>
* {@code
* T something = AccessController.doPrivilegedChecked(() -> {
* // code that requires privileges and may throw a checked exception
* return something;
* // or
* throw new Exception();
* });
* }
* </pre>
*/
public final class AccessController {
/**
* Don't allow instantiation an {@code AccessController}
*/
private AccessController() {}

/**
* Performs the specified action in a privileged block.
*
* <p> If the action's {@code run} method throws an (unchecked)
* exception, it will propagate through this method.
*
* @param action the action to be performed
*/
public static void doPrivileged(Runnable action) {
action.run();
}

/**
* Performs the specified action.
*
* <p> If the action's {@code run} method throws an <i>unchecked</i>
* exception, it will propagate through this method.
*
* @param <T> the type of the value returned by the
* PrivilegedExceptionAction's {@code run} method
*
* @param action the action to be performed
*
* @return the value returned by the action's {@code run} method
*/
public static <T> T doPrivileged(Supplier<T> action) {
return action.get();
}

/**
* Performs the specified action.
*
* <p> If the action's {@code run} method throws an <i>unchecked</i>
* exception, it will propagate through this method.
*
* @param <T> the type of the value returned by the
* PrivilegedExceptionAction's {@code run} method
*
* @param action the action to be performed
*
* @return the value returned by the action's {@code run} method
*
* @throws Exception if the specified action's
* {@code call} method threw a <i>checked</i> exception
*/
public static <T> T doPrivilegedChecked(Callable<T> action) throws Exception {
return action.call();
}

/**
* Performs the specified action in a privileged block.
*
* <p> If the action's {@code run} method throws an (unchecked)
* exception, it will propagate through this method.
*
* @param action the action to be performed
*
* @throws T if the specified action's
* {@code call} method threw a <i>checked</i> exception
*/
public static <T extends Exception> void doPrivilegedChecked(CheckedRunnable<T> action) throws T {
action.run();
}

/**
* A functional interface that represents a runnable action that can throw a checked exception.
*
* @param <E> the type of the exception that can be thrown
*/
public interface CheckedRunnable<E extends Exception> {

/**
* Executes the action.
*
* @throws E
*/
void run() throws E;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* 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.
*/

/**
* Classes for running code in a privileged context
*/
package org.opensearch.secure_sm;
1 change: 1 addition & 0 deletions libs/agent-sm/agent/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ dependencies {
implementation "net.bytebuddy:byte-buddy:${versions.bytebuddy}"
compileOnly "com.google.code.findbugs:jsr305:3.0.2"

testImplementation project(":libs:agent-sm:agent-policy")
testImplementation "junit:junit:${versions.junit}"
testImplementation "org.hamcrest:hamcrest:${versions.hamcrest}"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.lang.StackWalker.StackFrame;
import java.security.ProtectionDomain;
import java.util.Collection;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand All @@ -24,6 +25,18 @@
*/
public static final StackCallerProtectionDomainChainExtractor INSTANCE = new StackCallerProtectionDomainChainExtractor();

private static final StackWalker STACK_WALKER = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);

Check warning on line 28 in libs/agent-sm/agent/src/main/java/org/opensearch/javaagent/StackCallerProtectionDomainChainExtractor.java

View check run for this annotation

Codecov / codecov/patch

libs/agent-sm/agent/src/main/java/org/opensearch/javaagent/StackCallerProtectionDomainChainExtractor.java#L28

Added line #L28 was not covered by tests
/**
* Classes that are used to check if the stack frame is from AccessController. Temporarily supports both the
* AccessController from the JDK (marked for removal) and its replacement in the Java Agent.
*/
private static final Set<String> ACCESS_CONTROLLER_CLASSES = Set.of(

Check warning on line 33 in libs/agent-sm/agent/src/main/java/org/opensearch/javaagent/StackCallerProtectionDomainChainExtractor.java

View check run for this annotation

Codecov / codecov/patch

libs/agent-sm/agent/src/main/java/org/opensearch/javaagent/StackCallerProtectionDomainChainExtractor.java#L33

Added line #L33 was not covered by tests
"java.security.AccessController",
"org.opensearch.secure_sm.AccessController"
);

private static final Set<String> DO_PRIVILEGED_METHODS = Set.of("doPrivileged", "doPrivilegedChecked");

Check warning on line 38 in libs/agent-sm/agent/src/main/java/org/opensearch/javaagent/StackCallerProtectionDomainChainExtractor.java

View check run for this annotation

Codecov / codecov/patch

libs/agent-sm/agent/src/main/java/org/opensearch/javaagent/StackCallerProtectionDomainChainExtractor.java#L38

Added line #L38 was not covered by tests

/**
* Constructor
*/
Expand All @@ -36,7 +49,7 @@
@Override
public Collection<ProtectionDomain> apply(Stream<StackFrame> frames) {
return frames.takeWhile(
frame -> !(frame.getClassName().equals("java.security.AccessController") && frame.getMethodName().equals("doPrivileged"))
frame -> !(ACCESS_CONTROLLER_CLASSES.contains(frame.getClassName()) && DO_PRIVILEGED_METHODS.contains(frame.getMethodName()))
)
.map(StackFrame::getDeclaringClass)
.map(Class::getProtectionDomain)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,14 @@
import java.security.ProtectionDomain;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;

public class StackCallerProtectionDomainExtractorTests {

Expand Down Expand Up @@ -115,4 +117,144 @@ public Void run() {
}
});
}

@Test
public void testStackTruncationWithOpenSearchAccessController() {
org.opensearch.secure_sm.AccessController.doPrivileged(() -> {
StackCallerProtectionDomainChainExtractor extractor = StackCallerProtectionDomainChainExtractor.INSTANCE;
Set<ProtectionDomain> protectionDomains = (Set<ProtectionDomain>) extractor.apply(captureStackFrames().stream());
assertEquals(1, protectionDomains.size());
List<String> simpleNames = protectionDomains.stream().map(pd -> {
try {
return pd.getCodeSource().getLocation().toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
})
.map(URI::getPath)
.map(Paths::get)
.map(Path::getFileName)
.map(Path::toString)
// strip trailing “-VERSION.jar” if present
.map(name -> name.replaceFirst("-\\d[\\d\\.]*\\.jar$", ""))
// otherwise strip “.jar”
.map(name -> name.replaceFirst("\\.jar$", ""))
.toList();
assertThat(
simpleNames,
containsInAnyOrder(
"test" // from the build/classes/java/test directory
)
);
});
}

@Test
public void testStackTruncationWithOpenSearchAccessControllerUsingSupplier() {
org.opensearch.secure_sm.AccessController.doPrivileged((Supplier<Void>) () -> {
StackCallerProtectionDomainChainExtractor extractor = StackCallerProtectionDomainChainExtractor.INSTANCE;
Set<ProtectionDomain> protectionDomains = (Set<ProtectionDomain>) extractor.apply(captureStackFrames().stream());
assertEquals(1, protectionDomains.size());
List<String> simpleNames = protectionDomains.stream().map(pd -> {
try {
return pd.getCodeSource().getLocation().toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
})
.map(URI::getPath)
.map(Paths::get)
.map(Path::getFileName)
.map(Path::toString)
// strip trailing “-VERSION.jar” if present
.map(name -> name.replaceFirst("-\\d[\\d\\.]*\\.jar$", ""))
// otherwise strip “.jar”
.map(name -> name.replaceFirst("\\.jar$", ""))
.toList();
assertThat(
simpleNames,
containsInAnyOrder(
"test" // from the build/classes/java/test directory
)
);
return null;
});
}

@Test
public void testStackTruncationWithOpenSearchAccessControllerUsingCallable() throws Exception {
org.opensearch.secure_sm.AccessController.doPrivilegedChecked(() -> {
StackCallerProtectionDomainChainExtractor extractor = StackCallerProtectionDomainChainExtractor.INSTANCE;
Set<ProtectionDomain> protectionDomains = (Set<ProtectionDomain>) extractor.apply(captureStackFrames().stream());
assertEquals(1, protectionDomains.size());
List<String> simpleNames = protectionDomains.stream().map(pd -> {
try {
return pd.getCodeSource().getLocation().toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
})
.map(URI::getPath)
.map(Paths::get)
.map(Path::getFileName)
.map(Path::toString)
// strip trailing “-VERSION.jar” if present
.map(name -> name.replaceFirst("-\\d[\\d\\.]*\\.jar$", ""))
// otherwise strip “.jar”
.map(name -> name.replaceFirst("\\.jar$", ""))
.toList();
assertThat(
simpleNames,
containsInAnyOrder(
"test" // from the build/classes/java/test directory
)
);
return null;
});
}

@Test
public void testAccessControllerUsingCallableThrowsException() {
assertThrows(IllegalArgumentException.class, () -> {
org.opensearch.secure_sm.AccessController.doPrivilegedChecked(() -> { throw new IllegalArgumentException("Test exception"); });
});
}

@Test
public void testStackTruncationWithOpenSearchAccessControllerUsingCheckedRunnable() throws IllegalArgumentException {
org.opensearch.secure_sm.AccessController.doPrivilegedChecked(() -> {
StackCallerProtectionDomainChainExtractor extractor = StackCallerProtectionDomainChainExtractor.INSTANCE;
Set<ProtectionDomain> protectionDomains = (Set<ProtectionDomain>) extractor.apply(captureStackFrames().stream());
assertEquals(1, protectionDomains.size());
List<String> simpleNames = protectionDomains.stream().map(pd -> {
try {
return pd.getCodeSource().getLocation().toURI();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
})
.map(URI::getPath)
.map(Paths::get)
.map(Path::getFileName)
.map(Path::toString)
// strip trailing “-VERSION.jar” if present
.map(name -> name.replaceFirst("-\\d[\\d\\.]*\\.jar$", ""))
// otherwise strip “.jar”
.map(name -> name.replaceFirst("\\.jar$", ""))
.toList();
assertThat(
simpleNames,
containsInAnyOrder(
"test" // from the build/classes/java/test directory
)
);
});
}

@Test
public void testAccessControllerUsingCheckedRunnableThrowsException() {
assertThrows(IllegalArgumentException.class, () -> {
org.opensearch.secure_sm.AccessController.doPrivilegedChecked(() -> { throw new IllegalArgumentException("Test exception"); });
});
}
}
Loading
Loading