diff --git a/server/src/main/java/org/opensearch/action/ActionRequest.java b/server/src/main/java/org/opensearch/action/ActionRequest.java index 7ab87065bef7e..2254472dd6801 100644 --- a/server/src/main/java/org/opensearch/action/ActionRequest.java +++ b/server/src/main/java/org/opensearch/action/ActionRequest.java @@ -35,6 +35,7 @@ import org.opensearch.common.annotation.PublicApi; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; +import org.opensearch.identity.Subject; import org.opensearch.transport.TransportRequest; import java.io.IOException; @@ -47,6 +48,8 @@ @PublicApi(since = "1.0.0") public abstract class ActionRequest extends TransportRequest { + private Subject runAs; + public ActionRequest() { super(); // this does not set the listenerThreaded API, if needed, its up to the caller to set it @@ -67,6 +70,14 @@ public boolean getShouldStoreResult() { return false; } + public void runAs(Subject runAs) { + this.runAs = runAs; + } + + public Subject getRunAs() { + return this.runAs; + } + @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); diff --git a/server/src/main/java/org/opensearch/client/support/AbstractClient.java b/server/src/main/java/org/opensearch/client/support/AbstractClient.java index 509cd732357d6..f94e93e30fc46 100644 --- a/server/src/main/java/org/opensearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/opensearch/client/support/AbstractClient.java @@ -422,6 +422,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.tasks.TaskId; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.identity.Subject; import org.opensearch.threadpool.ThreadPool; import java.util.Map; @@ -480,7 +481,20 @@ public final vo Request request, ActionListener listener ) { - doExecute(action, request, listener); + Subject runAs = request.getRunAs(); + if (runAs != null) { + try { + runAs.runAs(() -> { + doExecute(action, request, listener); + return null; + }); + } catch (Exception e) { + throw new RuntimeException(e); + } + } else { + // run with default subject. If security is installed, default subject is the authenticated user + doExecute(action, request, listener); + } } protected abstract void doExecute(