use of org.apache.shiro.subject.ExecutionException in project ddf by codice.
the class Security method runWithSubjectOrElevate.
/**
* Runs the {@link Callable} in the current thread as the current security framework's
* {@link Subject}. If the security framework's {@link Subject} is not currently set and
* the Java Subject contains the admin role, elevates and runs the {@link Callable} as the
* system {@link Subject}.
*
* @param codeToRun code to run
* @param <T> type of the returned value
* @return value returned by the {@link Callable}
* @throws SecurityServiceException if the current subject didn' have enough permissions to run
* the code
* @throws InvocationTargetException wraps any exception thrown by {@link Callable#call()}.
* {@link Callable} exception can be retrieved using the
* {@link InvocationTargetException#getCause()}.
*/
public <T> T runWithSubjectOrElevate(@NotNull Callable<T> codeToRun) throws SecurityServiceException, InvocationTargetException {
notNull(codeToRun, "Callable cannot be null");
try {
try {
org.apache.shiro.subject.Subject subject = org.apache.shiro.SecurityUtils.getSubject();
return subject.execute(codeToRun);
} catch (IllegalStateException | UnavailableSecurityManagerException e) {
LOGGER.debug("No shiro subject available for running command, trying with Java Subject");
}
Subject subject = getSystemSubject();
if (subject == null) {
SecurityLogger.audit(INSUFFICIENT_PERMISSIONS_ERROR);
throw new SecurityServiceException(INSUFFICIENT_PERMISSIONS_ERROR);
}
SecurityLogger.auditWarn("Elevating current user permissions to use System subject");
return subject.execute(codeToRun);
} catch (ExecutionException e) {
throw new InvocationTargetException(e.getCause());
}
}
use of org.apache.shiro.subject.ExecutionException in project ddf by codice.
the class SecurityTest method testRunWithSubjectOrElevateWhenSystemSubjectIsUsedAndCallableThrowsException.
@Test
public void testRunWithSubjectOrElevateWhenSystemSubjectIsUsedAndCallableThrowsException() throws Exception {
when(SecurityUtils.getSubject()).thenThrow(new IllegalStateException());
when(systemSubject.execute(callable)).thenThrow(new ExecutionException(new UnsupportedOperationException()));
configureMocksForBundleContext("server");
Exception exception = security.runAsAdmin(() -> {
try {
security.runWithSubjectOrElevate(callable);
fail("InvocationTargetException expected");
return null;
} catch (Exception e) {
return e;
}
});
assertThat(exception, is(instanceOf(InvocationTargetException.class)));
assertThat(exception.getCause(), is(instanceOf(UnsupportedOperationException.class)));
}
Aggregations