Lack of data validation - Special Characters - Elixir

Lack of data validation - Special Characters - Elixir

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

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
end
        
        

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

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.

Compliant code

        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)
      {:error, changeset} ->
        render(conn, "new.html", changeset: changeset)
    end
  end
end

defmodule MyApp.Accounts.User do
  use Ecto.Schema
  import Ecto.Changeset

  schema "users" do
    field :name, :string
  end

  def changeset(user, attrs) do
    user
    |> cast(attrs, [:name])
    |> validate_format(:name, ~r/^[a-zA-Z0-9_]*$/)
  end
end
        
        

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.

References