Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
Expand Up @@ -15,8 +15,6 @@
import org.elasticsearch.telemetry.apm.internal.MetricNameValidator;
import org.elasticsearch.telemetry.metric.Instrument;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
Expand All @@ -35,7 +33,7 @@ public abstract class AbstractInstrument<T> implements Instrument {

public AbstractInstrument(Meter meter, Builder<T> builder) {
this.name = builder.getName();
this.instrumentBuilder = m -> AccessController.doPrivileged((PrivilegedAction<T>) () -> builder.build(m));
this.instrumentBuilder = m -> builder.build(m);
this.delegate.set(this.instrumentBuilder.apply(meter));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.telemetry.apm.internal.tracing.APMTracer;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Objects;
import java.util.Set;
Expand Down Expand Up @@ -94,16 +92,13 @@ public void setAgentSetting(String key, String value) {
return;
}
final String completeKey = "elastic.apm." + Objects.requireNonNull(key);
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
if (value == null || value.isEmpty()) {
LOGGER.trace("Clearing system property [{}]", completeKey);
System.clearProperty(completeKey);
} else {
LOGGER.trace("Setting setting property [{}] to [{}]", completeKey, value);
System.setProperty(completeKey, value);
}
return null;
});
if (value == null || value.isEmpty()) {
LOGGER.trace("Clearing system property [{}]", completeKey);
System.clearProperty(completeKey);
} else {
LOGGER.trace("Setting setting property [{}] to [{}]", completeKey, value);
System.setProperty(completeKey, value);
}
}

private static final String TELEMETRY_SETTING_PREFIX = "telemetry.";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.telemetry.apm.APMMeterRegistry;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.function.Supplier;

public class APMMeterService extends AbstractLifecycleComponent {
Expand Down Expand Up @@ -74,7 +72,7 @@ protected void doClose() {}

protected Meter createOtelMeter() {
assert this.enabled;
return AccessController.doPrivileged((PrivilegedAction<Meter>) otelMeterSupplier::get);
return otelMeterSupplier.get();
}

protected Meter createNoopMeter() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,6 @@
import org.elasticsearch.telemetry.tracing.TraceContext;
import org.elasticsearch.telemetry.tracing.Traceable;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.time.Instant;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -145,11 +143,9 @@ APMServices createApmServices() {
assert this.enabled;
assert this.services == null;

return AccessController.doPrivileged((PrivilegedAction<APMServices>) () -> {
var openTelemetry = GlobalOpenTelemetry.get();
var tracer = openTelemetry.getTracer("elasticsearch", Build.current().version());
return new APMServices(tracer, openTelemetry);
});
var openTelemetry = GlobalOpenTelemetry.get();
var tracer = openTelemetry.getTracer("elasticsearch", Build.current().version());
return new APMServices(tracer, openTelemetry);
}

private void destroyApmServices() {
Expand All @@ -175,7 +171,7 @@ public void startTrace(TraceContext traceContext, Traceable traceable, String sp
return;
}

spans.computeIfAbsent(spanId, _spanId -> AccessController.doPrivileged((PrivilegedAction<Context>) () -> {
spans.computeIfAbsent(spanId, _spanId -> {
logger.trace("Tracing [{}] [{}]", spanId, spanName);
final SpanBuilder spanBuilder = services.tracer.spanBuilder(spanName);

Expand All @@ -198,7 +194,7 @@ public void startTrace(TraceContext traceContext, Traceable traceable, String sp
updateThreadContext(traceContext, services, contextForNewSpan);

return contextForNewSpan;
}));
});
}

/**
Expand Down Expand Up @@ -282,8 +278,7 @@ private Context getParentContext(TraceContext traceContext) {
public Releasable withScope(Traceable traceable) {
final Context context = spans.get(traceable.getSpanId());
if (context != null) {
var scope = AccessController.doPrivileged((PrivilegedAction<Scope>) context::makeCurrent);
return scope::close;
return context.makeCurrent()::close;
}
return () -> {};
}
Expand Down Expand Up @@ -380,10 +375,7 @@ public void stopTrace(Traceable traceable) {
final var span = Span.fromContextOrNull(spans.remove(traceable.getSpanId()));
if (span != null) {
logger.trace("Finishing trace [{}]", traceable);
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
span.end();
return null;
});
span.end();
}
}

Expand All @@ -392,10 +384,7 @@ public void stopTrace(Traceable traceable) {
*/
@Override
public void stopTrace() {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
Span.current().end();
return null;
});
Span.current().end();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@

import org.elasticsearch.ElasticsearchStatusException;
import org.elasticsearch.ResourceNotFoundException;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.common.CheckedSupplier;
import org.elasticsearch.core.SuppressForbidden;
import org.elasticsearch.rest.RestStatus;

Expand All @@ -22,9 +20,6 @@
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Objects;

Expand Down Expand Up @@ -88,46 +83,44 @@ InputStream get(final PasswordAuthentication auth, final String url) throws IOEx

final String originalAuthority = new URL(url).getAuthority();

return doPrivileged(() -> {
String innerUrl = url;
HttpURLConnection conn = createConnection(auth, innerUrl);

int redirectsCount = 0;
while (true) {
switch (conn.getResponseCode()) {
case HTTP_OK:
return getInputStream(conn);
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
if (redirectsCount++ > 50) {
throw new IllegalStateException("too many redirects connection to [" + url + "]");
}

// deal with redirections (including relative urls)
final String location = conn.getHeaderField("Location");
final URL base = new URL(innerUrl);
final URL next = new URL(base, location);
innerUrl = next.toExternalForm();

// compare the *original* authority and the next authority to determine whether to include auth details.
// this means that the host and port (if it is provided explicitly) are considered. it also means that if we
// were to ping-pong back to the original authority, then we'd start including the auth details again.
final String nextAuthority = next.getAuthority();
if (originalAuthority.equals(nextAuthority)) {
conn = createConnection(auth, innerUrl);
} else {
conn = createConnection(NO_AUTH, innerUrl);
}
break;
case HTTP_NOT_FOUND:
throw new ResourceNotFoundException("{} not found", url);
default:
int responseCode = conn.getResponseCode();
throw new ElasticsearchStatusException("error during downloading {}", RestStatus.fromCode(responseCode), url);
}
String innerUrl = url;
HttpURLConnection conn = createConnection(auth, innerUrl);

int redirectsCount = 0;
while (true) {
switch (conn.getResponseCode()) {
case HTTP_OK:
return getInputStream(conn);
case HTTP_MOVED_PERM:
case HTTP_MOVED_TEMP:
case HTTP_SEE_OTHER:
if (redirectsCount++ > 50) {
throw new IllegalStateException("too many redirects connection to [" + url + "]");
}

// deal with redirections (including relative urls)
final String location = conn.getHeaderField("Location");
final URL base = new URL(innerUrl);
final URL next = new URL(base, location);
innerUrl = next.toExternalForm();

// compare the *original* authority and the next authority to determine whether to include auth details.
// this means that the host and port (if it is provided explicitly) are considered. it also means that if we
// were to ping-pong back to the original authority, then we'd start including the auth details again.
final String nextAuthority = next.getAuthority();
if (originalAuthority.equals(nextAuthority)) {
conn = createConnection(auth, innerUrl);
} else {
conn = createConnection(NO_AUTH, innerUrl);
}
break;
case HTTP_NOT_FOUND:
throw new ResourceNotFoundException("{} not found", url);
default:
int responseCode = conn.getResponseCode();
throw new ElasticsearchStatusException("error during downloading {}", RestStatus.fromCode(responseCode), url);
}
});
}
}

@SuppressForbidden(reason = "we need socket connection to download data from internet")
Expand All @@ -150,13 +143,4 @@ protected PasswordAuthentication getPasswordAuthentication() {
conn.setInstanceFollowRedirects(false);
return conn;
}

private static <R> R doPrivileged(final CheckedSupplier<R, IOException> supplier) throws IOException {
SpecialPermission.check();
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<R>) supplier::get);
} catch (PrivilegedActionException e) {
throw (IOException) e.getCause();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Expand Down Expand Up @@ -492,7 +490,7 @@ public static Whitelist loadFromResourceFiles(Class<?> owner, Map<String, Whitel
}
}

ClassLoader loader = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) owner::getClassLoader);
ClassLoader loader = owner.getClassLoader();

return new Whitelist(loader, whitelistClasses, whitelistStatics, whitelistClassBindings, Collections.emptyList());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;

import static java.lang.invoke.MethodHandles.Lookup;
Expand Down Expand Up @@ -504,9 +502,7 @@ private static Class<?> createLambdaClass(Compiler.Loader loader, ClassWriter cw
byte[] classBytes = cw.toByteArray();
// DEBUG:
// new ClassReader(classBytes).accept(new TraceClassVisitor(new PrintWriter(System.out)), ClassReader.SKIP_DEBUG);
return AccessController.doPrivileged(
(PrivilegedAction<Class<?>>) () -> loader.defineLambda(lambdaClassType.getClassName(), classBytes)
);
return loader.defineLambda(lambdaClassType.getClassName(), classBytes);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,7 @@

import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permissions;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
Expand All @@ -52,18 +48,12 @@ public final class PainlessScriptEngine implements ScriptEngine {
*/
public static final String NAME = "painless";

/**
* Permissions context used during compilation.
*/
private static final AccessControlContext COMPILATION_CONTEXT;

/*
* Setup the allowed permissions.
*/
static {
final Permissions none = new Permissions();
none.setReadOnly();
COMPILATION_CONTEXT = new AccessControlContext(new ProtectionDomain[] { new ProtectionDomain(null, none) });
}

/**
Expand Down Expand Up @@ -123,12 +113,7 @@ public <T> T compile(String scriptName, String scriptSource, ScriptContext<T> co
SpecialPermission.check();

// Create our loader (which loads compiled code with no permissions).
final Loader loader = AccessController.doPrivileged(new PrivilegedAction<Loader>() {
@Override
public Loader run() {
return compiler.createLoader(getClass().getClassLoader());
}
});
final Loader loader = compiler.createLoader(getClass().getClassLoader());

ScriptScope scriptScope = compile(contextsToCompilers.get(context), loader, scriptName, scriptSource, params);

Expand Down Expand Up @@ -398,17 +383,9 @@ ScriptScope compile(Compiler compiler, Loader loader, String scriptName, String

try {
// Drop all permissions to actually compile the code itself.
return AccessController.doPrivileged(new PrivilegedAction<ScriptScope>() {
@Override
public ScriptScope run() {
String name = scriptName == null ? source : scriptName;
return compiler.compile(loader, name, source, compilerSettings);
}
}, COMPILATION_CONTEXT);
String name = scriptName == null ? source : scriptName;
return compiler.compile(loader, name, source, compilerSettings);
// Note that it is safe to catch any of the following errors since Painless is stateless.
} catch (SecurityException e) {
// security exceptions are rethrown so that they can propagate to the ES log, they are not user errors
throw e;
} catch (OutOfMemoryError | StackOverflowError | LinkageError | Exception e) {
throw convertToScriptException(source, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,8 @@ private void ensureSasTokenPermissions() {
.client("default", LocationMode.PRIMARY_ONLY, randomFrom(OperationPurpose.values()));
final BlobServiceClient client = azureBlobServiceClient.getSyncClient();
try {
SocketAccess.doPrivilegedException(() -> {
final BlobContainerClient blobContainer = client.getBlobContainerClient(blobStore.toString());
return blobContainer.exists();
});
final BlobContainerClient blobContainer = client.getBlobContainerClient(blobStore.toString());
blobContainer.exists();
future.onFailure(
new RuntimeException(
"The SAS token used in this test allowed for checking container existence. This test only supports tokens "
Expand Down
Loading