Archive for January, 2008

Stricter validation for Rails attachment_fu plugin

Thursday, January 31st, 2008

I came across a little snag while using Rick Olson’s excellent attachment_fu plugin to resize images via ImageScience. The problem is that ImageScience version 1.1.3 gets very unhappy when asked to resize a file that isn’t an image. As mentioned here, if you pass ImageScience a simple ASCII text file, it will unceremoniously abort your Ruby process, dumping the cryptic message “terminate called after throwing an instance of ‘int’.”

I stumbled on this behavior in a unit test, but a user could get it by uploading a text file with an image extension (e.g. JPG). Right now attachment_fu does check that an uploaded file is of a certain MIME type, but it uses the MIME type reported by the CGI module to do so. Presumably CGI is only looking at the filename’s extension, so it’s quite easy to dupe.

I didn’t feel like having to switch back to RMagick for image processing (eyes bleeding installation, arcane configuration, memory leaks, etc), so I added a little stricter content type validation to attachment_fu. The patch uses the Unix file command to actually sniff the uploaded file’s starting bits and ensure it’s really one of the allowed content types. Couldn’t think of a good way to do this cross-platform, but if anyone has suggestions let me know.

The patch is here if you want it. To turn on strict validation, add the following to your has_attachment call:

:content_type_validation => true

more from the geek humor dept

Friday, January 25th, 2008

From Code Like a Pythonista: Idiomatic Python, an excellent introduction to python idiom:

from module import *

You’ve probably seen this “wild card” form of the import statement. You may even like it. Don’t use it.

To paraphrase a well-known exchange:

(Exterior Dagobah, jungle, swamp, and mist.)

LUKE: Is from module import * better than explicit imports?
YODA: No, not better. Quicker, easier, more seductive.
LUKE: But how will I know why explicit imports are better than the wild-card form?
YODA: Know you will when your code you try to read six months from now.

Oh dear.