Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 101 additions & 8 deletions lib/plug/parsers.ex
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ defmodule Plug.Parsers do
* `:validate_utf8` - boolean that tells whether or not we want to
validate that parsed binaries are utf8 strings.

* `:max_heap_size` - limits the memory the process may use while it reads
and parses the request. The value is the number of extra heap words
allowed on top of what the process already holds when parsing starts
(8 bytes per word on 64-bit systems). It also accepts a map in the shape
of `Process.flag(:max_heap_size, map)`, in which case `:size` is that
headroom. The previous flag value is restored after parsing. Defaults to
`4_000_000` (roughly 32MB of headroom); set it to `:infinity` to disable.
See the "Limiting memory usage" section below.

* `:body_reader` - an optional replacement (or wrapper) for
`Plug.Conn.read_body/2` to provide a function that gives access to the
raw body before it is parsed and discarded. It is in the standard format
Expand Down Expand Up @@ -153,6 +162,50 @@ defmodule Plug.Parsers do
{:multipart, length: 20_000_000} # Increase to 20MB max upload
]

## Limiting memory usage

The `:length` option limits the size of the request body, but the parsed
params may need much more memory than the body itself. For example, each
element of a JSON list of small integers, such as `1,`, takes 2 bytes in
the body and 16 bytes once decoded on 64-bit systems. A decoder may also
need several times the size of the decoded data while it runs.

`Plug.Parsers` sets a `:max_heap_size` while it parses a request, defaulting
to `4_000_000` words (roughly 32MB). You can raise it, lower it, or disable
it:

plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
json_decoder: Jason,
max_heap_size: 8_000_000

# or, to turn the limit off entirely
plug Plug.Parsers, parsers: [...], max_heap_size: :infinity

The size is in words (8 bytes on 64-bit systems). It is headroom on top of the
heap the process already holds when parsing starts, not an absolute ceiling:
the current heap size is read and the configured size is added to it. This way
a process that already holds memory, such as garbage left over from an earlier
request on the same keep-alive connection, is not killed while parsing a small
body.

If the limit is exceeded, the process is killed, so no error is raised and no
response is sent by `Plug.Parsers`. The web server decides how the connection
ends, and a warning is logged. Large binaries, such as the raw request body
and large string values, are stored outside of the process heap and, by
default, do not count towards the limit.

Pick the limit against the memory a single request legitimately needs to
parse, not the raw body size. A body made mostly of one large value (an
upload, a base64 field) costs almost no heap, because that value stays off the
heap. A body made of many small elements costs much more: decoding is a few
times the decoded size, and structured data expands further, so tens of
thousands of small fields or list elements are needed before the default
limit is reached. To keep a limit from killing legitimate large requests,
size it above the heap those requests need (or set `:infinity`), and pass a
map such as `%{size: 4_000_000, kill: true, error_logger: false}` if you want
to tune the kill or silence the log.
Comment on lines +169 to +207

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
element of a JSON list of small integers, such as `1,`, takes 2 bytes in
the body and 16 bytes once decoded on 64-bit systems. A decoder may also
need several times the size of the decoded data while it runs.
`Plug.Parsers` sets a `:max_heap_size` while it parses a request, defaulting
to `4_000_000` words (roughly 32MB). You can raise it, lower it, or disable
it:
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
json_decoder: Jason,
max_heap_size: 8_000_000
# or, to turn the limit off entirely
plug Plug.Parsers, parsers: [...], max_heap_size: :infinity
The size is in words (8 bytes on 64-bit systems). It is headroom on top of the
heap the process already holds when parsing starts, not an absolute ceiling:
the current heap size is read and the configured size is added to it. This way
a process that already holds memory, such as garbage left over from an earlier
request on the same keep-alive connection, is not killed while parsing a small
body.
If the limit is exceeded, the process is killed, so no error is raised and no
response is sent by `Plug.Parsers`. The web server decides how the connection
ends, and a warning is logged. Large binaries, such as the raw request body
and large string values, are stored outside of the process heap and, by
default, do not count towards the limit.
Pick the limit against the memory a single request legitimately needs to
parse, not the raw body size. A body made mostly of one large value (an
upload, a base64 field) costs almost no heap, because that value stays off the
heap. A body made of many small elements costs much more: decoding is a few
times the decoded size, and structured data expands further, so tens of
thousands of small fields or list elements are needed before the default
limit is reached. To keep a limit from killing legitimate large requests,
size it above the heap those requests need (or set `:infinity`), and pass a
map such as `%{size: 4_000_000, kill: true, error_logger: false}` if you want
to tune the kill or silence the log.
element of a JSON list of small integers, such as `1`, takes 2 bytes in
the body and 16 bytes once decoded on 64-bit systems. A decoder also
uses additional memory while it runs.
`Plug.Parsers` sets a `:max_heap_size` while it parses a request, defaulting
to `4_000_000` words (roughly 32MB). You can raise it, lower it, or disable
it:
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
json_decoder: Jason,
max_heap_size: 8_000_000
# or, to turn the limit off entirely
plug Plug.Parsers, parsers: [...], max_heap_size: :infinity
The current heap size is read and the configured size is added to it. This way
a process that already holds memory, such as existing data or garbage left from
an earlier request on the same connection, is not killed while parsing a small
body.
If the limit is exceeded, the process is killed, so no error is raised and no
response is sent by `Plug.Parsers`. The web server decides how the connection
ends, and a warning is logged. Large binaries, such as the raw request body
and large string values, are stored outside of the process heap and, by
default, do not count towards the limit.
To keep a limit from killing legitimate large requests, size it above the heap
those requests need (or set `:infinity`). Profile and benchmark if necessary.
Those limits are also enabled during tests, so representative tests will help
avoid false positives in production. You may also consider setting it to
`%{size: 4_000_000, kill: false, error_logger: true}` during an initial deployment,
to validate how frequently your production deployments will run into this.


## Built-in parsers

Plug ships with the following parsers:
Expand Down Expand Up @@ -255,13 +308,14 @@ defmodule Plug.Parsers do
{parsers, opts} = Keyword.pop(opts, :parsers)
{pass, opts} = Keyword.pop(opts, :pass, [])
{query_string_length, opts} = Keyword.pop(opts, :query_string_length, 1_000_000)
{max_heap_size, opts} = Keyword.pop(opts, :max_heap_size, 4_000_000)
validate_utf8 = Keyword.get(opts, :validate_utf8, true)

unless parsers do
raise ArgumentError, "Plug.Parsers expects a set of parsers to be given in :parsers"
end

{convert_parsers(parsers, opts), pass, query_string_length, validate_utf8}
{convert_parsers(parsers, opts), pass, query_string_length, validate_utf8, max_heap_size}
end

defp convert_parsers(parsers, root_opts) do
Expand All @@ -288,7 +342,52 @@ defmodule Plug.Parsers do
@impl true
def call(%{method: method, body_params: %Plug.Conn.Unfetched{}} = conn, options)
when method in @methods do
{parsers, pass, query_string_length, validate_utf8} = options
{parsers, pass, query_string_length, validate_utf8, max_heap_size} = options

with_max_heap_size(max_heap_size, fn ->
parse_body(conn, parsers, pass, query_string_length, validate_utf8)
end)
end

def call(%{body_params: body_params} = conn, {_, _, query_string_length, validate_utf8, _}) do
body_params = make_empty_if_unfetched(body_params)
{conn, params} = merge_params(conn, body_params, query_string_length, validate_utf8)
%{conn | params: params, body_params: body_params}
end

defp with_max_heap_size(limit, fun) when limit in [nil, :infinity], do: fun.()

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't seem to document nil is supported anywhere, so I'd pattern match on infinity directly.


defp with_max_heap_size(max_heap_size, fun) do
previous = Process.flag(:max_heap_size, add_current_heap_size(max_heap_size))

try do
fun.()
after
Process.flag(:max_heap_size, previous)
end
end

# The configured size is extra headroom on top of what the process already
# holds, not an absolute ceiling. Adding the current heap size means a
# process that already holds memory (for example, garbage left over from an
# earlier request on the same keep-alive connection) is not killed while
# parsing a small body.
#
# A bare word count also enables the kill and a logged warning. A map is
# honored as given (so `:kill` and `:error_logger` can be set), except that
# its `:size` is likewise treated as headroom over the current heap.
defp add_current_heap_size(size) when is_integer(size),
do: %{size: size + current_heap_size(), kill: true, error_logger: true}

defp add_current_heap_size(%{size: size} = max_heap_size),
do: %{max_heap_size | size: size + current_heap_size()}

defp current_heap_size do
{:total_heap_size, size} = Process.info(self(), :total_heap_size)
size
end

defp parse_body(conn, parsers, pass, query_string_length, validate_utf8) do
%{req_headers: req_headers} = conn

conn =
Expand Down Expand Up @@ -323,12 +422,6 @@ defmodule Plug.Parsers do
end
end

def call(%{body_params: body_params} = conn, {_, _, query_string_length, validate_utf8}) do
body_params = make_empty_if_unfetched(body_params)
{conn, params} = merge_params(conn, body_params, query_string_length, validate_utf8)
%{conn | params: params, body_params: body_params}
end

defp reduce(
conn,
[{parser, options} | rest],
Expand Down
104 changes: 104 additions & 0 deletions test/plug/parsers_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ defmodule Plug.ParsersTest do
{:ok, body, conn} = Plug.Conn.read_body(conn, opts)
{:ok, body <> "BAZ", conn}
end

def read_body_and_heap_size(conn, opts) do
{:max_heap_size, max_heap_size} = Process.info(self(), :max_heap_size)
Process.put(:max_heap_size_while_parsing, max_heap_size)
Plug.Conn.read_body(conn, opts)
end
end

def parse(conn, opts \\ []) do
Expand Down Expand Up @@ -620,4 +626,102 @@ defmodule Plug.ParsersTest do
assert conn.params["foo"] == "bar"
assert conn.body_params == %Plug.Conn.Unfetched{aspect: :body_params}
end

describe ":max_heap_size" do
@max_heap_size %{size: 100_000, kill: true, error_logger: false}

test "kills the process when parsing goes over the limit" do
body = String.duplicate("list[]=1&", 100_000)

{pid, ref} =
spawn_monitor(fn ->
conn(:post, "/", body)
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> parse(max_heap_size: @max_heap_size)
end)

assert_receive {:DOWN, ^ref, :process, ^pid, :killed}, 5_000
end

test "applies the limit while parsing and restores the previous value" do
{:max_heap_size, previous} = Process.info(self(), :max_heap_size)

conn =
conn(:post, "/?query=elixir", "body=foo")
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> parse(
max_heap_size: @max_heap_size,
body_reader: {BodyReader, :read_body_and_heap_size, []}
)

assert conn.params == %{"query" => "elixir", "body" => "foo"}

# The configured size is added on top of the current heap, so the flag
# applied while parsing is strictly larger than the 100_000 we asked for.
assert %{size: size, kill: true, error_logger: false} =
Process.get(:max_heap_size_while_parsing)

assert size > 100_000
assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous}
end

test "sets the limit relative to the current heap, not as an absolute ceiling" do
parent = self()

{_pid, _ref} =
spawn_monitor(fn ->
# Hold far more live data than the 100_000-word (~800 KB) headroom
# below. With an absolute max_heap_size this process would be killed
# at the first garbage collection, even for this tiny body; with
# headroom over the current heap it parses normally.
big = for i <- 1..200_000, do: {i, i + 1}
:erlang.garbage_collect()

conn =
conn(:post, "/?query=elixir", "body=foo")
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> parse(max_heap_size: @max_heap_size)

send(parent, {:parsed, conn.params, length(big)})
end)

assert_receive {:parsed, %{"query" => "elixir", "body" => "foo"}, 200_000}, 5_000
end

test "restores the previous value when parsing raises" do
{:max_heap_size, previous} = Process.info(self(), :max_heap_size)

assert_raise Plug.Parsers.UnsupportedMediaTypeError, fn ->
conn(:post, "/", "foo")
|> put_req_header("content-type", "text/plain")
|> parse(max_heap_size: @max_heap_size)
end

assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous}
end

test "applies the default limit while parsing" do
conn(:post, "/", "body=foo")
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> parse(body_reader: {BodyReader, :read_body_and_heap_size, []})

# Defaults to 4_000_000 words of headroom over the current heap, with the
# kill and a logged warning enabled.
assert %{size: size, kill: true, error_logger: true} =
Process.get(:max_heap_size_while_parsing)

assert size > 4_000_000
end

test "max_heap_size: :infinity disables the limit" do
{:max_heap_size, previous} = Process.info(self(), :max_heap_size)

conn(:post, "/", "body=foo")
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> parse(max_heap_size: :infinity, body_reader: {BodyReader, :read_body_and_heap_size, []})

assert Process.get(:max_heap_size_while_parsing) == previous
assert Process.info(self(), :max_heap_size) == {:max_heap_size, previous}
end
end
end