Prevent overlong content in user input, which can lead to resource exhaustion or other vulnerabilities
defmodule MyAppWeb.MyController do
use MyAppWeb, :controller
def create(conn, %{"body" => body}) do
# No input length validation
MyApp.create_item(body)
send_resp(conn, 200, "Item created")
end
end
This code is vulnerable because it doesn't validate the length of the 'body' parameter. An attacker can provide a very long input, potentially causing resource exhaustion or other vulnerabilities.
defmodule MyAppWeb.MyController do
use MyAppWeb, :controller
def create(conn, %{"body" => body}) do
if String.length(body) > 1000 do
send_resp(conn, 400, "Body is too long")
else
MyApp.create_item(body)
send_resp(conn, 200, "Item created")
end
end
end
This code is safe because it checks the length of the 'body' parameter before using it. If the length exceeds 1000, it returns an error response instead of passing the overlong input to 'MyApp.create_item'.