logo

Database

Data Uniqueness Not Properly Verified

Need

To ensure that sensitive data intended for single use cannot be reused or regenerated.

Context

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

• Usage of Elixir Ecto for database query and manipulation

• Usage of unique tokens for database record identification

Description

1. Non compliant code

defmodule VulnerableApp.Accounts do
  alias VulnerableApp.Repo
  alias VulnerableApp.Accounts.User

  def create_user(attrs \ %{}) do
    %User{}
    |> User.changeset(attrs)
  end...

The following Elixir code creates a user record with a unique token but does not validate the uniqueness of the token. This means that an attacker could create multiple users with the same token, leading to potential security issues.

2. Steps

• Use Ecto's unique constraint feature to ensure that the token is unique across all users.

• Handle Ecto's unique violation error when inserting a new user.

3. Secure code example

defmodule SecureApp.Accounts do
  alias SecureApp.Repo
  alias SecureApp.Accounts.User

  def create_user(attrs \ %{}) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()...

The following Elixir code creates a user record with a unique token and validates the uniqueness of the token. This prevents an attacker from creating multiple users with the same token.