Skip to content

Commit

Permalink
Remove AccessController.doPrivileged calls (openhab#3271)
Browse files Browse the repository at this point in the history
The `AccessController` and the `SecurityManager` is deprecated for removal in Java 17. We don't make use of the `SecurityManager` anyway, so we can safely remove it.

Signed-off-by: Jan N. Klug <github@klug.nrw>
GitOrigin-RevId: 98b4902
  • Loading branch information
J-N-K authored and splatch committed Jul 12, 2023
1 parent ae3532b commit 502958b
Show file tree
Hide file tree
Showing 9 changed files with 164 additions and 272 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.time.Instant;
import java.util.Base64;
import java.util.concurrent.ExecutionException;
Expand Down Expand Up @@ -137,7 +134,7 @@ public String getAuthorizationUrl(String authorizationEndpoint, String clientId,
* @return Access Token
* @throws IOException IO/ network exceptions
* @throws OAuthException Other exceptions
* @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* @throws OAuthResponseException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* Response
*/
public AccessTokenResponse grantTypePassword(String tokenUrl, String username, String password,
Expand Down Expand Up @@ -171,7 +168,7 @@ public AccessTokenResponse grantTypePassword(String tokenUrl, String username, S
* @return Access Token
* @throws IOException IO/ network exceptions
* @throws OAuthException Other exceptions
* @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* @throws OAuthResponseException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* Response
*/
public AccessTokenResponse grantTypeRefreshToken(String tokenUrl, String refreshToken, @Nullable String clientId,
Expand Down Expand Up @@ -206,7 +203,7 @@ public AccessTokenResponse grantTypeRefreshToken(String tokenUrl, String refresh
* @return Access Token
* @throws IOException IO/ network exceptions
* @throws OAuthException Other exceptions
* @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* @throws OAuthResponseException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* Response
*/
public AccessTokenResponse grantTypeAuthorizationCode(String tokenUrl, String authorizationCode, String clientId,
Expand Down Expand Up @@ -240,7 +237,7 @@ public AccessTokenResponse grantTypeAuthorizationCode(String tokenUrl, String au
* @return Access Token
* @throws IOException IO/ network exceptions
* @throws OAuthException Other exceptions
* @throws OAuthErrorException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* @throws OAuthResponseException Error codes given by authorization provider, as in RFC 6749 section 5.2 Error
* Response
*/
public AccessTokenResponse grantTypeClientCredentials(String tokenUrl, String clientId,
Expand Down Expand Up @@ -301,11 +298,8 @@ private AccessTokenResponse doRequest(final String grantType, HttpClient httpCli
String content = "";
try {
final FormContentProvider entity = new FormContentProvider(fields);
final ContentResponse response = AccessController
.doPrivileged((PrivilegedExceptionAction<ContentResponse>) () -> {
Request requestWithContent = request.content(entity);
return requestWithContent.send();
});
Request requestWithContent = request.content(entity);
final ContentResponse response = requestWithContent.send();

statusCode = response.getStatus();
content = response.getContentAsString();
Expand All @@ -326,18 +320,15 @@ private AccessTokenResponse doRequest(final String grantType, HttpClient httpCli
statusCode);
throw new OAuthException("Bad http response, http code " + statusCode);
}
} catch (PrivilegedActionException pae) {
Exception underlyingException = pae.getException();
if (underlyingException instanceof InterruptedException || underlyingException instanceof TimeoutException
|| underlyingException instanceof ExecutionException) {
throw new IOException("Exception in oauth communication, grant type " + grantType, underlyingException);
}
// Dont know what exception it is, wrap it up and throw it out
throw new OAuthException("Exception in oauth communication, grant type " + grantType, underlyingException);
} catch (InterruptedException | TimeoutException | ExecutionException e) {
throw new IOException("Exception in oauth communication, grant type " + grantType, e);
} catch (JsonSyntaxException e) {
throw new OAuthException(String.format(
"Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %i json: %s",
"Unable to deserialize json into AccessTokenResponse/ OAuthResponseException. httpCode: %d json: %s",
statusCode, content), e);
} catch (Exception e) {
// Dont know what exception it is, wrap it up and throw it out
throw new OAuthException("Exception in oauth communication, grant type " + grantType, e);
}
}

Expand All @@ -356,10 +347,7 @@ private HttpClient createHttpClient(String tokenUrl) throws OAuthException {
HttpClient httpClient = httpClientFactory.createHttpClient(HTTP_CLIENT_CONSUMER_NAME);
if (!httpClient.isStarted()) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<@Nullable Void>) () -> {
httpClient.start();
return null;
});
httpClient.start();
} catch (Exception e) {
throw new OAuthException("Exception while starting httpClient, tokenUrl: " + tokenUrl, e);
}
Expand All @@ -370,10 +358,7 @@ private HttpClient createHttpClient(String tokenUrl) throws OAuthException {
private void shutdownQuietly(@Nullable HttpClient httpClient) {
try {
if (httpClient != null) {
AccessController.doPrivileged((PrivilegedExceptionAction<@Nullable Void>) () -> {
httpClient.stop();
return null;
});
httpClient.stop();
}
} catch (Exception e) {
// there is nothing we can do here
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
*/
package org.openhab.core.automation.internal;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
Expand Down Expand Up @@ -92,10 +90,7 @@ public void run() {

public void dispose() {
synchronized (this) {
AccessController.doPrivileged((PrivilegedAction<@Nullable Void>) () -> {
executor.shutdownNow();
return null;
});
executor.shutdownNow();
}
}

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

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.ExecutionException;
Expand Down Expand Up @@ -130,13 +128,8 @@ private String toString(Collection<Invocation> invocationStack) {
}

private String getStacktrace(final Thread thread) {
StackTraceElement[] elements = AccessController.doPrivileged(new PrivilegedAction<StackTraceElement[]>() {
@Override
public StackTraceElement[] run() {
return thread.getStackTrace();
}
});
return Arrays.stream(elements).map(element -> "\tat " + element.toString()).collect(Collectors.joining("\n"));
StackTraceElement[] elements = thread.getStackTrace();
return Arrays.stream(elements).map(element -> "\tat " + element).collect(Collectors.joining("\n"));
}

String toString(Method method) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.stream.Stream;
Expand Down Expand Up @@ -56,25 +54,23 @@ public SafeCallerBuilderImpl(T target, Class<?>[] classes, SafeCallManager manag
@SuppressWarnings("unchecked")
@Override
public T build() {
return AccessController.doPrivileged((PrivilegedAction<T>) () -> {
InvocationHandler handler;
if (async) {
handler = new InvocationHandlerAsync<>(manager, target, identifier, timeout, exceptionHandler,
timeoutHandler);
} else {
handler = new InvocationHandlerSync<>(manager, target, identifier, timeout, exceptionHandler,
timeoutHandler);
}
ClassLoader classLoader = getClass().getClassLoader();
if (classLoader == null) {
throw new IllegalStateException(
"Cannot create proxy because '" + getClass().getName() + "' class loader is null");
}
return (T) Proxy.newProxyInstance(
CombinedClassLoader.fromClasses(classLoader,
Stream.concat(Stream.of(target.getClass()), Arrays.stream(interfaceTypes))),
interfaceTypes, handler);
});
InvocationHandler handler;
if (async) {
handler = new InvocationHandlerAsync<>(manager, target, identifier, timeout, exceptionHandler,
timeoutHandler);
} else {
handler = new InvocationHandlerSync<>(manager, target, identifier, timeout, exceptionHandler,
timeoutHandler);
}
ClassLoader classLoader = getClass().getClassLoader();
if (classLoader == null) {
throw new IllegalStateException(
"Cannot create proxy because '" + getClass().getName() + "' class loader is null");
}
return (T) Proxy.newProxyInstance(
CombinedClassLoader.fromClasses(classLoader,
Stream.concat(Stream.of(target.getClass()), Arrays.stream(interfaceTypes))),
interfaceTypes, handler);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
*/
package org.openhab.core.config.discovery;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -175,12 +173,7 @@ private void validateThingUID(@Nullable ThingUID bridgeUID) {
}

private String getStackTrace(final Thread thread) {
StackTraceElement[] elements = AccessController.doPrivileged(new PrivilegedAction<StackTraceElement[]>() {
@Override
public StackTraceElement[] run() {
return thread.getStackTrace();
}
});
StackTraceElement[] elements = thread.getStackTrace();
return Arrays.stream(elements).map(element -> "\tat " + element.toString()).collect(Collectors.joining("\n"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@
*/
package org.openhab.core.config.discovery.internal;

import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -254,13 +252,7 @@ public synchronized void thingDiscovered(final DiscoveryService source, final Di
}
for (final DiscoveryListener listener : listeners) {
try {
AccessController.doPrivileged(new PrivilegedAction<@Nullable Void>() {
@Override
public @Nullable Void run() {
listener.thingDiscovered(source, result);
return null;
}
});
listener.thingDiscovered(source, result);
} catch (Exception ex) {
logger.error("Cannot notify the DiscoveryListener '{}' on Thing discovered event!",
listener.getClass().getName(), ex);
Expand All @@ -280,13 +272,7 @@ public synchronized void thingRemoved(final DiscoveryService source, final Thing
}
for (final DiscoveryListener listener : listeners) {
try {
AccessController.doPrivileged(new PrivilegedAction<@Nullable Void>() {
@Override
public @Nullable Void run() {
listener.thingRemoved(source, thingUID);
return null;
}
});
listener.thingRemoved(source, thingUID);
} catch (Exception ex) {
logger.error("Cannot notify the DiscoveryListener '{}' on Thing removed event!",
listener.getClass().getName(), ex);
Expand All @@ -300,13 +286,8 @@ public synchronized void thingRemoved(final DiscoveryService source, final Thing
Set<ThingUID> removedResults = new HashSet<>();
for (final DiscoveryListener listener : listeners) {
try {
Collection<ThingUID> olderResults = AccessController
.doPrivileged(new PrivilegedAction<@Nullable Collection<ThingUID>>() {
@Override
public @Nullable Collection<ThingUID> run() {
return listener.removeOlderResults(source, timestamp, thingTypeUIDs, bridgeUID);
}
});
Collection<ThingUID> olderResults = listener.removeOlderResults(source, timestamp, thingTypeUIDs,
bridgeUID);
if (olderResults != null) {
removedResults.addAll(olderResults);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,6 @@
*/
package org.openhab.core.internal.events;

import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Dictionary;
import java.util.Hashtable;

Expand Down Expand Up @@ -54,23 +51,17 @@ public void post(final Event event) throws IllegalArgumentException, IllegalStat

private void postAsOSGiEvent(final EventAdmin eventAdmin, final Event event) throws IllegalStateException {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
Dictionary<String, Object> properties = new Hashtable<>(3);
properties.put("type", event.getType());
properties.put("payload", event.getPayload());
properties.put("topic", event.getTopic());
String source = event.getSource();
if (source != null) {
properties.put("source", source);
}
eventAdmin.postEvent(new org.osgi.service.event.Event("openhab", properties));
return null;
}
});
} catch (PrivilegedActionException pae) {
Exception e = pae.getException();
Dictionary<String, Object> properties = new Hashtable<>(3);
properties.put("type", event.getType());
properties.put("payload", event.getPayload());
properties.put("topic", event.getTopic());
String source = event.getSource();
if (source != null) {
properties.put("source", source);
}
eventAdmin.postEvent(new org.osgi.service.event.Event("openhab", properties));

} catch (Exception e) {
throw new IllegalStateException("Cannot post the event via the event bus. Error message: " + e.getMessage(),
e);
}
Expand Down
Loading

0 comments on commit 502958b

Please sign in to comment.