Email Flooding
Need
Prevent uncontrolled email sending that can lead to inbox saturation or spamming.
Context
- Usage of Elixir (version 1.11 and above) for building scalable and fault-tolerant applications
- Usage of Bamboo library for sending emails
Description
Non compliant code
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
- Introduce a delay between each email send.
- Limit the number of emails that can be sent in a given time period.
- Validate and sanitize user input to prevent abuse.
Compliant code
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.