Skip to content

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

Implement refresh tokens (#6815)

Artur Pataa9c0c12470ab
diff --git a/lib/plausible/oauth.ex b/lib/plausible/oauth.ex
index 6fb99a054c..fdcc840402 100644
--- a/lib/plausible/oauth.ex
+++ b/lib/plausible/oauth.ex
@@ -8,8 +8,8 @@ defmodule Plausible.OAuth do
`Plausible.OAuth.PKCE`, `Plausible.OAuth.CIMD` and
`Plausible.OAuth.ProtectedResources`.
- Only the `authorization_code` grant is implemented at the token endpoint;
- redeeming a refresh token is not wired up yet.
+ The token endpoint implements the `authorization_code` and `refresh_token`
+ grants. Every refresh rotates both tokens.
"""
use Plausible.Repo
@@ -20,6 +20,7 @@ defmodule Plausible.OAuth do
@authorization_code_ttl_seconds 600
@access_token_ttl_seconds 3600
@refresh_token_ttl_seconds 30 * 24 * 3600
+ @refresh_grace_period_seconds 60
@roles_with_oauth Membership.roles!([:owner, :admin, :editor, :billing, :viewer])
@@ -37,6 +38,9 @@ defmodule Plausible.OAuth do
@spec refresh_token_ttl_seconds() :: pos_integer()
def refresh_token_ttl_seconds(), do: @refresh_token_ttl_seconds
+ @spec refresh_grace_period_seconds() :: pos_integer()
+ def refresh_grace_period_seconds(), do: @refresh_grace_period_seconds
+
@doc """
Creates a single-use authorization code bound to the given user and team.
@@ -104,7 +108,7 @@ defmodule Plausible.OAuth do
{:ok, AuthorizationCode.t()} | {:error, :invalid_grant}
def consume_authorization_code(code, presented) when is_binary(code) do
with {:ok, auth_code} <- delete_and_fetch_code(Token.hash(code)),
- :ok <- check_not_expired(auth_code.expires_at),
+ :ok <- check_not_expired(auth_code.expires_at, now()),
:ok <-
PKCE.verify(
auth_code.code_challenge,
@@ -145,38 +149,179 @@ defmodule Plausible.OAuth do
@spec issue_token(AuthorizationCode.t()) ::
{:ok, token_response()} | {:error, Ecto.Changeset.t()}
def issue_token(%AuthorizationCode{} = auth_code) do
- access = Token.generate(:access)
- refresh = Token.generate(:refresh)
- now = now()
+ {grant_changes, response} = generate_tokens(auth_code.scopes, now())
changeset =
- Grant.changeset(%{
+ grant_changes
+ |> Map.merge(%{
client_id: auth_code.client_id,
client_name: auth_code.client_name,
scopes: auth_code.scopes,
resource: auth_code.resource,
user_id: auth_code.user_id,
- team_id: auth_code.team_id,
- access_token_hash: access.hash,
- access_token_hint: access.hint,
- access_token_expires_at: NaiveDateTime.add(now, @access_token_ttl_seconds, :second),
- refresh_token_hash: refresh.hash,
- refresh_token_hint: refresh.hint,
- refresh_token_expires_at: NaiveDateTime.add(now, @refresh_token_ttl_seconds, :second)
+ team_id: auth_code.team_id
})
+ |> Grant.changeset()
+
+ with {:ok, _grant} <- Repo.insert(changeset), do: {:ok, response}
+ end
+
+ @doc """
+ Exchanges a refresh token for a new access and refresh token pair on the same
+ grant. The presented token stops working, and so does the access token issued
+ with it.
+
+ `presented` may carry `:client_id`, `:resource` and `:scope`. Each one that is
+ present must match the grant. `:scope` can't narrow the grant, since the grant
+ holds one scope set for both tokens.
+
+ The token displaced by the latest rotation is still recognised. Presented
+ within #{@refresh_grace_period_seconds} seconds of that rotation, it is
+ exchanged again, so a client that lost the response can recover. The token it
+ replaces becomes the recognised one, without restarting the window. Presented
+ later, it means the token leaked, and the whole grant is revoked.
+ """
+ @type presented_refresh() :: %{
+ optional(:client_id) => String.t() | nil,
+ optional(:resource) => String.t() | nil,
+ optional(:scope) => String.t() | nil
+ }
+
+ @spec refresh_token(String.t(), presented_refresh()) ::
+ {:ok, token_response()} | {:error, :invalid_grant | :invalid_scope}
+ def refresh_token(raw_refresh, presented) when is_binary(raw_refresh) do
+ hash = Token.hash(raw_refresh)
+
+ {:ok, result} =
+ Repo.transaction(fn ->
+ now = now()
+
+ case lock_grant_by_refresh_hash(hash) do
+ %Grant{refresh_token_hash: ^hash} = grant ->
+ exchange_current(grant, presented, now)
+
+ %Grant{previous_refresh_token_hash: ^hash} = grant ->
+ handle_replay(grant, presented, now)
+
+ nil ->
+ {:error, :invalid_grant}
+ end
+ end)
+
+ result
+ end
+
+ def refresh_token(_raw_refresh, _presented), do: {:error, :invalid_grant}
+
+ defp exchange_current(grant, presented, now) do
+ with :ok <- validate_grant_refreshable(grant, presented, now) do
+ {grant_changes, response} = generate_tokens(grant.scopes, now)
+
+ grant
+ |> Ecto.Changeset.change(grant_changes)
+ |> Ecto.Changeset.change(
+ previous_refresh_token_hash: grant.refresh_token_hash,
+ rotated_at: now
+ )
+ |> Repo.update!()
+
+ {:ok, response}
+ end
+ end
+
+ defp handle_replay(grant, presented, now) do
+ if in_grace_period?(grant, now) do
+ with :ok <- validate_grant_refreshable(grant, presented, now) do
+ {grant_changes, response} = generate_tokens(grant.scopes, now)
- with {:ok, _grant} <- Repo.insert(changeset) do
- {:ok,
- %{
- access_token: access.raw,
- refresh_token: refresh.raw,
- token_type: "Bearer",
- expires_in: @access_token_ttl_seconds,
- scope: Enum.join(auth_code.scopes, " ")
- }}
+ grant
+ |> Ecto.Changeset.change(grant_changes)
+ |> Ecto.Changeset.change(previous_refresh_token_hash: grant.refresh_token_hash)
+ |> Repo.update!()
+
+ {:ok, response}
+ end
+ else
+ revoke_grant(grant)
+ {:error, :invalid_grant}
end
end
+ defp lock_grant_by_refresh_hash(hash) do
+ Repo.one(
+ from(g in Grant,
+ where: g.refresh_token_hash == ^hash or g.previous_refresh_token_hash == ^hash,
+ lock: "FOR UPDATE"
+ )
+ )
+ end
+
+ defp in_grace_period?(grant, now) do
+ NaiveDateTime.diff(now, grant.rotated_at, :second) < @refresh_grace_period_seconds
+ end
+
+ defp validate_grant_refreshable(grant, presented, now) do
+ with :ok <- check_not_revoked(grant),
+ :ok <- check_not_expired(grant.refresh_token_expires_at, now),
+ # client_id must match when sent, see the
+ # [token endpoint extension](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-token-endpoint-extension-3)
+ :ok <- match_if_present(grant.client_id, presented[:client_id]),
+ # Tokens stay restricted to the resource server they were granted for, see
+ # [access token privilege restriction](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-access-token-privilege-rest).
+ # MCP clients must send this with every token request, see
+ # [resource parameter implementation](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#resource-parameter-implementation)
+ :ok <- match_if_present(grant.resource, presented[:resource]),
+ :ok <- check_same_scopes(grant, presented[:scope]) do
+ case validate_role(Memberships.team_role(team_id: grant.team_id, user_id: grant.user_id)) do
+ :ok -> :ok
+ {:error, :not_a_member} -> {:error, :invalid_grant}
+ end
+ end
+ end
+
+ defp check_not_revoked(%Grant{revoked_at: nil}), do: :ok
+ defp check_not_revoked(_grant), do: {:error, :invalid_grant}
+
+ defp match_if_present(_expected, nil), do: :ok
+ defp match_if_present(expected, presented), do: match(expected, presented)
+
+ defp check_same_scopes(_grant, nil), do: :ok
+
+ defp check_same_scopes(grant, scope) do
+ with {:ok, resource} <- ProtectedResources.get_by_url(grant.resource),
+ {:ok, scopes} <-
+ ProtectedResources.normalize_granted_scopes(String.split(scope), resource),
+ true <- scopes == grant.scopes do
+ :ok
+ else
+ _ -> {:error, :invalid_scope}
+ end
+ end
+
+ defp generate_tokens(scopes, now) do
+ access_token = Token.generate(:access)
+ refresh_token = Token.generate(:refresh)
+
+ grant_changes = %{
+ access_token_hash: access_token.hash,
+ access_token_hint: access_token.hint,
+ access_token_expires_at: NaiveDateTime.add(now, @access_token_ttl_seconds, :second),
+ refresh_token_hash: refresh_token.hash,
+ refresh_token_hint: refresh_token.hint,
+ refresh_token_expires_at: NaiveDateTime.add(now, @refresh_token_ttl_seconds, :second)
+ }
+
+ response = %{
+ access_token: access_token.raw,
+ refresh_token: refresh_token.raw,
+ token_type: "Bearer",
+ expires_in: @access_token_ttl_seconds,
+ scope: Enum.join(scopes, " ")
+ }
+
+ {grant_changes, response}
+ end
+
@doc """
Looks up the grant a raw access token belongs to, preloading the bound user, team,
and their current role in the team. Returns the grant and role.
@@ -257,8 +402,8 @@ defmodule Plausible.OAuth do
end
end
- defp check_not_expired(expires_at) do
- if NaiveDateTime.compare(expires_at, now()) == :gt do
+ defp check_not_expired(expires_at, now) do
+ if NaiveDateTime.compare(expires_at, now) == :gt do
:ok
else
{:error, :invalid_grant}
diff --git a/lib/plausible/oauth/grant.ex b/lib/plausible/oauth/grant.ex
index fb967a905b..014bf0e9ca 100644
--- a/lib/plausible/oauth/grant.ex
+++ b/lib/plausible/oauth/grant.ex
@@ -63,7 +63,10 @@ defmodule Plausible.OAuth.Grant do
# and we revoke the whole grant, locking out the one that exchanged it first
# and the one trying to exchange it now. We can't know which one of them was malicious.
#
- # Inside the grace period, we return the current pair again idempotently.
+ # Inside the grace period, we issue a fresh pair, replacing the current one.
+ # Only hashes are stored, so the current pair can't be returned again.
+ # The replaced token becomes the previous one and `rotated_at` stays, so
+ # presenting it after the grace period revokes the grant too.
# Grace is needed to prevent a connection timeout from stopping a working integration.
field :previous_refresh_token_hash, :string
field :rotated_at, :naive_datetime
diff --git a/lib/plausible_web/controllers/oauth/metadata_controller.ex b/lib/plausible_web/controllers/oauth/metadata_controller.ex
index bf3f4d19cd..96430495ca 100644
--- a/lib/plausible_web/controllers/oauth/metadata_controller.ex
+++ b/lib/plausible_web/controllers/oauth/metadata_controller.ex
@@ -37,7 +37,7 @@ defmodule PlausibleWeb.OAuth.MetadataController do
authorization_endpoint: Endpoint.url() <> @authorization_endpoint,
token_endpoint: Endpoint.url() <> @token_endpoint,
response_types_supported: ["code"],
- grant_types_supported: ["authorization_code"],
+ grant_types_supported: ["authorization_code", "refresh_token"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
client_id_metadata_document_supported: true
diff --git a/lib/plausible_web/controllers/oauth/token_controller.ex b/lib/plausible_web/controllers/oauth/token_controller.ex
index b0b44a01c2..09abfd7abf 100644
--- a/lib/plausible_web/controllers/oauth/token_controller.ex
+++ b/lib/plausible_web/controllers/oauth/token_controller.ex
@@ -37,10 +37,7 @@ defmodule PlausibleWeb.OAuth.TokenController do
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)
+ send_token(conn, token)
else
{:error, :missing_param, _name} ->
send_error(conn, "invalid_request")
@@ -50,6 +47,30 @@ defmodule PlausibleWeb.OAuth.TokenController do
end
end
+ defp grant(%Plug.Conn{body_params: %{"grant_type" => "refresh_token"} = params} = conn) do
+ with {:ok, refresh_token} <- require_param(params, "refresh_token"),
+ {:ok, client_id} <- check_optional_param(params, "client_id"),
+ {:ok, resource} <- check_optional_param(params, "resource"),
+ {:ok, scope} <- check_optional_param(params, "scope"),
+ {:ok, token} <-
+ OAuth.refresh_token(refresh_token, %{
+ client_id: client_id,
+ resource: resource,
+ scope: scope
+ }) do
+ send_token(conn, token)
+ else
+ {:error, :missing_param, _name} ->
+ send_error(conn, "invalid_request")
+
+ {:error, :invalid_scope} ->
+ send_error(conn, "invalid_scope")
+
+ {: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
@@ -65,6 +86,20 @@ defmodule PlausibleWeb.OAuth.TokenController do
end
end
+ defp check_optional_param(params, name) do
+ case params[name] do
+ nil -> {:ok, nil}
+ _ -> require_param(params, name)
+ end
+ end
+
+ defp send_token(conn, token) do
+ conn
+ |> put_resp_header("cache-control", "no-store")
+ |> put_resp_header("pragma", "no-cache")
+ |> json(token)
+ end
+
defp send_error(conn, error) do
conn
|> put_status(400)
diff --git a/lib/plausible_web/endpoint.ex b/lib/plausible_web/endpoint.ex
index a63319e902..f9e853595e 100644
--- a/lib/plausible_web/endpoint.ex
+++ b/lib/plausible_web/endpoint.ex
@@ -2,7 +2,6 @@ defmodule PlausibleWeb.Endpoint do
use Plausible
use Sentry.PlugCapture
use Phoenix.Endpoint, otp_app: :plausible
- use PlausibleWeb.VerifiedRoutes
on_ce do
plug :maybe_handle_acme_challenge
@@ -79,7 +78,7 @@ defmodule PlausibleWeb.Endpoint do
json_decoder: Phoenix.json_library()
)
- plug(Sentry.PlugContext)
+ plug(Sentry.PlugContext, body_scrubber: {__MODULE__, :scrub_sentry_body})
plug(Plug.MethodOverride)
plug(Plug.Head)
@@ -99,13 +98,24 @@ defmodule PlausibleWeb.Endpoint do
# CORS must not be supported at the [authorization endpoint](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-authorization-endpoint)
def cors(conn, _opts) do
- if conn.request_path == ~p"/login/oauth/authorize" do
+ if conn.path_info == ["login", "oauth", "authorize"] do
conn
else
CORSPlug.call(conn, @cors_opts)
end
end
+ # OAuth token requests carry live credentials in the body
+ @sentry_scrubbed_keys Sentry.Scrubber.default_param_keys() ++
+ ["code", "code_verifier", "access_token", "refresh_token"]
+
+ # The event ingestion endpoint is high traffic, so its body is reported unscrubbed
+ def scrub_sentry_body(%{path_info: ["api", "event"]} = conn), do: conn.params
+
+ def scrub_sentry_body(conn) do
+ Sentry.Scrubber.scrub(conn.params, keys: @sentry_scrubbed_keys)
+ end
+
def runtime_session(conn, _opts) do
Plug.run(conn, [{Plug.Session, runtime_session_opts()}])
end
diff --git a/test/plausible/oauth_test.exs b/test/plausible/oauth_test.exs
index 02035873db..5bd02e1aea 100644
--- a/test/plausible/oauth_test.exs
+++ b/test/plausible/oauth_test.exs
@@ -7,6 +7,7 @@ defmodule Plausible.OAuthTest do
- `Step 2: consume_authorization_code/2` redeems that code, exactly once
- `Step 3: issue_token/1 and find_access_token/2`: opens a grant from the redeemed code, returns token AND resolves an access token back to its grant
- `Step 4: revoke_grant/1 and after_user_removed_from_team/2` invalidates both tokens
+ - `Step 5: refresh_token/2` rotates both tokens
"""
use Plausible.DataCase
@@ -448,6 +449,200 @@ defmodule Plausible.OAuthTest do
end
end
+ describe "Step 5: refresh_token/2" do
+ test "rejects an unknown token" do
+ assert {:error, :invalid_grant} = OAuth.refresh_token("made-up", %{})
+ assert {:error, :invalid_grant} = OAuth.refresh_token(nil, %{})
+ end
+
+ test "rejects a revoked grant", %{user: user, team: team} do
+ response_a = issue_tokens(user, team)
+ {:ok, grant, _role} = OAuth.find_access_token(response_a.access_token, mcp())
+
+ :ok = OAuth.revoke_grant(grant)
+
+ assert {:error, :invalid_grant} = OAuth.refresh_token(response_a.refresh_token, %{})
+ end
+
+ test "rejects an expired token", %{user: user, team: team} do
+ response_a = issue_tokens(user, team)
+
+ Plausible.Repo.update_all(
+ from(g in Grant, where: g.refresh_token_hash == ^Token.hash(response_a.refresh_token)),
+ set: [refresh_token_expires_at: past()]
+ )
+
+ assert {:error, :invalid_grant} = OAuth.refresh_token(response_a.refresh_token, %{})
+ end
+
+ test "rejects a grant whose user has since left the team" do
+ owner = new_user()
+ {:ok, team} = Plausible.Teams.get_or_create(owner)
+ member = add_member(team, role: :editor)
+ response_a = issue_tokens(member, team)
+
+ Plausible.Teams.Membership
+ |> Repo.get_by!(team_id: team.id, user_id: member.id)
+ |> Repo.delete!()
+
+ assert {:error, :invalid_grant} = OAuth.refresh_token(response_a.refresh_token, %{})
+ end
+
+ test "rejects a grant whose user has since been downgraded to guest" do
+ owner = new_user()
+ {:ok, team} = Plausible.Teams.get_or_create(owner)
+ member = add_member(team, role: :editor)
+ response_a = issue_tokens(member, team)
+
+ Plausible.Teams.Membership
+ |> Repo.get_by!(team_id: team.id, user_id: member.id)
+ |> Ecto.Changeset.change(role: :guest)
+ |> Repo.update!()
+
+ assert {:error, :invalid_grant} = OAuth.refresh_token(response_a.refresh_token, %{})
+ end
+
+ test "accepts valid refresh token, rotates access and refresh token, invalidates old access token",
+ %{user: user, team: team} do
+ response_a = issue_tokens(user, team)
+ assert {:ok, initial_grant, _role} = OAuth.find_access_token(response_a.access_token, mcp())
+ # make it about to expire
+ initial_grant =
+ initial_grant
+ |> Ecto.Changeset.change(
+ refresh_token_expires_at:
+ :second |> NaiveDateTime.utc_now() |> NaiveDateTime.add(5, :second)
+ )
+ |> Repo.update!()
+
+ assert {:ok, response_b} =
+ OAuth.refresh_token(response_a.refresh_token, %{})
+
+ assert_matches ^strict_map(%{
+ access_token: ^any(:string),
+ refresh_token: ^any(:string),
+ token_type: "Bearer",
+ expires_in: ^OAuth.access_token_ttl_seconds(),
+ scope: ^Enum.join(supported_scopes(), " ")
+ }) = response_b
+
+ refute response_b.access_token == response_a.access_token
+ refute response_b.refresh_token == response_a.refresh_token
+
+ assert {:error, :invalid_token} = OAuth.find_access_token(response_a.access_token, mcp())
+ assert {:ok, grant, _role} = OAuth.find_access_token(response_b.access_token, mcp())
+
+ assert_matches %Grant{
+ user_id: ^user.id,
+ team_id: ^team.id,
+ access_token_hash: ^Token.hash(response_b.access_token),
+ access_token_hint: ^String.slice(response_b.access_token, -4, 4),
+ refresh_token_hash: ^Token.hash(response_b.refresh_token),
+ refresh_token_hint: ^String.slice(response_b.refresh_token, -4, 4),
+ previous_refresh_token_hash: ^Token.hash(response_a.refresh_token),
+ rotated_at: %NaiveDateTime{},
+ revoked_at: nil
+ } = grant
+
+ assert NaiveDateTime.after?(
+ grant.refresh_token_expires_at,
+ initial_grant.refresh_token_expires_at
+ )
+ end
+
+ test "accepts a request specifying client ID, resource and scopes; rejects without invalidating the grant if any of them are invalid",
+ %{
+ user: user,
+ team: team
+ } do
+ response_a = issue_tokens(user, team)
+
+ expected_params = %{
+ client_id: @client_id,
+ resource: resource(),
+ scope: response_a.scope
+ }
+
+ assert {:ok, response_b} =
+ OAuth.refresh_token(response_a.refresh_token, expected_params)
+
+ for {invalid_params, expected_error} <- [
+ {%{expected_params | scope: "stats:write:*"}, {:error, :invalid_scope}},
+ {%{expected_params | client_id: "https://other.example.com/oauth-metadata"},
+ {:error, :invalid_grant}},
+ {%{expected_params | resource: "https://other.example.com/mcp"},
+ {:error, :invalid_grant}}
+ ] do
+ assert ^expected_error = OAuth.refresh_token(response_b.refresh_token, invalid_params)
+ end
+
+ assert {:ok, _} = OAuth.refresh_token(response_b.refresh_token, expected_params)
+ end
+
+ test "replay during grace: the previous refresh token on file is accepted (to prevent loss of access when fumbling refresh attempt due to bad network)",
+ %{
+ user: user,
+ team: team
+ } do
+ response_a = issue_tokens(user, team)
+
+ # client presents refresh token A, it's accepted, but the client loses the response
+ {:ok, response_b} = OAuth.refresh_token(response_a.refresh_token, %{})
+ {:ok, grant_b, _role} = OAuth.find_access_token(response_b.access_token, mcp())
+ assert {:error, :invalid_token} = OAuth.find_access_token(response_a.access_token, mcp())
+
+ # client presents refresh token A again, it's accepted
+ assert {:ok, response_c} = OAuth.refresh_token(response_a.refresh_token, %{})
+ assert {:ok, grant_c, _role} = OAuth.find_access_token(response_c.access_token, mcp())
+ assert {:error, :invalid_token} = OAuth.find_access_token(response_b.access_token, mcp())
+
+ # a refresh during the grace period doesn't move rotated at
+ assert_matches %Grant{
+ id: ^grant_b.id,
+ previous_refresh_token_hash: ^Token.hash(response_b.refresh_token),
+ rotated_at: ^grant_b.rotated_at,
+ revoked_at: nil
+ } = grant_c
+
+ # refresh token A is not on file any more, so this is not considered a refresh token replay scenario, the grant is not revoked
+ assert {:error, :invalid_grant} = OAuth.refresh_token(response_a.refresh_token, %{})
+ assert {:ok, _grant, _role} = OAuth.find_access_token(response_c.access_token, mcp())
+ end
+
+ test "replay outside grace: the previous refresh token on file is rejected and the whole grant is invalidated (to protect the user from an attacker taking over the grant with a logged / leaked refresh token)",
+ %{
+ user: user,
+ team: team
+ } do
+ response_a = issue_tokens(user, team)
+
+ # attacker or client presents refresh token A, it's accepted
+ {:ok, response_b} = OAuth.refresh_token(response_a.refresh_token, %{})
+ {:ok, grant_b, _role} = OAuth.find_access_token(response_b.access_token, mcp())
+ assert {:error, :invalid_token} = OAuth.find_access_token(response_a.access_token, mcp())
+
+ grant_b
+ |> Ecto.Changeset.change(
+ rotated_at:
+ :second
+ |> NaiveDateTime.utc_now()
+ |> NaiveDateTime.add(
+ -OAuth.refresh_grace_period_seconds(),
+ :second
+ )
+ )
+ |> Repo.update!()
+
+ # attacker or client presents refresh token A, it's rejected
+ assert {:error, :invalid_grant} = OAuth.refresh_token(response_a.refresh_token, %{})
+
+ # both attacker and client locked out
+ assert {:error, :invalid_token} = OAuth.find_access_token(response_b.access_token, mcp())
+ assert {:error, :invalid_grant} = OAuth.refresh_token(response_b.refresh_token, %{})
+ assert Repo.reload!(grant_b).revoked_at
+ end
+ end
+
defp pkce do
verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
challenge = :crypto.hash(:sha256, verifier) |> Base.url_encode64(padding: false)
@@ -477,9 +672,16 @@ defmodule Plausible.OAuthTest do
OAuth.create_authorization_code(user, team, attrs)
end
- defp past, do: NaiveDateTime.add(NaiveDateTime.utc_now(:second), -1, :second)
+ defp past, do: :second |> NaiveDateTime.utc_now() |> NaiveDateTime.add(-1, :second)
defp issue_grant(user, team, overrides \\ %{}) do
+ response = issue_tokens(user, team, overrides)
+ {:ok, grant, _role} = OAuth.find_access_token(response.access_token, mcp())
+
+ {grant, response.access_token}
+ end
+
+ defp issue_tokens(user, team, overrides \\ %{}) do
{verifier, challenge} = pkce()
{:ok, code} = create_code(user, team, challenge, overrides)
@@ -492,8 +694,6 @@ defmodule Plausible.OAuthTest do
})
{:ok, response} = OAuth.issue_token(consumed_code)
- {:ok, grant, _role} = OAuth.find_access_token(response.access_token, mcp())
-
- {grant, response.access_token}
+ response
end
end
diff --git a/test/plausible_web/controllers/oauth/metadata_controller_test.exs b/test/plausible_web/controllers/oauth/metadata_controller_test.exs
index 909e5cf914..b4fb49e282 100644
--- a/test/plausible_web/controllers/oauth/metadata_controller_test.exs
+++ b/test/plausible_web/controllers/oauth/metadata_controller_test.exs
@@ -12,7 +12,7 @@ defmodule PlausibleWeb.OAuth.MetadataControllerTest do
"authorization_endpoint" => ^(issuer <> "/login/oauth/authorize"),
"token_endpoint" => ^(issuer <> "/login/oauth/token"),
"response_types_supported" => ["code"],
- "grant_types_supported" => ["authorization_code"],
+ "grant_types_supported" => ["authorization_code", "refresh_token"],
"code_challenge_methods_supported" => ["S256"],
"token_endpoint_auth_methods_supported" => ["none"],
"client_id_metadata_document_supported" => true
diff --git a/test/plausible_web/controllers/oauth/token_controller_test.exs b/test/plausible_web/controllers/oauth/token_controller_test.exs
index 5d393d8a7b..b7f30a41c8 100644
--- a/test/plausible_web/controllers/oauth/token_controller_test.exs
+++ b/test/plausible_web/controllers/oauth/token_controller_test.exs
@@ -186,4 +186,189 @@ defmodule PlausibleWeb.OAuth.TokenControllerTest do
# passes when same params presented without Authorization header
assert build_conn() |> post("/login/oauth/token", valid_params) |> json_response(200)
end
+
+ describe "refresh_token grant" do
+ setup %{auth_code: auth_code} do
+ refresh_token = Token.generate(:refresh).raw
+
+ grant =
+ insert(:oauth_grant,
+ user_id: auth_code.user_id,
+ team_id: auth_code.team_id,
+ refresh_token: refresh_token
+ )
+
+ valid_refresh_params = %{
+ "grant_type" => "refresh_token",
+ "refresh_token" => refresh_token,
+ "client_id" => grant.client_id,
+ "resource" => grant.resource,
+ "scope" => Enum.join(grant.scopes, " ")
+ }
+
+ {:ok, grant: grant, valid_refresh_params: valid_refresh_params}
+ end
+
+ test "requires refresh_token", %{valid_refresh_params: valid_refresh_params} do
+ for params <- [
+ Map.delete(valid_refresh_params, "refresh_token"),
+ %{valid_refresh_params | "refresh_token" => ""}
+ ] do
+ conn = build_conn() |> post("/login/oauth/token", params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_request"}) =
+ json_response(conn, 400)
+ end
+ end
+
+ test "rejects request with optional params when they are malformed", %{
+ valid_refresh_params: valid_refresh_params
+ } do
+ for {param_key, invalid_value} <- [
+ {"client_id", ["https://other.example.com/oauth-metadata"]},
+ {"client_id", ""},
+ {"resource", ["https://other.example.com/mcp"]},
+ {"scope", ["admin"]}
+ ] do
+ conn =
+ build_conn()
+ |> post("/login/oauth/token", %{valid_refresh_params | param_key => invalid_value})
+
+ assert_matches ^strict_map(%{"error" => "invalid_request"}) =
+ json_response(conn, 400)
+ end
+ end
+
+ test "issues a new token pair on the same grant", %{
+ grant: grant,
+ valid_refresh_params: valid_refresh_params,
+ resource: resource
+ } do
+ resp_conn = build_conn() |> post("/login/oauth/token", valid_refresh_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"] == valid_refresh_params["refresh_token"]
+
+ assert {:ok, %{id: grant_id}, _role} =
+ OAuth.find_access_token(resp["access_token"], resource)
+
+ assert grant_id == grant.id
+ end
+
+ test "accepts a request carrying only grant_type and refresh_token", %{
+ valid_refresh_params: valid_refresh_params
+ } do
+ params = Map.take(valid_refresh_params, ["grant_type", "refresh_token"])
+
+ assert build_conn() |> post("/login/oauth/token", params) |> json_response(200)
+ end
+
+ test "rejects an unknown refresh token", %{valid_refresh_params: valid_refresh_params} do
+ params = %{valid_refresh_params | "refresh_token" => Token.generate(:refresh).raw}
+
+ conn = build_conn() |> post("/login/oauth/token", params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+ end
+
+ test "rejects a mismatched client_id", %{valid_refresh_params: valid_refresh_params} do
+ params = %{valid_refresh_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 scope that was not granted", %{valid_refresh_params: valid_refresh_params} do
+ params = %{valid_refresh_params | "scope" => "stats:write:*"}
+
+ conn = build_conn() |> post("/login/oauth/token", params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_scope"}) =
+ json_response(conn, 400)
+ end
+
+ test "replay during grace: the previous refresh token is exchanged again", %{
+ grant: grant,
+ valid_refresh_params: valid_refresh_params,
+ resource: resource
+ } do
+ # client presents the refresh token, it's accepted, but the client loses the response
+ %{"access_token" => lost_access_token} =
+ build_conn() |> post("/login/oauth/token", valid_refresh_params) |> json_response(200)
+
+ # client presents the same refresh token again, it's accepted
+ %{"access_token" => access_token} =
+ build_conn() |> post("/login/oauth/token", valid_refresh_params) |> json_response(200)
+
+ grant_id = grant.id
+ assert {:error, :invalid_token} = OAuth.find_access_token(lost_access_token, resource)
+ assert {:ok, %{id: ^grant_id}, _role} = OAuth.find_access_token(access_token, resource)
+
+ # the original refresh token is not on file any more, so it's refused without revoking the grant
+ conn = build_conn() |> post("/login/oauth/token", valid_refresh_params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+
+ assert {:ok, _grant, _role} = OAuth.find_access_token(access_token, resource)
+ end
+
+ test "replay outside grace: the grant is revoked", %{
+ grant: grant,
+ valid_refresh_params: valid_refresh_params
+ } do
+ %{"refresh_token" => rotated} =
+ build_conn() |> post("/login/oauth/token", valid_refresh_params) |> json_response(200)
+
+ grant
+ |> Plausible.Repo.reload!()
+ |> Ecto.Changeset.change(
+ rotated_at:
+ :second
+ |> NaiveDateTime.utc_now()
+ |> NaiveDateTime.add(
+ -OAuth.refresh_grace_period_seconds(),
+ :second
+ )
+ )
+ |> Plausible.Repo.update!()
+
+ conn = build_conn() |> post("/login/oauth/token", valid_refresh_params)
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+
+ conn =
+ build_conn()
+ |> post("/login/oauth/token", %{valid_refresh_params | "refresh_token" => rotated})
+
+ assert_matches ^strict_map(%{"error" => "invalid_grant"}) =
+ json_response(conn, 400)
+
+ assert %{revoked_at: %NaiveDateTime{}} = Plausible.Repo.reload!(grant)
+ end
+ end
end