Lack of data validation - Special Characters
Need
To prevent unexpected behavior and potential security risks from unvalidated user input.
Context
• Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
• Usage of Phoenix Framework for building web applications
Description
1. Non compliant code
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"user" => %{"name" => name}}) do
{:ok, user} = MyApp.Accounts.create_user(name)
render(conn, "show.html", user: user)
end
endIn this example, the user's name is accepted without validation. If a special character is included in the name, it can cause unexpected behavior or security vulnerabilities.
2. Steps
• Implement data validation for all user inputs.
• Use regular expressions to restrict the characters that can be included in the user's name.
• Handle validation errors gracefully and inform the user of the requirements.
3. Secure code example
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def create(conn, %{"user" => %{"name" => name}}) do
case MyApp.Accounts.create_user(name) do
{:ok, user} ->
render(conn, "show.html", user: user)
render(conn, "new.html", changeset: changeset)...In the secure code, the user's name is validated using a regular expression, ensuring that it contains only alphanumeric characters and underscores. If the validation fails, an error is returned and can be handled by the controller.