Restricted Fields Manipulation - Elixir

Restricted Fields Manipulation - Elixir

Need

Ensure data integrity and prevent unauthorized information updates.

Context

  • Usage of Elixir (1.12.0 and above) for building scalable and fault-tolerant applications
  • Usage of Ecto for data access and manipulation
  • Usage of Phoenix framework for web request handling

Description

Non compliant code

        defmodule MyApp.EmployeeController do
  use MyApp, :controller

  def update(conn, %{"employee" => employee_params}) do
    {:ok, employee} = MyApp.EmployeeContext.update_employee(employee_params)
    render(conn, "show.html", employee: employee)
  end
end
        
        

This Elixir/Phoenix code does not check if the current user has the correct permissions to update the employee data. As a result, an attacker can initiate a request to update the data of any employee, changing critical information.

Steps

  • Implement user authentication and permission checks.
  • Before updating the employee data, ensure that the current user has the necessary permissions to do so.

Compliant code

        defmodule MyApp.EmployeeController do
  use MyApp, :controller

  def update(conn, %{"employee" => employee_params}) do
    current_user = get_current_user(conn)
    if MyApp.EmployeeContext.can_update_employee?(current_user, employee_params["id"]) do
      {:ok, employee} = MyApp.EmployeeContext.update_employee(employee_params)
      render(conn, "show.html", employee: employee)
    else
      send_resp(conn, :forbidden, "You are not allowed to update this employee.")
    end
  end
end
        
        

This secure Elixir/Phoenix code example includes a permissions check before updating the employee data. The can_update_employee? function checks if the current user has the necessary permissions to update the specified employee. This prevents an attacker from updating the data of any employee.

References