prop/test/microwaveprop_web/api/rate_limiter_test.exs
Graham McIntire c6d2c48264
feat: secure /api/v1 REST API for regular-user actions
Adds bearer-token authenticated REST API at /api/v1 covering every
action a non-admin user can perform on the website: contact + beacon
submission, beacon-monitor management, propagation queries, profile
read/update, and self-service API token issuance/revocation.

Security: SHA-256-hashed bearer tokens (mwp_ prefix, plaintext shown
once at creation), RFC 9457 problem+json error responses, RFC 9651
RateLimit-* headers backed by an ETS bucket (600/min per token,
60/min per anonymous IP, 30/min on /auth/tokens), private-contact
filtering by viewer.

Docs at docs/api/README.md (prose reference) and docs/api/openapi.yaml
(OpenAPI 3.1 spec covering every endpoint, response, and schema).

Tests: 124 new tests across schema, plug, error renderer, rate
limiter, fallback, and every controller. 16/17 API modules at 100%
line coverage; FallbackController at 87.5% (one defmodule line, an
Erlang-cover artifact for action_fallback-only modules).
2026-05-09 08:59:54 -05:00

82 lines
2.1 KiB
Elixir

defmodule MicrowavepropWeb.Api.RateLimiterTest do
use ExUnit.Case, async: false
import Plug.Conn
import Plug.Test
alias MicrowavepropWeb.Api.RateLimiter
setup do
RateLimiter.reset()
:ok
end
describe "init/1" do
test "passes options through unchanged" do
assert RateLimiter.init(anon_limit: 5) == [anon_limit: 5]
end
end
describe "call/2 anonymous" do
test "annotates RateLimit headers and lets requests through under the limit" do
conn = RateLimiter.call(conn(:get, "/"), anon_limit: 3)
refute conn.halted
assert ["3"] = get_resp_header(conn, "ratelimit-limit")
assert ["2"] = get_resp_header(conn, "ratelimit-remaining")
assert [reset] = get_resp_header(conn, "ratelimit-reset")
assert String.to_integer(reset) >= 1
end
test "halts with 429 when the bucket is exhausted" do
opts = [anon_limit: 2, window_ms: 60_000]
_ = RateLimiter.call(conn(:get, "/"), opts)
_ = RateLimiter.call(conn(:get, "/"), opts)
conn = RateLimiter.call(conn(:get, "/"), opts)
assert conn.halted
assert conn.status == 429
assert get_resp_header(conn, "retry-after") != []
assert ["0"] = get_resp_header(conn, "ratelimit-remaining")
end
end
describe "call/2 authenticated" do
test "uses the auth_limit when current_api_token is assigned" do
conn =
:get
|> conn("/")
|> assign(:current_api_token, %{id: "tok-1"})
|> RateLimiter.call(auth_limit: 5, anon_limit: 1)
refute conn.halted
assert ["5"] = get_resp_header(conn, "ratelimit-limit")
end
test "different tokens occupy different buckets" do
opts = [auth_limit: 1]
conn_a =
:get
|> conn("/")
|> assign(:current_api_token, %{id: "A"})
|> RateLimiter.call(opts)
conn_b =
:get
|> conn("/")
|> assign(:current_api_token, %{id: "B"})
|> RateLimiter.call(opts)
refute conn_a.halted
refute conn_b.halted
end
end
describe "reset/0" do
test "clears the table even before any call" do
assert RateLimiter.reset() == :ok
end
end
end