To prevent potential security vulnerabilities due to trusting and mixing untrusted data in the same data structure or structured message.
defmodule VulnerableApp do
def handle_request(params) do
{:ok, message} = build_message(params)
send_message(message)
end
defp build_message(params) do
{:ok, "Hello #{params[:name]}, your account balance is #{params[:balance]}"}
end
end
This Elixir code directly includes user-provided data in a structured message without any validation or sanitization. An attacker can potentially manipulate the message to introduce malicious payloads.
defmodule SecureApp do
def handle_request(params) do
sanitized_params = sanitize(params)
case validate(sanitized_params) do
:ok -> {:ok, message} = build_message(sanitized_params)
send_message(message)
{:error, reason} -> {:error, reason}
end
end
defp build_message(params) do
{:ok, "Hello #{params[:name]}, your account balance is #{params[:balance]}"}
end
end
This Elixir code validates and sanitizes user-provided data before including it in a structured message, thereby preventing potential injection attacks.