spring-projects / spring-data-commons

Spring Data Commons. Interfaces and code shared between the various datastore specific implementations.
https://spring.io/projects/spring-data
Apache License 2.0
777 stars 675 forks source link

`ProxyingHandlerMethodArgumentResolver` conflicts with `@AuthenticationPrincipal` #2937

Closed spadou closed 2 months ago

spadou commented 1 year ago

In a Spring application (with Spring Boot 3.1.3 currently), using data and security the ProxyingHandlerMethodArgumentResolver will conflict with the use of @AuthenticationPrincipal in a controller when a custom interface is used for the principal. The ProxyingHandlerMethodArgumentResolver will be registered before AuthenticationPrincipalArgumentResolver and handle the argument as a projection in the fallback preventing @AuthenticationPrincipal from working.

I see this was improved in #1237, but only the Spring packages are filtered out. In my case I use a custom interface for the principal to inject due to others requirements, so it is not ignored by the ProxyingHandlerMethodArgumentResolver. The list of ignored packages also doesn't seem configurable so it is not an option to handle the issue. I could also exclude the SpringDataWebAutoConfiguration but this exclude everything (like pageable) so it is not ideal.

There is already a @ProjectedPayload in ProxyingHandlerMethodArgumentResolver so wouldn't it make sense to remove the fallback as it could cause issues in multiple situations?

Here a small example that reproduce the issue:

@SpringBootApplication
public class ArgumentResolverConflictApplication {

    public static void main(String[] args) {
        SpringApplication.run(ArgumentResolverConflictApplication.class, args);
    }

    @RestController
    public static class ArgumentResolverConflictRestController {

        @GetMapping("/principal")
        String principal(@AuthenticationPrincipal CustomUserDetails principal) {
            return principal.getUsername();
        }
    }

    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
        return new InMemoryUserDetailsManager(User.withUsername("user").password("{noop}password").build()) {
            @Override
            public UserDetails loadUserByUsername(String username) {
                var user = super.loadUserByUsername(username);
                return new CustomUser(user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
                        user.isAccountNonLocked(), user.getAuthorities());
            }
        };
    }

    public interface CustomUserDetails extends UserDetails {
    }

    public static class CustomUser extends User implements CustomUserDetails {
        public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked,
                          Collection<? extends GrantedAuthority> authorities) {
            super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        }
    }
}

If this is run with security and data (jdbc for example), the principal wont be injected in the controller but we'll have an empty projection instead. If SpringDataWebAutoConfiguration is excluded, it works as expected.

mp911de commented 1 year ago

Registering ProxyingHandlerMethodArgumentResolver later should allow other HandlerMethodArgumentResolvers to take precedence. Have you tried doing so by deferring the configuration (i.e. using Ordered or @Order)? Deferring RepositoryRestMvcAutoConfiguration to after the Spring Security web bits would be another path forward.

spadou commented 1 year ago

In this example I'm not configuring anything, it is all Spring Boot auto-configuration, and I don't see an easy way to define the order from external configuration. Defining an order for the WebMvcConfigurers would probably help, but currently neither SpringDataWebConfiguration or WebMvcSecurityConfiguration are defining one, so both would need to be updated.

odrotbohm commented 1 year ago

@rwinch – Do you think it would be possible to explicitly order WebMvcSecurityConfiguration to something like Ordered.LOWEST_PRECENDENCE - 100 so that data has a chance to get behind it?

spadou commented 1 year ago

Looking a bit more into this, and how the ProxyingHandlerMethodArgumentResolver is registered.

Maybe another solution would be to use the ProjectingArgumentResolverRegistrar, that is currently used to register the non catch-all instance of ProxyingHandlerMethodArgumentResolver at the start of the list, to also register the catch-all instance. This way custom argument resolvers are not used, so this avoid any issues with ordering, and we can ensure that the instance is registered at the end of the list in RequestMappingHandlerAdapter with the others catch-all.

odrotbohm commented 1 year ago

That's a good point. The origin of this particular arrangement was to be able to support @ModelAttribute-annotated parameters to in turn keep the programming model consistent no matter if you bind to a concrete class or an interface. I wonder if we should move to require explicit annotations on the parameter of either kind: @ModelAttribute, @ProjectedPayload. Spring Data REST could then augment that to also support types annotated with @Projection as well.

As that is a breaking change, I wonder if it makes sense to log a warning in case of a missing explicit declaration on the upcoming bug fix releases. /cc @mp911de

knalli commented 5 months ago

Well, I found this issue today because I've spend the morning finding the root cause of a strange issue. I think, I have run into the same situation. I also have an interface for the authentication principal (extension of UserDetails).

After upgrading to yesterdays's SB v3.3 including SDC v3.3, the handler resolver for a interface-typed @AuthenticationPrincipial (i.e. AuthenticationPrincipalArgumentResolver) stopped working (but an "empty" proxy of "null"). After realizing that ProxyingHandlerMethodArgumentResolver "catches" it, however, it makes some sense now.

The point here is: This only happens after I followed the warning-leveled-hint about configuring @EnableSpringDataWebSupport. Regardless the actual used pageSerializationMode, this seems to trigger another order. Because the number of resolvers within HandlerMethodArgumentResolverComposite is the same.

Although it seems no out-of-the-box issue for now, if someone fellow the recommendations and also uses interfaces on method arguments, it it actually bugged.

Raising attention for this issue here, and for my understanding, this "not-really-catch-all" handlers should be handled with much lower priority in general?

Edit: If still required, I build a small poc about this.

knalli commented 5 months ago

@odrotbohm At first: Is this the right place, or should I create a new issue for this? IMHO this is the same problem, and afaik you are happy with refreshing older issues. Please feel free to correct/advice me.

I've looked into this as well, but I'm not quite sure where to start. If I followed the trail correctly, the are only two instance setups of the proxy resolver. In both cases, I'm not sure how to apply an ordered property:

Also I'm still wondering why this simple enabler (using @EnableSpringDataWebSupport) causes such different resolver bean setup (-> SpringDataWebConfigurationImportSelector -> SpringDataWebSettingsRegistar (sic!) -> SpringDataJacksonConfiguration). Somehow this triggers that SpringDataWebConfiguration is processed some steps earlier.

Maybe SpringDataWebConfiguration itself should be processed later giving any other (like WebMvcSecurityConfiguration) the chance to process? Changing the security configuration's order only would apply a patch, but this will not solve the proxy resolver will handle all interface-based handler arguments ("catch all").

For refs: 5dd7b322b65652f90717c4f8cb930c5e471ad483 by Oliver introduced the SpringDataWebSettings.

odrotbohm commented 2 months ago

With other HandlerMethodArgumentResolver implementations registered that do not define an order explicitly, we cannot reliably order late in the lookup chain. I've added a guard to opt out of the support if any Spring annotation but @ModelAttribute is used with the parameter.