Skip to main content

Improper Type Assignation

Need

To prevent errors and potential security issues caused by assigning the wrong type of value to a variable

Context

  • Usage of Elixir for building scalable and fault-tolerant applications
  • Usage of Elixir for building scalable and fault-tolerant applications
  • Usage of dynamically typed language

Description

Non compliant code

defmodule VulnerableCode do
def add_one(input) do
input + 1
end
end

This Elixir code is vulnerable because it assigns a string to a variable that is expected to be a number. If a string is supplied instead of a number, an error will occur when trying to perform an arithmetic operation.

Steps

  • Perform type checking before using the variable.
  • Handle the error case when the value is not of the expected type.

Compliant code

defmodule SecureCode do
def add_one(input) when is_number(input) do
input + 1
end

def add_one(_input) do
{:error, "Input must be a number"}
end
end

This Elixir code is safe because it checks the type of the input before performing the arithmetic operation. If the input is not a number, an error message is returned instead of causing a runtime error.

References