Ajaxy rails docs.

May 10th, 2008

I don’t know if i’m the only one with the problem, but i just couldn’t get the “doc:rails” rake task to work with the jaxdoc RDoc template. I finished by running rdoc by hand to create the docs, here’s the code Tell me if I forgot to exclude something.

Sometimes (in my case 2 times) you may have more than one application running off the same database, partially sharing model code. In the first case I had 4 apps (one main and four satellites) running this way, but the userbase was not shared between them (most users didn’t actually know of the other apps), so common sessions were not needed. In the second case (a distrbuted file sharing network) users floated between the main site and satellites and I wanted to include flash[:notices] while redirecting them. As you know, flash messages are kept in the session, so i needed all the apps to share the session data for the user.

There are 2 things you need to do to share sessions (this applies when using subdomains, i’m not sure if it’s doable with totally different domains).

First: make all the apps use the same session key and secret by editing the environment.rb file:
1
2
3
4
  config.action_controller.session = {
    :session_key => '_your_session',
    :secret      => 'some_long_string_of_letters_and_numbers'
  }
This is done so all your apps recognize each others session data. Second, you need to alter the session_domain option of ActionController (in one of your initializers files):

ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS.update(:session_domain => ".yourdomain.com")
This one is to make the subdomains recognize the main domain’s cookies.

My problem, however, was that this setup worked only one way. I could set session variables in the main app and read from the satellite, but not the other way. As found out later, the problem is that the rails2 default session store is CookieStore. And cookies written by the top level domain can’t be altered by subdomains. To fix this i had to migrate to the ActiveRecord session store.

After a few hours of setting all of this up and testing, I decided that all of this was too much pain and security issues to be used in production, so I’ll just have another way of sending messages between the apps. But I also thought that someone may find this info useful (the CookieStore problem wasn’t evident to me), so I wanted to share it =)

SSL client certificate login pt.4

February 26th, 2008

Well, I made some progress and now the whole thing is a rails plugin, based on the restful_authentication one. You can get it here: git://github.com/labria/restful-authentication.git

The readme has all the info. If something is missing, not working or anything else, please tell me, it’s my first rails plugin ever. By the way if you even bother testing it or looking at the code, please leave me a comment.

Things to do yet:
  • remove some hard-coded stuff.
  • make certificate delivery more natural (if I happen to find a way to do it)
  • dunno, I think much more will come up…

SSL client certificate login pt.3

February 25th, 2008

Well, I made it, kinda…

The code is still a awful mess, but it works. Some portions of the code and setup are dictated by my setup involving a nginx server. With apache it should be simpler, with lighttpd it wouldn’t work at all, as far as I know.

Anyway, this is the way it works. You go to the site with http and register. The modified restful_authentication plugin instantly generates your client certificate. You get by clicking a link in the p12 format. The signing (self-signed) certificate is generated with the first user certificate (i’ll move this to a rake task later). After installing the certificate you can go to the site with https (before installing it nginx would reject you and redirect you to the non-https version of the login page). Now, if you log out and go to the session/new page, your certificate gets checked and, if your user is found (he should be), you get logged in automagically. Not much, but it’s all it does.

Now, about the code. There is not much code, really. Everything works from a combination of the modded restful_authentication plugin and the QuickCert library. If someone will actually find the whole thing useful, i’ll repackage it as a restful_authentication plugin fork, with some rake tasks and generators, and stuff. The nginx server is configured to use a self-signed certificate for the SSL connection, and the app generated certificate to check client certificates, this way:
server {
    listen       443;
    server_name  ssltest.startika.com;
    ssl                  on;
    ssl_certificate      /u/stuff/CA/demoCA/private/server.crt;
    ssl_certificate_key  /u/stuff/CA/demoCA/private/server.key;
    ssl_client_certificate /u/apps/ssltest/current/cert/CA/cacert.pem;
    ssl_verify_client on;
    ssl_verify_depth 2;
    ssl_session_timeout  5m;
    error_page 496 http://ssltest.startika.com/session/new;
    error_page 495 http://ssltest.startika.com/session/new;
    error_page 497 http://ssltest.startika.com/session/new;
    ssl_protocols  SSLv2 SSLv3 TLSv1;
    ssl_ciphers  ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
    ssl_prefer_server_ciphers   on;
    root   /u/apps/ssltest/current;
    location / {
      proxy_set_header X-Real-IP  $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-FORWARDED_PROTO https;
      proxy_set_header X-SSL_CLIENT_S_DN $ssl_client_s_dn;
      proxy_set_header X-SSL_PROTO $ssl_protocol;
      proxy_pass http://ssl_test;
      break;
  }
}

Well, if you want to see for yourself, just go to http://ssltest.startika.com/.

If you want to see the code (I’m ashamed of it, but it’s the only proof I have I actually made this), you can get it from github here: http://github.com/labria/rails-ssl-authentication/ (sorry for the mess, I’m quite a noob programmer yet…)

PS: If you will actually go and test the thing, don’t forget Safari has serious issues with certificates, better use Firefox =)

SSL client certificate login pt.2

February 23rd, 2008

Well, I’ve made some progress at last. Now my test app lets you logon automatically if you happen to have a certificate whose name and email matches a user in the DB. Still, you have to have some certificate just to get to the site, but “a progress there is”.

Now I’ll try to figure out how to generate certificates for users (and the root cert too). The code is a mess, but it works, kinda.

UPD: wow! I just found http://segment7.net/projects/ruby/QuickCert/, it may save me 90% of the pain with the almost undocumented OpenSSL library!

SSL client certificate login pt.1

February 23rd, 2008

Being inspired by Dr.Nic I jumped on the idea of making a plugin to handle Client Certificate login in a rails app. But before writing a string of code i bumped into a problem with my favorite web server — nginx. Then you set up client certificates in apache, you must use the SSLRequire directive to check if the client certificate provided by the user is what you wanted to see from him. This is actually useful when you do some manual user restriction. But in the case of a app behind Apache managing logins, you can just omit this directive, pass the SSL_CLIENT_S_DN header to your script and you’re done.

But with nxing, it’s not the case. You have to use the ssl_verify_client directive to check the user’s cert. If the check passes, nginx happily forward some header to your script and everything is fine. But, if the check fails, nginx generates an error. You have the option to handle that error (actually, redirect the user somewhere), but it’s not what I want. The problem is that you can NOT redirect the user to some page in the same domain while still using https, because the certificate will be checked again and the user will find himself in an infinite loop.

Maybe I should write a patch for nginx with something like “ssl_verify_client_enforce” option to override this behavior, but I’ll leave this for later. For now I’ll try implementing a schema where the user gets to a https://domain/login page, and if the certificate check fails I’ll redirect him to http://domain/login to check his username/password. This way i can make it work no matter what server it happens to use.

Sometimes you don’t want to reveal the real id of the object in the system to the user for some reason. For example, you don’t want to reveal the number of items in the system, or let the user view all of them by simply changing the id in the address.

The most obvious and easy way to do it is to generate a fake id for the object and use it instead. Lets say we have a model named Foo and you want it to have a fake id. Here’s the code for it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Foo < ActiveRecord::Base
  before_validation_on_create :generate_fake_id

  def to_param
    fake_id
  end

protected
  def generate_fake_id
    string = random_string
    while Foo.find_by_fake_id(string)
      string = random_string
    end
    self.fake_id = string
  end
  
  def random_string(size = 8)
    chars = (('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a)
    (1..size).collect{|a| chars[rand(chars.size)] }.join
  end
end
Now, when you create a Foo with for example “Foo.create(:name => ‘first foo’)”, the model generates a random string of 8 characters and stores it in fake_id. The fake id is only generated once, on creation, so it’s not changed later on. Now, for the helpers. Suppose you have map.resources :foos in your routes.rb. The helper you user before, foo_path(@foo) now generates a url with the fake id (foos/Hd45jdg3), because of the to_param method. All you have to do, is to change your foos_controller this way:
1
2
3
4
5
class FoosController < ApplicationController
  def show
    @foo = Foo.find_by_fake_id(params[:id])
  end
end
The uniqueness of the fake_id is guarantied by the Foo.find_by_fake_id call in the generate_fake_id method. Yes, it does add an extra query to the database, but it’s not really impaction performance much unless you are generating a lot of objects all of the time. You can change the way the fake id looks like by modifying the array used in random_string. For example if you want to eliminate symbols that look much alike you can have it this way:
1
2
3
4
def random_string(size = 8)
   chars = (('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a) - %w(i o 0 1 l O)
   (1..size).collect{|a| chars[rand(chars.size)] }.join
end
And also: don’t forget to add the fake_id field to the table in the database.

Moving to 2.0 glitches: RSS

December 6th, 2007

While moving a project to Rails 2.0RC I bumped into the fact that old-style RSS generation didn't work anymore. The code I was using before was:
1
2
3
  def rss
    render  :layout =>  false
  end
And the template was named rss.rxml What it became after some googling and trial-and-failure:
1
2
3
4
5
6
  def index
    request.format = :rss
    respond_to do |format|
      format.rss  { render :layout => false }
    end
  end
And the template (the same one, actually) is now named index.rss.builder. The weird thing was that I tried to use :xml instead of :rss, and it didn't work. Anyway, it's working fine now.

Welcome!

December 5th, 2007

This is kinda YARW. Sounds much like YARV, but with the sole exception that W stands for weblog. Ruby blogs are numerous, but I think one more won't hurt. Maybe one day I'll have a revelation and post something really useful here. But not today, I'm too tired installing Mephisto and fighting it's multisite mod.