old-techblog/_posts/2018-01-18-rack-filter-para...

2.5 KiB

layout title slug date categories
post 2017 roundup part 2: rack-filter-param rack-filter-param 2018-01-18 06:00:00 +0000 ruby gems foss rack

Hot on the heels of thes is another Ruby gem: this time containing some Rack middleware.

rack-filter-param solves a simple problem. As the name suggests, it allows HTTP parameters to be filtered from incoming requests based on arbitrary application logic.

The middleware needs only the most minimal configuration. For example, here it is being configured to strip the client_id parameter from incoming requests, based on some assumed application-level logic:

{% highlight ruby %} use Rack::FilterParam, { param: :client_id, if: -> (value) { should_I_do_it?(value) } } {% endhighlight %}

When the application method should_I_do_it? returns a truthy value, the client_id parameter is stripped from the request, which is then passed upstream.

It is a library born of a real-world refactoring problem. A legacy authentication library, that had been part of Mixlr's API, was being replaced with a newer library. While doing so it was discovered that a particular HTTP querystring parameter, hard-coded into numerous client apps, triggered some unwanted and buggy behaviour in the new library.

Fixing the problem by pushing out updates to the client apps, and removing the parameter completely, wasn't an option. That would have left the app broken for all users who didn't or couldn't update to the new version. And patching the new library felt wrong too, because it would only increase future maintenance burden and make it more difficult to keep the library up-to-date.

The next step was to attempt to remove the parameter using Nginx, but the unwanted behaviour was only triggered when the parameter had certain values. In other words, the removal of the parameter depended on application logic, and application logic belongs in the application and not hidden in the front-end web server configuration.

So the correct solution appeared to be to manipulate the request at the Rack middleware layer, which is part of the application but kicks in early enough to be able to remove the parameter in good time. And extracting it as a gem kept the application itself clean of legacy code paths, and allowed it to be re-used by anybody in the future.

You can read more and browse the source code over on my GitHub page.

https://github.com/rfwatson/rack-filter-param