Skip to content

DLS for pluggable data formats and query execution - #6569

Draft
nibix wants to merge 1 commit into
opensearch-project:mainfrom
nibix:pluggable-df-dls
Draft

nibix wants to merge 1 commit into
opensearch-project:mainfrom
nibix:pluggable-df-dls

Conversation

@nibix

@nibix nibix commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator

Description

Adds logical-plan DLS enforcement for analytics queries according to RFC spec in #22756 .

This implements the security plugin side of the core PR opensearch-project/OpenSearch#23168 .

It mostly boils down to exposing DLS rules via the AccessPolicyProviderPlugin interface.

Testing

  • Unit tests cover unrestricted, fully restricted (match_none), combined role queries, grouped restrictions, and overlapping-group rejection.
  • Security integration tests install a mock logical-read consumer that obtains policies through ReadAccessPolicyService. They verify the actual Security provider returns the expected restriction for a DLS user and no restriction for an unrestricted user.
  • This complements the OpenSearch-side analytics QA test, which uses a mock AccessPolicyProviderPlugin to validate analytics enforcement independently of the Security plugin.

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.
For more information on following Developer Certificate of Origin and signing off your commits, please check here.

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

PR Reviewer Guide 🔍

(Review updated until commit 952e874)

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 Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

PR Code Suggestions ✨

Latest suggestions up to 952e874

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
Group restrictions by stable key

Grouping is performed by QueryBuilder keys in a HashMap, which relies on
equals/hashCode. For a fully-restricted index, combine returns a
MatchNoneQueryBuilder from DlsRestriction.FULL's queries, and more generally
different QueryBuilder instances with equivalent semantics may not implement equals
reliably, so identical restrictions won't be grouped. Consider keying by the
rendered query string (as DocumentPrivileges.RenderedDlsQuery already provides) to
ensure stable grouping across indices.

src/main/java/org/opensearch/security/privileges/dlsfls/ReadAccessPolicyProviderImpl.java [53-54]

 QueryBuilder query = combine(restriction.getQueries());
+// Group by stable string representation to avoid relying on QueryBuilder.equals()
 indicesByRestriction.computeIfAbsent(query, ignored -> new LinkedHashSet<>()).add(index);
Suggestion importance[1-10]: 6

__

Why: Valid concern that QueryBuilder.equals/hashCode may not reliably group semantically equivalent queries, which could lead to redundant index groups. However, the suggestion's improved_code is identical to the existing_code (only a comment is added), so the actual fix is not demonstrated.

Low
Validate required path parameter

request.param("indices") can be null if the parameter is absent, causing an NPE in
split. Although this is test-only infrastructure, consider validating and returning
a clear error so test failures are easier to diagnose.

src/integrationTest/java/org/opensearch/security/privileges/int_tests/CompositeIndexAuthorizationIntTests.java [280-283]

 protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
-    MockReadAccessRequest mockRequest = new MockReadAccessRequest(request.param("indices").split(","));
+    String indicesParam = request.param("indices");
+    if (indicesParam == null || indicesParam.isEmpty()) {
+        throw new IllegalArgumentException("'indices' path parameter is required");
+    }
+    MockReadAccessRequest mockRequest = new MockReadAccessRequest(indicesParam.split(","));
     return channel -> client.execute(MockReadAccessAction.INSTANCE, mockRequest, new RestToXContentListener<>(channel));
 }
Suggestion importance[1-10]: 2

__

Why: This is test-only infrastructure where the path parameter {indices} is required by the route definition, so it will not be null. The suggestion offers negligible value.

Low
Possible issue
Guard against null DLS config

baseContext.config() may return null if DLS/FLS configuration has not yet been
initialized (e.g. during early startup or in SSL-only mode), which would NPE here.
Guard against a null config and treat it as unrestricted to be consistent with the
null privilegesContext branch above.

src/main/java/org/opensearch/security/privileges/dlsfls/ReadAccessPolicyProviderImpl.java [48-49]

+DlsFlsProcessedConfig config = baseContext.config();
+if (config == null) {
+    return ReadAccessPolicy.unrestricted();
+}
 for (String index : context.concreteIndices()) {
-    DlsRestriction restriction = baseContext.config().getDocumentPrivileges().getRestriction(privilegesContext, index);
+    DlsRestriction restriction = config.getDocumentPrivileges().getRestriction(privilegesContext, index);
Suggestion importance[1-10]: 4

__

Why: Defensive null-check for baseContext.config() is reasonable, but it's unclear whether config() can actually return null in practice given this provider is instantiated after configuration setup; the impact is minor.

Low

Previous suggestions

Suggestions up to commit b9970c8
CategorySuggestion                                                                                                                                    Impact
General
Deduplicate indices before grouping

Grouping by QueryBuilder key relies on equals/hashCode, but if the same index
appears multiple times in context.concreteIndices() (duplicates), it would be
silently added only once to the group but still passed into ReadAccessPolicyImpl,
which throws on duplicates across groups. Deduplicate input indices or guard against
duplicates to avoid an unexpected IllegalArgumentException on legitimate caller
input.

src/main/java/org/opensearch/security/privileges/dlsfls/ReadAccessPolicyProviderImpl.java [46-56]

 Map<QueryBuilder, Set<String>> indicesByRestriction = new LinkedHashMap<>();
 Set<String> unrestrictedIndices = new LinkedHashSet<>();
+Set<String> seen = new LinkedHashSet<>();
 for (String index : context.concreteIndices()) {
+    if (seen.add(index) == false) {
+        continue;
+    }
     DlsRestriction restriction = baseContext.config().getDocumentPrivileges().getRestriction(privilegesContext, index);
     if (restriction.isUnrestricted()) {
         unrestrictedIndices.add(index);
     } else {
         QueryBuilder query = combine(restriction.getQueries());
         indicesByRestriction.computeIfAbsent(query, ignored -> new LinkedHashSet<>()).add(index);
     }
 }
Suggestion importance[1-10]: 5

__

Why: Valid edge case: duplicate indices in context.concreteIndices() could cause ReadAccessPolicyImpl to throw IllegalArgumentException since addGroup fails on duplicate index entries. Moderate impact as duplicates may not be common but could occur.

Low
Fix hasRestrictions computation accuracy

hasRestrictions is set to true whenever the input map is non-empty, but a key may
map to an empty collection of indices, in which case no actual restriction is
applied to any index. Compute hasRestrictions based on whether any group with a
restriction was actually added, to prevent reporting restrictions that are not
enforced.

src/main/java/org/opensearch/security/privileges/dlsfls/ReadAccessPolicyImpl.java [53-56]

 this.indexGroups = List.copyOf(groups);
 this.coveredConcreteIndices = Collections.unmodifiableSet(covered);
 this.restrictionsByIndex = Collections.unmodifiableMap(byIndex);
-this.hasRestrictions = indicesByRestriction.isEmpty() == false;
+this.hasRestrictions = byIndex.values().stream().anyMatch(Optional::isPresent);
Suggestion importance[1-10]: 4

__

Why: The suggestion addresses a minor edge case where the input map has keys mapping to empty collections. The impact is limited since callers typically don't pass empty value collections, but the improvement makes the computation more semantically accurate.

Low
Suggestions up to commit f801083
CategorySuggestion                                                                                                                                    Impact
General
Group indices by stable restriction key

Using a QueryBuilder as a Map key relies on equals/hashCode, which many QueryBuilder
subclasses (e.g., BoolQueryBuilder built from multiple role queries) do implement,
but the combine method creates a new BoolQueryBuilder per index even for identical
inputs. Two indices with the same set of role queries will produce two
BoolQueryBuilder instances that must be equal to be grouped — verify equality holds,
or group by the underlying List (or its rendered-string form) before combining to
guarantee grouping works as tested.

src/main/java/org/opensearch/security/privileges/dlsfls/ReadAccessPolicyProviderImpl.java [46-56]

-Map<QueryBuilder, Set<String>> indicesByRestriction = new LinkedHashMap<>();
+Map<List<DocumentPrivileges.RenderedDlsQuery>, Set<String>> indicesByRestrictionKey = new LinkedHashMap<>();
+Map<List<DocumentPrivileges.RenderedDlsQuery>, QueryBuilder> combinedByKey = new LinkedHashMap<>();
 Set<String> unrestrictedIndices = new LinkedHashSet<>();
 for (String index : context.concreteIndices()) {
     DlsRestriction restriction = baseContext.config().getDocumentPrivileges().getRestriction(privilegesContext, index);
     if (restriction.isUnrestricted()) {
         unrestrictedIndices.add(index);
     } else {
-        QueryBuilder query = combine(restriction.getQueries());
-        indicesByRestriction.computeIfAbsent(query, ignored -> new LinkedHashSet<>()).add(index);
+        List<DocumentPrivileges.RenderedDlsQuery> key = restriction.getQueries();
+        combinedByKey.computeIfAbsent(key, k -> combine(k));
+        indicesByRestrictionKey.computeIfAbsent(key, ignored -> new LinkedHashSet<>()).add(index);
     }
 }
+Map<QueryBuilder, Set<String>> indicesByRestriction = new LinkedHashMap<>();
+indicesByRestrictionKey.forEach((k, v) -> indicesByRestriction.put(combinedByKey.get(k), v));
Suggestion importance[1-10]: 6

__

Why: The concern is valid: using freshly-constructed BoolQueryBuilder instances as map keys depends on equals/hashCode being properly implemented across subclasses. The test groupsIndicesWithEqualRestrictions passes only because QueryBuilder.equals is implemented, but the suggestion improves robustness by using a more explicit grouping key.

Low
Mirror super call in serialization

The writeTo method does not call super.writeTo(out), but the matching constructor
calls super(in). While ActionResponse.writeTo is typically a no-op, the asymmetry is
inconsistent with the request class in the same file which correctly calls
super.writeTo(out). Add the super call for symmetry and future-proofing.

src/integrationTest/java/org/opensearch/security/privileges/int_tests/CompositeIndexAuthorizationIntTests.java [221-223]

 public MockReadAccessResponse(StreamInput in) throws IOException {
     super(in);
     restrictions = in.readMap(StreamInput::readString, StreamInput::readString);
 }
 
 @Override
 public void writeTo(StreamOutput out) throws IOException {
+    super.writeTo(out);
     out.writeMap(restrictions, StreamOutput::writeString, StreamOutput::writeString);
 }
Suggestion importance[1-10]: 3

__

Why: Minor consistency improvement in test code; ActionResponse.writeTo is typically a no-op, so the practical impact is low.

Low

@nibix

nibix commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator Author

@cwperks @DarshitChanpura @Bukhtawar @niravpi

Please have a look at this.

It should already be the complete implementation. I left it in draft state, because we have to coordinate merging on the core and security side (at the moment compilation fails because it is missing the new interfaces introduced in core).

@github-actions

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit b9970c8

@github-actions

github-actions Bot commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

Persistent review updated to latest commit 952e874

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.

1 participant