Resolving security issues with Rubocop
Sometimes when you are observing your project source code you can see code like:
So, in simple Rails application it’s ok, there is no any problems, it works like a charm. But it can broke your businesses logic, so by passing in params
id of person who doesn’t belong to your specific group you still will be able to explore his information. To avoid such problems you should use protected scope to find your person:
How to avoid such problems? Seems like it is an issue for static code analyzer, rubocop
in our case.
Ok, let’s define code examples which should be reported:
Now we will use ruby-parse
to observe AST of this parts:
The third example it synthetic but we will use it just to illustrate concept. Now we are starting to write our cop:
Now we need to catch AST node where we are calling :find method. Ruby-parser provides a list of methods which you can use to catch corresponding AST nodes. Each node in on_send
method consists of thee parts [receiver, method, args]. So, firstly we need to filter non-find methods.
Easy enough. If we will explore all ASTs that we have we can detect pattern for calling :find on constants:
Each level of (send ? _ _)
is method calling on constant. In rubocop you can use #def_node_matcher
. But there is no any special matcher to define optional nesting AST (at least I can find it in documentation. Ok, let’s simple flatten on node children.
It’s pretty simple, if this node has child – let’s retentive it! And now we need to check is there any constant node?
Last action – add warning:
It is good enough code which will help you to detect problems with unsafe searches. Some additional words:
- You should add your cope to
lib/
- You should resolve somehow cases when you really need to call find on
all
scope. For example
How to deal with it? My suggest is to move constant to method which indicates that you are know what are you doing:
That’s all.