Repository navigation
Add a shared PluginClient for running actions as a plugin's system subject - #1023
Conversation
…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>
PR Reviewer Guide 🔍(Review updated until commit bf05321)Here are some key observations to aid the review process:
|
PR Code Suggestions ✨Latest suggestions up to bf05321 Explore these optional code suggestions:
Previous suggestionsSuggestions up to commit 6a1eb36
Suggestions up to commit 50872ed
Suggestions up to commit 9203011
|
Codecov Report✅ All modified and coverable lines are covered by tests. ❌ 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. 🚀 New features to boost your workflow:
|
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>
|
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>
|
Persistent review updated to latest commit 6a1eb36 |
|
@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>
|
Persistent review updated to latest commit bf05321 |
|
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
left a comment
There was a problem hiding this comment.
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.
Description
Adds
PluginClient, a base class that runs transport actions as the plugin subject that core assigns throughIdentityAwarePlugin. Plugins moving offThreadContext.stashContextcan 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
NodeClientmakes to every caller, such asfailed to find action, are still thrown.Design decisions
One subclass per plugin. The class is abstract, and
setSubject,doExecuteandgetRemoteClusterClientare final. Core binds every component returned fromcreateComponentsby its runtime class. Plugins that share a classloader throughextendedPluginsshare 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:PluginSubject, notSubject.Subject.runAsruns inline by default, and the security plugin'sUserimplementsSubject. Passing the current user's subject would therefore run actions as that user with no error. Only core-assigned plugin subjects implementPluginSubject.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 pairnewStoredContext(false)withActionListener.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.getRemoteClusterClientreturns 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 throwsUnsupportedOperationException.Two differences between the existing per-plugin copies look like bugs but are not. Using
stashContext()instead ofnewStoredContext(false)makes no observable difference, becauserunAsstashes the context first. Wrapping the asynchronous call in try-with-resources makes no difference either, because bothSecurePluginSubject.runAsand core'sNoopPluginSubject.runAsalready stash and restore around their own body.Not changed here
SecureClientWrapperin this repository is not replaced or deprecated. It still has a caller inNotificationsPluginInterface.sendNotification, and it keeps the tenant header across the stash, which this class does not do.Testing
buildpasses: 749 unit tests, no failures.Each
PluginClienttest was confirmed to fail against the mutant it guards, and to be the only failure. The mutants were:runAsnewStoredContextplusrunBeforeformThe 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
PluginClientin 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 acreateComponentsoverload that supplies thePluginSubject. The subject could then be final, which would remove the setter and the unassigned-subject check.Check List
--signoff.By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.