Prevent XSS vulnerabilities due to unvalidated user input in server error responses
defmodule MyApp.ErrorHandlerController do
use MyAppWeb, :controller
def error(conn, %{'msg' => msg}) do
send_resp(conn, 500, msg)
end
end
This code is vulnerable because it directly includes the 'msg' parameter from the user input in the server error response without any validation or sanitization. This can lead to a Cross-Site Scripting (XSS) attack if a user includes malicious script in the 'msg' parameter.
defmodule MyApp.ErrorHandlerController do
use MyAppWeb, :controller
def error(conn, %{'msg' => msg}) do
sanitized_msg = Phoenix.HTML.html_escape(msg)
send_resp(conn, 500, sanitized_msg)
end
end
This code is secure because it uses the 'html_escape/1' function from the 'Phoenix.HTML' module to sanitize the 'msg' parameter. This function escapes potentially unsafe characters, thereby preventing any scripts included in the 'msg' parameter from being executed.