logo

Email Flooding - Elixir


Need

Prevent uncontrolled email sending that can lead to inbox saturation or spamming.


Context

  1. Usage of Elixir (version 1.11 and above) for building scalable and fault-tolerant applications
  2. Usage of Bamboo library for sending emails

Description

Insecure Code Example

def send_email(user, message) do
  new_email(to: user.email, subject: "Alert", body: message)
  |> Mailer.deliver_now()
end

def handle_request(request) do
  Enum.each(request.users, &send_email(&1, request.message))
end

In this example, the handle_request function sends an email to every user in a request without any rate limiting. This allows for potential email flooding if the users list is large or if requests are sent consecutively with little time in between.

Steps

  1. Introduce a delay between each email send.
  2. Limit the number of emails that can be sent in a given time period.
  3. Validate and sanitize user input to prevent abuse.

Secure Code Example

def send_email(user, message) do
  new_email(to: user.email, subject: "Alert", body: message)
  |> Mailer.deliver_later()
end

def handle_request(request) do
  request.users
  |> Enum.take(100)
  |> Enum.each(&send_email(&1, request.message))
end

This code introduces rate limiting by using the deliver_later() function, which queues the emails for later delivery rather than sending them immediately. It also limits the number of users that can receive an email in a single request to 100.


References

  • 122 - Email Flooding

  • Last updated

    2023/09/18