Stricter validation for Rails attachment_fu plugin

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

Comments are closed.