From 920301197e53c893e8145e39182b32013f25ce66 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Fri, 2 Oct 2026 21:29:48 +0000 Subject: [PATCH 1/4] Add a shared PluginClient for running actions as a plugin's system subject Plugins moving off ThreadContext.stashContext each need a client that routes transport actions through the PluginSubject assigned by IdentityAwarePlugin. Eight plugins have written their own copy of this, around 60 lines each, and the copies have diverged. Two of the differences are real defects: - geospatial and job-scheduler let a synchronous failure escape doExecute; flow-framework and anomaly-detection rethrow it as a RuntimeException. Either way listener.onFailure never fires and the failure reaches a caller that was using the listener contract as a synchronous throw instead. - The caller's context has to be restored from the listener via runBefore. A transport response arrives on a pooled thread that never carried that context, so nothing else puts it back before the listener body runs. Two further differences are stylistic rather than behavioral, and this class picks the clearer form without implying the others are broken: holding the StoredContext in a local rather than try-with-resources, and newStoredContext instead of stashContext. Both SecurePluginSubject.runAs and NoopPluginSubject .runAs already stash and restore around their body, so the calling thread is back to the caller's context before doExecute returns either way. Three copies also log the subject's principal name at info on every transport action, which is per-request noise at a level that is on by default. This logs at debug. Verified: compileJava, compileTestJava and the four unit tests pass. Each of the two behavioral tests was confirmed to fail against the variant it guards, and to be the only failure: dropping the runBefore restore reds the context test alone, rethrowing reds the failure test alone. The try-with-resources and stashContext variants were also measured and left all four tests green, which is what established that those two are not defects. The fake subject in the test self-restores, matching both real implementations; a fake that does not will report false failures against those two variants. Signed-off-by: Darshit Chanpura --- .../commons/client/PluginClient.java | 81 ++++++++ .../commons/client/PluginClientTest.java | 189 ++++++++++++++++++ 2 files changed, 270 insertions(+) create mode 100644 src/main/java/org/opensearch/commons/client/PluginClient.java create mode 100644 src/test/java/org/opensearch/commons/client/PluginClientTest.java diff --git a/src/main/java/org/opensearch/commons/client/PluginClient.java b/src/main/java/org/opensearch/commons/client/PluginClient.java new file mode 100644 index 00000000..47111a70 --- /dev/null +++ b/src/main/java/org/opensearch/commons/client/PluginClient.java @@ -0,0 +1,81 @@ +/* + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.opensearch.commons.client; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.opensearch.action.ActionRequest; +import org.opensearch.action.ActionType; +import org.opensearch.common.util.concurrent.ThreadContext; +import org.opensearch.core.action.ActionListener; +import org.opensearch.core.action.ActionResponse; +import org.opensearch.identity.Subject; +import org.opensearch.transport.client.Client; +import org.opensearch.transport.client.FilterClient; + +/** + * Executes transport actions as the consuming plugin's assigned system subject rather than as the + * authenticated user, which is how a plugin reaches the system indices it owns. Replaces wrapping + * client calls in {@code ThreadContext.stashContext()}, which grants unrestricted access rather + * than access scoped to the plugin's own registered system indices. + *

+ * A plugin constructs one of these around the client it receives in {@code createComponents}, then + * implements {@code IdentityAwarePlugin} and passes the subject along in {@code assignSubject}: + * + *

+ * public void assignSubject(PluginSubject pluginSubject) {
+ *     this.pluginClient.setSubject(pluginSubject);
+ * }
+ * 
+ * + * The subject is assigned whether or not the security plugin is installed, so there is no + * conditional path for the unsecured case. + */ +public class PluginClient extends FilterClient { + + private static final Logger log = LogManager.getLogger(PluginClient.class); + + // Assigned from IdentityAwarePlugin.assignSubject, which runs on a different thread than the + // transport actions that read it. + private volatile Subject subject; + + public PluginClient(Client delegate) { + super(delegate); + } + + public void setSubject(Subject subject) { + this.subject = subject; + } + + @Override + protected void doExecute( + ActionType action, + Request request, + ActionListener listener + ) { + Subject currentSubject = this.subject; + if (currentSubject == null) { + throw new IllegalStateException("PluginClient is not initialized with a subject."); + } + + // Saves the caller's context so the listener can be given it back. runAs performs the switch + // itself and restores on exit, so this is about the listener, which runs later and on a + // thread that never carried the caller's context. newStoredContext(false) over stashContext() + // and a local over try-with-resources are both for clarity; neither changes behavior here. + ThreadContext.StoredContext storedContext = threadPool().getThreadContext().newStoredContext(false); + + try { + currentSubject.runAs(() -> { + log.debug("Running transport action as subject: {}", currentSubject.getPrincipal().getName()); + super.doExecute(action, request, ActionListener.runBefore(listener, storedContext::restore)); + }); + } catch (Exception e) { + // Reported through the listener rather than thrown, so an async caller is not left waiting. + storedContext.close(); + listener.onFailure(e); + } + } +} diff --git a/src/test/java/org/opensearch/commons/client/PluginClientTest.java b/src/test/java/org/opensearch/commons/client/PluginClientTest.java new file mode 100644 index 00000000..bb941392 --- /dev/null +++ b/src/test/java/org/opensearch/commons/client/PluginClientTest.java @@ -0,0 +1,189 @@ +/* + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.opensearch.commons.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.security.Principal; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.opensearch.action.ActionRequest; +import org.opensearch.action.ActionRequestValidationException; +import org.opensearch.action.ActionType; +import org.opensearch.common.CheckedRunnable; +import org.opensearch.common.settings.Settings; +import org.opensearch.common.util.concurrent.ThreadContext; +import org.opensearch.core.action.ActionListener; +import org.opensearch.core.action.ActionResponse; +import org.opensearch.core.common.io.stream.StreamOutput; +import org.opensearch.threadpool.ThreadPool; +import org.opensearch.transport.client.Client; + +/** + * Covers the four behaviors that distinguish this client from the per-plugin copies it replaces: + * the action runs through the subject, the caller's context is restored exactly once and only after + * the listener completes, a synchronous failure reaches the listener instead of escaping, and an + * unassigned subject is a programming error rather than a silent no-op. + */ +public class PluginClientTest { + + private static final String CALLER_TRANSIENT = "caller.marker"; + private static final String SUBJECT_TRANSIENT = "subject.marker"; + + private ThreadContext threadContext; + private Client delegate; + private AtomicReference> capturedListener; + + @BeforeEach + public void setUp() { + threadContext = new ThreadContext(Settings.EMPTY); + capturedListener = new AtomicReference<>(); + + ThreadPool threadPool = mock(ThreadPool.class); + when(threadPool.getThreadContext()).thenReturn(threadContext); + + delegate = mock(Client.class); + when(delegate.settings()).thenReturn(Settings.EMPTY); + when(delegate.threadPool()).thenReturn(threadPool); + + // Captures the listener without invoking it, so the test controls when the action completes. + // That is what makes the restore-timing assertion below meaningful. + doAnswer(invocation -> { + capturedListener.set(invocation.getArgument(2)); + return null; + }).when(delegate).execute(any(ActionType.class), any(ActionRequest.class), any(ActionListener.class)); + } + + @Test + public void runsActionThroughTheAssignedSubject() { + RecordingSubject subject = new RecordingSubject(threadContext, null); + PluginClient pluginClient = new PluginClient(delegate); + pluginClient.setSubject(subject); + + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, e -> {})); + + assertEquals(1, subject.runAsInvocations.get()); + assertNotNull(capturedListener.get(), "delegate should have been reached"); + } + + @Test + public void listenerSeesTheCallerContextEvenOnAThreadThatNeverHadIt() throws Exception { + threadContext.putTransient(CALLER_TRANSIENT, "set-by-caller"); + + RecordingSubject subject = new RecordingSubject(threadContext, null); + PluginClient pluginClient = new PluginClient(delegate); + pluginClient.setSubject(subject); + + AtomicReference seenByListener = new AtomicReference<>("listener did not run"); + pluginClient + .execute( + DUMMY_ACTION, + new DummyRequest(), + ActionListener.wrap(r -> seenByListener.set(threadContext.getTransient(CALLER_TRANSIENT)), e -> {}) + ); + + // Completing on a separate thread is what makes this discriminate. A transport response + // arrives on a pooled thread that never carried the caller's context, so the restore wired + // to the listener is the only thing that can put it back. + Thread responder = new Thread(() -> capturedListener.get().onResponse(new DummyResponse())); + responder.start(); + responder.join(); + + assertEquals("set-by-caller", seenByListener.get()); + } + + @Test + public void deliversSynchronousFailureToTheListenerRatherThanThrowing() { + RuntimeException boom = new RuntimeException("subject refused"); + RecordingSubject subject = new RecordingSubject(threadContext, boom); + PluginClient pluginClient = new PluginClient(delegate); + pluginClient.setSubject(subject); + + AtomicReference failure = new AtomicReference<>(); + // No assertThrows here on purpose: escaping synchronously would leave an async caller + // waiting forever, so the contract is that the listener is told. + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, failure::set)); + + assertSame(boom, failure.get()); + assertNull(capturedListener.get(), "delegate should not have been reached"); + } + + @Test + public void rejectsUseBeforeASubjectIsAssigned() { + PluginClient pluginClient = new PluginClient(delegate); + + IllegalStateException e = assertThrows( + IllegalStateException.class, + () -> pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, ex -> {})) + ); + assertEquals("PluginClient is not initialized with a subject.", e.getMessage()); + } + + /** + * Stands in for the security plugin's subject. Marks the thread context on entry so a test can + * tell the subject's context apart from the caller's, and can be asked to fail. + */ + private static class RecordingSubject implements org.opensearch.identity.Subject { + + private final AtomicInteger runAsInvocations = new AtomicInteger(); + private final ThreadContext threadContext; + private final RuntimeException failure; + + RecordingSubject(ThreadContext threadContext, RuntimeException failure) { + this.threadContext = threadContext; + this.failure = failure; + } + + @Override + public Principal getPrincipal() { + return () -> "plugin:test"; + } + + @Override + public void runAs(CheckedRunnable runnable) throws E { + runAsInvocations.incrementAndGet(); + if (failure != null) { + throw failure; + } + // Mirrors SecurePluginSubject and NoopPluginSubject: both stash, inject, and restore on + // exit. The restore matters, because it means the calling thread is already back to the + // caller's context by the time doExecute returns. + try (ThreadContext.StoredContext ignored = threadContext.stashContext()) { + threadContext.putTransient(SUBJECT_TRANSIENT, "set-by-subject"); + runnable.run(); + } + } + } + + private static final ActionType DUMMY_ACTION = new ActionType<>( + "cluster:admin/plugin_client_test", + in -> new DummyResponse() + ); + + private static class DummyRequest extends ActionRequest { + @Override + public ActionRequestValidationException validate() { + return null; + } + } + + private static class DummyResponse extends ActionResponse { + @Override + public void writeTo(StreamOutput out) throws IOException {} + } +} From 50872ed465f4e29935c98fa3ec0dd1e4e0f7fba2 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 12 Oct 2026 17:21:20 +0000 Subject: [PATCH 2/4] Restore the caller's context with core's ContextPreservingActionListener The hand-rolled pairing of newStoredContext with ActionListener.runBefore installed the caller's context on the responding thread and never took it off again, so a pooled transport thread kept it for whatever ran next. It also dropped response headers the action produced, since the snapshot was taken with preserveResponseHeaders false. ContextPreservingActionListener.wrapPreservingContext is core's primitive for this. It restores the caller's context around the callback and puts the responding thread's own context back afterwards, and preserves response headers. Using it removes the StoredContext bookkeeping from this class entirely. Also adds a constructor taking the subject eagerly, for callers that already have one, and Javadoc on the public and protected members. Verified: spotlessCheck, compileJava, compileTestJava and five unit tests pass. Each behavioural test was confirmed to fail against the variant it guards, and to be the only failure. Reinstating the previous newStoredContext plus runBefore form reds the new responding-thread test alone, which is what establishes that this change is load-bearing rather than cosmetic. Passing the raw listener reds the caller-context test alone, and rethrowing reds the failure test alone. Signed-off-by: Darshit Chanpura --- .../commons/client/PluginClient.java | 47 ++++-- ...ClientTest.java => PluginClientTests.java} | 142 +++++++++++------- 2 files changed, 122 insertions(+), 67 deletions(-) rename src/test/java/org/opensearch/commons/client/{PluginClientTest.java => PluginClientTests.java} (55%) diff --git a/src/main/java/org/opensearch/commons/client/PluginClient.java b/src/main/java/org/opensearch/commons/client/PluginClient.java index 47111a70..85775189 100644 --- a/src/main/java/org/opensearch/commons/client/PluginClient.java +++ b/src/main/java/org/opensearch/commons/client/PluginClient.java @@ -9,7 +9,7 @@ import org.apache.logging.log4j.Logger; import org.opensearch.action.ActionRequest; import org.opensearch.action.ActionType; -import org.opensearch.common.util.concurrent.ThreadContext; +import org.opensearch.action.support.ContextPreservingActionListener; import org.opensearch.core.action.ActionListener; import org.opensearch.core.action.ActionResponse; import org.opensearch.identity.Subject; @@ -42,14 +42,44 @@ public class PluginClient extends FilterClient { // transport actions that read it. private volatile Subject subject; + /** + * Wraps a client so its actions run as the plugin subject. The subject arrives later, through + * {@link #setSubject(Subject)}, so actions executed before then fail fast. + * + * @param delegate the client whose actions this wraps + */ public PluginClient(Client delegate) { super(delegate); } + /** + * Wraps a client with its subject already known, for callers that have one before they build the + * client. Core assigns the subject after {@code createComponents}, so most plugins cannot use this. + * + * @param delegate the client whose actions this wraps + * @param subject the plugin's system subject + */ + public PluginClient(Client delegate, Subject subject) { + super(delegate); + this.subject = subject; + } + + /** + * Assigns the subject every subsequent action runs as, normally the one handed to + * {@code IdentityAwarePlugin.assignSubject}. + * + * @param subject the plugin's system subject + */ public void setSubject(Subject subject) { this.subject = subject; } + /** + * Runs the action as the assigned subject. + * + * @param listener notified with the caller's thread context in place, not the subject's + * @throws IllegalStateException if no subject has been assigned yet + */ @Override protected void doExecute( ActionType action, @@ -61,20 +91,19 @@ protected void throw new IllegalStateException("PluginClient is not initialized with a subject."); } - // Saves the caller's context so the listener can be given it back. runAs performs the switch - // itself and restores on exit, so this is about the listener, which runs later and on a - // thread that never carried the caller's context. newStoredContext(false) over stashContext() - // and a local over try-with-resources are both for clarity; neither changes behavior here. - ThreadContext.StoredContext storedContext = threadPool().getThreadContext().newStoredContext(false); + // Snapshot taken before runAs, which clears the context. Core's wrapper restores the caller's + // context around the callback and puts the responding thread's own back afterwards, so the + // caller's context is not left behind on a pooled thread. + ActionListener callerContext = ContextPreservingActionListener + .wrapPreservingContext(listener, threadPool().getThreadContext()); try { currentSubject.runAs(() -> { log.debug("Running transport action as subject: {}", currentSubject.getPrincipal().getName()); - super.doExecute(action, request, ActionListener.runBefore(listener, storedContext::restore)); + super.doExecute(action, request, callerContext); }); } catch (Exception e) { - // Reported through the listener rather than thrown, so an async caller is not left waiting. - storedContext.close(); + // Reported through the listener so an async caller is not left waiting. listener.onFailure(e); } } diff --git a/src/test/java/org/opensearch/commons/client/PluginClientTest.java b/src/test/java/org/opensearch/commons/client/PluginClientTests.java similarity index 55% rename from src/test/java/org/opensearch/commons/client/PluginClientTest.java rename to src/test/java/org/opensearch/commons/client/PluginClientTests.java index bb941392..fa56726d 100644 --- a/src/test/java/org/opensearch/commons/client/PluginClientTest.java +++ b/src/test/java/org/opensearch/commons/client/PluginClientTests.java @@ -17,7 +17,6 @@ import java.io.IOException; import java.security.Principal; -import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.BeforeEach; @@ -34,85 +33,98 @@ import org.opensearch.threadpool.ThreadPool; import org.opensearch.transport.client.Client; -/** - * Covers the four behaviors that distinguish this client from the per-plugin copies it replaces: - * the action runs through the subject, the caller's context is restored exactly once and only after - * the listener completes, a synchronous failure reaches the listener instead of escaping, and an - * unassigned subject is a programming error rather than a silent no-op. - */ -public class PluginClientTest { +/** Covers the behaviors that distinguish this client from the per-plugin copies it replaces. */ +public class PluginClientTests { private static final String CALLER_TRANSIENT = "caller.marker"; private static final String SUBJECT_TRANSIENT = "subject.marker"; + private static final String RESPONDER_TRANSIENT = "responder.marker"; + + private static final ActionType DUMMY_ACTION = new ActionType<>( + "cluster:admin/plugin_client_test", + in -> new DummyResponse() + ); private ThreadContext threadContext; - private Client delegate; - private AtomicReference> capturedListener; + private PluginClient pluginClient; + private ActionListener capturedListener; @BeforeEach public void setUp() { threadContext = new ThreadContext(Settings.EMPTY); - capturedListener = new AtomicReference<>(); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.getThreadContext()).thenReturn(threadContext); - delegate = mock(Client.class); + Client delegate = mock(Client.class); when(delegate.settings()).thenReturn(Settings.EMPTY); when(delegate.threadPool()).thenReturn(threadPool); - // Captures the listener without invoking it, so the test controls when the action completes. - // That is what makes the restore-timing assertion below meaningful. + // Captures the listener without invoking it, so each test decides when the action completes. doAnswer(invocation -> { - capturedListener.set(invocation.getArgument(2)); + capturedListener = invocation.getArgument(2); return null; }).when(delegate).execute(any(ActionType.class), any(ActionRequest.class), any(ActionListener.class)); + + pluginClient = new PluginClient(delegate); } @Test public void runsActionThroughTheAssignedSubject() { - RecordingSubject subject = new RecordingSubject(threadContext, null); - PluginClient pluginClient = new PluginClient(delegate); - pluginClient.setSubject(subject); + RecordingSubject subject = assignSubject(null); - pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, e -> {})); + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ignoring()); - assertEquals(1, subject.runAsInvocations.get()); - assertNotNull(capturedListener.get(), "delegate should have been reached"); + assertEquals(1, subject.runAsInvocations); + assertNotNull(capturedListener, "delegate should have been reached"); } @Test - public void listenerSeesTheCallerContextEvenOnAThreadThatNeverHadIt() throws Exception { + public void listenerSeesTheCallerContextAndNotTheSubjects() throws Exception { threadContext.putTransient(CALLER_TRANSIENT, "set-by-caller"); + assignSubject(null); - RecordingSubject subject = new RecordingSubject(threadContext, null); - PluginClient pluginClient = new PluginClient(delegate); - pluginClient.setSubject(subject); - - AtomicReference seenByListener = new AtomicReference<>("listener did not run"); - pluginClient - .execute( - DUMMY_ACTION, - new DummyRequest(), - ActionListener.wrap(r -> seenByListener.set(threadContext.getTransient(CALLER_TRANSIENT)), e -> {}) - ); + AtomicReference callerSeen = new AtomicReference<>("listener did not run"); + AtomicReference subjectSeen = new AtomicReference<>("listener did not run"); + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> { + callerSeen.set(threadContext.getTransient(CALLER_TRANSIENT)); + subjectSeen.set(threadContext.getTransient(SUBJECT_TRANSIENT)); + }, e -> {})); // Completing on a separate thread is what makes this discriminate. A transport response - // arrives on a pooled thread that never carried the caller's context, so the restore wired - // to the listener is the only thing that can put it back. - Thread responder = new Thread(() -> capturedListener.get().onResponse(new DummyResponse())); - responder.start(); - responder.join(); + // arrives on a pooled thread that never carried the caller's context, so the wrapper around + // the listener is the only thing that can put it back. + completeOnAnotherThread(null); + + assertEquals("set-by-caller", callerSeen.get()); + assertNull(subjectSeen.get(), "the subject's context must not leak into the listener"); + } - assertEquals("set-by-caller", seenByListener.get()); + @Test + public void restoresTheRespondingThreadsContextAfterTheListenerReturns() throws Exception { + threadContext.putTransient(CALLER_TRANSIENT, "set-by-caller"); + assignSubject(null); + + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ignoring()); + + // The responding thread marks itself, completes the action, then checks its own context once + // the listener has returned. Restoring the caller's context and leaving it there would strand + // it on a pooled thread for whatever runs next. + AtomicReference responderAfter = new AtomicReference<>(); + AtomicReference callerLeftBehind = new AtomicReference<>(); + completeOnAnotherThread(() -> { + responderAfter.set(threadContext.getTransient(RESPONDER_TRANSIENT)); + callerLeftBehind.set(threadContext.getTransient(CALLER_TRANSIENT)); + }); + + assertEquals("set-by-responder", responderAfter.get(), "responding thread's own context must come back"); + assertNull(callerLeftBehind.get(), "the caller's context must not be left on the responding thread"); } @Test public void deliversSynchronousFailureToTheListenerRatherThanThrowing() { RuntimeException boom = new RuntimeException("subject refused"); - RecordingSubject subject = new RecordingSubject(threadContext, boom); - PluginClient pluginClient = new PluginClient(delegate); - pluginClient.setSubject(subject); + assignSubject(boom); AtomicReference failure = new AtomicReference<>(); // No assertThrows here on purpose: escaping synchronously would leave an async caller @@ -120,29 +132,51 @@ public void deliversSynchronousFailureToTheListenerRatherThanThrowing() { pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, failure::set)); assertSame(boom, failure.get()); - assertNull(capturedListener.get(), "delegate should not have been reached"); + assertNull(capturedListener, "delegate should not have been reached"); } @Test public void rejectsUseBeforeASubjectIsAssigned() { - PluginClient pluginClient = new PluginClient(delegate); - IllegalStateException e = assertThrows( IllegalStateException.class, - () -> pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, ex -> {})) + () -> pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ignoring()) ); assertEquals("PluginClient is not initialized with a subject.", e.getMessage()); } + private RecordingSubject assignSubject(RuntimeException failure) { + RecordingSubject subject = new RecordingSubject(threadContext, failure); + pluginClient.setSubject(subject); + return subject; + } + + /** Completes the captured action on a thread that never carried the caller's context. */ + private void completeOnAnotherThread(Runnable afterListenerReturns) throws InterruptedException { + Thread responder = new Thread(() -> { + threadContext.putTransient(RESPONDER_TRANSIENT, "set-by-responder"); + capturedListener.onResponse(new DummyResponse()); + if (afterListenerReturns != null) { + afterListenerReturns.run(); + } + }); + responder.start(); + responder.join(); + } + + private static ActionListener ignoring() { + return ActionListener.wrap(r -> {}, e -> {}); + } + /** - * Stands in for the security plugin's subject. Marks the thread context on entry so a test can - * tell the subject's context apart from the caller's, and can be asked to fail. + * Stands in for the security plugin's subject. Stashes and restores around its body the way both + * real implementations do, and marks the context so a test can tell the subject's apart from the + * caller's. */ private static class RecordingSubject implements org.opensearch.identity.Subject { - private final AtomicInteger runAsInvocations = new AtomicInteger(); private final ThreadContext threadContext; private final RuntimeException failure; + private int runAsInvocations; RecordingSubject(ThreadContext threadContext, RuntimeException failure) { this.threadContext = threadContext; @@ -156,13 +190,10 @@ public Principal getPrincipal() { @Override public void runAs(CheckedRunnable runnable) throws E { - runAsInvocations.incrementAndGet(); + runAsInvocations++; if (failure != null) { throw failure; } - // Mirrors SecurePluginSubject and NoopPluginSubject: both stash, inject, and restore on - // exit. The restore matters, because it means the calling thread is already back to the - // caller's context by the time doExecute returns. try (ThreadContext.StoredContext ignored = threadContext.stashContext()) { threadContext.putTransient(SUBJECT_TRANSIENT, "set-by-subject"); runnable.run(); @@ -170,11 +201,6 @@ public void runAs(CheckedRunnable runnable) throws E { } } - private static final ActionType DUMMY_ACTION = new ActionType<>( - "cluster:admin/plugin_client_test", - in -> new DummyResponse() - ); - private static class DummyRequest extends ActionRequest { @Override public ActionRequestValidationException validate() { From 6a1eb36b0b47db95b6bdbf5a6d69f023664d6ff6 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Mon, 12 Oct 2026 21:26:54 +0000 Subject: [PATCH 3/4] Make PluginClient a per-plugin base class that behaves like the wrapped client - Take a PluginSubject rather than any Subject. Subject.runAs runs inline by default, and the security plugin's User implements Subject, so passing a non-plugin subject ran actions in the caller's context without any error. - Make the subject set once and reject null, so a live client cannot change identity or drop back to uninitialised. - Make the class abstract with final setSubject, doExecute and getRemoteClusterClient. Core binds each createComponents result by its runtime class, and plugins that share a classloader through extendedPlugins share this class, so a shared concrete type would let one plugin inject another's client. A one-line subclass per plugin gives each its own binding. - Refuse getRemoteClusterClient. FilterClient returns the delegate's remote client unwrapped, which does not run as the subject, and a plugin subject has no meaning on another cluster. - Remove the catch around runAs. Neither real subject throws before running its body, and core already routes validation and filter-chain failures to the listener, so the catch only converted the synchronous throws NodeClient makes to every caller into listener failures. It also notified the listener a second time when the listener itself threw during synchronous completion. Verified: build passes (749 tests, 0 failures). Each new test was confirmed to fail against the mutant it guards and to be the only failure: running the action outside runAs, reintroducing the catch, dropping response headers, assigning the subject without checks, returning the remote client, passing the raw listener, and restoring the previous newStoredContext plus runBefore form. Signed-off-by: Darshit Chanpura --- .../commons/client/PluginClient.java | 109 ++++---- .../commons/client/PluginClientTests.java | 237 ++++++++++++------ 2 files changed, 227 insertions(+), 119 deletions(-) diff --git a/src/main/java/org/opensearch/commons/client/PluginClient.java b/src/main/java/org/opensearch/commons/client/PluginClient.java index 85775189..78e297fc 100644 --- a/src/main/java/org/opensearch/commons/client/PluginClient.java +++ b/src/main/java/org/opensearch/commons/client/PluginClient.java @@ -5,6 +5,9 @@ package org.opensearch.commons.client; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.opensearch.action.ActionRequest; @@ -12,99 +15,107 @@ import org.opensearch.action.support.ContextPreservingActionListener; import org.opensearch.core.action.ActionListener; import org.opensearch.core.action.ActionResponse; -import org.opensearch.identity.Subject; +import org.opensearch.identity.PluginSubject; import org.opensearch.transport.client.Client; import org.opensearch.transport.client.FilterClient; /** - * Executes transport actions as the consuming plugin's assigned system subject rather than as the - * authenticated user, which is how a plugin reaches the system indices it owns. Replaces wrapping - * client calls in {@code ThreadContext.stashContext()}, which grants unrestricted access rather - * than access scoped to the plugin's own registered system indices. + * Runs transport actions as the consuming plugin's system subject rather than as the authenticated + * user, so the plugin can reach the system indices it registered. Use it instead of + * {@code ThreadContext.stashContext()}: a stashed context carries no user, and the security plugin + * lets a local request with no user through without evaluating privileges, whereas the plugin + * subject is authorized only for the plugin's own system indices and the permissions it declares. + *

+ * Core assigns the subject through {@code IdentityAwarePlugin.assignSubject} after + * {@code createComponents}, with or without the security plugin installed. Build this client in + * {@code createComponents} and call {@link #setSubject(PluginSubject)} from {@code assignSubject}. + * Apart from the identity it runs as, it behaves like the client it wraps, including which failures + * are thrown and which reach the listener. *

- * A plugin constructs one of these around the client it receives in {@code createComponents}, then - * implements {@code IdentityAwarePlugin} and passes the subject along in {@code assignSubject}: - * - *

- * public void assignSubject(PluginSubject pluginSubject) {
- *     this.pluginClient.setSubject(pluginSubject);
- * }
- * 
- * - * The subject is assigned whether or not the security plugin is installed, so there is no - * conditional path for the unsecured case. + * Each plugin declares its own subclass. Core binds every component returned from + * {@code createComponents} by its runtime class, and plugins sharing a classloader through + * {@code extendedPlugins} share this class, so a shared type would let one plugin inject another's + * client and run as its subject. */ -public class PluginClient extends FilterClient { +public abstract class PluginClient extends FilterClient { private static final Logger log = LogManager.getLogger(PluginClient.class); - // Assigned from IdentityAwarePlugin.assignSubject, which runs on a different thread than the - // transport actions that read it. - private volatile Subject subject; + // Set once, from assignSubject, on a different thread from the actions that read it. + private final AtomicReference subject = new AtomicReference<>(); /** - * Wraps a client so its actions run as the plugin subject. The subject arrives later, through - * {@link #setSubject(Subject)}, so actions executed before then fail fast. + * Wraps a client so its actions run as the plugin subject, which is assigned later. * * @param delegate the client whose actions this wraps */ - public PluginClient(Client delegate) { + protected PluginClient(Client delegate) { super(delegate); } /** - * Wraps a client with its subject already known, for callers that have one before they build the - * client. Core assigns the subject after {@code createComponents}, so most plugins cannot use this. + * Wraps a client with its subject already known. * * @param delegate the client whose actions this wraps * @param subject the plugin's system subject */ - public PluginClient(Client delegate, Subject subject) { + protected PluginClient(Client delegate, PluginSubject subject) { super(delegate); - this.subject = subject; + setSubject(subject); } /** - * Assigns the subject every subsequent action runs as, normally the one handed to - * {@code IdentityAwarePlugin.assignSubject}. + * Assigns the subject every action runs as. It can be assigned once; assigning the same subject + * again is a no-op. * - * @param subject the plugin's system subject + * @param subject the plugin's system subject, normally the one passed to {@code assignSubject} + * @throws IllegalStateException if a different subject is already assigned + */ + public final void setSubject(PluginSubject subject) { + Objects.requireNonNull(subject, "subject"); + if (!this.subject.compareAndSet(null, subject) && this.subject.get() != subject) { + throw new IllegalStateException("PluginClient already has a subject assigned."); + } + } + + /** + * Not supported, because a plugin subject has no meaning on another cluster. + * + * @param clusterAlias the remote cluster that was requested + * @return never returns + * @throws UnsupportedOperationException always */ - public void setSubject(Subject subject) { - this.subject = subject; + @Override + public final Client getRemoteClusterClient(String clusterAlias) { + throw new UnsupportedOperationException("PluginClient cannot run actions on a remote cluster."); } /** * Runs the action as the assigned subject. * - * @param listener notified with the caller's thread context in place, not the subject's - * @throws IllegalStateException if no subject has been assigned yet + * @param action the action to run as the subject + * @param request the request to run it with + * @param listener notified with the caller's thread context in place rather than the subject's + * @throws IllegalStateException if no subject has been assigned yet, which is a wiring error */ @Override - protected void doExecute( + protected final void doExecute( ActionType action, Request request, ActionListener listener ) { - Subject currentSubject = this.subject; + PluginSubject currentSubject = subject.get(); if (currentSubject == null) { throw new IllegalStateException("PluginClient is not initialized with a subject."); } - // Snapshot taken before runAs, which clears the context. Core's wrapper restores the caller's - // context around the callback and puts the responding thread's own back afterwards, so the - // caller's context is not left behind on a pooled thread. + // Captured before runAs stashes the context; core restores it around the callback, then puts + // the responding thread's own context back. ActionListener callerContext = ContextPreservingActionListener .wrapPreservingContext(listener, threadPool().getThreadContext()); - - try { - currentSubject.runAs(() -> { - log.debug("Running transport action as subject: {}", currentSubject.getPrincipal().getName()); - super.doExecute(action, request, callerContext); - }); - } catch (Exception e) { - // Reported through the listener so an async caller is not left waiting. - listener.onFailure(e); - } + currentSubject.runAs(() -> { + log.debug("Running transport action as subject: {}", currentSubject.getPrincipal().getName()); + super.doExecute(action, request, callerContext); + }); } } diff --git a/src/test/java/org/opensearch/commons/client/PluginClientTests.java b/src/test/java/org/opensearch/commons/client/PluginClientTests.java index fa56726d..b0ce5670 100644 --- a/src/test/java/org/opensearch/commons/client/PluginClientTests.java +++ b/src/test/java/org/opensearch/commons/client/PluginClientTests.java @@ -6,10 +6,10 @@ package org.opensearch.commons.client; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; @@ -17,8 +17,16 @@ import java.io.IOException; import java.security.Principal; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opensearch.action.ActionRequest; @@ -30,10 +38,11 @@ import org.opensearch.core.action.ActionListener; import org.opensearch.core.action.ActionResponse; import org.opensearch.core.common.io.stream.StreamOutput; +import org.opensearch.identity.PluginSubject; import org.opensearch.threadpool.ThreadPool; import org.opensearch.transport.client.Client; -/** Covers the behaviors that distinguish this client from the per-plugin copies it replaces. */ +/** Tests that PluginClient runs actions as its subject and notifies the listener in the caller's context. */ public class PluginClientTests { private static final String CALLER_TRANSIENT = "caller.marker"; @@ -46,73 +55,79 @@ public class PluginClientTests { ); private ThreadContext threadContext; + private Client delegate; private PluginClient pluginClient; + private ExecutorService responder; + private ActionListener capturedListener; + private String subjectSeenByDelegate; + private String callerSeenByDelegate; + private Consumer> delegateBehaviour; @BeforeEach public void setUp() { threadContext = new ThreadContext(Settings.EMPTY); + responder = Executors.newSingleThreadExecutor(); ThreadPool threadPool = mock(ThreadPool.class); when(threadPool.getThreadContext()).thenReturn(threadContext); - Client delegate = mock(Client.class); + delegate = mock(Client.class); when(delegate.settings()).thenReturn(Settings.EMPTY); when(delegate.threadPool()).thenReturn(threadPool); - // Captures the listener without invoking it, so each test decides when the action completes. + // Records the context the action ran in and keeps the listener, so each test decides when and + // how the action completes. By default it does not complete, as for an asynchronous action. + delegateBehaviour = listener -> {}; doAnswer(invocation -> { + subjectSeenByDelegate = threadContext.getTransient(SUBJECT_TRANSIENT); + callerSeenByDelegate = threadContext.getTransient(CALLER_TRANSIENT); capturedListener = invocation.getArgument(2); + delegateBehaviour.accept(capturedListener); return null; }).when(delegate).execute(any(ActionType.class), any(ActionRequest.class), any(ActionListener.class)); - pluginClient = new PluginClient(delegate); + pluginClient = new TestPluginClient(delegate); + } + + @AfterEach + public void tearDown() { + responder.shutdownNow(); } @Test - public void runsActionThroughTheAssignedSubject() { - RecordingSubject subject = assignSubject(null); + public void runsTheActionInsideTheSubject() { + threadContext.putTransient(CALLER_TRANSIENT, "set-by-caller"); + PluginClient preassigned = new TestPluginClient(delegate, new RecordingSubject(threadContext)); - pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ignoring()); + preassigned.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.noOp()); - assertEquals(1, subject.runAsInvocations); - assertNotNull(capturedListener, "delegate should have been reached"); + assertEquals("set-by-subject", subjectSeenByDelegate, "the action must run inside runAs"); + assertNull(callerSeenByDelegate, "the caller's context must not reach the action"); } @Test public void listenerSeesTheCallerContextAndNotTheSubjects() throws Exception { - threadContext.putTransient(CALLER_TRANSIENT, "set-by-caller"); - assignSubject(null); - - AtomicReference callerSeen = new AtomicReference<>("listener did not run"); - AtomicReference subjectSeen = new AtomicReference<>("listener did not run"); - pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> { - callerSeen.set(threadContext.getTransient(CALLER_TRANSIENT)); - subjectSeen.set(threadContext.getTransient(SUBJECT_TRANSIENT)); - }, e -> {})); - - // Completing on a separate thread is what makes this discriminate. A transport response - // arrives on a pooled thread that never carried the caller's context, so the wrapper around - // the listener is the only thing that can put it back. - completeOnAnotherThread(null); + assertListenerSeesCallerContext(listener -> listener.onResponse(new DummyResponse())); + } - assertEquals("set-by-caller", callerSeen.get()); - assertNull(subjectSeen.get(), "the subject's context must not leak into the listener"); + @Test + public void listenerSeesTheCallerContextOnFailure() throws Exception { + assertListenerSeesCallerContext(listener -> listener.onFailure(new RuntimeException("action failed"))); } @Test public void restoresTheRespondingThreadsContextAfterTheListenerReturns() throws Exception { threadContext.putTransient(CALLER_TRANSIENT, "set-by-caller"); - assignSubject(null); - - pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ignoring()); + assignSubject(); + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.noOp()); - // The responding thread marks itself, completes the action, then checks its own context once - // the listener has returned. Restoring the caller's context and leaving it there would strand - // it on a pooled thread for whatever runs next. + // Restoring the caller's context and leaving it there would strand it on a pooled thread for + // whatever runs next. AtomicReference responderAfter = new AtomicReference<>(); AtomicReference callerLeftBehind = new AtomicReference<>(); - completeOnAnotherThread(() -> { + completeOnAnotherThread(listener -> { + listener.onResponse(new DummyResponse()); responderAfter.set(threadContext.getTransient(RESPONDER_TRANSIENT)); callerLeftBehind.set(threadContext.getTransient(CALLER_TRANSIENT)); }); @@ -122,65 +137,141 @@ public void restoresTheRespondingThreadsContextAfterTheListenerReturns() throws } @Test - public void deliversSynchronousFailureToTheListenerRatherThanThrowing() { - RuntimeException boom = new RuntimeException("subject refused"); - assignSubject(boom); + public void listenerSeesResponseHeadersTheActionAdded() throws Exception { + assignSubject(); + AtomicReference> warnings = new AtomicReference<>(); + pluginClient + .execute( + DUMMY_ACTION, + new DummyRequest(), + ActionListener.wrap(r -> warnings.set(threadContext.getResponseHeaders().get("Warning")), e -> {}) + ); + + completeOnAnotherThread(listener -> { + threadContext.addResponseHeader("Warning", "deprecated"); + listener.onResponse(new DummyResponse()); + }); + + assertEquals(List.of("deprecated"), warnings.get()); + } - AtomicReference failure = new AtomicReference<>(); - // No assertThrows here on purpose: escaping synchronously would leave an async caller - // waiting forever, so the contract is that the listener is told. - pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, failure::set)); + @Test + public void throwsADelegateFailureToTheCallerAsTheWrappedClientWould() { + assignSubject(); + RuntimeException boom = new RuntimeException("failed to find action"); + delegateBehaviour = listener -> { throw boom; }; + + List failures = new ArrayList<>(); + RuntimeException thrown = assertThrows( + RuntimeException.class, + () -> pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(r -> {}, failures::add)) + ); - assertSame(boom, failure.get()); - assertNull(capturedListener, "delegate should not have been reached"); + assertSame(boom, thrown); + assertEquals(List.of(), failures, "a failure thrown before the listener exists must not also reach it"); + } + + @Test + public void doesNotNotifyAgainWhenTheListenerItselfThrows() { + assignSubject(); + delegateBehaviour = listener -> listener.onResponse(new DummyResponse()); + + RuntimeException listenerBug = new RuntimeException("listener bug"); + AtomicInteger calls = new AtomicInteger(); + ActionListener throwing = new ActionListener<>() { + @Override + public void onResponse(DummyResponse response) { + calls.incrementAndGet(); + throw listenerBug; + } + + @Override + public void onFailure(Exception e) { + calls.incrementAndGet(); + } + }; + + RuntimeException surfaced = assertThrows( + RuntimeException.class, + () -> pluginClient.execute(DUMMY_ACTION, new DummyRequest(), throwing) + ); + assertSame(listenerBug, surfaced); + assertEquals(1, calls.get(), "the listener must be told exactly once"); } @Test public void rejectsUseBeforeASubjectIsAssigned() { IllegalStateException e = assertThrows( IllegalStateException.class, - () -> pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ignoring()) + () -> pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.noOp()) ); - assertEquals("PluginClient is not initialized with a subject.", e.getMessage()); + assertTrue(e.getMessage().contains("subject")); } - private RecordingSubject assignSubject(RuntimeException failure) { - RecordingSubject subject = new RecordingSubject(threadContext, failure); + @Test + public void acceptsTheSameSubjectTwiceButRejectsADifferentOne() { + RecordingSubject first = assignSubject(); + pluginClient.setSubject(first); + + assertThrows(IllegalStateException.class, () -> pluginClient.setSubject(new RecordingSubject(threadContext))); + } + + @Test + public void rejectsANullSubject() { + assertThrows(NullPointerException.class, () -> pluginClient.setSubject(null)); + assertThrows(NullPointerException.class, () -> new TestPluginClient(delegate, null)); + } + + @Test + public void refusesARemoteClusterClient() { + assertThrows(UnsupportedOperationException.class, () -> pluginClient.getRemoteClusterClient("remote")); + } + + private void assertListenerSeesCallerContext(Consumer> completion) throws Exception { + threadContext.putTransient(CALLER_TRANSIENT, "set-by-caller"); + assignSubject(); + + AtomicReference callerSeen = new AtomicReference<>("listener did not run"); + AtomicReference subjectSeen = new AtomicReference<>("listener did not run"); + Consumer record = ignored -> { + callerSeen.set(threadContext.getTransient(CALLER_TRANSIENT)); + subjectSeen.set(threadContext.getTransient(SUBJECT_TRANSIENT)); + }; + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.wrap(record::accept, record::accept)); + + // A response arrives on a pooled thread that never carried the caller's context, so the wrapper + // around the listener is the only thing that can put it back. + completeOnAnotherThread(completion); + + assertEquals("set-by-caller", callerSeen.get()); + assertNull(subjectSeen.get(), "the subject's context must not leak into the listener"); + } + + private RecordingSubject assignSubject() { + RecordingSubject subject = new RecordingSubject(threadContext); pluginClient.setSubject(subject); return subject; } /** Completes the captured action on a thread that never carried the caller's context. */ - private void completeOnAnotherThread(Runnable afterListenerReturns) throws InterruptedException { - Thread responder = new Thread(() -> { + private void completeOnAnotherThread(Consumer> completion) throws Exception { + responder.submit(() -> { threadContext.putTransient(RESPONDER_TRANSIENT, "set-by-responder"); - capturedListener.onResponse(new DummyResponse()); - if (afterListenerReturns != null) { - afterListenerReturns.run(); - } - }); - responder.start(); - responder.join(); - } - - private static ActionListener ignoring() { - return ActionListener.wrap(r -> {}, e -> {}); + completion.accept(capturedListener); + }).get(10, TimeUnit.SECONDS); } /** - * Stands in for the security plugin's subject. Stashes and restores around its body the way both - * real implementations do, and marks the context so a test can tell the subject's apart from the + * Stands in for the plugin subject. Stashes and restores around its body as NoopPluginSubject and + * SecurePluginSubject do, and marks the context so a test can tell the subject's apart from the * caller's. */ - private static class RecordingSubject implements org.opensearch.identity.Subject { + private static class RecordingSubject implements PluginSubject { private final ThreadContext threadContext; - private final RuntimeException failure; - private int runAsInvocations; - RecordingSubject(ThreadContext threadContext, RuntimeException failure) { + RecordingSubject(ThreadContext threadContext) { this.threadContext = threadContext; - this.failure = failure; } @Override @@ -190,10 +281,6 @@ public Principal getPrincipal() { @Override public void runAs(CheckedRunnable runnable) throws E { - runAsInvocations++; - if (failure != null) { - throw failure; - } try (ThreadContext.StoredContext ignored = threadContext.stashContext()) { threadContext.putTransient(SUBJECT_TRANSIENT, "set-by-subject"); runnable.run(); @@ -201,6 +288,16 @@ public void runAs(CheckedRunnable runnable) throws E { } } + private static final class TestPluginClient extends PluginClient { + TestPluginClient(Client delegate) { + super(delegate); + } + + TestPluginClient(Client delegate, PluginSubject subject) { + super(delegate, subject); + } + } + private static class DummyRequest extends ActionRequest { @Override public ActionRequestValidationException validate() { From bf0532130cd77e97948945ece0ce752eb37e4a89 Mon Sep 17 00:00:00 2001 From: Darshit Chanpura Date: Thu, 22 Oct 2026 21:44:49 +0000 Subject: [PATCH 4/4] Check PluginClient's subject in one atomic step and pin down two tests - setSubject reads the current value with compareAndExchange instead of compareAndSet followed by get. Both are correct because the subject is never reset, but the new form does not depend on that. - The set-once test now asserts that a rejected second subject does not replace the first. A version that overwrote the subject and then threw passed every test before this change. - The remote-client test now has the delegate hand out a remote client, so only PluginClient's own refusal can make it throw. Before, it relied on Mockito returning null. - Document the NullPointerException that setSubject and the two-argument constructor throw for a null subject. Verified: build passes (749 tests). Overwriting then throwing, plain assignment, throwing on the same subject, accepting null, and forwarding the remote client each fail exactly one test, the intended one. Signed-off-by: Darshit Chanpura --- .../opensearch/commons/client/PluginClient.java | 5 ++++- .../commons/client/PluginClientTests.java | 17 +++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/opensearch/commons/client/PluginClient.java b/src/main/java/org/opensearch/commons/client/PluginClient.java index 78e297fc..cbe3fba3 100644 --- a/src/main/java/org/opensearch/commons/client/PluginClient.java +++ b/src/main/java/org/opensearch/commons/client/PluginClient.java @@ -58,6 +58,7 @@ protected PluginClient(Client delegate) { * * @param delegate the client whose actions this wraps * @param subject the plugin's system subject + * @throws NullPointerException if the subject is null */ protected PluginClient(Client delegate, PluginSubject subject) { super(delegate); @@ -69,11 +70,13 @@ protected PluginClient(Client delegate, PluginSubject subject) { * again is a no-op. * * @param subject the plugin's system subject, normally the one passed to {@code assignSubject} + * @throws NullPointerException if the subject is null * @throws IllegalStateException if a different subject is already assigned */ public final void setSubject(PluginSubject subject) { Objects.requireNonNull(subject, "subject"); - if (!this.subject.compareAndSet(null, subject) && this.subject.get() != subject) { + PluginSubject existing = this.subject.compareAndExchange(null, subject); + if (existing != null && existing != subject) { throw new IllegalStateException("PluginClient already has a subject assigned."); } } diff --git a/src/test/java/org/opensearch/commons/client/PluginClientTests.java b/src/test/java/org/opensearch/commons/client/PluginClientTests.java index b0ce5670..00509836 100644 --- a/src/test/java/org/opensearch/commons/client/PluginClientTests.java +++ b/src/test/java/org/opensearch/commons/client/PluginClientTests.java @@ -213,7 +213,11 @@ public void acceptsTheSameSubjectTwiceButRejectsADifferentOne() { RecordingSubject first = assignSubject(); pluginClient.setSubject(first); - assertThrows(IllegalStateException.class, () -> pluginClient.setSubject(new RecordingSubject(threadContext))); + assertThrows(IllegalStateException.class, () -> pluginClient.setSubject(new RecordingSubject(threadContext, "second"))); + + // The rejected subject must not have replaced the first one. + pluginClient.execute(DUMMY_ACTION, new DummyRequest(), ActionListener.noOp()); + assertEquals("set-by-subject", subjectSeenByDelegate); } @Test @@ -224,6 +228,9 @@ public void rejectsANullSubject() { @Test public void refusesARemoteClusterClient() { + // The delegate does hand out a remote client, so only PluginClient's own refusal can make this throw. + when(delegate.getRemoteClusterClient("remote")).thenReturn(mock(Client.class)); + assertThrows(UnsupportedOperationException.class, () -> pluginClient.getRemoteClusterClient("remote")); } @@ -269,9 +276,15 @@ private void completeOnAnotherThread(Consumer> com private static class RecordingSubject implements PluginSubject { private final ThreadContext threadContext; + private final String marker; RecordingSubject(ThreadContext threadContext) { + this(threadContext, "set-by-subject"); + } + + RecordingSubject(ThreadContext threadContext, String marker) { this.threadContext = threadContext; + this.marker = marker; } @Override @@ -282,7 +295,7 @@ public Principal getPrincipal() { @Override public void runAs(CheckedRunnable runnable) throws E { try (ThreadContext.StoredContext ignored = threadContext.stashContext()) { - threadContext.putTransient(SUBJECT_TRANSIENT, "set-by-subject"); + threadContext.putTransient(SUBJECT_TRANSIENT, marker); runnable.run(); } }