Files
pinchflat/test/pinchflat_web/api_auth_plug_test.exs
T
hermes-agent 75f75d8d19
Nix Flake Check / Nix Flake Check (push) Successful in 1m55s
Build and Test / Build and Test (push) Successful in 8m25s
Make API auth mandatory, manage tokens via web UI
BREAKING CHANGE: API authentication is now always required. The
PINCHFLAT_API_TOKEN env var is no longer used. Instead, tokens are
stored in the database and managed via Settings → API Access.

Changes:
- Add api_token column to settings table (migration)
- ApiAuthPlug reads from DB; returns 401 if no token configured
- Add API Access section to Settings page with generate/regenerate/revoke
- Add POST /settings/generate_api_token and /settings/revoke_api_token
- Remove api_token from config.exs and runtime.exs
- Update all API controller tests to set auth token in setup
- Update auth plug tests for mandatory authentication
- 1008 tests pass, zero warnings
2026-07-04 11:51:40 +00:00

76 lines
1.9 KiB
Elixir

defmodule PinchflatWeb.ApiAuthPlugTest do
use PinchflatWeb.ConnCase
import Pinchflat.ProfilesFixtures
alias Pinchflat.Settings
setup do
# Ensure api_token is cleared in DB for each test
Settings.set(api_token: nil)
:ok
end
describe "when no api_token is configured" do
test "returns 401 without Authorization header", %{conn: conn} do
conn = get(conn, ~p"/api/v1/media_profiles")
assert %{status: 401} = conn
end
test "returns 401 even with a Bearer token", %{conn: conn} do
conn =
conn
|> put_req_header("authorization", "Bearer some-token")
|> get(~p"/api/v1/media_profiles")
assert %{status: 401} = conn
end
end
describe "when api_token is configured" do
setup do
Settings.set(api_token: "secret-token-123")
:ok
end
test "allows access with correct Bearer token", %{conn: conn} do
conn =
conn
|> put_req_header("authorization", "Bearer secret-token-123")
|> get(~p"/api/v1/media_profiles")
assert %{status: 200} = conn
end
test "returns 401 without Authorization header", %{conn: conn} do
conn = get(conn, ~p"/api/v1/media_profiles")
assert %{status: 401} = conn
assert json_response(conn, 401)["errors"]["detail"] == "Unauthorized"
end
test "returns 401 with incorrect token", %{conn: conn} do
conn =
conn
|> put_req_header("authorization", "Bearer wrong-token")
|> get(~p"/api/v1/media_profiles")
assert %{status: 401} = conn
end
test "returns 401 with malformed Authorization header", %{conn: conn} do
conn =
conn
|> put_req_header("authorization", "secret-token-123")
|> get(~p"/api/v1/media_profiles")
assert %{status: 401} = conn
end
test "healthcheck endpoint does not require auth", %{conn: conn} do
conn = get(conn, ~p"/healthcheck")
assert %{status: 200} = conn
end
end
end