Skip to content

Add a shared PluginClient for running actions as a plugin's system subject - #1023

Merged
cwperks merged 4 commits into
opensearch-project:mainfrom
DarshitChanpura:centralize-plugin-client
Oct 29, 2026
Merged

cwperks merged 4 commits into
opensearch-project:mainfrom
DarshitChanpura:centralize-plugin-client

Conversation

@DarshitChanpura

@DarshitChanpura DarshitChanpura commented Oct 6, 2026 •

Copy link
Copy Markdown
Member

Description

Adds PluginClient, a base class that runs transport actions as the plugin subject that core assigns through IdentityAwarePlugin. Plugins moving off ThreadContext.stashContext can extend it instead of each writing their own copy.

A stashed context carries no user. The security plugin lets a local request with no user through without evaluating privileges. The plugin subject is authorized only for the plugin's own registered system indices and the permissions it declares.

Apart from the identity it runs as, the client behaves like the client it wraps. Failures that core reports through the listener still reach the listener. The synchronous throws that NodeClient makes to every caller, such as failed to find action, are still thrown.

Design decisions

One subclass per plugin. The class is abstract, and setSubject, doExecute and getRemoteClusterClient are final. Core binds every component returned from createComponents by its runtime class. Plugins that share a classloader through extendedPlugins share this class. With a shared concrete type, one plugin could inject another plugin's client and run as its subject. A one-line subclass per plugin gives each plugin its own binding:

final class FlowFrameworkPluginClient extends PluginClient { ... }

PluginSubject, not Subject. Subject.runAs runs inline by default, and the security plugin's User implements Subject. Passing the current user's subject would therefore run actions as that user with no error. Only core-assigned plugin subjects implement PluginSubject.

Set once. The subject can be assigned once, and null is rejected. Assigning the same subject again is a no-op.

Restoring the caller's context. The client uses core's ContextPreservingActionListener.wrapPreservingContext. It restores the caller's context around the callback and then puts the responding thread's own context back. It also keeps response headers the action added. The per-plugin copies pair newStoredContext(false) with ActionListener.runBefore. That approach puts the caller's context on the responding thread and never removes it, and it drops response headers. Moving a plugin onto this class is therefore a small behaviour improvement, not an exact copy of its old behaviour. Each migration PR should say so.

No remote cluster client. FilterClient.getRemoteClusterClient returns the delegate's remote client unwrapped, and that client does not run as the subject. A plugin subject is authorized by the local cluster's security plugin, so it has no meaning on another cluster. The method throws UnsupportedOperationException.

Two differences between the existing per-plugin copies look like bugs but are not. Using stashContext() instead of newStoredContext(false) makes no observable difference, because runAs stashes the context first. Wrapping the asynchronous call in try-with-resources makes no difference either, because both SecurePluginSubject.runAs and core's NoopPluginSubject.runAs already stash and restore around their own body.

Not changed here

SecureClientWrapper in this repository is not replaced or deprecated. It still has a caller in NotificationsPluginInterface.sendNotification, and it keeps the tenant header across the stash, which this class does not do.

Testing

build passes: 749 unit tests, no failures.

Each PluginClient test was confirmed to fail against the mutant it guards, and to be the only failure. The mutants were:

  • running the action outside runAs
  • adding back a catch that sends synchronous failures to the listener
  • dropping response headers
  • assigning the subject without checks
  • returning the remote client
  • passing the raw listener
  • the previous newStoredContext plus runBefore form
  • overwriting the subject and then throwing, so a rejected subject replaces the first

The fake subject in the tests stashes and restores around its body, like both real implementations. A fake that does not do this reports failures against variants that behave the same in production.

One check is needed when plugins adopt the class. Two plugins mock their local PluginClient in tests. Mockito 5 mocks abstract classes, so this should work, but each plugin's resolved Mockito version should be confirmed.

Related

Tracking issue: opensearch-project/opensearch-plugins#238
RFC: opensearch-project/security#4439

A later improvement would move this class into core next to FilterClient, and add a createComponents overload that supplies the PluginSubject. The subject could then be final, which would remove the setter and the unassigned-subject check.

Check List

  • New functionality includes testing.
  • Commits are signed per the DCO using --signoff.

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

…bject

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 <dchanp@amazon.com>
@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit bf05321)

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ No major issues detected

@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to bf05321

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Document reference-equality semantics for subject assignment

The constructor PluginClient(Client, PluginSubject) calls setSubject before the
object is fully constructed, and setSubject throws IllegalStateException on
conflict. Since compareAndExchange returns the previous value (null on first call),
the current logic is correct, but consider documenting that setSubject is safe to
call from a constructor, or guard against re-entrancy issues if subclasses override
behavior. More importantly, the check existing != subject uses reference equality
which is intentional but should be clearly documented so callers don't pass
equal-but-not-same subjects.

src/main/java/org/opensearch/commons/client/PluginClient.java [76-82]

 public final void setSubject(PluginSubject subject) {
     Objects.requireNonNull(subject, "subject");
+    // Reference equality: assigning the exact same instance twice is a no-op; any other
+    // instance (even one that is .equals) is treated as a conflict.
     PluginSubject existing = this.subject.compareAndExchange(null, subject);
     if (existing != null && existing != subject) {
         throw new IllegalStateException("PluginClient already has a subject assigned.");
     }
 }
Suggestion importance[1-10]: 2

__

Why: The suggestion only adds a comment documenting existing behavior without changing any logic. It's a minor documentation improvement with low impact.

Low

Previous suggestions

Suggestions up to commit 6a1eb36
CategorySuggestion                                                                                                                                    Impact
General
Fix race in idempotent subject assignment

The current logic has a race: if two threads call setSubject with different subjects
concurrently, the second thread's compareAndSet fails, then this.subject.get() may
read the first thread's value which could equal its own only by coincidence; more
importantly, a successful CAS followed by another thread's CAS failure+get can read
the just-set value and mistakenly treat it as idempotent. Use the return value of
the CAS plus a single read to make the check deterministic.

src/main/java/org/opensearch/commons/client/PluginClient.java [74-79]

 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.");
     }
 }
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies a subtle race condition where the compareAndSet + get pattern is not atomic, and compareAndExchange provides a cleaner, deterministic check. However, the practical impact is minor since setSubject is typically called once from assignSubject during initialization, not concurrently.

Low
Suggestions up to commit 50872ed
CategorySuggestion                                                                                                                                    Impact
General
Preserve caller context on failure path

When runAs fails, the failure is reported to the raw listener without the caller's
thread context restored, while a successful path routes through callerContext. This
inconsistency means onFailure callbacks won't see caller transients/headers. Report
the failure through callerContext so context-preservation is symmetric for success
and failure.

src/main/java/org/opensearch/commons/client/PluginClient.java [100-108]

 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);
+    callerContext.onFailure(e);
 }
Suggestion importance[1-10]: 7

__

Why: Valid observation: using callerContext.onFailure(e) instead of listener.onFailure(e) would make context preservation symmetric for success and failure paths. However, since the synchronous failure occurs on the caller's thread (which still has the caller's context), the practical impact is limited, but it's still a correctness/consistency improvement.

Medium
Suggestions up to commit 9203011
CategorySuggestion                                                                                                                                    Impact
Possible issue
Avoid potential double listener notification

If super.doExecute throws synchronously after wrapping the listener with
ActionListener.runBefore, the catch block will call listener.onFailure(e) while the
stored context may already have been restored (or will be restored again via
storedContext.close()), and more importantly the listener may be invoked twice if
the inner call partially completed. Additionally, if runAs throws after invoking the
wrapped listener, calling listener.onFailure again would be a double-notify. Guard
against double invocation by only treating exceptions thrown before the delegate
call as listener failures.

src/main/java/org/opensearch/commons/client/PluginClient.java [70-79]

 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();
+    try {
+        storedContext.restore();
+    } catch (Exception ignored) {}
     listener.onFailure(e);
 }
Suggestion importance[1-10]: 3

__

Why: The concern about double listener invocation is theoretically valid if super.doExecute throws after partially notifying the listener, but the suggested fix (replacing storedContext.close() with storedContext.restore()) does not actually address the double-notify issue it raises. The improvement is marginal and potentially misleading.

Low

@codecov

codecov Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.61%. Comparing base (3a69aab) to head (bf05321).
⚠️ Report is 123 commits behind head on main.

❌ Your project check has failed because the head coverage (70.61%) is below the target coverage (75.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #1023      +/-   ##
============================================
- Coverage     73.97%   70.61%   -3.37%     
- Complexity      916     1157     +241     
============================================
  Files           135      176      +41     
  Lines          6102     7994    +1892     
  Branches        753      958     +205     
============================================
+ Hits           4514     5645    +1131     
- Misses         1253     1949     +696     
- Partials        335      400      +65     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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 <dchanp@amazon.com>
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 50872ed

…ed 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 <dchanp@amazon.com>
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 6a1eb36

@cwperks

cwperks commented Oct 19, 2026

Copy link
Copy Markdown
Member

@DarshitChanpura is there anything remaining before taking this out of draft?

- 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 <dchanp@amazon.com>
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit bf05321

@DarshitChanpura

Copy link
Copy Markdown
Member Author

Nothing remaining on this one, so I've marked it ready for review.

Testing the plugin migrations against it turned up two changes in the security plugin. Neither blocks this class:

@cwperks cwperks left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

btw one thing I want to work on in the future is naming when it comes to these kinds of things. In OSD we have a notion of internal user scoped client (conventionally kibanauser for getting some dynamic dashboards info from the backend) and then user scoped client for making requests with the user's credentials to the backend.

The purpose of this PluginSubject is to move more towards zero-trust for plugins where plugins have to explicitly request permissions to do things rather then having blanket system-level access.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants