Sync’ up! … without getting drained

feb 11

Safe-guarding ikura in Rails

N.B. This post is deprecated. For archival purposes, it remains here, but generally, it ought to be disregarded by readers.

When you have your ikura workers in place it’s imperative that your URI end-points are not open for anyone to call. You only want ikura to be able to access them.

It takes no more than a few lines of code to make your end-points protected, so let’s look at some code with this safe-guard in place. Here is a Rails controller without the ikura IP restriction:

class UsersController < ApplicationController

  require 'json'

  ## GET '/sample-cohort.json'
  def sample_cohort
    users = User::latest_cohort
    Job::new(:user_cohort, users)
    {status: 'ok'}.to_json
  end

end

As you can see, the above code has no mechanism restricting ikura’s access to the resource. But the following does:

class UsersController < ApplicationController

  require 'json'

  before_filter :protect, :only => [:sample_cohort]

  ## GET '/sample-cohort.json'
  def sample_cohort
    users = User::latest_cohort
    Job::new(:user_cohort, users)
    {status: 'ok'}.to_json
  end

  private

    def protect
      ips = ['192.241.197.30']
      return true if ips.include?(request.remote_ip)
      head :forbidden
    end

end

In the second version, we created a filtering method that peers into the request’s IP. It returns true if the request is indeed ikura’s IP. Otherwise, it complains to the request with a ‘403’ restricted access error.

If you want to perform the restriction more abstractly, consult this Rails guide on the matter. You can perform behind-the-scenes magic this way; it’s your choice how you ultimately go about it.

So, there you have it. Locking down your Rails API end-points for only ikura to see is frighteningly simple. It only takes a few lines of code & should prove effective and straightforward to any web developer.