To prevent server saturation and potential Denial of Service (DoS) attacks
defmodule VulnerableApp.ApiController do
use Plug.Router
def index(conn, _params) do
# API logic here
send_resp(conn, 200, "OK")
end
plug :match
plug :dispatch
get "/", do: index(conn, params)
end
The following Elixir code exposes an API endpoint without any rate limiting, allowing clients to send as many requests as they want in a short period of time. This makes the application vulnerable to DoS attacks and log flooding.
defmodule SecureApp.ApiController do
use Plug.Router
use PlugAttack
plug PlugAttack.Blocker, otp_app: :my_app, name: :api
def index(conn, _params) do
# API logic here
send_resp(conn, 200, "OK")
end
plug :match
plug :dispatch
get "/", do: index(conn, params)
defoverridable [block: 2]
def block(conn, _opts), do: send_resp(conn, 429, "Too Many Requests")
end
The following Elixir code uses the 'plug_attack' library to implement rate limiting on the API endpoint. This prevents clients from sending too many requests in a short period of time, protecting the application from DoS attacks and log flooding.