Skip to content

Keep plugin reads of their own system index realtime - #6668

Merged
DarshitChanpura merged 3 commits into
opensearch-project:mainfrom
DarshitChanpura:plugin-subject-realtime-get
Nov 4, 2026
Merged

DarshitChanpura merged 3 commits into
opensearch-project:mainfrom
DarshitChanpura:plugin-subject-realtime-get

Conversation

@DarshitChanpura

@DarshitChanpura DarshitChanpura commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Description

GET on a plugin's own system index is not realtime under the plugin subject.

  • Category: Bug fix

  • Why these changes are required?

    Plugins are moving their system index reads and writes from ThreadContext.stashContext() to the plugin subject (PluginSubject.runAs). Under a stashed context the transient user is null, so SecurityFilter does not evaluate the request, and a GET or multi-get keeps its default realtime=true. Under the plugin subject the request is evaluated. With the default legacy privileges evaluator, SystemIndexAccessEvaluator.evaluate then sets realtime(false) and requestCache(false) on every request that touches the security index or a system index. A plugin that indexes a document without a refresh and reads it back by id gets "not found" until the next refresh. Plugin integration tests that create and then get a document fail on this after the move.

  • Why the override exists

    The block came in with the first release of this plugin for the security index. It was extended to protected indices in opendistro-for-elasticsearch/security PR 126 and to system indices in opendistro-for-elasticsearch/security PR 690. Each change added the override together with a rule in the index searcher wrapper (SystemIndexSearcherWrapper): an empty reader on the security index for anyone but the admin, on protected indices for users without a protected index role, and on system indices for users without system index access. DlsFlsValveImpl turns realtime off for the same reason when DLS, FLS or field masking applies.

    • A realtime GET of a document that has not been refreshed yet is read from the translog (InternalEngine.get, TranslogLeafReader). The index searcher wrappers do not apply to that read. Turning realtime off makes the GET read through the wrapped reader, so it returns what a search would return for the same user.
    • The shard request cache key is the reader and the request. It does not include the user, and the wrappers keep the cache key of the underlying reader. Turning the cache off keeps a result computed through one user's reader from being returned to another user.

    The nextgen (v4) evaluator has no such override. Its authorization denies or removes indices that the user has no privileges for before the request runs.

  • What is the old behavior before changes and new behavior after changes?

    Before: under the legacy evaluator, a GET, multi-get or size 0 search by a plugin subject on its own system index is not realtime and does not use the request cache.

    After: the legacy evaluator keeps realtime and the request cache for a request from a plugin subject when every requested index is one of the plugin's own registered system indices, the request is not _all, and none of the indices is the security index or a protected index. For such a request the wrappers return the full reader: isAdminDnOrPluginRequest() lets the plugin through the system index rule, and DlsFlsBaseContext has no DLS or FLS context for plugin requests. A realtime read or a cached result therefore returns the same documents as a non-realtime read. Everything else keeps the override:

    • normal users on system indices and on the security index
    • a plugin subject on another plugin's system index (the evaluator denies this before the override)
    • a plugin subject on a request that also names an index that is not its own
    • a plugin's own system index that is also a protected index, because the wrapper gives the plugin subject an empty reader there unless it has a protected index role

    The check uses the plugin's matching indices that the evaluator already computes for its authorization decision. That set is now computed once in evaluate and passed down.

    Not changed:

    • ProtectedIndexAccessEvaluator and DlsFlsValveImpl. A plugin subject's index action on its own system indices returns from SystemIndexAccessEvaluator before ProtectedIndexAccessEvaluator runs, and DlsFlsValveImpl returns early for plugin requests. Its resource sharing branch rewrites only SearchRequest, so a GET is not affected. For a search on a resource index, the resource sharing filter is part of the query, so it is part of the request cache key.
    • With system index protection disabled, the override already applied only to the security index.
    • The nextgen evaluator.
    • Multi-get is evaluated as a cluster permission, so a plugin needs indices:data/read/mget in its declared permissions to use it. With system index permissions enabled it is also denied on the plugin's own system index unless the plugin declares the system index permission for it. Both are current behaviour.

Issues Resolved

None filed.

Testing

New integration tests, all run against a real cluster with refresh disabled on the index so that only a realtime read sees an unrefreshed document:

  • PluginSystemIndexRealtimeIntTests, parameterized over the legacy evaluator, the legacy evaluator with system index permissions, and v4 (21 cases):
    • a plugin subject indexes a document and reads it back by id with GET and with multi-get, and sees it
    • a plugin subject's size 0 search on its own index is served from the request cache on repeat
    • controls: a normal user with system index access gets "not found" for an unrefreshed document and no request cache hits under the legacy evaluator (both found and cached under v4); a multi-get by the plugin subject that also names a regular index stays non-realtime under the legacy evaluator; a plugin subject's GET on another plugin's system index is denied
  • PluginProtectedSystemIndexRealtimeIntTests: a plugin's own system index that is also a protected index stays non-realtime for the plugin subject.
  • SystemIndexDisabledTests: with system index protection disabled, the plugin subject's GET on its own index is realtime (it was before this change too).
  • PluginReadAfterWriteTests in the sample resource plugin, with resource sharing enabled: the plugin's GET of a resource by id returns an update that has not been refreshed.
  • SystemIndexAccessEvaluatorPluginSubjectTest (unit): one case per condition of the check (own indices, own and regular index, _all, the security index, a protected index).

The test plugin declares indices:data/read/mget and read access to the regular index in a test plugin-additional-permissions.yml, as real plugins declare what they read. The file is in src/integrationTest/plugin-permissions, which is on the class path of the root integration tests only. The sample resource plugin's integration tests load the root integration test output, and the security plugin reads the first plugin-additional-permissions.yml on the plugin's class path, so a copy in src/integrationTest/resources would replace the sample plugin's own file.

Without the change in SystemIndexAccessEvaluator, 5 cases of PluginSystemIndexRealtimeIntTests, PluginReadAfterWriteTests and the own index unit case fail; with it all pass. Each control was checked by breaking the check: turning the system index override off for every user fails the 4 normal user cases and the mixed multi-get case, dropping the "every index" condition fails the mixed multi-get case and its unit case, dropping the protected index condition fails PluginProtectedSystemIndexRealtimeIntTests and its unit case, and dropping the _all or security index condition fails its unit case. In the legacy configuration without system index permissions, skipping the override for every user makes a normal user's GET return a document that the same user's search does not return.

Check List

  • New functionality includes testing
  • New functionality has been documented
  • New Roles/Permissions have a corresponding security dashboards plugin PR
  • API changes companion pull request created
  • 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.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

The legacy privileges evaluator turns off realtime gets and the search
request cache for every request on the security index or a system
index. A realtime get of an unrefreshed document is read from the
translog, which the security index searcher wrappers do not filter,
and the request cache key does not include the user.

For a plugin subject the wrappers do not filter its own system
indices, unless they are protected indices. So a GET or multi-get by
the plugin subject on its own system index missed a write made just
before it until the next refresh, which did not happen when plugins
read under a stashed thread context.

Keep realtime and the request cache when a plugin subject requests
only its own registered system indices, not as _all, and none of them
is the security index or a protected index. All other requests keep
the override.

Signed-off-by: Darshit Chanpura <dchanp@amazon.com>
@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit ee0d655)

Here are some key observations to aid the review process:

🧪 PR contains tests
🔒 No security concerns identified
✅ No TODO sections
🔀 No multiple PR themes
⚡ Recommended focus areas for review

Protected-index check scope

protectedIndexMatcher.matchAny(requestedResolved.getAllIndices()) only short-circuits realtime/request-cache suppression when none of the resolved indices is protected. If the plugin's own system index name matches a protected index pattern, realtime and request cache remain disabled for the plugin, which matches the stated intent and the protected-index integration test. However, this also means that for any non-plugin request where resolved indices contain a system index but no protected index, the new condition (requestContainsAnySystemIndices && !ownUnprotectedSystemIndicesOnly) behaves exactly as before only if ownUnprotectedSystemIndicesOnly is false — confirm the composite boolean cannot inadvertently become true for non-plugin users (it depends on getMatchingPluginIndices returning empty for non-plugin users, which it does, so this is likely safe but worth a careful review).

// A realtime get of an unrefreshed document reads the translog, which the security index searcher wrappers do
// not filter, and the request cache key does not include the user. The wrappers do not filter a plugin's reads
// of its own system indices unless they are protected, so those reads keep realtime and the request cache.
final boolean ownUnprotectedSystemIndicesOnly = containsOnlyPluginSystemIndices(requestedResolved, matchingPluginIndices)
    && !protectedIndexMatcher.matchAny(requestedResolved.getAllIndices());
if (requestedResolved.isLocalAll()
    || requestedResolved.getAllIndices().contains(securityIndex)
    || (requestContainsAnySystemIndices(requestedResolved) && !ownUnprotectedSystemIndicesOnly)) {

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to ee0d655

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Ensure refresh interval reset always runs

If the initial _settings call to disable refresh fails, the try/finally is not
entered and the refresh interval is never reset, leaking state to other tests
sharing this @ClassRule cluster. Move the refresh-disable call inside the try (or
use a surrounding try/finally that covers it) so the reset always runs.

sample-resource-plugin/src/integrationTest/java/org/opensearch/sample/resource/feature/enabled/PluginReadAfterWriteTests.java [53-67]

-try {
-    HttpResponse response = api.getResource(resourceId, FULL_ACCESS_USER);
-    response.assertStatusCode(HttpStatus.SC_OK);
-    assertThat(response.getBody(), containsString("renamed"));
-} finally {
-    try (TestRestClient client = cluster.getRestClient(cluster.getAdminCertificate())) {
+try (TestRestClient client = cluster.getRestClient(cluster.getAdminCertificate())) {
+    client.putJson(RESOURCE_INDEX_NAME + "/_settings", "{\"index.refresh_interval\":\"-1\"}").assertStatusCode(HttpStatus.SC_OK);
+    try {
+        client.postJson(RESOURCE_INDEX_NAME + "/_update/" + resourceId, "{\"doc\":{\"name\":\"renamed\"}}")
+            .assertStatusCode(HttpStatus.SC_OK);
+        HttpResponse response = api.getResource(resourceId, FULL_ACCESS_USER);
+        response.assertStatusCode(HttpStatus.SC_OK);
+        assertThat(response.getBody(), containsString("renamed"));
+    } finally {
         client.putJson(RESOURCE_INDEX_NAME + "/_settings", "{\"index.refresh_interval\":null}").assertStatusCode(HttpStatus.SC_OK);
     }
 }
Suggestion importance[1-10]: 6

__

Why: Valid point about test state leaking if the initial refresh-disable call fails. The suggestion improves test isolation by ensuring the reset always runs, though the current code would also be guarded if the setup call throws (test fails and state isn't reset either way).

Low
Avoid NPE on multi-get response

item.getFailure().getFailure() returns Exception, but sendFailure expects Exception
fine — however getFailure().getFailure() can return a Throwable that is not an
Exception on some paths; also, accessing response.getResponses()[0].getResponse()
without checking non-null can NPE if the first item was skipped or omitted. Guard
against a null getResponse() to avoid an NPE that would be returned to clients as an
opaque 500.

src/integrationTest/java/org/opensearch/security/systemindex/sampleplugin/RestWriteThenReadOnSystemIndexAction.java [90-98]

 pluginClient.multiGet(multiGetRequest, ActionListener.wrap(response -> {
     for (MultiGetItemResponse item : response.getResponses()) {
         if (item.isFailed()) {
             sendFailure(channel, item.getFailure().getFailure());
             return;
         }
     }
-    sendFound(channel, response.getResponses()[0].getResponse().isExists());
+    var first = response.getResponses()[0].getResponse();
+    sendFound(channel, first != null && first.isExists());
 }, e -> sendFailure(channel, e)));
Suggestion importance[1-10]: 4

__

Why: Minor defensive programming suggestion. In practice, if the item is not failed, getResponse() should be non-null, so the NPE risk is low. The improvement is marginal for a test helper.

Low

Previous suggestions

Suggestions up to commit d1bdf3f
CategorySuggestion                                                                                                                                    Impact
General
Ensure refresh interval is always restored

If the assertThat assertion in the try block fails (e.g., status code mismatch
throws before containsString), the index.refresh_interval reset in finally runs, but
if the initial putJson to disable refresh succeeds and a subsequent setup line
throws, the refresh interval is left at -1, polluting other tests. Move the
refresh-disabling setup inside the try block so the finally reliably restores it.

sample-resource-plugin/src/integrationTest/java/org/opensearch/sample/resource/feature/enabled/PluginReadAfterWriteTests.java [53-67]

-try (TestRestClient client = cluster.getRestClient(cluster.getAdminCertificate())) {
-    client.putJson(RESOURCE_INDEX_NAME + "/_settings", "{\"index.refresh_interval\":\"-1\"}").assertStatusCode(HttpStatus.SC_OK);
-    client.postJson(RESOURCE_INDEX_NAME + "/_update/" + resourceId, "{\"doc\":{\"name\":\"renamed\"}}")
-        .assertStatusCode(HttpStatus.SC_OK);
-}
+try {
+    try (TestRestClient client = cluster.getRestClient(cluster.getAdminCertificate())) {
+        client.putJson(RESOURCE_INDEX_NAME + "/_settings", "{\"index.refresh_interval\":\"-1\"}").assertStatusCode(HttpStatus.SC_OK);
+        client.postJson(RESOURCE_INDEX_NAME + "/_update/" + resourceId, "{\"doc\":{\"name\":\"renamed\"}}")
+            .assertStatusCode(HttpStatus.SC_OK);
+    }
 
-try {
     HttpResponse response = api.getResource(resourceId, FULL_ACCESS_USER);
     response.assertStatusCode(HttpStatus.SC_OK);
     assertThat(response.getBody(), containsString("renamed"));
 } finally {
     try (TestRestClient client = cluster.getRestClient(cluster.getAdminCertificate())) {
         client.putJson(RESOURCE_INDEX_NAME + "/_settings", "{\"index.refresh_interval\":null}").assertStatusCode(HttpStatus.SC_OK);
     }
 }
Suggestion importance[1-10]: 5

__

Why: Valid test hygiene improvement: moving the setup inside the try/finally ensures the refresh interval is reliably restored even if an assertion in setup fails, preventing test pollution. Minor impact as the current setup is unlikely to throw.

Low
Verify system index registry reset works

Constructing a new SystemIndices(Map.of()) instance in @After likely does not reset
any shared/static registry state used by
SystemIndexRegistry.matchesPluginSystemIndexPattern. If this is relying on a static
side-effect from the SystemIndices constructor, confirm that behaviour; otherwise
tests may bleed registered plugin patterns across test methods and across other test
classes, producing flaky results.

src/test/java/org/opensearch/security/privileges/actionlevel/legacy/SystemIndexAccessEvaluatorPluginSubjectTest.java [69-71]

 @After
 public void resetSystemIndexRegistry() {
+    // Ensure this actually clears the registry consulted by SystemIndexRegistry; otherwise state leaks between tests.
     new SystemIndices(Map.of());
 }
Suggestion importance[1-10]: 3

__

Why: This is a verify-only suggestion with no concrete fix, and the improved_code is essentially identical to existing_code with just an added comment. Low value.

Low
Possible issue
Avoid NPE on multi-get response

item.getFailure().getFailure() returns an Exception, but sendFailure accepts
Exception; however getFailure() on MultiGetItemResponse.Failure returns
Exception-typed cause which may be null in some paths. More importantly, after the
loop, if the first response is itself a failure case where getResponse() can be null
for non-existent indices, calling .isExists() will NPE. Guard against a null
response before dereferencing.

src/integrationTest/java/org/opensearch/security/systemindex/sampleplugin/RestWriteThenReadOnSystemIndexAction.java [90-98]

 pluginClient.multiGet(multiGetRequest, ActionListener.wrap(response -> {
     for (MultiGetItemResponse item : response.getResponses()) {
         if (item.isFailed()) {
             sendFailure(channel, item.getFailure().getFailure());
             return;
         }
     }
-    sendFound(channel, response.getResponses()[0].getResponse().isExists());
+    MultiGetItemResponse first = response.getResponses()[0];
+    sendFound(channel, first.getResponse() != null && first.getResponse().isExists());
 }, e -> sendFailure(channel, e)));
Suggestion importance[1-10]: 4

__

Why: The null-check guard is defensive; in the test context (document just indexed before mget), getResponse() would not be null. The suggestion adds minor robustness but is low impact for a test helper.

Low
Suggestions up to commit 6a458ac
CategorySuggestion                                                                                                                                    Impact
General
Harden plugin-only shortcut against _all requests

containsOnlyPluginSystemIndices returns true when getAllIndices() equals the
plugin's matched indices, but this can include _all/wildcards that isLocalAll()
would flag. The current ordering with isLocalAll() first mitigates it, but also
ensure the plugin-only shortcut does not apply when the request originally used _all
by checking !requestedResolved.isLocalAll() explicitly in
containsOnlyPluginSystemIndices to avoid regressions if evaluation order changes.

src/main/java/org/opensearch/security/privileges/actionlevel/legacy/SystemIndexAccessEvaluator.java [194-198]

-final boolean ownUnprotectedSystemIndicesOnly = containsOnlyPluginSystemIndices(requestedResolved, matchingPluginIndices)
+final boolean ownUnprotectedSystemIndicesOnly = !requestedResolved.isLocalAll()
+    && containsOnlyPluginSystemIndices(requestedResolved, matchingPluginIndices)
     && !protectedIndexMatcher.matchAny(requestedResolved.getAllIndices());
 if (requestedResolved.isLocalAll()
     || requestedResolved.getAllIndices().contains(securityIndex)
     || (requestContainsAnySystemIndices(requestedResolved) && !ownUnprotectedSystemIndicesOnly)) {
Suggestion importance[1-10]: 4

__

Why: The existing isLocalAll() check already handles the _all case first, so the proposed change is defensive but not currently necessary; it adds minor robustness against future reordering.

Low
Possible issue
Guard against null response in multi-get handler

After checking for item failures, response.getResponses()[0].getResponse() can still
be null if the first item was a failure path that was not caught (e.g., a partial
item without an exception), causing a NullPointerException. Guard against a null
getResponse() before calling isExists() to make the handler robust.

src/integrationTest/java/org/opensearch/security/systemindex/sampleplugin/RestWriteThenReadOnSystemIndexAction.java [90-98]

 pluginClient.multiGet(multiGetRequest, ActionListener.wrap(response -> {
     for (MultiGetItemResponse item : response.getResponses()) {
         if (item.isFailed()) {
             sendFailure(channel, item.getFailure().getFailure());
             return;
         }
     }
-    sendFound(channel, response.getResponses()[0].getResponse().isExists());
+    MultiGetItemResponse first = response.getResponses()[0];
+    sendFound(channel, first.getResponse() != null && first.getResponse().isExists());
 }, e -> sendFailure(channel, e)));
Suggestion importance[1-10]: 3

__

Why: This is test-only code and the scenario of a non-failed item with null getResponse() is unlikely in practice; the suggestion offers minor defensive hardening.

Low

@cwperks

cwperks commented Oct 23, 2026

Copy link
Copy Markdown
Member

@DarshitChanpura when this happens I think that plugins should generally use RefreshPolicy.IMMEDIATE on writes to a system index. They are low volume enough writes that RefreshPolicy.IMMEDIATE is justified IMO.

The security plugin reads the first plugin-additional-permissions.yml
on a plugin's class path. The sample resource plugin's integration
tests load the root integration test output before the sample plugin's
own resources, so the root test plugin's file replaced the sample
plugin's file and its plugin subject lost its cluster permissions.

Move the root file to src/integrationTest/plugin-permissions, which is
on the root integration test class path only.

Signed-off-by: Darshit Chanpura <dchanp@amazon.com>
Signed-off-by: Darshit Chanpura <dchanp@amazon.com>
@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit d1bdf3f

@DarshitChanpura

Copy link
Copy Markdown
Member Author

Agreed that plugins should set a refresh policy on their writes to system indices. Those writes are low volume, and IMMEDIATE (or WAIT_UNTIL) is what makes a write visible to a search. A search is never realtime, so a plugin that searches right after it writes needs the refresh policy either way.

I'd still like to keep this change for GETs. Without the security plugin, a GET by id is realtime, so a plugin can read its own write with no refresh. Under a plugin subject the legacy evaluator makes that same GET non-realtime, so code that works with security off misses the write with security on, and nothing reports it. Covering that only through refresh policies means every write path in every plugin has to get it right, and a miss shows up only on a secured cluster.

So I'd propose both:

  • this PR keeps a plugin subject's GET and multi-get on its own registered system indices realtime;
  • the plugin migrations set a refresh policy on system index writes that are searched afterwards. I'll add that to the migration checklist.

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit ee0d655

@codecov

codecov Bot commented Oct 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.85%. Comparing base (3ae9025) to head (ee0d655).

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #6668      +/-   ##
==========================================
+ Coverage   76.81%   76.85%   +0.04%     
==========================================
  Files         487      487              
  Lines       32228    32234       +6     
  Branches     4870     4871       +1     
==========================================
+ Hits        24755    24773      +18     
+ Misses       5252     5244       -8     
+ Partials     2221     2217       -4     
Files with missing lines Coverage Δ
...actionlevel/legacy/SystemIndexAccessEvaluator.java 80.12% <100.00%> (+2.62%) ⬆️

... and 11 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@DarshitChanpura

Copy link
Copy Markdown
Member Author

@cwperks @RyanL1997 could you take a look when you have a moment? CI is green. Once this merges, reporting PR opensearch-project/reporting#1232 can come out of draft.

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