Search in sources :

Example 21 with JoinPoint

use of org.aspectj.lang.JoinPoint in project herd by FINRAOS.

the class NamespaceSecurityAdviceTest method checkPermissionAssertMultipleAccessDeniedExceptionsAreGatheredIntoSingleMessageWhenMultipleAnnotations.

@Test
public void checkPermissionAssertMultipleAccessDeniedExceptionsAreGatheredIntoSingleMessageWhenMultipleAnnotations() throws Exception {
    // Mock a join point of the method call
    // mockMethodMultipleAnnotations("namespace1", "namespace2");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethodMultipleAnnotations", String.class, String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace1", "namespace2" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { "foo", "bar" });
    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    // User has no permissions
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    } catch (Exception e) {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ]\" permission(s) to the namespace \"foo\"%n" + "User \"%s\" does not have \"[WRITE]\" permission(s) to the namespace \"bar\"", userId, userId), e.getMessage());
    }
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodSignature(org.aspectj.lang.reflect.MethodSignature) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) Method(java.lang.reflect.Method) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) AccessDeniedException(org.springframework.security.access.AccessDeniedException) JoinPoint(org.aspectj.lang.JoinPoint) AbstractServiceTest(org.finra.herd.service.AbstractServiceTest) Test(org.junit.Test)

Example 22 with JoinPoint

use of org.aspectj.lang.JoinPoint in project herd by FINRAOS.

the class NamespaceSecurityAdviceTest method checkPermissionAssertNoErrorWhenUserHasMultiplePermissions.

@Test
public void checkPermissionAssertNoErrorWhenUserHasMultiplePermissions() throws Exception {
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getMethod()).thenReturn(method);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace" });
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { "foo" });
    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ, NamespacePermissionEnum.WRITE)));
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    } catch (AccessDeniedException e) {
        fail();
    }
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodSignature(org.aspectj.lang.reflect.MethodSignature) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) NamespaceAuthorization(org.finra.herd.model.api.xml.NamespaceAuthorization) Method(java.lang.reflect.Method) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) JoinPoint(org.aspectj.lang.JoinPoint) AbstractServiceTest(org.finra.herd.service.AbstractServiceTest) Test(org.junit.Test)

Example 23 with JoinPoint

use of org.aspectj.lang.JoinPoint in project herd by FINRAOS.

the class NamespaceSecurityAdviceTest method checkPermissionAssertNoExceptionWhenNull.

/**
 * Assert no access denied exception when parameter value is null.
 */
@Test
public void checkPermissionAssertNoExceptionWhenNull() throws Exception {
    // Mock a join point of the method call
    // mockMethod(null);
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { null });
    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    } catch (AccessDeniedException e) {
        fail();
    }
}
Also used : ApplicationUser(org.finra.herd.model.dto.ApplicationUser) AccessDeniedException(org.springframework.security.access.AccessDeniedException) MethodSignature(org.aspectj.lang.reflect.MethodSignature) SecurityUserWrapper(org.finra.herd.model.dto.SecurityUserWrapper) Method(java.lang.reflect.Method) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) JoinPoint(org.aspectj.lang.JoinPoint) AbstractServiceTest(org.finra.herd.service.AbstractServiceTest) Test(org.junit.Test)

Example 24 with JoinPoint

use of org.aspectj.lang.JoinPoint in project irida by phac-nml.

the class ValidMethodParametersAspect method validateParameters.

/**
 * Aspect that matches any method execution in our package with one or more
 * parameters that have the {@link Valid} annotation.
 *
 * @param jp
 *            the {@link JoinPoint} representing the captured method
 *            execution.
 */
@SuppressWarnings("unchecked")
@Before("execution(* ca.corefacility.bioinformatics.irida..*(.., @javax.validation.Valid (*), ..))")
public void validateParameters(JoinPoint jp) {
    // This is an array of the *actual* arguments passed to the method.
    Object[] args = jp.getArgs();
    List<List<Annotation>> annotations = getParameterAnnotations(jp);
    // pass the argument to the validator for validation.
    for (int i = 0; i < args.length; i++) {
        List<Annotation> argAnnotations = annotations.get(i);
        boolean anyValidAnnotation = false;
        for (Annotation a : argAnnotations) {
            if (a.annotationType().equals(Valid.class)) {
                anyValidAnnotation = true;
                break;
            }
        }
        if (anyValidAnnotation) {
            // if any parameter is annotated with @Valid, proceed with
            // validation using the validator.
            Set<ConstraintViolation<Object>> violations;
            if (args[i] instanceof Iterable) {
                // the element that we're currently validating is a
                // collection of elements; we should validate each of those
                // elements individually.
                violations = new HashSet<>();
                for (Object o : (Iterable<Object>) args[i]) {
                    violations.addAll(validator.validate(o));
                }
            } else {
                violations = validator.validate(args[i]);
            }
            if (!violations.isEmpty()) {
                // ConstraintViolationException.
                if (logger.isDebugEnabled()) {
                    final StringBuilder sb = new StringBuilder();
                    sb.append("Found constraint violations when validating [").append(jp.getSignature().toShortString()).append("], properties violating constraints:\n");
                    for (final ConstraintViolation<Object> violation : violations) {
                        sb.append("\t").append(violation.getRootBeanClass().toString()).append(".").append(violation.getPropertyPath().toString()).append(": ").append(violation.getMessage()).append("\n");
                    }
                    logger.debug(sb.toString());
                }
                throw new ConstraintViolationException(violations);
            }
        }
    }
}
Also used : JoinPoint(org.aspectj.lang.JoinPoint) Annotation(java.lang.annotation.Annotation) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) ArrayList(java.util.ArrayList) List(java.util.List) Before(org.aspectj.lang.annotation.Before)

Example 25 with JoinPoint

use of org.aspectj.lang.JoinPoint in project eventapis by kloiasoft.

the class CommandExecutionInterceptor method recordCommand.

private CommandRecord recordCommand(JoinPoint jp, CommandHandler commandHandler, Command command) throws ConcurrentEventException, EventStoreException {
    EventRepository eventRepository;
    CommandDto commandDto = null;
    CommandRecord commandRecord = new CommandRecord();
    commandRecord.setEventName(commandHandler.getClass().getSimpleName());
    for (int i = 0; i < jp.getArgs().length; i++) {
        Object arg = jp.getArgs()[i];
        commandRecord.getParameters().put(i, arg);
    }
    // }
    try {
        Field declaredField = commandHandler.getClass().getDeclaredField(command.eventRepository());
        if (!declaredField.isAccessible())
            declaredField.setAccessible(true);
        eventRepository = (EventRepository) declaredField.get(commandHandler);
    } catch (IllegalAccessException | NoSuchFieldException e) {
        log.error("Error while accessing EventRecorder(" + command.eventRepository() + ") of Command:" + commandHandler.getClass().getSimpleName() + " message: " + e.getMessage(), e);
        return null;
    }
    if (eventRepository != null) {
        eventRepository.getEventRecorder().recordEntityEvent(commandRecord, System.currentTimeMillis(), Optional.empty(), entityEvent -> new DefaultConcurrencyResolver());
    } else
        log.error("Error while accessing EventRecorder(" + command.eventRepository() + " is null ) of Command:" + commandHandler.getClass().getSimpleName());
    return commandRecord;
}
Also used : Field(java.lang.reflect.Field) DefaultConcurrencyResolver(com.kloia.eventapis.cassandra.DefaultConcurrencyResolver) EventRepository(com.kloia.eventapis.api.EventRepository) CommandDto(com.kloia.eventapis.api.CommandDto) CommandRecord(com.kloia.eventapis.pojos.CommandRecord) JoinPoint(org.aspectj.lang.JoinPoint)

Aggregations

JoinPoint (org.aspectj.lang.JoinPoint)59 MethodSignature (org.aspectj.lang.reflect.MethodSignature)31 Method (java.lang.reflect.Method)30 Test (org.junit.Test)29 AccessDeniedException (org.springframework.security.access.AccessDeniedException)26 AbstractServiceTest (org.finra.herd.service.AbstractServiceTest)25 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)25 SecurityUserWrapper (org.finra.herd.model.dto.SecurityUserWrapper)22 ApplicationUser (org.finra.herd.model.dto.ApplicationUser)21 NamespaceAuthorization (org.finra.herd.model.api.xml.NamespaceAuthorization)14 ProceedingJoinPoint (org.aspectj.lang.ProceedingJoinPoint)11 Before (org.aspectj.lang.annotation.Before)5 CodeSignature (org.aspectj.lang.reflect.CodeSignature)4 Annotation (java.lang.annotation.Annotation)3 ArrayList (java.util.ArrayList)3 IView (com.yydcdut.note.views.IView)2 IOException (java.io.IOException)2 Arrays (java.util.Arrays)2 List (java.util.List)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2