Spring QueryDsl pagination filter by ACL permissions

Viewed 1013

Let's assume the following Spring JPA based repository with QueryDsl support.

@Repository
public interface TeamRepository extends JpaRepository<Team, Long>, QuerydslPredicateExecutor<Team> {

}

The application uses Access Control Lists (ACL) in service layer for checking permission for individual resources using @PreAuthorize(hasPermission(#id, 'Team', 'READ') for example.

I want to allow a user to request all teams for which he has read permission. I tried to use @PostFilter(hasPermission(filterObject, 'READ'), that works pretty good as long as I use Iterable<Team> findAll(Predicate predicate). But when I try to make use of pagination, @PostFilter seems to throw an exception.

java.lang.IllegalArgumentException: Filter target must be a collection, array, or stream type, but was Page 1 of 0 containing UNKNOWN instances

The official Spring Security Reference Documentation recommends to write a custom query using @Query which supports pagination.

How could I write such a complex query which supports QueryDsl's Predicate, Pagination and filtering based on permissions?

Approach 03/24/20

In another forum I came across the following QueryDsl based approach: Instead of a native or custom query, the ACL tables are mapped as @Immutable JPA entities, thus generating Q classes and using them to filter for permissions manually.

@Entity
@Immutable
@Table(name = "acl_object_identity")
public class AclObjectIdentity implements Serializable {

    ...
}

How could you do this using a custom repository, extending QueryDslRepositorySupport, so that the part of the query that checks permissions is automatically appended and hidden inside of a custom repository implementation?

1 Answers

Based on this approach I have developed a possibility which is more a dirty workaround than a solution.

The approach is to add an additional permission filter to existing predicates, for example those generated by web support. For this, the ACL tables must first be mapped as @Immutable JPA entities so that QueryDsl can generate the corresponding Q classes.

Such predicates to which an ACL Permission Filter should be appended are marked with the following annotation.

public Page<PostDTO> findAll(@QueryDslAclPermission(root = Post.class, permission = "READ") Predicate predicate, Pageable pageable) {

    ...
}

This annotation holds primarily meta information about the domain type that are required for building the filter query.

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER, ElementType.TYPE})
public @interface QueryDslAclPermission {

    Class<?> root();

    String permission();

    String identifier() default "id";
}

The actual filter query is generated and appended using the the following class and Spring's AOP Module.

@Aspect
@Component
public class QueryDslAclPermissionAspect {

    private PermissionFactory permissionFactory;

    @Autowired
    public QueryDslAclPermissionAspect(PermissionFactory permissionFactory) {
        this.permissionFactory = permissionFactory;
    }

    @Around(value = "execution(* *(.., @QueryDslAclPermission (*), ..))")
    public Object addPermissionFilter(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Parameter[] parameters = method.getParameters();
        Object[] arguments = joinPoint.getArgs();

        for(int index = 0; index < parameters.length; ++index) {

            if(parameters[index].getType().equals(Predicate.class) &&
                    parameters[index].isAnnotationPresent(QueryDslAclPermission.class)) {

                Predicate predicate = (Predicate) arguments[index];
                QueryDslAclPermission aclPermission = parameters[index].getAnnotation(QueryDslAclPermission.class);

                arguments[index] = addPermissionFilter(predicate, aclPermission);
            }
        }

        return joinPoint.proceed(arguments);
    }

    private Predicate addPermissionFilter(Predicate predicate, QueryDslAclPermission aclPermission) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(null == authentication || !authentication.isAuthenticated()) {
            throw new IllegalStateException("Permission filtering not possible for unauthenticated principal");
        }

        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        PrincipalSid principalSid = new PrincipalSid(userDetails.getUsername());

        NumberPath<Long> idPath = new PathBuilderFactory().create(aclPermission.root())
                .getNumber(aclPermission.identifier(), Long.class);

        return idPath.in(selectPermitted(aclPermission.root(), principalSid,
                permissionFactory.buildFromName(aclPermission.permission()))).and(predicate);
    }

    private JPQLQuery<Long> selectPermitted(Class<?> targetType, PrincipalSid sid, Permission permission) {

        return selectAclEntry(targetType, sid, permission)
                .select(QAclEntry.aclEntry.aclObjectIdentity.objectIdIdentity);
    }

    private JPQLQuery<AclEntry> selectAclEntry(Class<?> targetType, PrincipalSid sid, Permission permission) {

        return new JPAQuery<AclEntry>().from(QAclEntry.aclEntry)
                .where(QAclEntry.aclEntry.aclObjectIdentity.id.in(selectAclObjectIdentity(targetType)
                        .select(QAclObjectIdentity.aclObjectIdentity.id))
                        .and(QAclEntry.aclEntry.aclSid.id.eq(selectAclSid(sid).select(QAclSid.aclSid.id)))
                        .and(QAclEntry.aclEntry.mask.eq(permission.getMask())));
    }

    private JPQLQuery<AclObjectIdentity> selectAclObjectIdentity(Class<?> targetType) {

        return new JPAQuery<AclObjectIdentity>().from(QAclObjectIdentity.aclObjectIdentity)
                .where(QAclObjectIdentity.aclObjectIdentity.objectIdClass.id.eq(selectAclClass(targetType)
                        .select(QAclClass.aclClass.id)));
    }

    private JPQLQuery<AclSid> selectAclSid(PrincipalSid sid) {

        return new JPAQuery<AclSid>().from(QAclSid.aclSid)
                .where(QAclSid.aclSid.sid.eq(sid.getPrincipal()));
    }

    private JPQLQuery<AclClass> selectAclClass(Class<?> targetType) {

        return new JPAQuery<AclClass>().from(QAclClass.aclClass)
                .where(QAclClass.aclClass.className.eq(targetType.getSimpleName()));
    }
}

Edit 09/20/2022

A more generic approach based on JPA's Specification<T> and a custom repository implementation can be found in my GitHub Gist. It is decoupled from QueryDsl.

Related