Page MenuHomePhorge

No OneTemporary

Size
55 KB
Referenced Files
None
Subscribers
None
diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index 448f767..be7fd4a 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,39 +1,39 @@
# SPDX-FileCopyrightText: 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
-image: elixir:1.7
+image: elixir:1.13
variables:
MIX_ENV: test
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- deps
- _build
stages:
- test
- publish
before_script:
- mix local.hex --force
- mix local.rebar --force
- mix deps.get
- mix compile --force
lint:
stage: test
script:
- mix format --check-formatted
unit-testing:
stage: test
coverage: '/(\d+\.\d+\%) \| Total/'
script:
- mix test --trace --preload-modules --cover
analysis:
stage: test
script:
- mix credo --strict --only=warnings,todo,fixme,consistency,readability
diff --git a/.woodpecker/lint.yaml b/.woodpecker/lint.yaml
new file mode 100644
index 0000000..f26a095
--- /dev/null
+++ b/.woodpecker/lint.yaml
@@ -0,0 +1,57 @@
+when:
+ - event: pull_request
+ path: [ "**/*.ex", "**/*.eex", "**/*.exs", "mix.exs", "mix.lock", ".woodpecker/**" ]
+ - event: push
+ branch: ${CI_REPO_DEFAULT_BRANCH}
+ path: [ "**/*.ex", "**/*.eex", "**/*.exs", "mix.exs", "mix.lock", ".woodpecker/**" ]
+
+variables:
+ script_file_entrypoint: &script_file_entrypoint
+ - /bin/sh
+ - -c
+ - 'printf "%s" "$CI_SCRIPT" | base64 -d > /tmp/ci-script.sh && /bin/sh -xe /tmp/ci-script.sh'
+ elixir_image: &elixir_image
+ docker.io/elixir:1.15-alpine
+
+steps:
+ mix-format:
+ image: *elixir_image
+ entrypoint: *script_file_entrypoint
+ failure: ignore
+ commands:
+ - |
+ if ! mix format --check-formatted; then
+ touch fail.stamp
+ exit 1
+ fi
+
+ credo:
+ image: *elixir_image
+ entrypoint: *script_file_entrypoint
+ failure: ignore
+ environment:
+ MIX_ENV: test
+ commands:
+ - adduser -D -h /home/testuser testuser
+ - mkdir -p /home/testuser/.mix /home/testuser/.hex
+ - chown -R testuser:testuser . /home/testuser
+ - su testuser -c "HOME=/home/testuser mix local.hex --force"
+ - su testuser -c "HOME=/home/testuser mix local.rebar --force"
+ - su testuser -c "HOME=/home/testuser mix deps.get"
+ - |
+ if ! su testuser -c "HOME=/home/testuser mix credo"; then
+ touch fail.stamp
+ exit 1
+ fi
+
+ ensure-status:
+ image: *elixir_image
+ entrypoint: *script_file_entrypoint
+ commands: |
+ if test -f fail.stamp; then
+ echo "One or more previous steps failed. Failing workflow..."
+ exit 1
+ else
+ echo "All steps passed."
+ exit 0
+ fi
diff --git a/.woodpecker/unit-testing-elixir-1.15.yaml b/.woodpecker/unit-testing-elixir-1.15.yaml
new file mode 100644
index 0000000..9f644fa
--- /dev/null
+++ b/.woodpecker/unit-testing-elixir-1.15.yaml
@@ -0,0 +1,27 @@
+when:
+ - event: pull_request
+ path: [ "**/*.ex", "**/*.eex", "**/*.exs", "mix.exs", ".woodpecker/**" ]
+ - event: push
+ branch: ${CI_REPO_DEFAULT_BRANCH}
+ path: [ "**/*.ex", "**/*.eex", "**/*.exs", "mix.exs", ".woodpecker/**" ]
+
+variables:
+ script_file_entrypoint: &script_file_entrypoint
+ - /bin/sh
+ - -c
+ - 'printf "%s" "$CI_SCRIPT" | base64 -d > /tmp/ci-script.sh && /bin/sh -xe /tmp/ci-script.sh'
+
+steps:
+ unit-testing-elixir-1.15:
+ image: elixir:1.15-alpine
+ entrypoint: *script_file_entrypoint
+ environment:
+ MIX_ENV: test
+ commands:
+ - adduser -D -h /home/testuser testuser
+ - mkdir -p /home/testuser/.mix /home/testuser/.hex
+ - chown -R testuser:testuser . /home/testuser
+ - su testuser -c "HOME=/home/testuser mix local.hex --force"
+ - su testuser -c "HOME=/home/testuser mix local.rebar --force"
+ - su testuser -c "HOME=/home/testuser mix deps.get"
+ - su testuser -c "HOME=/home/testuser mix test --preload-modules --warnings-as-errors"
diff --git a/.woodpecker/unit-testing-elixir-1.19.yaml b/.woodpecker/unit-testing-elixir-1.19.yaml
new file mode 100644
index 0000000..e7f928b
--- /dev/null
+++ b/.woodpecker/unit-testing-elixir-1.19.yaml
@@ -0,0 +1,27 @@
+when:
+ - event: pull_request
+ path: [ "**/*.ex", "**/*.eex", "**/*.exs", "mix.exs", ".woodpecker/**" ]
+ - event: push
+ branch: ${CI_REPO_DEFAULT_BRANCH}
+ path: [ "**/*.ex", "**/*.eex", "**/*.exs", "mix.exs", ".woodpecker/**" ]
+
+variables:
+ script_file_entrypoint: &script_file_entrypoint
+ - /bin/sh
+ - -c
+ - 'printf "%s" "$CI_SCRIPT" | base64 -d > /tmp/ci-script.sh && /bin/sh -xe /tmp/ci-script.sh'
+
+steps:
+ unit-testing-elixir-1.19:
+ image: elixir:1.19-alpine
+ entrypoint: *script_file_entrypoint
+ environment:
+ MIX_ENV: test
+ commands:
+ - adduser -D -h /home/testuser testuser
+ - mkdir -p /home/testuser/.mix /home/testuser/.hex
+ - chown -R testuser:testuser . /home/testuser
+ - su testuser -c "HOME=/home/testuser mix local.hex --force"
+ - su testuser -c "HOME=/home/testuser mix local.rebar --force"
+ - su testuser -c "HOME=/home/testuser mix deps.get"
+ - su testuser -c "HOME=/home/testuser mix test --preload-modules --warnings-as-errors"
diff --git a/config/config.exs b/config/config.exs
index 08941af..d4210f3 100644
--- a/config/config.exs
+++ b/config/config.exs
@@ -1,10 +1,10 @@
# SPDX-FileCopyrightText: 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
-use Mix.Config
+import Config
config :http_signatures, adapter: HTTPSignatures.NullAdapter
if Mix.env() == :test do
config :http_signatures, adapter: HTTPSignatures.TestAdapter
end
diff --git a/lib/http_signatures/http_signatures.ex b/lib/http_signatures/http_signatures.ex
index bea941b..ea7ce9d 100644
--- a/lib/http_signatures/http_signatures.ex
+++ b/lib/http_signatures/http_signatures.ex
@@ -1,114 +1,302 @@
# Pleroma: A lightweight social networking server
-# SPDX-FileCopyrightText: 2017-2019 Pleroma Authors <https://pleroma.social/>
+# SPDX-FileCopyrightText: 2017-2026 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
# https://tools.ietf.org/html/draft-cavage-http-signatures-08
defmodule HTTPSignatures do
@moduledoc """
HTTP Signatures library.
"""
require Logger
+ @doc "Split raw signature string into a Map of individual components."
+ @spec split_signature(binary()) :: map()
def split_signature(sig) do
default = %{"headers" => "date"}
sig =
sig
|> String.trim()
|> String.split(",")
|> Enum.reduce(default, fn part, acc ->
[key | rest] = String.split(part, "=")
value = Enum.join(rest, "=")
Map.put(acc, key, String.trim(value, "\""))
end)
Map.put(sig, "headers", String.split(sig["headers"], ~r/\s/))
end
+ @spec validate(map(), map(), any()) :: boolean()
def validate(headers, signature, public_key) do
- sigstring =
- build_signing_string(
- headers,
- signature["headers"],
- signature["created"],
- signature["expires"]
- )
+ headers = stringify_keys(headers)
+
+ # Request-target isn't supposed to be in request headers coming from the outside,
+ # it is supposed to be added by the validate_conn/1 caller prior to calling us.
+ with :ok <- validate_required_headers(headers, signature["headers"]),
+ :ok <- validate_signature_params(signature) do
+ sigstring =
+ build_signing_string(
+ headers,
+ signature["headers"],
+ signature["created"],
+ signature["expires"]
+ )
+
+ Logger.debug("Signature: #{signature["signature"]}")
+ Logger.debug("Sigstring: #{sigstring}")
- Logger.debug("Signature: #{signature["signature"]}")
- Logger.debug("Sigstring: #{sigstring}")
- {:ok, sig} = Base.decode64(signature["signature"])
- :public_key.verify(sigstring, :sha256, sig, public_key)
+ {:ok, sig} = Base.decode64(signature["signature"])
+ :public_key.verify(sigstring, :sha256, sig, public_key)
+ else
+ {:error, :host_header} ->
+ Logger.error("#{__MODULE__}: required header Host not found in signature headers")
+ false
+
+ {:error, :request_target_header} ->
+ Logger.error(
+ "#{__MODULE__}: required header (request-target) or @request-target not found in signature headers"
+ )
+
+ false
+
+ {:error, reason} ->
+ Logger.error("#{__MODULE__}: invalid signature parameter #{reason}")
+ false
+ end
end
+ @doc "Fetch public key and validate signature."
+ @spec validate_conn(Plug.Conn.t()) :: boolean()
def validate_conn(conn) do
adapter = Application.get_env(:http_signatures, :adapter)
with {:ok, public_key} <- adapter.fetch_public_key(conn) do
- if validate_conn(conn, public_key) do
- true
- else
- Logger.debug("Could not validate, trying to refetch any relevant keys")
-
- with {:ok, public_key} <- adapter.refetch_public_key(conn) do
- validate_conn(conn, public_key)
- end
+ case validate_conn(conn, public_key) do
+ true ->
+ true
+
+ false ->
+ maybe_refetch_key_and_retry(conn, adapter)
end
else
e ->
Logger.debug("Could not validate against known public keys: #{inspect(e)}")
false
end
end
+ @doc "Validate signature using specified public key."
+ @spec validate_conn(Plug.Conn.t(), any()) :: boolean()
def validate_conn(conn, public_key) do
headers = Enum.into(conn.req_headers, %{})
signature = split_signature(headers["signature"])
validate(headers, signature, public_key)
end
@doc "Get signature for conn in split form."
+ @spec signature_for_conn(Plug.Conn.t()) :: map()
def signature_for_conn(conn) do
with headers <- Enum.into(conn.req_headers, %{}),
signature when is_binary(signature) <- headers["signature"] do
split_signature(signature)
else
_ ->
%{}
end
end
- def build_signing_string(headers, used_headers, created, expires) do
+ @spec build_signing_string(map(), list()) :: String.t()
+ def build_signing_string(headers, used_headers) do
+ headers = stringify_keys(headers)
+ build_signing_string(headers, used_headers, headers["(created)"], headers["(expires)"])
+ end
+
+ @spec build_signing_string(map(), list(), any(), any()) :: String.t()
+ defp build_signing_string(headers, used_headers, created, expires) do
+ headers = stringify_keys(headers)
+
used_headers
|> Enum.map_join("\n", fn
- "(created)" -> "(created): #{created}"
- "(expires)" -> "(expires): #{expires}"
- header -> "#{header}: #{headers[header]}"
+ "(created)" -> "(created): #{created || headers["(created)"]}"
+ "(expires)" -> "(expires): #{expires || headers["(expires)"]}"
+ header -> "#{header}: #{headers[to_string(header)]}"
end)
end
+ @doc "Create rsa-sha256 signature."
+ @spec sign(any(), String.t(), map()) :: String.t()
def sign(private_key, key_id, headers) do
+ headers = stringify_keys(headers)
+ header_names = Enum.sort(Map.keys(headers))
+
sigstring =
build_signing_string(
headers,
- Enum.sort(Map.keys(headers)),
+ header_names,
headers["(created)"],
headers["(expires)"]
)
signature =
:public_key.sign(sigstring, :sha256, private_key)
|> Base.encode64()
[
keyId: key_id,
- algorithm: "rsa-sha256",
- headers: Map.keys(headers) |> Enum.sort() |> Enum.join(" "),
+ algorithm: signature_algorithm(header_names),
+ headers: Enum.join(header_names, " "),
signature: signature,
created: headers["(created)"],
expires: headers["(expires)"]
]
|> Enum.filter(fn {_, v} -> v != nil end)
- |> Enum.map_join(",", fn {k, v} -> "#{k}=\"#{v}\"" end)
+ |> Enum.map_join(",", &format_signature_param/1)
+ end
+
+ defp stringify_keys(headers), do: Map.new(headers, fn {k, v} -> {to_string(k), v} end)
+
+ defp format_signature_param({key, value}) when key in [:created, :expires],
+ do: "#{key}=#{value}"
+
+ defp format_signature_param({key, value}), do: "#{key}=\"#{value}\""
+
+ defp signature_algorithm(headers) do
+ if special_signature_header?(headers), do: "hs2019", else: "rsa-sha256"
+ end
+
+ defp empty?(nil), do: true
+ defp empty?(""), do: true
+ defp empty?(_), do: false
+
+ defp has_header?(header_name, req_headers, sig_headers),
+ do: header_name in sig_headers && !empty?(req_headers[header_name])
+
+ defp has_request_target?(req_headers, sig_headers) do
+ has_header?("(request-target)", req_headers, sig_headers) ||
+ has_header?("@request-target", req_headers, sig_headers)
+ end
+
+ defp special_signature_header?(sig_headers),
+ do: "(created)" in sig_headers || "(expires)" in sig_headers
+
+ defp validate_signature_params(signature) do
+ sig_headers = signature["headers"] || []
+
+ with :ok <- validate_special_header_algorithm(signature, sig_headers),
+ :ok <- validate_created_param(signature, sig_headers) do
+ validate_expires_param(signature, sig_headers)
+ end
+ end
+
+ defp validate_special_header_algorithm(signature, sig_headers) do
+ if special_signature_header?(sig_headers) &&
+ disallowed_special_algorithm?(signature["algorithm"]) do
+ {:error, :special_header_algorithm}
+ else
+ :ok
+ end
+ end
+
+ defp disallowed_special_algorithm?(algorithm) when is_binary(algorithm) do
+ algorithm = String.downcase(algorithm)
+ Enum.any?(["rsa", "hmac", "ecdsa"], &String.starts_with?(algorithm, &1))
+ end
+
+ defp disallowed_special_algorithm?(_), do: false
+
+ defp validate_created_param(signature, sig_headers) do
+ if "(created)" in sig_headers do
+ signature["created"]
+ |> parse_integer_timestamp()
+ |> validate_created_timestamp()
+ else
+ :ok
+ end
+ end
+
+ defp validate_expires_param(signature, sig_headers) do
+ if "(expires)" in sig_headers do
+ signature["expires"]
+ |> parse_timestamp()
+ |> validate_expires_timestamp()
+ else
+ :ok
+ end
+ end
+
+ defp parse_integer_timestamp(value) when is_integer(value), do: {:ok, value}
+
+ defp parse_integer_timestamp(value) when is_binary(value) do
+ case Integer.parse(value) do
+ {timestamp, ""} -> {:ok, timestamp}
+ _ -> :error
+ end
+ end
+
+ defp parse_integer_timestamp(_), do: :error
+
+ defp parse_timestamp(value) when is_integer(value), do: {:ok, value}
+
+ defp parse_timestamp(value) when is_float(value), do: {:ok, value}
+
+ defp parse_timestamp(value) when is_binary(value) do
+ case Float.parse(value) do
+ {timestamp, ""} -> {:ok, timestamp}
+ _ -> :error
+ end
+ end
+
+ defp parse_timestamp(_), do: :error
+
+ defp validate_created_timestamp({:ok, timestamp}) do
+ if timestamp <= System.system_time(:second), do: :ok, else: {:error, :created_in_future}
+ end
+
+ defp validate_created_timestamp(:error), do: {:error, :created_param}
+
+ defp validate_expires_timestamp({:ok, timestamp}) do
+ if timestamp >= System.system_time(:second), do: :ok, else: {:error, :expires_in_past}
+ end
+
+ defp validate_expires_timestamp(:error), do: {:error, :expires_param}
+
+ defp validate_required_headers(req_headers, sig_headers) do
+ sig_headers = sig_headers || []
+
+ cond do
+ not has_header?("host", req_headers, sig_headers) -> {:error, :host_header}
+ not has_request_target?(req_headers, sig_headers) -> {:error, :request_target_header}
+ true -> :ok
+ end
+ end
+
+ defp retryable_signature_failure?(conn) do
+ headers = Enum.into(conn.req_headers, %{})
+ signature = signature_for_conn(conn)
+
+ validate_required_headers(headers, signature["headers"]) == :ok
+ end
+
+ defp maybe_refetch_key_and_retry(conn, adapter) do
+ if retryable_signature_failure?(conn) do
+ refetch_key_and_retry(conn, adapter)
+ else
+ false
+ end
+ end
+
+ @spec refetch_key_and_retry(Plug.Conn.t(), any()) :: boolean()
+ defp refetch_key_and_retry(conn, adapter) do
+ Logger.debug("Could not validate, trying to refetch any relevant keys")
+
+ with {:ok, public_key} <- adapter.refetch_public_key(conn) do
+ validate_conn(conn, public_key)
+ else
+ e ->
+ Logger.debug("Failed to refetch public key: #{inspect(e)}")
+ false
+ end
end
end
diff --git a/mix.exs b/mix.exs
index a7bf8ae..b6489cd 100644
--- a/mix.exs
+++ b/mix.exs
@@ -1,46 +1,47 @@
# SPDX-FileCopyrightText: 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
defmodule HttpSignatures.MixProject do
use Mix.Project
def project do
[
app: :http_signatures,
description: "Library for manipulating and validating HTTP signatures",
version: "0.1.2",
- elixir: "~> 1.7",
+ elixir: "~> 1.10",
elixirc_options: [warnings_as_errors: true],
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
deps: deps(),
package: package()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger, :public_key]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:credo, "~> 1.0", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.19", only: :dev, runtime: false},
- {:dialyxir, "~> 1.1.0", only: [:dev], runtime: false}
+ {:dialyxir, "~> 1.4.0", only: [:dev], runtime: false},
+ {:plug, "~> 1.18"}
]
end
defp package do
[
licenses: ["LGPL-3.0-only"],
links: %{"GitLab" => "https://git.pleroma.social/pleroma/elixir-libraries/http_signatures"}
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
end
diff --git a/test/http_signatures_test.exs b/test/http_signatures_test.exs
index a4fbee3..fdf4ffa 100644
--- a/test/http_signatures_test.exs
+++ b/test/http_signatures_test.exs
@@ -1,273 +1,521 @@
# Pleroma: A lightweight social networking server
# SPDX-FileCopyrightText: 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
# Test data from https://tools.ietf.org/html/draft-cavage-http-signatures-08#appendix-C
+defmodule HTTPSignatures.NoRefetchAdapter do
+ @behaviour HTTPSignatures.Adapter
+
+ @public_key hd(:public_key.pem_decode(File.read!("test/public.key")))
+ |> :public_key.pem_entry_decode()
+
+ def fetch_public_key(_), do: {:ok, @public_key}
+ def refetch_public_key(_), do: raise("unexpected key refetch")
+end
+
defmodule HttpSignaturesTest do
use ExUnit.Case
+ import ExUnit.CaptureLog
+
@public_key hd(:public_key.pem_decode(File.read!("test/public.key")))
|> :public_key.pem_entry_decode()
@private_key hd(:public_key.pem_decode(File.read!("test/private.key")))
|> :public_key.pem_entry_decode()
@headers %{
"(request-target)" => "post /foo?param=value&pet=dog",
"host" => "example.com",
"date" => "Thu, 05 Jan 2014 21:31:40 GMT",
# the same date, in unix timestamp
"(created)" => "1388957500",
# 10000 seconds later
"(expires)" => "1388967500",
"content-type" => "application/json",
"digest" => "SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=",
"content-length" => "18"
}
@default_signature """
keyId="Test",algorithm="rsa-sha256",signature="jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9HpFQlG7N4YcJPteKTu4MWCLyk+gIr0wDgqtLWf9NLpMAMimdfsH7FSWGfbMFSrsVTHNTk0rK3usrfFnti1dxsM4jl0kYJCKTGI/UWkqiaxwNiKqGcdlEDrTcUhhsFsOIo8VhddmZTZ8w="
"""
@basic_signature """
keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date",signature="HUxc9BS3P/kPhSmJo+0pQ4IsCo007vkv6bUm4Qehrx+B1Eo4Mq5/6KylET72ZpMUS80XvjlOPjKzxfeTQj4DiKbAzwJAb4HX3qX6obQTa00/qPDXlMepD2JtTw33yNnm/0xV7fQuvILN/ys+378Ysi082+4xBQFwvhNvSoVsGv4="
"""
- # IO.puts HTTPSignatures.sign(@private_key, "Test", %{
- # "(request-target)" => "post /foo?param=value&pet=dog",
- # "host" => "example.com",
- # "(created)" => "1388957500", # the same date, in unix timestamp
- # "(expires)" => "1388967500", # 10000 seconds later
- # })
- @timestamped_signature """
- keyId="Test",algorithm="rsa-sha256",headers="(created) (expires) (request-target) host",signature="rR4LdJSX1ZkmFmh9HUxQt0DFFPuYfvaV+mVMhEws6fMkxHO2AE0vAteYp22T7DFRYcCiXoLrqp+53aKaCX1ade2KZM7obKJ78fMZ4jETqUM9P/ziSHCIEmnNohWoGrCkpU775AXmh0A7lsfKeNLYqdYkS6G85asxn1QGWzeE4O8=",created="1388957500",expires="1388967500"
- """
-
@all_headers_signature """
keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date content-type digest content-length",signature="Ef7MlxLXoBovhil3AlyjtBwAL9g4TN3tibLj7uuNB3CROat/9KaeQ4hW2NiJ+pZ6HQEOx9vYZAyi+7cmIkmJszJCut5kQLAwuX+Ms/mUFvpKlSo9StS2bMXDBNjOh4Auj774GFj4gwjS+3NhFeoqyr/MuN6HsEnkvn6zdgfE2i0="
"""
+ defp timestamped_headers(created, expires) do
+ Map.merge(@headers, %{"(created)" => created, "(expires)" => expires})
+ end
+
+ defp timestamped_signature(created, expires) do
+ HTTPSignatures.sign(@private_key, "Test", %{
+ "(created)" => created,
+ "(expires)" => expires,
+ "(request-target)" => @headers["(request-target)"],
+ "host" => @headers["host"]
+ })
+ end
+
test "split up a signature" do
- expected = %{
+ default_sig = %{
"keyId" => "Test",
"algorithm" => "rsa-sha256",
"signature" =>
"jKyvPcxB4JbmYY4mByyBY7cZfNl4OW9HpFQlG7N4YcJPteKTu4MWCLyk+gIr0wDgqtLWf9NLpMAMimdfsH7FSWGfbMFSrsVTHNTk0rK3usrfFnti1dxsM4jl0kYJCKTGI/UWkqiaxwNiKqGcdlEDrTcUhhsFsOIo8VhddmZTZ8w=",
"headers" => ["date"]
}
- assert HTTPSignatures.split_signature(@default_signature) == expected
- end
+ all_header_sig = %{
+ "algorithm" => "rsa-sha256",
+ "headers" => [
+ "(request-target)",
+ "host",
+ "date",
+ "content-type",
+ "digest",
+ "content-length"
+ ],
+ "keyId" => "Test",
+ "signature" =>
+ "Ef7MlxLXoBovhil3AlyjtBwAL9g4TN3tibLj7uuNB3CROat/9KaeQ4hW2NiJ+pZ6HQEOx9vYZAyi+7cmIkmJszJCut5kQLAwuX+Ms/mUFvpKlSo9StS2bMXDBNjOh4Auj774GFj4gwjS+3NhFeoqyr/MuN6HsEnkvn6zdgfE2i0="
+ }
- test "validates the default case" do
- signature = HTTPSignatures.split_signature(@default_signature)
- assert HTTPSignatures.validate(@headers, signature, @public_key)
+ assert HTTPSignatures.split_signature(@default_signature) == default_sig
+ assert HTTPSignatures.split_signature(@all_headers_signature) == all_header_sig
end
test "validates the basic case" do
signature = HTTPSignatures.split_signature(@basic_signature)
- assert HTTPSignatures.validate(@headers, signature, @public_key)
+ assert true == HTTPSignatures.validate(@headers, signature, @public_key)
end
test "validates the timestamped case" do
- signature = HTTPSignatures.split_signature(@timestamped_signature)
- assert HTTPSignatures.validate(@headers, signature, @public_key)
+ created = System.system_time(:second) - 1
+ expires = created + 3_600
+ signature = timestamped_signature(created, expires)
+
+ assert signature =~ ~s|algorithm="hs2019"|
+ assert signature =~ ~s|headers="(created) (expires) (request-target) host"|
+ assert signature =~ ~s|created=#{created}|
+ assert signature =~ ~s|expires=#{expires}|
+ refute signature =~ ~s|created="#{created}"|
+ refute signature =~ ~s|expires="#{expires}"|
+
+ signature = HTTPSignatures.split_signature(signature)
+ assert HTTPSignatures.validate(timestamped_headers(created, expires), signature, @public_key)
+ end
+
+ test "rejects timestamped signatures created in the future" do
+ created = System.system_time(:second) + 3_600
+ expires = created + 3_600
+ signature = HTTPSignatures.split_signature(timestamped_signature(created, expires))
+
+ assert false ==
+ HTTPSignatures.validate(
+ timestamped_headers(created, expires),
+ signature,
+ @public_key
+ )
+ end
+
+ test "rejects expired timestamped signatures" do
+ created = System.system_time(:second) - 3_600
+ expires = System.system_time(:second) - 1
+ signature = HTTPSignatures.split_signature(timestamped_signature(created, expires))
+
+ assert false ==
+ HTTPSignatures.validate(
+ timestamped_headers(created, expires),
+ signature,
+ @public_key
+ )
+ end
+
+ test "rejects timestamped signatures with missing timestamp params" do
+ created = System.system_time(:second) - 1
+ expires = created + 3_600
+ headers = timestamped_headers(created, expires)
+ signature = timestamped_signature(created, expires)
+ without_created = String.replace(signature, ~r/,created=\d+/, "")
+ without_expires = String.replace(signature, ~r/,expires=\d+/, "")
+
+ assert false ==
+ HTTPSignatures.validate(
+ headers,
+ HTTPSignatures.split_signature(without_created),
+ @public_key
+ )
+
+ assert false ==
+ HTTPSignatures.validate(
+ headers,
+ HTTPSignatures.split_signature(without_expires),
+ @public_key
+ )
+ end
+
+ test "rejects legacy algorithms for timestamped signatures" do
+ created = System.system_time(:second) - 1
+ expires = created + 3_600
+
+ signature =
+ timestamped_signature(created, expires)
+ |> String.replace(~s|algorithm="hs2019"|, ~s|algorithm="rsa-sha256"|)
+ |> HTTPSignatures.split_signature()
+
+ assert false ==
+ HTTPSignatures.validate(
+ timestamped_headers(created, expires),
+ signature,
+ @public_key
+ )
end
test "validates the all-headers case" do
signature = HTTPSignatures.split_signature(@all_headers_signature)
- assert HTTPSignatures.validate(@headers, signature, @public_key)
+ assert true == HTTPSignatures.validate(@headers, signature, @public_key)
+ end
+
+ test "validates the @request-target case" do
+ headers = Map.put(@headers, "@request-target", @headers["(request-target)"])
+
+ signature =
+ HTTPSignatures.sign(@private_key, "Test", %{
+ "@request-target" => headers["@request-target"],
+ "host" => headers["host"]
+ })
+ |> HTTPSignatures.split_signature()
+
+ assert true == HTTPSignatures.validate(headers, signature, @public_key)
end
test "it contructs a signing string" do
expected = "date: Thu, 05 Jan 2014 21:31:40 GMT\ncontent-length: 18"
assert expected ==
HTTPSignatures.build_signing_string(
@headers,
- ["date", "content-length"],
- @headers["(created)"],
- @headers["(expires)"]
+ ["date", "content-length"]
)
expected = "(created): 1388957500\n(expires): 1388967500\ncontent-length: 18"
assert expected ==
HTTPSignatures.build_signing_string(
@headers,
- ["(created)", "(expires)", "content-length"],
- @headers["(created)"],
- @headers["(expires)"]
+ ["(created)", "(expires)", "content-length"]
)
end
test "it parses the http signature for a conn" do
conn = %{
req_headers: [
{"host", "localtesting.pleroma.lol"},
{"connection", "close"},
{"content-length", "2316"},
{"user-agent", "http.rb/2.2.2 (Mastodon/2.1.0.rc3; +http://mastodon.example.org/)"},
{"date", "Sun, 10 Dec 2017 14:23:49 GMT"},
{"digest", "SHA-256=x/bHADMW8qRrq2NdPb5P9fl0lYpKXXpe5h5maCIL0nM="},
{"content-type", "application/activity+json"},
{"(request-target)", "post /users/demiurge/inbox"},
{"signature",
"keyId=\"http://mastodon.example.org/users/admin#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"i0FQvr51sj9BoWAKydySUAO1RDxZmNY6g7M62IA7VesbRSdFZZj9/fZapLp6YSuvxUF0h80ZcBEq9GzUDY3Chi9lx6yjpUAS2eKb+Am/hY3aswhnAfYd6FmIdEHzsMrpdKIRqO+rpQ2tR05LwiGEHJPGS0p528NvyVxrxMT5H5yZS5RnxY5X2HmTKEgKYYcvujdv7JWvsfH88xeRS7Jlq5aDZkmXvqoR4wFyfgnwJMPLel8P/BUbn8BcXglH/cunR0LUP7sflTxEz+Rv5qg+9yB8zgBsB4C0233WpcJxjeD6Dkq0EcoJObBR56F8dcb7NQtUDu7x6xxzcgSd7dHm5w==\""}
]
}
result = HTTPSignatures.signature_for_conn(conn)
assert result["keyId"] == "http://mastodon.example.org/users/admin#main-key"
end
- test "it validates a conn" do
- public_key_pem =
- "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnGb42rPZIapY4Hfhxrgn\nxKVJczBkfDviCrrYaYjfGxawSw93dWTUlenCVTymJo8meBlFgIQ70ar4rUbzl6GX\nMYvRdku072d1WpglNHXkjKPkXQgngFDrh2sGKtNB/cEtJcAPRO8OiCgPFqRtMiNM\nc8VdPfPdZuHEIZsJ/aUM38EnqHi9YnVDQik2xxDe3wPghOhqjxUM6eLC9jrjI+7i\naIaEygUdyst9qVg8e2FGQlwAeS2Eh8ygCxn+bBlT5OyV59jSzbYfbhtF2qnWHtZy\nkL7KOOwhIfGs7O9SoR2ZVpTEQ4HthNzainIe/6iCR5HGrao/T8dygweXFYRv+k5A\nPQIDAQAB\n-----END PUBLIC KEY-----\n"
-
- [public_key] = :public_key.pem_decode(public_key_pem)
+ describe "validate_conn/1" do
+ test "it validates a conn" do
+ public_key_pem =
+ "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnGb42rPZIapY4Hfhxrgn\nxKVJczBkfDviCrrYaYjfGxawSw93dWTUlenCVTymJo8meBlFgIQ70ar4rUbzl6GX\nMYvRdku072d1WpglNHXkjKPkXQgngFDrh2sGKtNB/cEtJcAPRO8OiCgPFqRtMiNM\nc8VdPfPdZuHEIZsJ/aUM38EnqHi9YnVDQik2xxDe3wPghOhqjxUM6eLC9jrjI+7i\naIaEygUdyst9qVg8e2FGQlwAeS2Eh8ygCxn+bBlT5OyV59jSzbYfbhtF2qnWHtZy\nkL7KOOwhIfGs7O9SoR2ZVpTEQ4HthNzainIe/6iCR5HGrao/T8dygweXFYRv+k5A\nPQIDAQAB\n-----END PUBLIC KEY-----\n"
+
+ [public_key] = :public_key.pem_decode(public_key_pem)
+
+ public_key =
+ public_key
+ |> :public_key.pem_entry_decode()
+
+ conn = %{
+ req_headers: [
+ {"host", "localtesting.pleroma.lol"},
+ {"connection", "close"},
+ {"content-length", "2316"},
+ {"user-agent", "http.rb/2.2.2 (Mastodon/2.1.0.rc3; +http://mastodon.example.org/)"},
+ {"date", "Sun, 10 Dec 2017 14:23:49 GMT"},
+ {"digest", "SHA-256=x/bHADMW8qRrq2NdPb5P9fl0lYpKXXpe5h5maCIL0nM="},
+ {"content-type", "application/activity+json"},
+ {"(request-target)", "post /users/demiurge/inbox"},
+ {"signature",
+ "keyId=\"http://mastodon.example.org/users/admin#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"i0FQvr51sj9BoWAKydySUAO1RDxZmNY6g7M62IA7VesbRSdFZZj9/fZapLp6YSuvxUF0h80ZcBEq9GzUDY3Chi9lx6yjpUAS2eKb+Am/hY3aswhnAfYd6FmIdEHzsMrpdKIRqO+rpQ2tR05LwiGEHJPGS0p528NvyVxrxMT5H5yZS5RnxY5X2HmTKEgKYYcvujdv7JWvsfH88xeRS7Jlq5aDZkmXvqoR4wFyfgnwJMPLel8P/BUbn8BcXglH/cunR0LUP7sflTxEz+Rv5qg+9yB8zgBsB4C0233WpcJxjeD6Dkq0EcoJObBR56F8dcb7NQtUDu7x6xxzcgSd7dHm5w==\""}
+ ]
+ }
+
+ assert HTTPSignatures.validate_conn(conn, public_key)
+ end
+
+ test "it validates a conn and fetches the key" do
+ conn = %{
+ params: %{"actor" => "http://mastodon.example.org/users/admin"},
+ req_headers: [
+ {"host", "localtesting.pleroma.lol"},
+ {"x-forwarded-for", "127.0.0.1"},
+ {"connection", "close"},
+ {"content-length", "2307"},
+ {"user-agent", "http.rb/2.2.2 (Mastodon/2.1.0.rc3; +http://mastodon.example.org/)"},
+ {"date", "Sun, 11 Feb 2018 17:12:01 GMT"},
+ {"digest", "SHA-256=UXsAnMtR9c7mi1FOf6HRMtPgGI1yi2e9nqB/j4rZ99I="},
+ {"content-type", "application/activity+json"},
+ {"signature",
+ "keyId=\"http://mastodon.example.org/users/admin#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"qXKqpQXUpC3d9bZi2ioEeAqP8nRMD021CzH1h6/w+LRk4Hj31ARJHDwQM+QwHltwaLDUepshMfz2WHSXAoLmzWtvv7xRwY+mRqe+NGk1GhxVZ/LSrO/Vp7rYfDpfdVtkn36LU7/Bzwxvvaa4ZWYltbFsRBL0oUrqsfmJFswNCQIG01BB52BAhGSCORHKtQyzo1IZHdxl8y80pzp/+FOK2SmHkqWkP9QbaU1qTZzckL01+7M5btMW48xs9zurEqC2sM5gdWMQSZyL6isTV5tmkTZrY8gUFPBJQZgihK44v3qgfWojYaOwM8ATpiv7NG8wKN/IX7clDLRMA8xqKRCOKw==\""},
+ {"(request-target)", "post /users/demiurge/inbox"}
+ ]
+ }
+
+ assert HTTPSignatures.validate_conn(conn)
+ end
+
+ test "validate this" do
+ conn = %{
+ params: %{"actor" => "https://niu.moe/users/rye"},
+ req_headers: [
+ {"x-forwarded-for", "149.202.73.191"},
+ {"host", "testing.pleroma.lol"},
+ {"x-cluster-client-ip", "149.202.73.191"},
+ {"connection", "upgrade"},
+ {"content-length", "2396"},
+ {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://niu.moe/)"},
+ {"date", "Sun, 18 Feb 2018 20:31:51 GMT"},
+ {"digest", "SHA-256=dzH+vLyhxxALoe9RJdMl4hbEV9bGAZnSfddHQzeidTU="},
+ {"content-type", "application/activity+json"},
+ {"signature",
+ "keyId=\"https://niu.moe/users/rye#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"wtxDg4kIpW7nsnUcVJhBk6SgJeDZOocr8yjsnpDRqE52lR47SH6X7G16r7L1AUJdlnbfx7oqcvomoIJoHB3ghP6kRnZW6MyTMZ2jPoi3g0iC5RDqv6oAmDSO14iw6U+cqZbb3P/odS5LkbThF0UNXcfenVNfsKosIJycFjhNQc54IPCDXYq/7SArEKJp8XwEgzmiC2MdxlkVIUSTQYfjM4EG533cwlZocw1mw72e5mm/owTa80BUZAr0OOuhoWARJV9btMb02ZyAF6SCSoGPTA37wHyfM1Dk88NHf7Z0Aov/Fl65dpRM+XyoxdkpkrhDfH9qAx4iuV2VEWddQDiXHA==\""},
+ {"(request-target)", "post /inbox"}
+ ]
+ }
+
+ assert HTTPSignatures.validate_conn(conn)
+ end
+
+ test "validate this too" do
+ conn = %{
+ params: %{"actor" => "https://niu.moe/users/rye"},
+ req_headers: [
+ {"x-forwarded-for", "149.202.73.191"},
+ {"host", "testing.pleroma.lol"},
+ {"x-cluster-client-ip", "149.202.73.191"},
+ {"connection", "upgrade"},
+ {"content-length", "2342"},
+ {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://niu.moe/)"},
+ {"date", "Sun, 18 Feb 2018 21:44:46 GMT"},
+ {"digest", "SHA-256=vS8uDOJlyAu78cF3k5EzrvaU9iilHCX3chP37gs5sS8="},
+ {"content-type", "application/activity+json"},
+ {"signature",
+ "keyId=\"https://niu.moe/users/rye#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"IN6fHD8pLiDEf35dOaRHzJKc1wBYh3/Yq0ItaNGxUSbJTd2xMjigZbcsVKzvgYYjglDDN+disGNeD+OBKwMqkXWaWe/lyMc9wHvCH5NMhpn/A7qGLY8yToSt4vh8ytSkZKO6B97yC+Nvy6Fz/yMbvKtFycIvSXCq417cMmY6f/aG+rtMUlTbKO5gXzC7SUgGJCtBPCh1xZzu5/w0pdqdjO46ePNeR6JyJSLLV4hfo3+p2n7SRraxM4ePVCUZqhwS9LPt3Zdhy3ut+IXCZgMVIZggQFM+zXLtcXY5HgFCsFQr5WQDu+YkhWciNWtKFnWfAsnsg5sC330lZ/0Z8Z91yA==\""},
+ {"(request-target)", "post /inbox"}
+ ]
+ }
+
+ assert HTTPSignatures.validate_conn(conn)
+ end
+
+ test "this too" do
+ conn = %{
+ params: %{"actor" => "https://mst3k.interlinked.me/users/luciferMysticus"},
+ req_headers: [
+ {"host", "soc.canned-death.us"},
+ {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://mst3k.interlinked.me/)"},
+ {"date", "Sun, 11 Mar 2018 12:19:36 GMT"},
+ {"digest", "SHA-256=V7Hl6qDK2m8WzNsjzNYSBISi9VoIXLFlyjF/a5o1SOc="},
+ {"content-type", "application/activity+json"},
+ {"signature",
+ "keyId=\"https://mst3k.interlinked.me/users/luciferMysticus#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"CTYdK5a6lYMxzmqjLOpvRRASoxo2Rqib2VrAvbR5HaTn80kiImj15pCpAyx8IZp53s0Fn/y8MjCTzp+absw8kxx0k2sQAXYs2iy6xhdDUe7iGzz+XLAEqLyZIZfecynaU2nb3Z2XnFDjhGjR1vj/JP7wiXpwp6o1dpDZj+KT2vxHtXuB9585V+sOHLwSB1cGDbAgTy0jx/2az2EGIKK2zkw1KJuAZm0DDMSZalp/30P8dl3qz7DV2EHdDNfaVtrs5BfbDOZ7t1hCcASllzAzgVGFl0BsrkzBfRMeUMRucr111ZG+c0BNOEtJYOHSyZsSSdNknElggCJekONYMYk5ZA==\""},
+ {"x-forwarded-for", "2607:5300:203:2899::31:1337"},
+ {"x-forwarded-host", "soc.canned-death.us"},
+ {"x-forwarded-server", "soc.canned-death.us"},
+ {"connection", "Keep-Alive"},
+ {"content-length", "2006"},
+ {"(request-target)", "post /inbox"}
+ ]
+ }
+
+ assert HTTPSignatures.validate_conn(conn)
+ end
+
+ test "handles fetch_public_key errors" do
+ conn = %{
+ params: %{"actor" => "https://example.org/users/fetch_fail"},
+ req_headers: [
+ {"host", "soc.canned-death.us"},
+ {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://mst3k.interlinked.me/)"},
+ {"date", "Sun, 11 Mar 2018 12:19:36 GMT"},
+ {"digest", "SHA-256=V7Hl6qDK2m8WzNsjzNYSBISi9VoIXLFlyjF/a5o1SOc="},
+ {"content-type", "application/activity+json"},
+ {"signature",
+ "keyId=\"https://mst3k.interlinked.me/users/luciferMysticus#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"CTYdK5a6lYMxzmqjLOpvRRASoxo2Rqib2VrAvbR5HaTn80kiImj15pCpAyx8IZp53s0Fn/y8MjCTzp+absw8kxx0k2sQAXYs2iy6xhdDUe7iGzz+XLAEqLyZIZfecynaU2nb3Z2XnFDjhGjR1vj/JP7wiXpwp6o1dpDZj+KT2vxHtXuB9585V+sOHLwSB1cGDbAgTy0jx/2az2EGIKK2zkw1KJuAZm0DDMSZalp/30P8dl3qz7DV2EHdDNfaVtrs5BfbDOZ7t1hCcASllzAzgVGFl0BsrkzBfRMeUMRucr111ZG+c0BNOEtJYOHSyZsSSdNknElggCJekONYMYk5ZA==\""},
+ {"x-forwarded-for", "2607:5300:203:2899::31:1337"},
+ {"x-forwarded-host", "soc.canned-death.us"},
+ {"x-forwarded-server", "soc.canned-death.us"},
+ {"connection", "Keep-Alive"},
+ {"content-length", "2006"},
+ {"(request-target)", "post /inbox"}
+ ]
+ }
+
+ assert capture_log(fn ->
+ assert false == HTTPSignatures.validate_conn(conn)
+ end) =~
+ ~s[Could not validate against known public keys: {:error, "no public key found"}]
+ end
+
+ test "handles refetch_public_key errors" do
+ conn = %{
+ params: %{"actor" => "https://example.org/users/refetch_fail"},
+ req_headers: [
+ {"host", "soc.canned-death.us"},
+ {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://mst3k.interlinked.me/)"},
+ {"date", "Sun, 11 Mar 2018 12:19:36 GMT"},
+ {"digest", "SHA-256=V7Hl6qDK2m8WzNsjzNYSBISi9VoIXLFlyjF/a5o1SOc="},
+ {"content-type", "application/activity+json"},
+ {"signature",
+ "keyId=\"https://mst3k.interlinked.me/users/luciferMysticus#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"CTYdK5a6lYMxzmqjLOpvRRASoxo2Rqib2VrAvbR5HaTn80kiImj15pCpAyx8IZp53s0Fn/y8MjCTzp+absw8kxx0k2sQAXYs2iy6xhdDUe7iGzz+XLAEqLyZIZfecynaU2nb3Z2XnFDjhGjR1vj/JP7wiXpwp6o1dpDZj+KT2vxHtXuB9585V+sOHLwSB1cGDbAgTy0jx/2az2EGIKK2zkw1KJuAZm0DDMSZalp/30P8dl3qz7DV2EHdDNfaVtrs5BfbDOZ7t1hCcASllzAzgVGFl0BsrkzBfRMeUMRucr111ZG+c0BNOEtJYOHSyZsSSdNknElggCJekONYMYk5ZA==\""},
+ {"x-forwarded-for", "2607:5300:203:2899::31:1337"},
+ {"x-forwarded-host", "soc.canned-death.us"},
+ {"x-forwarded-server", "soc.canned-death.us"},
+ {"connection", "Keep-Alive"},
+ {"content-length", "2006"},
+ {"(request-target)", "post /inbox"}
+ ]
+ }
+
+ assert capture_log(fn ->
+ assert false == HTTPSignatures.validate_conn(conn)
+ end) =~ ~s[Failed to refetch public key: {:error, "no public key found"}]
+ end
+ end
- public_key =
- public_key
- |> :public_key.pem_entry_decode()
+ test "it generates a signature" do
+ assert HTTPSignatures.sign(
+ @private_key,
+ "http://mastodon.example.org/users/admin#main-key",
+ %{host: "mastodon.example.org"}
+ ) =~ "keyId=\""
+ end
- conn = %{
+ test "enforces (request-target) being present in headers" do
+ targetless_sig =
+ HTTPSignatures.sign(@private_key, "https://mastodon.example.com/users/admin#main-key", %{
+ host: "mastodon.example.com"
+ })
+
+ targetted_sig =
+ HTTPSignatures.sign(@private_key, "https://mastodon.example.com/users/admin#main-key", %{
+ host: "mastodon.example.com",
+ "(request-target)": "post /inbox"
+ })
+
+ # (request-target) isn't supposed to be in request headers coming from the outside,
+ # it is supposed to be added by the validate_conn/1 caller prior to calling us.
+ sig_conn = %{
+ params: %{"actor" => "https://mastodon.example.com/users/admin"},
req_headers: [
- {"host", "localtesting.pleroma.lol"},
- {"connection", "close"},
- {"content-length", "2316"},
- {"user-agent", "http.rb/2.2.2 (Mastodon/2.1.0.rc3; +http://mastodon.example.org/)"},
- {"date", "Sun, 10 Dec 2017 14:23:49 GMT"},
- {"digest", "SHA-256=x/bHADMW8qRrq2NdPb5P9fl0lYpKXXpe5h5maCIL0nM="},
- {"content-type", "application/activity+json"},
- {"(request-target)", "post /users/demiurge/inbox"},
- {"signature",
- "keyId=\"http://mastodon.example.org/users/admin#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"i0FQvr51sj9BoWAKydySUAO1RDxZmNY6g7M62IA7VesbRSdFZZj9/fZapLp6YSuvxUF0h80ZcBEq9GzUDY3Chi9lx6yjpUAS2eKb+Am/hY3aswhnAfYd6FmIdEHzsMrpdKIRqO+rpQ2tR05LwiGEHJPGS0p528NvyVxrxMT5H5yZS5RnxY5X2HmTKEgKYYcvujdv7JWvsfH88xeRS7Jlq5aDZkmXvqoR4wFyfgnwJMPLel8P/BUbn8BcXglH/cunR0LUP7sflTxEz+Rv5qg+9yB8zgBsB4C0233WpcJxjeD6Dkq0EcoJObBR56F8dcb7NQtUDu7x6xxzcgSd7dHm5w==\""}
+ {"host", "mastodon.example.com"},
+ {"(request-target)", "post /inbox"},
+ {"signature", targetless_sig}
]
}
- assert HTTPSignatures.validate_conn(conn, public_key)
- end
-
- test "it validates a conn and fetches the key" do
- conn = %{
- params: %{"actor" => "http://mastodon.example.org/users/admin"},
- req_headers: [
- {"host", "localtesting.pleroma.lol"},
- {"x-forwarded-for", "127.0.0.1"},
- {"connection", "close"},
- {"content-length", "2307"},
- {"user-agent", "http.rb/2.2.2 (Mastodon/2.1.0.rc3; +http://mastodon.example.org/)"},
- {"date", "Sun, 11 Feb 2018 17:12:01 GMT"},
- {"digest", "SHA-256=UXsAnMtR9c7mi1FOf6HRMtPgGI1yi2e9nqB/j4rZ99I="},
- {"content-type", "application/activity+json"},
- {"signature",
- "keyId=\"http://mastodon.example.org/users/admin#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"qXKqpQXUpC3d9bZi2ioEeAqP8nRMD021CzH1h6/w+LRk4Hj31ARJHDwQM+QwHltwaLDUepshMfz2WHSXAoLmzWtvv7xRwY+mRqe+NGk1GhxVZ/LSrO/Vp7rYfDpfdVtkn36LU7/Bzwxvvaa4ZWYltbFsRBL0oUrqsfmJFswNCQIG01BB52BAhGSCORHKtQyzo1IZHdxl8y80pzp/+FOK2SmHkqWkP9QbaU1qTZzckL01+7M5btMW48xs9zurEqC2sM5gdWMQSZyL6isTV5tmkTZrY8gUFPBJQZgihK44v3qgfWojYaOwM8ATpiv7NG8wKN/IX7clDLRMA8xqKRCOKw==\""},
- {"(request-target)", "post /users/demiurge/inbox"}
- ]
+ header_conn = %{
+ params: %{"actor" => "https://mastodon.example.com/users/admin"},
+ req_headers: [{"host", "mastodon.example.com"}, {"signature", targetted_sig}]
}
- assert HTTPSignatures.validate_conn(conn)
+ assert false == HTTPSignatures.validate_conn(sig_conn)
+ assert false == HTTPSignatures.validate_conn(header_conn)
end
- test "validate this" do
- conn = %{
- params: %{"actor" => "https://niu.moe/users/rye"},
- req_headers: [
- {"x-forwarded-for", "149.202.73.191"},
- {"host", "testing.pleroma.lol"},
- {"x-cluster-client-ip", "149.202.73.191"},
- {"connection", "upgrade"},
- {"content-length", "2396"},
- {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://niu.moe/)"},
- {"date", "Sun, 18 Feb 2018 20:31:51 GMT"},
- {"digest", "SHA-256=dzH+vLyhxxALoe9RJdMl4hbEV9bGAZnSfddHQzeidTU="},
- {"content-type", "application/activity+json"},
- {"signature",
- "keyId=\"https://niu.moe/users/rye#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"wtxDg4kIpW7nsnUcVJhBk6SgJeDZOocr8yjsnpDRqE52lR47SH6X7G16r7L1AUJdlnbfx7oqcvomoIJoHB3ghP6kRnZW6MyTMZ2jPoi3g0iC5RDqv6oAmDSO14iw6U+cqZbb3P/odS5LkbThF0UNXcfenVNfsKosIJycFjhNQc54IPCDXYq/7SArEKJp8XwEgzmiC2MdxlkVIUSTQYfjM4EG533cwlZocw1mw72e5mm/owTa80BUZAr0OOuhoWARJV9btMb02ZyAF6SCSoGPTA37wHyfM1Dk88NHf7Z0Aov/Fl65dpRM+XyoxdkpkrhDfH9qAx4iuV2VEWddQDiXHA==\""},
- {"(request-target)", "post /inbox"}
- ]
- }
+ test "enforces Host being present in headers" do
+ hostless_sig =
+ HTTPSignatures.sign(@private_key, "https://mastodon.example.com/users/admin#main-key", %{
+ "(request-target)": "post /inbox"
+ })
- assert HTTPSignatures.validate_conn(conn)
- end
+ host_sig =
+ HTTPSignatures.sign(@private_key, "https://mastodon.example.com/users/admin#main-key", %{
+ host: "mastodon.example.com",
+ "(request-target)": "post /inbox"
+ })
- test "validate this too" do
- conn = %{
- params: %{"actor" => "https://niu.moe/users/rye"},
+ host_conn = %{
+ params: %{"actor" => "https://mastodon.example.com/users/admin"},
req_headers: [
- {"x-forwarded-for", "149.202.73.191"},
- {"host", "testing.pleroma.lol"},
- {"x-cluster-client-ip", "149.202.73.191"},
- {"connection", "upgrade"},
- {"content-length", "2342"},
- {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://niu.moe/)"},
- {"date", "Sun, 18 Feb 2018 21:44:46 GMT"},
- {"digest", "SHA-256=vS8uDOJlyAu78cF3k5EzrvaU9iilHCX3chP37gs5sS8="},
- {"content-type", "application/activity+json"},
- {"signature",
- "keyId=\"https://niu.moe/users/rye#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"IN6fHD8pLiDEf35dOaRHzJKc1wBYh3/Yq0ItaNGxUSbJTd2xMjigZbcsVKzvgYYjglDDN+disGNeD+OBKwMqkXWaWe/lyMc9wHvCH5NMhpn/A7qGLY8yToSt4vh8ytSkZKO6B97yC+Nvy6Fz/yMbvKtFycIvSXCq417cMmY6f/aG+rtMUlTbKO5gXzC7SUgGJCtBPCh1xZzu5/w0pdqdjO46ePNeR6JyJSLLV4hfo3+p2n7SRraxM4ePVCUZqhwS9LPt3Zdhy3ut+IXCZgMVIZggQFM+zXLtcXY5HgFCsFQr5WQDu+YkhWciNWtKFnWfAsnsg5sC330lZ/0Z8Z91yA==\""},
- {"(request-target)", "post /inbox"}
+ {"(request-target)", "post /inbox"},
+ {"host", "mastodon.example.com"},
+ {"signature", hostless_sig}
]
}
- assert HTTPSignatures.validate_conn(conn)
- end
+ hostless_conn = %{
+ params: %{"actor" => "https://mastodon.example.com/users/admin"},
+ req_headers: [{"(request-target)", "post /inbox"}, {"signature", host_sig}]
+ }
- test "it generates a signature" do
- assert HTTPSignatures.sign(
- @private_key,
- "http://mastodon.example.org/users/admin#main-key",
- %{host: "mastodon.example.org"}
- ) =~ "keyId=\""
+ assert false == HTTPSignatures.validate_conn(host_conn)
+ assert false == HTTPSignatures.validate_conn(hostless_conn)
end
- test "this too" do
+ test "does not refetch keys when required headers are missing" do
+ previous_adapter = Application.get_env(:http_signatures, :adapter)
+ Application.put_env(:http_signatures, :adapter, HTTPSignatures.NoRefetchAdapter)
+
+ on_exit(fn ->
+ Application.put_env(:http_signatures, :adapter, previous_adapter)
+ end)
+
+ signature =
+ HTTPSignatures.sign(@private_key, "https://mastodon.example.com/users/admin#main-key", %{
+ host: "mastodon.example.com"
+ })
+
conn = %{
- params: %{"actor" => "https://mst3k.interlinked.me/users/luciferMysticus"},
- req_headers: [
- {"host", "soc.canned-death.us"},
- {"user-agent", "http.rb/3.0.0 (Mastodon/2.2.0; +https://mst3k.interlinked.me/)"},
- {"date", "Sun, 11 Mar 2018 12:19:36 GMT"},
- {"digest", "SHA-256=V7Hl6qDK2m8WzNsjzNYSBISi9VoIXLFlyjF/a5o1SOc="},
- {"content-type", "application/activity+json"},
- {"signature",
- "keyId=\"https://mst3k.interlinked.me/users/luciferMysticus#main-key\",algorithm=\"rsa-sha256\",headers=\"(request-target) user-agent host date digest content-type\",signature=\"CTYdK5a6lYMxzmqjLOpvRRASoxo2Rqib2VrAvbR5HaTn80kiImj15pCpAyx8IZp53s0Fn/y8MjCTzp+absw8kxx0k2sQAXYs2iy6xhdDUe7iGzz+XLAEqLyZIZfecynaU2nb3Z2XnFDjhGjR1vj/JP7wiXpwp6o1dpDZj+KT2vxHtXuB9585V+sOHLwSB1cGDbAgTy0jx/2az2EGIKK2zkw1KJuAZm0DDMSZalp/30P8dl3qz7DV2EHdDNfaVtrs5BfbDOZ7t1hCcASllzAzgVGFl0BsrkzBfRMeUMRucr111ZG+c0BNOEtJYOHSyZsSSdNknElggCJekONYMYk5ZA==\""},
- {"x-forwarded-for", "2607:5300:203:2899::31:1337"},
- {"x-forwarded-host", "soc.canned-death.us"},
- {"x-forwarded-server", "soc.canned-death.us"},
- {"connection", "Keep-Alive"},
- {"content-length", "2006"},
- {"(request-target)", "post /inbox"}
- ]
+ params: %{"actor" => "https://mastodon.example.com/users/admin"},
+ req_headers: [{"host", "mastodon.example.com"}, {"signature", signature}]
}
- assert HTTPSignatures.validate_conn(conn)
+ assert false == HTTPSignatures.validate_conn(conn)
end
test "Signatures are stable on OTP26+ with undefined Map.keys/1 ordering" do
user_ap_id = ~s|https://mastodon.social/users/lambadalambda#main-key|
# credo:disable-for-lines:10 Credo.Check.Readability.MaxLineLength
private_key =
{:RSAPrivateKey, :"two-prime",
28_756_005_415_572_484_042_763_333_825_843_542_309_845_812_712_410_557_401_080_975_665_944_065_546_687_053_162_744_064_118_733_269_231_397_398_437_337_112_118_822_093_392_471_512_223_279_218_516_015_781_047_498_524_701_011_344_834_660_702_300_339_866_912_903_829_480_780_711_421_965_266_995_321_160_936_070_443_834_148_409_010_341_833_400_730_167_696_056_399_186_720_243_079_891_586_296_037_178_998_225_766_461_225_833_387_132_735_728_367_079_742_073_397_917_419_922_243_432_508_105_117_797_420_565_462_233_617_076_268_056_263_255_047_301_378_690_482_484_074_947_841_896_587_287_731_635_988_553_127_288_143_474_145_525_724_255_965_068_001_976_777_796_779_533_346_344_982_614_532_834_052_163_179_471_788_571_859_959_462_813_779_224_935_806_760_043_776_072_659_926_191_283_296_091_970_506_062_030_984_091_470_929_266_003_011,
65_537,
25_233_957_481_263_615_321_105_929_907_140_426_297_194_450_296_637_489_603_371_636_030_768_012_109_037_222_140_003_526_671_473_370_973_612_835_255_371_123_456_268_345_987_778_455_955_579_105_800_632_735_218_909_015_602_715_449_920_523_322_539_825_529_794_789_191_349_004_359_581_262_836_335_214_000_723_765_372_612_446_022_890_653_506_246_486_594_506_922_860_631_830_586_989_403_926_452_005_709_205_303_322_232_716_957_756_646_692_607_039_707_869_476_684_696_402_780_134_400_419_892_792_178_031_077_409_586_563_911_414_056_442_023_360_496_531_178_932_232_960_305_935_443_131_268_902_698_561_476_776_016_479_175_692_849_949_462_150_713_017_077_076_502_024_471_442_627_225_940_981_940_235_409_308_119_456_929_193_383_984_043_313_294_569_986_326_805_396_849_905_695_401_341_785_041_176_269_677_759_870_702_155_638_035_216_833,
177_783_479_898_101_225_090_255_510_574_083_286_496_133_004_386_710_828_810_208_011_585_370_522_423_888_313_371_324_368_555_961_532_882_416_417_904_776_985_934_672_514_976_013_258_017_209_904_688_467_121_759_107_569_488_391_607_820_963_070_360_845_953_724_899_435_077_154_851_205_162_368_630_793_919_412_726_847_267_327_206_524_298_869_094_621_709_415_910_252_626_752_919_831_010_415_748_000_011_171_076_295_507,
161_747_342_509_294_677_375_914_222_076_718_822_400_941_009_725_673_497_592_218_662_627_801_812_486_196_781_966_854_364_060_860_604_565_261_653_867_622_254_133_771_945_941_570_294_029_162_561_824_060_451_304_312_080_304_336_296_778_308_854_167_291_375_658_502_471_854_680_814_450_977_871_287_689_807_234_161_418_665_899_011_960_362_411_939_434_739_945_865_837_893_017_653_193_120_275_492_634_544_890_342_133_073,
123_805_792_744_090_236_231_352_842_624_633_216_540_229_399_990_922_616_477_243_136_560_183_183_131_724_655_293_252_252_262_470_488_414_492_620_912_707_582_908_471_838_976_307_567_979_117_793_613_942_520_560_353_851_471_393_328_796_571_914_616_150_395_685_653_681_393_507_030_443_145_175_121_546_663_534_758_084_477_982_611_022_208_463_716_823_171_582_964_249_502_302_157_684_475_706_308_237_675_051_295_467_455,
43_886_525_847_998_503_945_839_856_828_481_836_213_643_179_195_598_305_296_013_431_479_127_391_086_402_355_569_138_109_796_454_266_603_284_903_628_088_849_398_152_688_446_724_796_197_973_185_747_828_599_800_010_336_328_664_846_259_546_333_289_634_484_977_333_276_691_333_662_550_426_301_283_819_829_290_902_213_203_488_353_612_145_267_697_743_695_099_217_027_471_712_771_550_117_715_775_974_296_614_737_687_265,
90_283_918_084_263_940_362_515_004_232_322_731_054_469_960_381_679_586_824_438_807_054_374_237_285_157_945_298_098_405_267_918_780_650_461_768_149_536_719_331_445_672_754_509_549_303_377_662_269_991_550_734_109_336_424_702_266_640_645_630_618_719_389_738_627_119_442_677_159_263_798_411_854_553_104_387_445_904_992_891_045_248_551_150_818_831_926_648_119_173_927_771_126_688_710_466_061_199_827_928_052_600_203,
:asn1_NOVALUE}
headers = %{host: "test.test", "content-length": 100}
expected_signature =
~s|keyId="https://mastodon.social/users/lambadalambda#main-key",algorithm="rsa-sha256",headers="content-length host",signature="sibUOoqsFfTDerquAkyprxzDjmJm6erYc42W5w1IyyxusWngSinq5ILTjaBxFvfarvc7ci1xAi+5gkBwtshRMWm7S+Uqix24Yg5EYafXRun9P25XVnYBEIH4XQ+wlnnzNIXQkU3PU9e6D8aajDZVp3hPJNeYt1gIPOA81bROI8/glzb1SAwQVGRbqUHHHKcwR8keiR/W2h7BwG3pVRy4JgnIZRSW7fQogKedDg02gzRXwUDFDk0pr2p3q6bUWHUXNV8cZIzlMK+v9NlyFbVYBTHctAR26GIAN6Hz0eV0mAQAePHDY1mXppbA8Gpp6hqaMuYfwifcXmcc+QFm4e+n3A=="|
signature = HTTPSignatures.sign(private_key, user_ap_id, headers)
assert signature == expected_signature
end
end
diff --git a/test/support/test_adapter.ex b/test/support/test_adapter.ex
index 52950d9..74a7a29 100644
--- a/test/support/test_adapter.ex
+++ b/test/support/test_adapter.ex
@@ -1,36 +1,39 @@
# Pleroma: A lightweight social networking server
# SPDX-FileCopyrightText: 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
defmodule HTTPSignatures.TestAdapter do
@behaviour HTTPSignatures.Adapter
@moduledoc "Test adapter for HTTPSignatures library."
@mastodon_admin_pubkey hd(
:public_key.pem_decode(
File.read!("test/admin@mastodon.example.org.key")
)
)
|> :public_key.pem_entry_decode()
@rye_pubkey hd(:public_key.pem_decode(File.read!("test/rye@niu.moe.key")))
|> :public_key.pem_entry_decode()
@lm_pubkey hd(
:public_key.pem_decode(File.read!("test/lucifermysticus@mst3k.interlinked.me.key"))
)
|> :public_key.pem_entry_decode()
+ def fetch_public_key(%{params: %{"actor" => "https://example.org/users/fetch_fail"}}),
+ do: {:error, "no public key found"}
+
def fetch_public_key(_), do: {:ok, @mastodon_admin_pubkey}
def refetch_public_key(%{params: %{"actor" => "https://niu.moe/users/rye"}}),
do: {:ok, @rye_pubkey}
def refetch_public_key(%{
params: %{"actor" => "https://mst3k.interlinked.me/users/luciferMysticus"}
}),
do: {:ok, @lm_pubkey}
def refetch_public_key(_), do: {:error, "no public key found"}
end
diff --git a/test/test_helper.exs b/test/test_helper.exs
index 4a84ab5..95aeafd 100644
--- a/test/test_helper.exs
+++ b/test/test_helper.exs
@@ -1,4 +1,6 @@
# SPDX-FileCopyrightText: 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
+ExUnit.configure(capture_log: true, max_cases: System.schedulers_online())
+
ExUnit.start()

File Metadata

Mime Type
text/x-diff
Expires
Sat, Aug 8, 3:34 AM (8 h, 36 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1722854
Default Alt Text
(55 KB)

Event Timeline