Skip to content

Open source, privacy-first web analytics. Lightweight, cookie-free Google Analytics alternative. Self-hosted or cloud.

Implement POST /login/oauth/token endpoint (#6711)

Artur Pata033845ffc77a
diff --git a/lib/plausible_web/controllers/oauth/token_controller.ex b/lib/plausible_web/controllers/oauth/token_controller.ex
index b2cd7e6c34..b0b44a01c2 100644
--- a/lib/plausible_web/controllers/oauth/token_controller.ex
+++ b/lib/plausible_web/controllers/oauth/token_controller.ex
@@ -5,13 +5,69 @@ defmodule PlausibleWeb.OAuth.TokenController do
use PlausibleWeb, :controller
+ alias Plausible.OAuth
+
@doc """
Exchanges an authorization code or a refresh token for an access token at the
[token endpoint](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-token-endpoint).
"""
def token(conn, _params) do
+ if client_authentication_attempted?(conn) do
+ send_error(conn, "invalid_request")
+ else
+ grant(conn)
+ end
+ end
+
+ defp client_authentication_attempted?(conn) do
+ get_req_header(conn, "authorization") != []
+ end
+
+ defp grant(%Plug.Conn{body_params: %{"grant_type" => "authorization_code"} = params} = conn) do
+ with {:ok, code} <- require_param(params, "code"),
+ {:ok, verifier} <- require_param(params, "code_verifier"),
+ {:ok, redirect_uri} <- require_param(params, "redirect_uri"),
+ {:ok, client_id} <- require_param(params, "client_id"),
+ {:ok, resource} <- require_param(params, "resource"),
+ {:ok, auth_code} <-
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: client_id,
+ redirect_uri: redirect_uri,
+ resource: resource
+ }),
+ {:ok, token} <- OAuth.issue_token(auth_code) do
+ conn
+ |> put_resp_header("cache-control", "no-store")
+ |> put_resp_header("pragma", "no-cache")
+ |> json(token)
+ else
+ {:error, :missing_param, _name} ->
+ send_error(conn, "invalid_request")
+
+ {:error, _} ->
+ send_error(conn, "invalid_grant")
+ end
+ end
+
+ defp grant(%Plug.Conn{body_params: %{"grant_type" => _unsupported_grant_type}} = conn) do
+ send_error(conn, "unsupported_grant_type")
+ end
+
+ defp grant(conn) do
+ send_error(conn, "invalid_request")
+ end
+
+ defp require_param(params, name) do
+ case params[name] do
+ value when is_binary(value) and value != "" -> {:ok, value}
+ _ -> {:error, :missing_param, name}
+ end
+ end
+
+ defp send_error(conn, error) do
conn
- |> put_status(501)
- |> json(%{error: "not_implemented"})
+ |> put_status(400)
+ |> json(%{error: error})
end
end
diff --git a/test/plausible_web/controllers/oauth/token_controller_test.exs b/test/plausible_web/controllers/oauth/token_controller_test.exs
new file mode 100644
index 0000000000..78068f4868
--- /dev/null
+++ b/test/plausible_web/controllers/oauth/token_controller_test.exs
@@ -0,0 +1,189 @@
+defmodule PlausibleWeb.OAuth.TokenControllerTest do
+ use PlausibleWeb.ConnCase, async: true
+
+ alias Plausible.OAuth
+ alias Plausible.OAuth.{ProtectedResources, Token}
+
+ setup do
+ user = new_user()
+ {:ok, team} = Plausible.Teams.get_or_create(user)
+
+ code = "plausible-oauth-ac-test-code"
+ verifier = String.duplicate("v", 43)
+ resource = ProtectedResources.mcp()
+
+ auth_code =
+ insert(:oauth_authorization_code,
+ user: user,
+ team: team,
+ resource: ProtectedResources.get_resource_url(resource),
+ scopes: resource.scopes_supported,
+ code: code,
+ verifier: verifier
+ )
+
+ valid_params = %{
+ "grant_type" => "authorization_code",
+ "client_id" => auth_code.client_id,
+ "code" => code,
+ "code_verifier" => verifier,
+ "redirect_uri" => auth_code.redirect_uri,
+ "resource" => auth_code.resource
+ }
+
+ {:ok, auth_code: auth_code, resource: resource, valid_params: valid_params}
+ end
+
+ test "rejects a request with no grant_type" do
+ conn = build_conn() |> post("/login/oauth/token", %{})
+
+ assert_matches ^strict_map(%{"error" => "invalid_request"}) =
+ json_response(conn, 400)
+ end
+
+ test "rejects unknown grant_type" do
+ conn =
+ build_conn()
+ |> post("/login/oauth/token", %{"grant_type" => "foo"})
+
+ assert_matches ^strict_map(%{"error" => "unsupported_grant_type"}) =
+ json_response(conn, 400)
+ end
+
+ test "requires every parameter of the authorization_code grant", %{
+ valid_params: valid_params
+ } do
+ for param <- Map.keys(valid_params) -- ["grant_type"] do
+ conn = build_conn() |> post("/login/oauth/token", Map.delete(valid_params, param))
+
+ assert_matches ^strict_map(%{"error" => "invalid_request"}) =
+ json_response(conn, 400)
+
+ # empty param is the same as missing param
+ conn = build_conn() |> post("/login/oauth/token", %{valid_params | param => ""})
+
+ assert_matches ^strict_map(%{"error" => "invalid_request"}) =
+ json_response(conn, 400)
+ end
+ end
+
+ test "rejects a code redeemed under a different client_id", %{valid_params: valid_params} do
+ params = %{valid_params | "client_id" => "https://other.example.com/oauth-metadata"}
+
+ conn = build_conn() |> post("/login/oauth/token", params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+ end
+
+ test "rejects a mismatched redirect_uri", %{valid_params: valid_params} do
+ params = %{valid_params | "redirect_uri" => "https://other.example.com/callback"}
+
+ conn = build_conn() |> post("/login/oauth/token", params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+ end
+
+ test "rejects a mismatched resource", %{valid_params: valid_params} do
+ params = %{valid_params | "resource" => "https://elsewhere.example.com/mcp"}
+
+ conn = build_conn() |> post("/login/oauth/token", params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+ end
+
+ test "rejects wrong PKCE verifier, grant can't be used even if correct verifier presented after",
+ %{valid_params: valid_params} do
+ params = %{valid_params | "code_verifier" => "not-the-verifier"}
+
+ conn = build_conn() |> post("/login/oauth/token", params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+
+ conn = build_conn() |> post("/login/oauth/token", valid_params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+ end
+
+ test "exchanges a valid code for a bearer token bound to the code", %{
+ valid_params: valid_params,
+ auth_code: auth_code,
+ resource: resource
+ } do
+ resp_conn = build_conn() |> post("/login/oauth/token", valid_params)
+
+ resp = json_response(resp_conn, 200)
+
+ assert get_resp_header(resp_conn, "cache-control") == ["no-store"]
+ assert get_resp_header(resp_conn, "pragma") == ["no-cache"]
+
+ assert_matches ^strict_map(%{
+ "access_token" =>
+ ^any(
+ :string,
+ &String.starts_with?(&1, Token.plaintext_prefix(:access))
+ ),
+ "refresh_token" =>
+ ^any(
+ :string,
+ &String.starts_with?(&1, Token.plaintext_prefix(:refresh))
+ ),
+ "token_type" => "Bearer",
+ "expires_in" => ^OAuth.access_token_ttl_seconds(),
+ "scope" => "sites:read:*"
+ }) = resp
+
+ refute resp["refresh_token"] == resp["access_token"]
+
+ assert {:ok, grant} = OAuth.find_access_token(resp["access_token"], resource)
+
+ assert_matches %{
+ user: %{id: ^auth_code.user_id},
+ team: %{id: ^auth_code.team_id},
+ resource: ^auth_code.resource,
+ refresh_token_hash: ^Token.hash(resp["refresh_token"]),
+ revoked_at: nil
+ } = grant
+ end
+
+ test "code can be exchanged only once", %{valid_params: valid_params} do
+ assert build_conn() |> post("/login/oauth/token", valid_params) |> json_response(200)
+
+ conn = build_conn() |> post("/login/oauth/token", valid_params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+ end
+
+ test "rejects parameters provided in the query string", %{valid_params: valid_params} do
+ conn =
+ build_conn() |> post("/login/oauth/token?" <> URI.encode_query(valid_params), %{})
+
+ assert_matches ^strict_map(%{"error" => "invalid_request"}) =
+ json_response(conn, 400)
+
+ # passes when same params presented in body
+ assert build_conn() |> post("/login/oauth/token", valid_params) |> json_response(200)
+ end
+
+ test "refuses requests with Authorization header", %{valid_params: valid_params} do
+ for header <- ["", "Basic x", "Bearer x"] do
+ resp_conn =
+ build_conn()
+ |> put_req_header("authorization", header)
+ |> post("/login/oauth/token", valid_params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_request"}) =
+ json_response(resp_conn, 400)
+
+ assert get_resp_header(resp_conn, "www-authenticate") == []
+ end
+
+ # passes when same params presented without Authorization header
+ assert build_conn() |> post("/login/oauth/token", valid_params) |> json_response(200)
+ end
+end
diff --git a/test/support/factory.ex b/test/support/factory.ex
index 2be18eff06..df1d0af1b5 100644
--- a/test/support/factory.ex
+++ b/test/support/factory.ex
@@ -275,6 +275,32 @@ defmodule Plausible.Factory do
}
end
+ @doc """
+ Takes the plaintext `:code` and `:verifier` a test will present at the token
+ endpoint, and stores what the server keeps for them - the code's hash and the
+ verifier's S256 challenge. Both default to fresh random values.
+ """
+ def oauth_authorization_code_factory(attrs) do
+ {code, attrs} =
+ Map.pop_lazy(attrs, :code, fn -> Plausible.OAuth.Token.generate(:code).raw end)
+
+ {verifier, attrs} =
+ Map.pop_lazy(attrs, :verifier, fn ->
+ :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
+ end)
+
+ auth_code = %Plausible.OAuth.AuthorizationCode{
+ code_hash: Plausible.OAuth.Token.hash(code),
+ code_challenge: :crypto.hash(:sha256, verifier) |> Base.url_encode64(padding: false),
+ code_challenge_method: "S256",
+ client_id: "https://client.example.com/oauth-metadata",
+ redirect_uri: "https://client.example.com/callback",
+ expires_at: NaiveDateTime.add(NaiveDateTime.utc_now(:second), 600, :second)
+ }
+
+ merge_attributes(auth_code, attrs)
+ end
+
def imported_visitors_factory do
%{
table: "imported_visitors",