CanCanCommunity / cancancan

The authorization Gem for Ruby on Rails.
MIT License
5.6k stars 638 forks source link

Resource Loader gets ignored with Whitespace-Only ID in URL (e.g., "\n") #835

Open Federico-G opened 1 year ago

Federico-G commented 1 year ago

Steps to reproduce

When requesting a URL with all whitespaces as the ID (e.g., https://{site}/%A0), the method controller_resource_loader.rb#load_resource_instance fails to call find_resource because the id_param is nil. Consequently the 404 resource isn't invoked and the program continues with the @model set to nil

https://github.com/CanCanCommunity/cancancan/blob/a1e9a082b2dc2458e83ff95aa0506ad7a2069e96/lib/cancan/controller_resource_loader.rb#L106-L112

The reason for id_param being nil is that @params[id_param_key].present? evaluates to false when the string value consists only
of whitespaces ("\n" in this example)

https://github.com/CanCanCommunity/cancancan/blob/a1e9a082b2dc2458e83ff95aa0506ad7a2069e96/lib/cancan/controller_resource_finder.rb#L30-L32

I believe a potential solution could involve modifying the id_param method to return nil only if @params[id_param_key] is empty:

@params[id_param_key].to_s unless @params[id_param_key].empty?

Expected behavior

Eventually, a 404 resource

Actual behavior

The program goes on with the model nil

System configuration

Rails version: 6.1.5

Ruby version: 3.1

CanCanCan version 3.3 but tested in 3.5 (latest)

coorasse commented 6 months ago

Sounds legit to me. Please open a PR 👍