GitHub Security Alerts

GitHub recently introduced security alerts for Ruby and JavaScript applications. If they see that your application has dependencies with known security vulnerabilities, they will notify you.

New security vulnerabilities are discovered all the time, so it’s important that you keep your application and its dependencies up-to-date. I have first-hand experience with these alerts. Here’s what it looks like and how to fix any issues.

Notification

As you probably know, I wrote the book Rails Crash Course which was published back in October 2014. This book included two sample applications which are hosted on GitHub. Being over 3 years old, these applications now have outdated dependencies with known security vulnerabilities.

As promised, GitHub let me know about these vulnerabilities. First I received an email like this:

The email continues on for a total of 8 Ruby gems with known security vulnerabilities. Visiting the GitHub repo for this app, I’m greeted with this message:

Note that only the owner of the repo or other who have been specifically assigned access to vulnerability alerts can see this message. Otherwise, it would be easy for attackers to locate vulnerable applications.

Resolution

Looking over the listed vulnerable dependencies, I notice that all of the gems appear to be part of Rails. With that in mind, I’ll first update Rails.

Checking the application‘s Gemfile, I see that it’s using a fixed version of Rails. In this case the Gemfile is explicitly installing version 4.1.7. The security alert email recommends changing this to ~> 4.1.14.1.

The tilde followed by a greater than ~> forms an arrow that means to install a version of Rails matching all but the last digit in the given number. In this case, it means to install version 4.1.14.n, where n is any number greater than or equal to 1.

This way you can install security updates, while continuing to use the known good 4.1 version. Later versions, such as 5.2, may not be compatible with the application as written. Upgrading a Rails application to a new major version may require code changes and is a post for another day.

After updating the Gemfile, run the command bin/bundle update rails. This will take a few minutes as bundler resolves dependencies then downloads and installs the newer version of Rails. Once that’s complete, make sure the application still runs.

Not Quite Done

In a perfect world, this would be the end of this blog post. Unfortunately, Rails 4.1.14.1 also has a known security vulnerability. After pushing this change to GitHub, it recommended upgrading to version 4.2.5.1.

Of course, Rails 4.2.5.1 also has a known security vulnerability. This required an upgrade to Rails 4.2.7.1. GitHub also pointed out a security vulnerability in the version of the jquery-rails gem I was using. On their recommendation, I upgraded it to version ~> 3.1.3. And with that, I was done.

You can see the changes in the commit named Rails Security Update on GitHub. If you used a later version of Rails when you worked through the book you may not need these changes. Also, these instructions were only tested on Mac OS X. Users on Linux or Windows may need to make adjustments.

Portfolio Code

Now that your GitHub profile is looking good and you’ve set up your top project, it’s time to take a look at your actual code. As I said before, this is really what it all comes down to for most coding jobs. If you can’t prove your ability to write code, you won’t get the job.

Style

I usually start by trying to find the main part of the project. In a Rails app, this is typically a model file or maybe one of the controllers. For an Express app, I’ll start at app.js. For non-web apps, I’ll look for the main entry point. Once I’ve found a file with some real (not autogenerated) code in it, I look for several things.

Consistent Style – I’m not so concerned with whose style guide you follow, but I do expect you to pick one and stick to it. If you’re writing Ruby, use Rubocop. Your Python should always follow PEP 8. Check out Prettier if you need to clean up your JavaScript.

Clear Names – I’m fine with terse names and abbreviations, but I should be able to look at the name of a function and have some idea of it’s purpose. Variable names follow the same rules. Variables used only in loops or iterators can be single letters, but everything else should be easy to understand.

Idiomatic Code – Different languages naturally have different ways of performing the same task. For example, I wouldn’t expect to see a for loop used to iterate over an array in Ruby. I would expect to see an Enumerable method such as .each or .map. In Python, I would expect to see a list comprehension.

Tests

I don’t care when you write tests, as long as you write them. I’m not dogmatic about test-driven development, but I do expect production-ready code to have an automated test suite.

Include instructions for running your tests in the README file for the project. Also setup a continuous integration server, such as Travis CI, on your GitHub repo so the tests run automatically.

Beyond simply having a test suite, you need to make sure you’re testing the right things. Knowing what to test, and what not to test, is usually a sign of an experienced programmer.

It’s safe to assume that the framework you’re using is well tested. It’s not necessary to include tests that ensure that Rails associations and validations are working. It’s better to include tests that specify exactly what makes a model object and its associated objects valid or invalid.

Comments

In my experience comments are often not found in production code. This may come as a surprise to some programmers. Comments are typically only found before especially complex code or when something is implemented in a non-standard way. Comments used as documentation, before public classes and methods, are appreciated.

The most important rule is comment why something is done a certain way, not how it is done. I should be able to determine how something is done by reading the code. If I have questions about why the code was written that way I expect to find that answer in a comment.

Commit History

Finally, I like to also take a look at the commit history on a project. It’s interesting to see how long the candidate has been working on this project. Is this something that was put together just for a job search, or is this a real project?

You can learn a lot by someone’s commit messages. If I see a series of messages like “typo”, “fixing”, “fixing again”, “really fixing this time”, etc. I get a little worried. This is a red flag that maybe this person really doesn’t know what they’re doing.

I also see if more than one person has committed to the project. If so, I’ll go back to the code and check out the “Blame” view. Maybe that really impressive method I saw earlier was written by someone else. Group projects are fine, but never try to take credit for someone else’s work.

Your GitHub Portfolio

In my last post, I talked about how to setup your GitHub profile when looking for a job. Now that your GitHub profile page is looking good, shape up the details of your top repositories. You can customize the six popular repositories that appear on your profile page. These repositories should show off your best work and match the skills needed for the position you’re currently seeking.

When I’m reviewing a candidate, I sometimes skip the popular repositories and go to the repositories tab. I like to see what the candidate is currently doing. Projects appear in order by most recent commit on here. Since a recruiter or hiring manager might only look at one or two projects, be sure those at the top of the list look good.

Once I click on a project, it should be pretty easy to see what you’re trying to accomplish. Include a brief description at the top of the repo. Explain what the project does in simple terms. A few sentences is enough. You’ll provide complete details later in the README file.

Next, include a website. If this is a web application, this should probably be the address of a live demo. Even better, link to a post on your site that describes the project. That post should then link to the live demo. A demo running on a free Heroku site is fine.

As the reviewer scans down the list of files, there should be a clear structure. Most frameworks, such as Ruby on Rails, provide this structure for you. Things I look for include a breakdown of the application into components, usually following the model-view-controller pattern, and a test or spec directory.

After the list of files in the project, include a detailed README file. This is your chance to elaborate on the purpose of the project. What is special about this application? What technologies did you use to build it? What did you learn from this project?

Finally, explain how to run the project locally. What are the requirements, and how do I install the correct versions? Again, the framework and tools you use should make this easy. Hopefully everything is just a bundle or yarn command away.

Now that I know what your project is all about, it’s time to dig into the code. I’ll cover what I look for in a code review in my next post.

Looking For Engineers

We’re currently looking to hire two more experienced Ruby / JavaScript engineers here in the Sharethrough Austin office. This is one of the hardest parts of my job as an Engineering Manager. If you’re interested, I thought I’d offer a few tips to make it easier for recruiters and hiring managers to pick you out of the crowd of applicants.

After I look over an applicant’s resume or LinkedIn profile, the next place I go is their GitHub page. I have some advice about other parts of an engineering candidate’s application, and I’m already working on a few more posts like this one. Since GitHub is basically the first place I look, I’ll start here.

As someone looking for a job writing code, GitHub can be one of your most valuable assets. The most important question that a potential employer has about you is “can this person code?” If you can’t code, nothing else really matters. Even if you’re a perfect culture fit for the team, if you can’t contribute you won’t get the job.

Your GitHub profile and your code repositories should demonstrate your ability to get things done by writing code. The fastest way to learn programming is by doing. The best way to improve your ability is consistent practice. Write lots of code and share it publicly.

Your Profile

As with all profiles, I recommend you use your real, full name on GitHub. This isn’t required, of course, but be sure that your username is fairly easy to pronounce and remember. Imagine telling it to someone over the phone. Also, don’t use anything that someone might find offensive.

The same goes for your profile photo. A recent photo of yourself is best. It doesn’t have to be a professional headshot. A picture of you doing something you enjoy is fine. Almost anything is better than the default pixel art face.

Write a short bio about yourself. This doesn’t have to be anything fancy, just a few sentences about your interests and experiences. This could even be simply your job title and your current company. Add your real email address. This should be the same address you use on LinkedIn. If you have a personal website, link to it on your profile. If not, link to your profile on LinkedIn.

Your profile is also a great place to show off things that you’re passionate about other than coding. Maybe you’re on a mountain bike or climbing wall. If you’re wearing headphones in your photo, I might ask you about music. Feel free to show off your personality and interests, but do it in a way that still looks good to potential employers.

After the profile, I head over to the repositories tab next. I’ll finish up a post with my tips for polishing up your repositories in a few days.

Lone Star Ruby Conf 2013

Tickets are now on sale for the Lone Star Ruby Conference 2013 in Austin, TX from July 18-20. The speaker line-up this year looks amazing.

This will be my third year to attend and my second year to offer training. I am teaching two sessions on July 18.

My morning session is called From X to Ruby. It is designed for developers with experience in other languages who are looking to move to Ruby. I will cover the basics of Ruby syntax and idioms with an emphasis on things that are different from other languages.

My afternoon session is simply called Advanced Ruby. It is the perfect next step for people in my morning session, or anyone else who has some experience with Ruby, wanting to “level up” their skills. I will discuss Ruby’s object model, modules / mixins, and metaprogramming.

I’m looking forward to reconnecting with the community, both local and from around the world. If you’re at all interested in Ruby, I highly recommend this conference and I hope to see you there.

Upcoming Events

It’s a great time to be a Rubyist in Austin. There are several upcoming events that I’m looking forward to attending.

First, I’m giving a talk on Rails Application Security at the Austin on Rails meeting tomorrow evening. The meeting will also feature lightning talks covering a variety of beginner topics. Be sure to get there early.

Next, the second session of my GeekAustin Beginning Rails class starts August 4. The last class went really well and I’m looking forward to teaching it again. There are still seats available. For full details and to sign up, see the EventBright page at http://geekaustinrailsclass.eventbrite.com/.

Then, the Lone Star Ruby Conf starts on August 11 with a day of training. Followed by the conference proper on August 12 and 13. The keynote speakers and session topics are all outstanding this year. I am not speaking (this year), but I plan to be an active participant. Hopefully I’ll see you around town.

Your First Rails 3 Plugin

On several different projects I have needed to find the newest and oldest record in certain models. The code to do this is pretty simple (especially in Rails 3).

For example, here is a snippet to find the newest Post:

@post = Post.order('created_at DESC').first

We can make this even better by defining a method in the Post class like this:

def newest
  order('created_at DESC').first
end

With this new method our code becomes:

@post = Post.newest

But now we’re faced with having to add that method to lots of different models. This sounds like a perfect job for a simple Rails 3 plugin.

It’s Just a Gem

Plugins in Rails 3 are created just like any other Ruby gem. You can use whatever you like to create a new gem. Currently, I’m using Bundler:

bundle gem date_filter

This will create several files for you. The most important are the gemspec file and the contents of the lib directory.

The gemspec

Your gemspec file tells the world about your gem. The first thing you’ll want to do is edit this file and fill in the information marked with TODO – your name, e-mail address, gem summary, and gem description.

The rest of the file should take care of itself. Note that the gem version is stored in date_filter/version.rb. Also, the list of files, test files, and executables is filled in automatically with git commands.

The lib directory

Inside the lib directory you’ll find a file called date_filter.rb and a directory called date_filter. A common practice is to keep the contents of date_filter.rb pretty minimal.

Most of your actual code should go in separate files inside the date_filter
directory. For example, here is my date_filter.rb file in its entirety:

require 'active_record'
require File.expand_path('../date_filter/base', __FILE__)

ActiveRecord::Base.class_eval { include DateFilter::Base }

Note that I am requiring ActiveRecord here. This is based on wycats advice – If You Override Something, Require It

Next I require base.rb inside the date_filter directory. This contains the source for the plugin.

The last line actually includes my code into ActiveRecord::Base. Since I am adding class methods, I use class_eval.

date_filter/base.rb

Finally, here is the code for the plugin. It’s common practice to separate class methods from instance methods in Rails plugins. In this case I have a separate module for the class methods.

When DateFilter::Base is included into ActiveRecord::Base the method included is called. This method then extends ActiveRecord::Base with the methods in the ClassMethods module.

module DateFilter
  module Base
    def self.included(base)
      base.send :extend, ClassMethods
    end

    module ClassMethods
      def newest
        order('created_at DESC').first
      end

      def oldest
        order('created_at ASC').first
      end
    end
  end
end

Building and Installing

If you made it this far, you’re ready to build and install your new plugin. Bundler includes some rake tasks to help with this
automatically. You can see these by running rake -T

rake build
rake install
rake release

rake build will create a directory called pkg and build your new gem into this directory. You can then install it with the gem command.

rake install will build and install your new gem. To use it in a Rails project, you will need to add it to your Gemfile and run bundle install.

Releasing

If you have an account at RubyGems.org you can also release your new gem. Check your profile page for your API key. Include your API key in ~/.gem/credentials as instructed, then run rake release to build and upload your gem to the site.

This should get you started building your own Rails 3 plugins. There are still a couple of pretty important things missing from this process – tests and documentation. I plan to cover both of these in a future post.

The complete source for this plugin is up at github. The gem is also available at RubyGems.org.

GeekAustin Rails Class

Starting on May 26 I will be teaching a beginning Ruby on Rails class for GeekAustin. The class will meet every Thursday from 7:00 PM – 9:00 PM at Cospace. I have developed a pretty ambitious course outline that I hope to cover in just 8 weeks.

The class is only $120 for 16 hours of training. The demand for Rails developers is so high right now, this is a tiny investment to get started in a very hot market. Someone who understands Rails inside and out can make that money back in a couple of hours (or less).

You will need to know some HTML and CSS. Previous programming experience would also be helpful, but is not required. Prior experience with Ruby or Rails is also not required. I’m going to cover everything you need to know and provide plenty of references to other materials to fill in any gaps in your knowledge.

I have really missed teaching, and I am so thankful for this opportunity. Developing the course outline and working on materials has been great. It seems like I’m exercising a part of my brain I haven’t used in a while. I honestly can’t wait to get started teaching this.

This class will fill up fast. For full details and to sign up, see the EventBright page at http://geekaustinrailsclass.eventbrite.com/

Editing Multiple Records in Rails

I recently had a requirement to create a single form with data from more than one record. This is a simple request, but I had never done it before in Rails.

After experimenting for a while (and reading quite a few forum posts and StackOverflow answers) I came up with a working solution. Hopefully this will save someone a little time in the future.

First, let’s create a simple Rails app for managing users. Each user will have a first name, last name, and e-mail address. I’m using scaffolding to generate the code.

rails new multi_edit
cd multi_edit
bundle install
rails g scaffold User first_name:string last_name:string email:string
rake db:migrate

Next, add the new routes for editing all users. I tried to stick to the RESTful convention with these. I’m just using the word ‘all’ in place of the :id.

match 'users/all/edit' => 'users#edit_all', :as => :edit_all, :via => :get
match 'users/all' => 'users#update_all', :as => :update_all, :via => :put

Now, let’s add the edit_all method to our UsersController to get started. The only thing it needs to do is get all users.

def edit_all
  @users = User.all
end

Next, we build the form for editing all users.

<%= form_for :user, :url => update_all_path, :html => { :method => :put } do %>
  <table>
    <tr>
      <th>First Name</th>
      <th>Last Name</th>
      <th>E-Mail</th>
    </tr>
    <% @users.each do |user| %>
      <%= fields_for "user[]", user do |user_fields| %>
    <tr>
      <td><%= user_fields.text_field :first_name %></td>
      <td><%= user_fields.text_field :last_name %></td>
      <td><%= user_fields.email_field :email %></td>
    </tr>
      <% end %>
    <% end %>
  </table>

  <div class="actions">
    <%= submit_tag %>
  </div>
<% end %>

The interesting part of this code starts around line 9. As expected, we iterate over the users with @users.each.

The next line tells Rails to name the fields for each user with array notation. For example, user_fields.text_field :first_name will output a text field named user[1][first_name].

The params hash will include a ‘user’ key that contains a hash of information for each user. The key for each of these hashes will be the user id.

Now that we know what the params will look like, it’s pretty straight-forward to write the update_all method.

def update_all
  params['user'].keys.each do |id|
    @user = User.find(id.to_i)
    @user.update_attributes(params['user'][id])
  end
  redirect_to(users_url)
end

We iterate over each key in params['user'], then find and update the user associated with that id. I am leaving error checking as an exercise for the reader…

The complete source code for this simple application is on my GitHub page at https://github.com/anthonylewis/multi_edit