Negative Security Testing

Part of my day job is to help with software security at my company. Part of this involves reviewing our controllers to make sure that people who shouldn’t be able to access them can’t get in. I’ve created both Cucumber specs and RSpec examples to do this. So far I prefer the RSpec method since it allows me to do a little more introspection.

A little bit of a background on our setup. Like most Rails shops, we use CanCan for our authorization and Devise for the authentication. With CanCan we define roles for the users such that the roles are granted access to certain areas of the system.

When I first wrote up the blacklist test in Cucumber, I had to manually specify which roles weren’t allowed and which actions to test in each controller. Obviously, this would only do real testing up until a new role or action was added. When I switched to RSpec I was able to just give a whitelist of what roles are allowed and then get the available actions through introspection. See my code below:

I included an example of how to set it up for what I call the support controller. All you need to do is give it the roles that are allowed and then it creates a user with every role except those. Then in your controller spec, add this line:

it_behaves_like "a secure support controller"

Voilà! Now you know if anyone ever breaks the security in your controller.

As for the positive side of making sure that a good user can still get in, I just rely on the regular specs since any good test suite will hit every action at least once.