Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create a test endpoint that accepts raw code to test the JSM Replacement #45

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
*/
package org.opensearch.security.systemindex;

import java.util.List;
import java.util.Map;

import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.opensearch.core.rest.RestStatus;
import org.opensearch.security.systemindex.sampleplugin.SystemIndexPlugin1;
import org.opensearch.security.systemindex.sampleplugin.SystemIndexPlugin2;
import org.opensearch.test.framework.TestSecurityConfig.AuthcDomain;
import org.opensearch.test.framework.cluster.ClusterManager;
import org.opensearch.test.framework.cluster.LocalCluster;
import org.opensearch.test.framework.cluster.TestRestClient;
import org.opensearch.test.framework.cluster.TestRestClient.HttpResponse;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.opensearch.security.support.ConfigConstants.SECURITY_RESTAPI_ROLES_ENABLED;
import static org.opensearch.security.support.ConfigConstants.SECURITY_SYSTEM_INDICES_ENABLED_KEY;
import static org.opensearch.test.framework.TestSecurityConfig.Role.ALL_ACCESS;
import static org.opensearch.test.framework.TestSecurityConfig.User.USER_ADMIN;

@RunWith(com.carrotsearch.randomizedtesting.RandomizedRunner.class)
@ThreadLeakScope(ThreadLeakScope.Scope.NONE)
public class RunCodeTests {

public static final AuthcDomain AUTHC_DOMAIN = new AuthcDomain("basic", 0).httpAuthenticatorWithChallenge("basic").backend("internal");

@ClassRule
public static final LocalCluster cluster = new LocalCluster.Builder().clusterManager(ClusterManager.SINGLENODE)
.anonymousAuth(false)
.authc(AUTHC_DOMAIN)
.users(USER_ADMIN)
.plugin(SystemIndexPlugin1.class, SystemIndexPlugin2.class)
.nodeSettings(
Map.of(
SECURITY_RESTAPI_ROLES_ENABLED,
List.of("user_" + USER_ADMIN.getName() + "__" + ALL_ACCESS.getName()),
SECURITY_SYSTEM_INDICES_ENABLED_KEY,
true
)
)
.build();

@Test
public void testRunCode() {
// Define the policy file location
String policyFile = "integration-test.policy";

// Set the system property for security policy
System.setProperty("java.security.policy", RunCodeTests.class.getClassLoader().getResource(policyFile).getPath());

// Enable the Security Manager (Deprecated in Java 17+)
System.setSecurityManager(new SecurityManager());
System.out.println("Security manager: " + System.getSecurityManager());
try (TestRestClient client = cluster.getRestClient(USER_ADMIN)) {
// TODO write a test that calls POST /run-code with a simple System.out.println("Hello, world!")
// String javaCode = "System.setProperty(\\\"test.key\\\",\\\"Hello, world!\\\");";
// String javaCode = "System.out.println(\\\"Hello, world!\\\");";
String javaCode =
"java.nio.file.Path filePath = java.nio.file.Paths.get(\\\"/Users/cwperx/Projects/opensearch/OpenSearch/build/distribution/local/opensearch-3.0.0-SNAPSHOT/config/opensearch.yml\\\");"
+ "String content = new String(java.nio.file.Files.readAllBytes(filePath), java.nio.charset.StandardCharsets.UTF_8);"
+ "System.out.println(\\\"content: \\\" + content);";
String requestBody = "{\"code\": \"" + javaCode + "\"}";

System.out.println("Calling run-code");

HttpResponse response = client.postJson("run-code", requestBody);

System.out.println("Finished run-code");

// Verify response
assertThat(response.getStatusCode(), equalTo(RestStatus.OK.getStatus()));
assertThat(response.getBody(), response.getBody().contains("\"acknowledged\":true"));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
*/

package org.opensearch.security.systemindex.sampleplugin;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;

import org.opensearch.client.Client;
import org.opensearch.client.node.NodeClient;
import org.opensearch.rest.BaseRestHandler;
import org.opensearch.rest.RestRequest;
import org.opensearch.rest.action.RestToXContentListener;
import org.opensearch.security.DefaultObjectMapper;

import static java.util.Collections.singletonList;
import static org.opensearch.rest.RestRequest.Method.POST;

public class RestRunCodeAction extends BaseRestHandler {

private final Client client;

public RestRunCodeAction(Client client) {
this.client = client;
}

@Override
public List<Route> routes() {
return singletonList(new Route(POST, "/run-code"));
}

@Override
public String getName() {
return "run_code";
}

@Override
public RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
final JsonNode json;
try {
json = DefaultObjectMapper.readTree(request.content().utf8ToString());
} catch (IOException e) {
throw new RuntimeException(e);
}
RunCodeRequest runRequest = new RunCodeRequest(json.get("code").asText());
return channel -> client.execute(RunCodeAction.INSTANCE, runRequest, new RestToXContentListener<>(channel));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
*/

package org.opensearch.security.systemindex.sampleplugin;

// CS-SUPPRESS-SINGLE: RegexpSingleline It is not possible to use phrase "cluster manager" instead of master here
import org.opensearch.action.ActionType;
import org.opensearch.action.support.master.AcknowledgedResponse;
// CS-ENFORCE-SINGLE

public class RunCodeAction extends ActionType<AcknowledgedResponse> {
public static final RunCodeAction INSTANCE = new RunCodeAction();
public static final String NAME = "cluster:monitor/code";

private RunCodeAction() {
super(NAME, AcknowledgedResponse::new);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
*/

package org.opensearch.security.systemindex.sampleplugin;

import java.io.IOException;

import org.opensearch.action.ActionRequest;
import org.opensearch.action.ActionRequestValidationException;
import org.opensearch.core.common.io.stream.StreamInput;

public class RunCodeRequest extends ActionRequest {

private final String code;

public RunCodeRequest(String code) {
this.code = code;
}

public RunCodeRequest(StreamInput in) throws IOException {
super(in);
this.code = in.readString();
}

@Override
public ActionRequestValidationException validate() {
return null;
}

public String getCode() {
return this.code;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,17 @@ public List<RestHandler> getRestHandlers(
new RestBulkIndexDocumentIntoMixOfSystemIndexAction(client, pluginClient),
new RestSearchOnSystemIndexAction(pluginClient),
new RestGetOnSystemIndexAction(pluginClient),
new RestUpdateOnSystemIndexAction(pluginClient)
new RestUpdateOnSystemIndexAction(pluginClient),
new RestRunCodeAction(client)
);
}

@Override
public List<ActionHandler<? extends ActionRequest, ? extends ActionResponse>> getActions() {
return Arrays.asList(
new ActionHandler<>(IndexDocumentIntoSystemIndexAction.INSTANCE, TransportIndexDocumentIntoSystemIndexAction.class),
new ActionHandler<>(RunClusterHealthAction.INSTANCE, TransportRunClusterHealthAction.class)
new ActionHandler<>(RunClusterHealthAction.INSTANCE, TransportRunClusterHealthAction.class),
new ActionHandler<>(RunCodeAction.INSTANCE, TransportRunCodeAction.class)
);
}

Expand Down
Loading
Loading