rails security review checklist

I’m reviewing the security of a web app built with Ruby on Rails, so I put together a checklist for a security audit. This isn’t a bank or high security situation, but there were a number of engineers and quite a bit of open source code, so I thought a few checks were in order.

Here’s the list I came up with that I thought other folks might appreciate as a starting point (special thanks to the sfruby list, Mike Gunderloy, and Scott Bronson for feedback):

0) Make sure your Rails and gems are up to date for latest security patches (see rails security mailing list for recent advisory notes)

1) Active Record audit:
  A) SQL injection:
    (i) whole word search for “find”, “first”, and “all” then visually inspect all instances of ActiveRecord find calls for potential SQL injection vulnerability (also search for “sql” not whole work search to find find_by_sql and “execute” to find cases where raw sql is executed.
    (ii) search your models for “named_scope” and check :conditions
  B) check for mass assignment Either disable mass assignment as Eric suggests in his article, or audit its use. If doing an audit, check every model to make sure it declares which attributes are settable with attr_accessible. (While attr_protected may technically work, a white list approach is recommended by security experts and the rails security advisory on this topic)

2) Scripting attack: search all eRB files for <%= and ensure that if dynamically generated text was originally entered by the user, it is HTML escaped. Consider rails_xss

3) Secure Access: If some of the site does not have public access, check controllers and ensure that public actions are specifically allowed and that protected access is the default

4) search for “eval” (whole word) and verify that usages are safe (assume javascript eval is ok)

5) search for “forgery” (not whole word), make sure that
config.action_controller.allow_forgery_protection = false
is only disabled in test config
protect_from_forgery should be in the ApplicationController, unless there is a good reason for it not to be

6) check user auth and review that controller actions are limited to expected use

7) passwords: not saved as clear-text in the db, not logged

8) check that private data is not stored in cookies

Posted in code | 5 Comments

markdown to textile with vim regex

So, I needed to change markdown to textile and google didn’t yield any handy scripts, so I sharpened my vim fu with Rubular, my favorite regular expression tester and came up with a few substitutions that took care of everything but lists and code blocks.

In vi, type ESC to go into command mode, then :%s/one/two/g will find every instance of “one” and replace it with “two”

First the easy stuff, headers. ^ finds the beginning of the line.

:%s/^# /h1. /g
:%s/^## /h2. /g
:%s/^### /h3. /g

To replace images, I needed to replace ![alt-text](link) with !link! so I needed to capture text. I suppose I didn’t really need the first capture, but I was working on the replace expression for a regular link when I realized it would be easier to do the images first. To understand the expression below, you need to know that \(stuff\) captures some text which can be inserted in the replacement text with \1 and \2, etc. So to get everything between square brackets, I use [\(.*\)]

:%s/!\[\(.*\)](\(.*\))/!\2!/g

All of my images appeared on a single line, so I didn’t catch a potential issue in the above expression until I got to replacing text links. I needed to use a non “greedy” capture so that I wouldn’t pull in text after the link that happened to include a parenthetical comment. Normally, in reg ex I would use (.*?) but in vim I needed to write \(.\{-}\) …wtf?

:%s/\[\(.*\)](\(.\{-}\))/"\1":\2/g

Special thanks to Adam Wolf’s tip via ShareGrove which helped me document these steps.

you can put VIM in a mode where the command history is just like another buffer. Not in insert mode, try q:

You should get a new buffer that you can edit with the command history in it, so “*yy would yank the current line into the system clipboard, etc.

Posted in code | Leave a comment

creating a custom rake task

There’s a nice Railscast introduction to rake for Rails, which goes into a number of other important details that aren’t covered in this post. Below is a little tutorial of creating a Rails rake task and getting it to run remotely on heroku.

Introduction to Rake

In lib/tasks, create a file called greet.rake

task :greet do
   puts "Hello world"
end

By naming the task .rake and putting it in this special place rails will automatically pick it up and make it available to you. You can see it listed if you type: rake -T on the command line. To run it:

rake greet

which will print “Hello world”

to run one task before another, specify a dependency like this (multiple tasks may be specified in the same file):

task :ask => :greet do
   puts "How are you?"
end

Writing a Practical Rake Task

Now for the task at hand, I’m going to create a rake task which creates a bunch of fake data for me to test with. First I’ll create a little experimental app:

rails rake_example
cd rake example
script/generate scaffold person first_name:string last_name:string
rake db:migrate

Here’s the rake task (lib/tasks/fake_people.rake):

require 'faker'

namespace :admin  do
  desc "create some fake data"
  task :fake_people => :environment do
    print "How many fake people do you want?"
    num_people = $stdin.gets.to_i
    num_people.times do
      Person.create(:first_name => Faker::Name.first_name,
                    :last_name => Faker::Name.last_name)
    end
    print "#{num_people} created.\n"
  end
end

Note that I’m using the faker gem (docs here) and I created a task dependency on loading the rails environment so I could access my Person model.

Now I can run

rake admin:fake_people

and it will prompt me to ask how many I want and then it will create them. Cool goodness, yes?

Running Remotely on Heroku

We’re not done yet. I want to deploy this on heroku and be able to run the task remotely. For this, there are two gotchas, first I can’t run an interactive script remotely; also I need to tell heroku that I am using the fake gem and make sure it is installed.

1) removing interactivity

Instead of an interactive script, we can set an environment variable or command line argument (thanks to a tip by Adam Wiggins).

My modified task looks like this:

require 'faker'

namespace :admin  do
  desc "create some fake data"
  task :fake_people => :environment do
    num_people = ENV['NUM_RECORDS'].to_i
    num_people.times do
      Person.create(:first_name => Faker::Name.first_name,
                    :last_name => Faker::Name.last_name)
    end
    print "#{num_people} created.\n"
  end
end

which I can call locally from the command line like this:

rake admin:fake_people NUM_RECORDS=1

2) adding gem to heroku

I need to create a gems manifest, which sounds fancy, but is simply creating a .gems file at the root of my app with contents similar to what I would put in my config environment.rb to specify that my app requires a gem:

faker --version ">=0.3.1"

3) Deploy and Run

So I can deploy my app to heroku with the usual steps

git init
git add .
git commit -m "example app for rake script testing"
heroku create
git push heroku master
heroku rake db:migrate

and run the task remotely:

heroku rake admin:fake_people NUM_RECORDS=1
Posted in code | 1 Comment

rails exceptions in xml

We ran into an issue last week where our XML APIs were returning HTML under certain error conditions, rather than the expected XML. Our solution was to add the following code to the ApplicationController:

  rescue_from Exception do |exception|
    respond_to do |format|
      format.xml  { render :xml =>
           "<error>Internal Server Error #{exception.message}</error>",
           :status => 500 }
      format.html { render :html => {:file => 'public/500.html'}, :status => 500 }
      format.json { render :json =>
            {:error => "Internal Server Error #{exception.message}"}.to_json,
             :status => 500 }
    end
  end

We might have also declared a rescue_action, and I’m not sure of the benefits of one over the other, except that perhaps we needed to implement a general form of rescue_from since we had another more specific form already declared.

It seemed to me that this should be the default behavior in rails, so I decided to dig into it a little more and see what I could discover. I started by making a little test app to reproduce the exception. The particular case from last week was a database limit that wasn’t being caught in the app with a length validation. When I tried to re-create the error in MySql, I noticed that no exception is thrown since MySql will just truncate the data (although perhaps that is only because I am not running MySql in strict mode). In PostgreSQL, the database layer will throw an exception.

Test app setup:

rails -d postgresql test_postgresql
cd test_postgresql/
script/generate scaffold person first:string last:string present:boolean

Edit the migration to create a database limit:

class CreatePeople < ActiveRecord::Migration
  def self.up
    create_table :people do |t|
      t.string :first, :limit => 40
      t.string :last, :limit => 40
      t.boolean :present

      t.timestamps
    end
  end

  def self.down
    drop_table :people
  end
end

Create the postgres user. Note double-quotes around user, single quotes around password. It has to be that way. Go figure.

$ sudo su postgres -c psql
postgres=# create user "test_postgresql" with superuser password 'password';
CREATE ROLE
postgres=# \q

Finally create the database, run migration, and start the server:

rake db:create:all
rake db:migrate
./script/server

If you point your browser at http://localhost:3000/people and try to create a person with more that 40 characters in the first name, you will see the following error:

ActiveRecord::StatementInvalid in PeopleController#create
PGError: ERROR:  value too long for type character varying(40)

That is all well and good; however, if you do the same in XML, you will get the same error in HTML.

$ curl -X POST -d "<person><first>This is a first name that is too long for the database limit</first></person>" -H "Content-Type: application/xml" http://localhost:3000/people.xml
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Action Controller: Exception caught</title>
  <style>
    body { background-color: #fff; color: #333; }

    body, p, ol, ul, td {
      font-family: verdana, arial, helvetica, sans-serif;
      font-size:   13px;
      line-height: 18px;
    }

That seems like a bug to me. Perhaps this should be a lighthouse ticket rather than a blog post.. still not confident in identifying bugs in Rails, so I figured I’d post here first.

Posted in code | 10 Comments

rails models are views?

Rails appears pretty strict about separation of the abstraction layers that make up its notion of a web application: models, view and controllers. If you were to suggest calling a presentation method, such as url_for, in your model, the stoic Rails advocate will have an allergic reaction. However, Rails thinks nothing of rendering a model directly as a view, such as:

format.json { render :json => @products }

Now, one might argue that this is controller code and the controller is allowed to interpret the model as a view. The controller’s job is to mediate this interaction. However, I feel that it is a dangerous shortcut, made even more so by how hard to seems to be to override. Perhaps the json implementation is simply incomplete.

In xml, this strange controller pattern is easily corrected by providing an xml view. The xml builder syntax is particularly readable, and it is easy to design your XML API effectively.

I haven’t found an equivalent for json. I tried to use a JSON API today to no avail. My model included image data which breaks when auto-rendered in JSON. What I really wanted was to include a URL instead of the image data, which I implement neatly in my xml.builder view:

xml.instruct!
xml.products("type"=>"array") do
  @products.each do |product|
    xml.product do
      xml.sku product.sku
      xml.name product.name
      xml.brand product.brand
      xml.img_url url_for(:controller => :products, :action => :show, :format=>:png, :id => product.id, :only_path => false)
    end
  end
end

The problem is that I want a similar view in JSON. The to_json API leads me to put this logic in my model (gasp!). In fact, the ActiveRecord::Serialization docs give an example of providing a method to generate JSON instead of a literal attribute. The example is of a “permalink” which seem suspiciously like something that belongs is the view layer.

  konata.to_json(:methods => :permalink)
  # => {"id": 1, "name": "Konata Izumi", "age": 16,
        "created_at": "2006/08/01", "awesome": true,
        "permalink": "1-konata-izumi"}

Today’s solution was to go back to using my comfortable old XML API, but I would prefer to consume JSON from the other side. I wonder if anyone is working on a JSON builder or if there is some clear solution that I haven’t yet stumbled upon.

Posted in code | 3 Comments

ruby unit test frameworks

In preparation for teaching Ruby in a class with test first teaching. I decided to evaluate a few test frameworks. I thought initially to use Test::Unit, since it seemed easy to understand and ships with Rails. Wolfram Arnold argued that Test::Unit would burden the new folks with legacy. Alex Chaffee also advocated RSpec, but other friends from the Twittervese had good things to say about shoulda. Some folks declared it to be simply a matter of taste.

Even so, I wanted to make an informed decision and refine my palette for Ruby tools, so I wrote a simple exercise in each of Test::Unit, Shoulda and RSpec.

Test::Unit

require 'test/unit'
require 'pig_latin'

class PigLatinTest < Test::Unit::TestCase
    include PigLatinTranslator

    def test_simple_word
        s = translate("nix")
        assert_equal("ixnay", s)
    end

    def test_word_beginning_with_vowel
        s = translate("apple")
        assert_equal("appleay", s)
    end

    def test_two_consonant_word
        s = translate("stupid")
        assert_equal("upidstay", s)
    end
end

With the above code saved as "test_pig_latin.rb" you run it by simply executing it with Ruby.

$ ruby test_pig_latin.rb
Loaded suite test_pig_latin
Started
FFF
Finished in 0.01091 seconds.

  1) Failure:
test_simple_word(PigLatinTest) [test_pig_latin.rb:9]:
<"ixnay"> expected but was
<"translation">.

  2) Failure:
test_two_consonant_word(PigLatinTest) [test_pig_latin.rb:19]:
<"upidstay"> expected but was
<"translation">.

  3) Failure:
test_word_beginning_with_vowel(PigLatinTest) [test_pig_latin.rb:14]:
<"appleay"> expected but was
<"translation">.

3 tests, 3 assertions, 3 failures, 0 errors

Shoulda

Notice in the code below that Shoulda is simply and extension to Test::Unit. The PigLatinTest also subclasses Test::Unit::TestCase, just as the example above; however, the code inside the test case looks substantially different (and more readable in my opinion). You can actually mix Shoulda tests (below) with regular TestCase test methods (above) in the same TestCase. This is an advantage to Shoulda over RSpec if you have a codebase that already has lots of unit tests; however, I have also used RSpec and Test::Unit in the same project (you just have to remember to 'rake test' and 'rake spec').

require 'rubygems'
require 'shoulda'
require 'pig_latin'

class PigLatinTest < Test::Unit::TestCase
  include PigLatinTranslator

  context "#translate" do

    should "translate a simple word: nix" do
      s = translate("nix")
      assert_equal("ixnay", s)
    end

    should "translate a word beginning with a vowel: apple" do
      s = translate("apple")
      assert_equal("appleay", s)
    end

    should "translate a two consonent word: stupid" do
      s = translate("stupid")
      assert_equal("upidstay", s)
    end

  end
end

With the code above saved as "test_shoulda_pig_latin.rb" you use the same process as above by just executing the file with ruby.

$ ruby test_shoulda_pig_latin.rb
Loaded suite test_shoulda_pig_latin
Started
FFF
Finished in 0.008268 seconds.

 1) Failure:
test: #translate should translate a simple word. (PigLatinTest)
 [test_shoulda_pig_latin.rb:12:in `__bind_1251676444_52936'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `call'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `test: #translate should translate a simple word. ']:
<"ixnay"> expected but was
<"translation">.

 2) Failure:
test: #translate should translate a two consonent word. (PigLatinTest)
 [test_shoulda_pig_latin.rb:22:in `__bind_1251676444_58860'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `call'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `test: #translate should translate a two consonent word. ']:
<"upidstay"> expected but was
<"translation">.

 3) Failure:
test: #translate should translate a word beginning with a vowel. (PigLatinTest)
 [test_shoulda_pig_latin.rb:17:in `__bind_1251676444_59935'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `call'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `test: #translate should translate a word beginning with a vowel. ']:
<"appleay"> expected but was
<"translation">.

3 tests, 3 assertions, 3 failures, 0 errors

RSpec

require "pig_latin"

describe "#translate" do
  include PigLatinTranslator

  it "should translate a simple word" do
    s = translate("nix")
    s.should == "ixnay"
  end

  it "should translate a word beginning with a vowel" do
    pending
    s = translate("apple")
    s.should == "appleay"
  end

  it "should translate a two consonent word: stupid" do
    pending
    s = translate("stupid")
    s.should == "upidstay"
  end

end

The code above is saved in a file called "pig_latin_spec.rb" and run it using the 'spec' command. You will need to have installed the rspec gem (sudo gem install rspec).

$ spec pig_latin_spec.rb
F**

Pending:

#translate should translate a word beginning with a vowel (TODO)
./pig_latin_spec.rb:11

#translate should translate a two consonent word: stupid (TODO)
./pig_latin_spec.rb:17

1)
'#translate should translate a simple word' FAILED
expected: "ixnay",
     got: "translation" (using ==)
./pig_latin_spec.rb:8:

Finished in 0.035728 seconds

3 examples, 1 failure, 2 pending

Conclusion

I like RSpec best since I find the output to be most readable. I love the pending keyword, which allows me to set up the tests as an exercise for the class with only one test failing. I find it helps focus on exactly one test and one failure. I considered going with Shoulda because the tests are just as readable as RSpec, even if the output takes some learning to read, because of my initial thought that Test::Unit held less magic. However, on closer inspection, I realized that Test::Unit has one significant magical incantation: you merely declare a class and when that class is defined, it runs the test. This seemed not the kind of topic I would want to teach in an intro class. Even some experienced programmers might struggle with understanding the mechanism that allows such a construct to function. I concluded that all of the test frameworks require serious magic, and picked RSpec since I found it to be most usable for test writing and analysis of the output.

Caveat: this exercise was for pure Ruby. In Rails, I wonder if Shoulda tests would be more concise, making them easier to write and read and, therefore, making it worth the steeper learning curve on reading the output.

Posted in code | 7 Comments

rails admin interface roundup

After my recent ActiveScaffold post, I heard about several newer alternatives from Jaime Flournoy, Mike Gunderloy, and some more web surfing. I evaluated four plugins for admin UI, using the following methodology:


rails xxx_simple
cd xxx_simple/
./script/generate scaffold Task title:string notes:text complete:boolean
rake db:migrate

plus whatever annotations to the code the plugin needed. Then I ran a little script to generate 500 records:

500.times do |counter|
  `curl -X POST -d "Another thing #{counter}More text with #{counter} thing" -H "Content-Type: application/xml" http://localhost:3000/tasks.xml`
end

They all support related models, but I only have screen shots from my simple test. I’ve listed them below with the ones I liked best at the top.

typus

Typus is the one I’m moving forward with. It has a clean interface and has nice configuration options. You can configure which columns are displayed and which are searched (with a nice UI touch of displaying the search criteria under the search box). It is actively maintained with quite a few contributors and a responsive google group. I really like how relationships are displayed (for which I don’t have a picture, sorry). The only drawback (for me) is that it has its own auth and I don’t really want to introduce a separate set of admin users for the project I am working on, and I’ll be looking into making a change to support my own auth.  By default, it adds it’s own typus_users table, but this could be a plus for some.


script/plugin install git://github.com/fesplugas/typus.git
script/generate typus
rake db:migrate
./script/server

Now visit http://localhost:3000/admin and you will be prompted for your email address, from which it will automatically create the first admin user (pretty slick). The default UI looks like this:


I ran into just one glitch where Rails reported "A copy of ApplicationController has been removed from the module tree but is still active!" but it was easily fixed. The error didn't happen in my simple project, but did in my real app. Francesc Esplugas has looked into it and so far can't reproduce it.

admin_data

I really liked admin_data. The simplicity of the install was breath-taking:

ruby script/plugin install git://github.com/neerajdotname/admin_data.git
sudo gem install will_paginate
./script/server

that's it. Now visit http://localhost:3000/admin_data and you'll see the following interface:


I didn't try it, but I really like the admin_data approach to integrating with the application's authentication: Add the following lines of code in an initializer at ~/config/initializers/admin_data.rb


# authorization check to see if the data should be shown to the user
ADMIN_DATA_VIEW_AUTHORIZATION = Proc.new { |controller|
   controller.send("admin_logged_in?") }
# authorization check to see if the user should be allowed to update the data
ADMIN_DATA_UPDATE_AUTHORIZATION = Proc.new { |controller| return false }

streamlined

Streamlined is nice, but not as pretty as ActiveScaffold. Not compatible with Rails 2.3. This and active_scaffold seem to be a little older than typus and admin_data and require you to modify your code similarly. I thought it nice that it provided its own admin layout. In my simple test I applied the series of steps and nested route as with active_scaffold.

class MyNiftyController < ApplicationController
  layout 'streamlined'
  acts_as_streamlined

...[anything else you want to do]
end


active_scaffold

See my previous post for details. This seems to be the grand-daddy of this genre of plugins and has a very active google group. I liked this plugin when I first tried it, but it hung when I applied it to my real app. Also, @jamieflournoy notes that he didn't like the UI for editing related models as much as he did Streamlined.

Posted in code | 6 Comments

getting started with activescaffold

The ActiveScafold plugin for Rails promises to be a huge time saver.  In just a few easy steps, you can create a full web interface for your database, complete with inline editing and fold out panels.  Of course, it helps to have some grasp about what it is doing or you can get stuck like I did this morning.  I’m no expert (yet), but since it is so very cool, I wanted to share what I’ve learned (with the help of Sean Dick and Ivan Storck at tonight’s SFRuby Hack session).

After installing the plugin, there are just 3 lines of code that magically generate the HTML pages, but the trick is knowing where to put them. There’s a nice intro on the github wiki that outlines common use cases:

  • Prototyping
  • Admin Interfaces
  • Embedded, Widget-Style
  • Data-Heavy Applications

The use case that led me to ActiveScaffold today was the creation of an admin interface.  I’m working on a website and the end user stuff is pretty nice, but there are a bunch of tables where the data needs a little love… no one wants to launch the site without at least a few corrections in the data and it is crazy to either delay the launch while we build an admin interface or have an engineer make corrections with sql updates.  Enter ActiveScaffold: a way to allow admins to make the changes they need with very little software development.  (Later I expect we’ll need to add some fancy bits to the admin interface, but ActiveScaffold promises to be configurable and extensible enough when the time comes and the key point is that I don’t expect to need those features this week.)

ActiveScaffold for Admin

Make a little app for this experiment:

rails active_scaffold
cd active_scaffold
./script/generate scaffold Task title:string notes:text  complete:boolean
rake db:migrate

Install the plugin, which is compatible with Rails 2.3.2 (yay!) and previous versions of rails (if you install  a specific revision)

./script/plugin install git://github.com/activescaffold/active_scaffold.git

Now we have an app that lets you create, view, edit and delete tasks. This is the end-user app, you could edit the views and remove controller actions to prevent editing, deleting and/or creation. We want to leave this interface as is, but create a separate set of pages to allow an administrator to view, create, modify and delete tasks.

Sean came up with the idea of using routes with a namespace to facilitate this. Here’s what we came up with:

In config/routes.rb add the following code:

map.namespace :admin do |admin|
   admin.resources :tasks
end

Create a copy of /app/views/layouts/tasks.html.erb and call it admin.html.erb (in same folder), then add the following lines inside the <head> tag:

<%= javascript_include_tag :defaults %>
<%= active_scaffold_includes %>

Create app/controllers/task_controller.rb:

class Admin::TasksController < TasksController
   layout "admin"
   active_scaffold :task
end

Check it out:

http://localhost:3000/admin/tasks


and when you click edit:

Posted in code | 8 Comments

openlaszlo simple post code

Here’s a little form for sending an XML post in OpenLaszlo. This is a useful little snippet of code, since as if you get one little content header or something wrong, Rails will be unforgiving with its powerful, yet strict implementation of REST.

What the app looks like (enter text in the top, click the button, response is printed in the lower box):

The code:

<canvas title="Test Post" proxied="false">
  <dataset src="http:/projects.xml" name="ds"
    ondata="response.setAttribute('text'this.childNodes[0].serialize())"/>
  <simplelayout spacing="4"/>
  <edittext id="postdata" multiline="true" width="400" height="200"
     text='&lt;project&gt; &lt;title&gt;XXX&lt;/title&gt; &lt;/project&gt;'/>
  <button text="post">
    <handler name="onclick">
    ds.setQueryParam("lzpostbody", postdata.text);
    ds.setAttribute("querytype", "POST");
    ds.setHeader("Content-Type", "application/xml")
    ds.doRequest();
  </handler>
  </button>
  <edittext id="response" multiline="true" width="400" height="280"/>
</canvas>

Posted in code | Leave a comment

simple web services with rails

Rails enables web services by default, which is pretty awesome, and I’ve been relying on that for a while. It is pretty nifty how Rails will magically parse XML post parameters, create an in-memory object and then save that object to the database without your having to write one line of code. However, when the magic fails it can be pretty hard to debug. I found it useful to run basic tests on the command line using curl (hearing the voice of Zach Moazeni in my head saying: “test your assumptions.”)

Below is a writeup of the set of curl commands and sample output for testing the default Rails XML REST APIs. This can serve as a cheat sheet for the experienced or an introduction for folks new to rails who want a basic understanding of the default webservice APIs.

Create an app, by typing the following commands into your terminal:


$ rails basic_app
$ cd basic_app
$ ./script/generate scaffold project title:string description:text
$ rake db:migrate
$ ./script/server

In Rails 2.3, you also need to added the following line to the top of app/controllers/projects_controller.rb (This will allow external access to the APIs.) You can make this change while the server is running, btw.


skip_before_filter :verify_authenticity_token

Leave that window open where you can see it, since it will output useful stuff from the log. Then in another terminal window, experiment with the following commands to interact with your application APIs.

Create

POST /projects.xml

Create a project object based on the XML representation given in the post body and save in the projects database table.

$ curl -X POST -d "<project><title>Awesome</title><description>This is an awesome project.</description></project>" -H "Content-Type: application/xml" http://localhost:3000/projects.xml

<?xml version="1.0" encoding="UTF-8"?>
<project>
  <created-at type="datetime">2009-06-21T10:13:43-07:00</created-at>
  <description>This is an awesome project.</description>
  <id type="integer">6</id>
  <title>Awesome</title>
  <updated-at type="datetime">2009-06-21T10:13:43-07:00</updated-at>
</project>

Index

GET /projects.xml

This returns a list of all of the projects in the database with an automatically generated XML representation.

$ curl http://localhost:3000/projects.xml<?xml version="1.0" encoding="UTF-8"?>

<projects type="array">
<project>
  <created-at type="datetime">2009-06-21T10:13:19-07:00</created-at>
  <description>This is an awesome project.</description>
  <id type="integer">1</id>
  <title>Awesome</title>
  <updated-at type="datetime">2009-06-21T10:13:19-07:00</updated-at>
</project>
<project>
  <created-at type="datetime">2009-06-21T10:13:43-07:00</created-at>
  <description>New information here</description>
  <id type="integer">2</id>
  <title>Awesome</title>
  <updated-at type="datetime">2009-06-21T10:49:21-07:00</updated-at>
</project>
</projects>

Show

GET /projects/1.xml

This returns an xml representation of the project with id #1

$ curl http://localhost:3000/projects/1.xml<?xml version="1.0" encoding="UTF-8"?>

<project>
  <created-at type="datetime">2009-06-21T10:45:19-07:00</created-at>
  <description>This is an awesome project.</description>
  <id type="integer">8</id>
  <title>Awesome</title>
  <updated-at type="datetime">2009-06-21T10:45:19-07:00</updated-at>
</project>

Update

PUT /projects/1.xml

This modifies the project with id #1

curl -X PUT -d "<project><description>New information here</description></project>" -H "Content-Type: application/xml" http://localhost:3000/projects/1.xml

Posted in code | 3 Comments