Questions › How to handle maliciously large input in a Rails form textarea

I have a textarea in one of my Rails forms that accepts free-form input from the user.

Client-side, I can set a maxlength: 500 on the form to prevent someone from maliciously pasting an excessively long input.

Server-side, how can I implement this same safeguard? Someone could bypass my form by disabling that property or POST directly to my endpoint with a textarea parameter that's incredibly long. I'm assuming an attack like that would bring down my server as it tries to parse the large text.

I can always check for length in my controller (e.g. if params[:input].length < 500...) but by that time the params[] is already set and has had to parse that input.

Does Rails take care of that type of attack? Or is there anything I can/should do?


2 Answers :
Muaaz Rafi answered

You can simply add a model validation, assuming you are storing your value via active record.

validates_length_of :input, :minimum => 5, :maximum => 500, :allow_blank => true

Server will reject if length exceeds the length. Or you can apply JavaScript before posting the form which checks the length of the textarea, let me know if you need further help or explanation.

user2490003 replied
Thanks for the response! I agree I can implement a model validation. However the controller receives and processes the request before it even tries to save it to the model/DB. A really really large text string could exceed the available memory when the controller tries to process it, right? This is more of an edge case, but I'm just concerned how Rails begins to handle this (potential) security vulnerability;
Richard Peck replied
In that case, just put a max length limit on the textarea input;
Muaaz Rafi replied
For that simple add a before filter and reject the request from controller level. You can also access when request hits the rack stack but further you will need to dig deep for that.;
Nick M answered

Let's put common sense and nature's laws first for a second. I think you're better off not worrying about this since for the user to send enogh data to slow down your app server they will have to wait for ages for this data to upload (actually reach your server). So if they do manage to send some 500gigs the web server will probably not accept it/error out/process will die and get restarted. So I'd be more concerned of 1000 users sending small chunks at the same time, say 1 meg each second each connection...this would cause the web server to spawn additional processes and run out of RAM/CPU so it would be a more efficient attack instead of sending a large chunk in one shot.

But If you feel there are chances your app will be exposed to this kind of malicious user/DoS attack then I'd suggest looking at a Cloudflare plan.