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?
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
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.