Skip to content

Commit

Permalink
Get pass sharable resource indices to DLS classes and test cleanup
Browse files Browse the repository at this point in the history
Signed-off-by: Craig Perkins <[email protected]>
  • Loading branch information
cwperks committed Jan 9, 2025
1 parent 66402ca commit f20daa6
Show file tree
Hide file tree
Showing 7 changed files with 134 additions and 128 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.junit.Assert;

import org.opensearch.client.Request;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.Response;
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
import org.opensearch.common.xcontent.json.JsonXContent;
import org.opensearch.core.xcontent.NamedXContentRegistry;
Expand Down Expand Up @@ -54,55 +54,76 @@ public void testPluginsAreInstalled() throws IOException {
);
}

public void testCreateSampleResource() throws IOException, InterruptedException {
String strongPassword = "myStrongPassword123!";
Request createUserRequest = new Request("PUT", "/_opendistro/_security/api/internalusers/craig");
createUserRequest.setJsonEntity("{\"password\":\"" + strongPassword + "\",\"backend_roles\":[\"admin\"]}");
client().performRequest(createUserRequest);

RequestOptions.Builder requestOptions = RequestOptions.DEFAULT.toBuilder();
requestOptions.setWarningsHandler((warnings) -> false);
private static Map<String, String> createSampleResource(String name, Optional<Tuple<String, String>> credentials) throws IOException {
RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder();
options.setWarningsHandler((warnings) -> false);
credentials.ifPresent(
stringStringTuple -> options.addHeader(
"Authorization",
"Basic "
+ Base64.getEncoder()
.encodeToString((stringStringTuple.v1() + ":" + stringStringTuple.v2()).getBytes(StandardCharsets.UTF_8))
)
);

Request createRequest = new Request("POST", "/_plugins/resource_sharing_example/resource");
createRequest.setEntity(new StringEntity("{\"name\":\"ExampleResource1\"}"));
createRequest.setOptions(requestOptions);
Response response = client().performRequest(createRequest);
Request request = new Request("POST", "/_plugins/resource_sharing_example/resource");
request.setEntity(new StringEntity("{\"name\":\"" + name + "\"}"));
request.setOptions(options);
Response response = client().performRequest(request);
Map<String, String> createResourceResponse = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
response.getEntity().getContent()
).mapStrings();
System.out.println("createResourceResponse: " + createResourceResponse);
return createResourceResponse;
}

Request createRequest2 = new Request("POST", "/_plugins/resource_sharing_example/resource");
createRequest2.setEntity(new StringEntity("{\"name\":\"ExampleResource2\"}"));
RequestOptions.Builder requestOptions2 = RequestOptions.DEFAULT.toBuilder();
requestOptions2.setWarningsHandler((warnings) -> false);
requestOptions2.addHeader(
"Authorization",
"Basic " + Base64.getEncoder().encodeToString(("craig:" + strongPassword).getBytes(StandardCharsets.UTF_8))
private static Map<String, String> updateSharing(String resourceId, String payload, Optional<Tuple<String, String>> credentials)
throws IOException {
RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder();
options.setWarningsHandler((warnings) -> false);
credentials.ifPresent(
stringStringTuple -> options.addHeader(
"Authorization",
"Basic "
+ Base64.getEncoder()
.encodeToString((stringStringTuple.v1() + ":" + stringStringTuple.v2()).getBytes(StandardCharsets.UTF_8))
)
);
createRequest2.setOptions(requestOptions2);
Response response2 = client().performRequest(createRequest2);
ObjectMapper objectMapper = new ObjectMapper();
JsonNode indexResponseNode = objectMapper.readTree(response2.getEntity().getContent());

String resourceId = indexResponseNode.get("resourceId").asText();
Map<String, String> createResourceResponse2 = JsonXContent.jsonXContent.createParser(
Request updateSharingRequest = new Request("PUT", "/_plugins/_security/resource/sample_resource/" + resourceId + "/share_with");
updateSharingRequest.setEntity(new StringEntity(payload));
options.addHeader("Content-Type", "application/json");
updateSharingRequest.setOptions(options);
Response updateResponse = client().performRequest(updateSharingRequest);
Map<String, String> updateSharingResponse = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
response2.getEntity().getContent()
updateResponse.getEntity().getContent()
).mapStrings();
System.out.println("createResourceResponse2: " + createResourceResponse2);
return updateSharingResponse;
}

public void testCreateSampleResource() throws IOException, InterruptedException {
RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder();
options.setWarningsHandler((warnings) -> false);

String strongPassword = "myStrongPassword123!";
Request createUserRequest = new Request("PUT", "/_opendistro/_security/api/internalusers/testuser");
createUserRequest.setJsonEntity("{\"password\":\"" + strongPassword + "\",\"backend_roles\":[\"admin\"]}");
client().performRequest(createUserRequest);

createSampleResource("ExampleResource1", Optional.empty());
String resourceId = createSampleResource("ExampleResource2", Optional.of(Tuple.tuple("testuser", strongPassword))).get(
"resourceId"
);

// Sleep to give ResourceSharingListener time to create the .resource-sharing index
Thread.sleep(1000);

Request listRequest = new Request("GET", "/_plugins/resource_sharing_example/resource");
listRequest.setOptions(requestOptions);
listRequest.setOptions(options);
Response listResponse = client().performRequest(listRequest);
JsonNode resNode = objectMapper.readTree(listResponse.getEntity().getContent());
System.out.println("resNode: " + resNode);
Map<String, Object> listResourceResponse = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
Expand All @@ -111,7 +132,7 @@ public void testCreateSampleResource() throws IOException, InterruptedException
System.out.println("listResourceResponse: " + listResourceResponse);

Request resourceSharingRequest = new Request("POST", "/.sample_extension_resources/_search");
resourceSharingRequest.setOptions(requestOptions);
resourceSharingRequest.setOptions(options);
Response resourceSharingResponse = adminClient().performRequest(resourceSharingRequest);
Map<String, Object> resourceSharingResponseMap = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
Expand All @@ -120,18 +141,11 @@ public void testCreateSampleResource() throws IOException, InterruptedException
).map();
System.out.println("sampleResources: " + resourceSharingResponseMap);

Request updateSharingRequest = new Request("PUT", "/_plugins/_security/resource/sample_resource/" + resourceId + "/share_with");
updateSharingRequest.setEntity(
new StringEntity("{\"share_with\":{\"users\": [\"admin\"], \"backend_roles\": [], \"allowed_actions\": [\"*\"]}}")
Map<String, String> updateSharingResponse = updateSharing(
resourceId,
"{\"share_with\":{\"users\": [\"admin\"], \"backend_roles\": [], \"allowed_actions\": [\"*\"]}}",
Optional.of(Tuple.tuple("testuser", strongPassword))
);
requestOptions.addHeader("Content-Type", "application/json");
updateSharingRequest.setOptions(requestOptions);
Response updateResponse = client().performRequest(updateSharingRequest);
Map<String, String> updateSharingResponse = JsonXContent.jsonXContent.createParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
updateResponse.getEntity().getContent()
).mapStrings();
System.out.println("updateSharingResponse: " + updateSharingResponse);

Thread.sleep(1000);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.apache.logging.log4j.Logger;

import org.opensearch.OpenSearchException;
import org.opensearch.ResourceNotFoundException;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.get.GetResponse;
import org.opensearch.action.support.ActionFilters;
Expand Down Expand Up @@ -82,6 +83,11 @@ private void getResource(GetResourceRequest request, ActionListener<GetResourceR
ActionListener<GetResponse> getListener = new ActionListener<>() {
@Override
public void onResponse(GetResponse getResponse) {
System.out.println("Get response: " + getResponse.isExists());
if (!getResponse.isExists()) {
getResourceListener.onFailure(new ResourceNotFoundException("Resource not found"));
return;
}
try {
XContentParser parser = XContentHelper.createParser(
xContentRegistry,
Expand All @@ -91,27 +97,6 @@ public void onResponse(GetResponse getResponse) {
);
T resource = resourceParser.parse(parser, getResponse.getId());
System.out.println("resource: " + resource);
// ActionListener<Boolean> shareListener = new ActionListener<>() {
// @Override
// public void onResponse(Boolean isShared) {
// if (isShared) {
// getResourceListener.onResponse(resource);
// } else {
// getResourceListener.onFailure(
// new OpenSearchException("User is not authorized to access this resource")
// );
// }
// }
//
// @Override
// public void onFailure(Exception e) {
// getResourceListener.onFailure(
// new OpenSearchException("Failed to check sharing status: " + e.getMessage(), e)
// );
// }
// };
//
// resourceSharingService.isSharedWithCurrentUser(request.getResourceId(), shareListener);
getResourceListener.onResponse(resource);
} catch (IOException e) {
throw new OpenSearchException("Caught exception while loading resources: " + e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -727,7 +727,8 @@ public void onIndexModule(IndexModule indexModule) {
evaluator,
dlsFlsValve::getCurrentConfig,
dlsFlsBaseContext,
namedXContentRegistry.get()
namedXContentRegistry.get(),
sharableResourceIndices
)
);
System.out.println("this.indicesToListen: " + this.sharableResourceIndices);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,8 @@ private class DlsGetEvaluator {
private final boolean hasDeletions;

public DlsGetEvaluator(final Query dlsQuery, final LeafReader in, boolean applyDlsHere) throws IOException {
// System.out.println("DlsGetEvaluator");
// System.out.println("dlsQuery: " + dlsQuery);
// System.out.println("applyDlsHere: " + applyDlsHere);
if (dlsQuery != null && applyDlsHere) {
// if (dlsQuery != null) {
System.out.println("Applying dls query on get request: " + dlsQuery.toString());
// borrowed from Apache Lucene (Copyright Apache Software Foundation (ASF))
// https://github.com/apache/lucene-solr/blob/branch_6_3/lucene/misc/src/java/org/apache/lucene/index/PKIndexSplitter.java
final IndexSearcher searcher = new IndexSearcher(DlsFlsFilterLeafReader.this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,6 @@ public void handleSearchContext(SearchContext searchContext, ThreadPool threadPo
+ "}"
+ "}"
);
System.out.println("queryString: " + queryString);
dlsRestriction = new DlsRestriction(
List.of(new DocumentPrivileges.RenderedDlsQuery(parseQuery(queryString, namedXContentRegistry), queryString))
);
Expand Down
Loading

0 comments on commit f20daa6

Please sign in to comment.