CodeSampleX

Ejemplo

plug 1.20.3: Parse URL-encoded query and body payloads with Plug.Parsers, handle bracket and index nesting, enforce body length and media type constraints, and merge parameters with body precedence

Muestra verificada para hex plug 1.20.3: Parse URL-encoded query and body payloads with Plug.Parsers, handle bracket and index nesting, enforce body length…

sha256:9dce0763273861f09b535b5038a90b99d7963e9d4b14f08db4d9a29542a9b76a

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
2
Entorno declarado elixir linux x64 elixir elixir mix

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
elixir 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-17
elixir 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:PASS · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · hex@1
2026-08-18

Caso

HOW
Objetivo
Parse URL-encoded query and body payloads with Plug.Parsers, handle bracket and index nesting, enforce body length and media type constraints, and merge parameters with body precedence
Paquetes
Símbolos
  • Plug.Parsers
  • Plug.Parsers.URLENCODED
  • Plug.Conn.Query
  • Plug.Conn.fetch_query_params
Entorno
elixir
Creado
2026-08-17T19:19:04Z

Contrato

  1. assert Plug.Parsers decodes nested maps and array brackets into structured maps while assigning body parameters precedence over query parameters on key collisions during merged parameter resolution
  2. assert indexed bracket syntax produces a string-keyed map rather than a list in Plug.Conn.Query
  3. assert Plug.Parsers.init/1 raises ArgumentError when the :parsers option is missing or empty
  4. assert non-UTF8 urlencoded payloads raise Plug.Parsers.BadEncodingError with plug_status 400
  5. assert unhandled media types raise Plug.Parsers.UnsupportedMediaTypeError unless matching the :pass whitelist which leaves body_params unfetched
  6. assert body payloads exceeding the :length limit raise Plug.Parsers.RequestTooLargeError
  7. assert custom parser modules implementing Plug.Parsers behaviour can return {:ok, ...}, {:error, :too_large, ...}, or delegate with {:next, ...}

Archivos

  • NOTES.md
  • csx.json
  • lib/csx_plug_parsers/csv_parser.ex
  • lib/csx_plug_parsers/pipeline.ex
  • mix.exs
  • mix.lock
  • test/contract_test.exs
  • test/test_helper.exs

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# Plug Parameter Parsing, Media Type Dispatching, and Request Lifecycle

## Prior Solutions

A query to the known solution catalog for `plug` returned existing samples:
- `sha256:3ef390aae7cf632653e7ba065c15143a68dcd2829bcc012a4bf60960c4dcda4b` ("Configure Plug.Session cookie storage, signing salts, 64-byte secret key constraints, and lazy cookie serialization"), which focuses on cookie store cryptographic key validation and lazy session serialization.
- `sha256:f7cb5b2f102e81a511f97af235bf61218cafe9e3bac8f599cb824293963da6c0` ("Test a Plug router end to end with Plug.Test, with no HTTP server, no socket and no network"), which focuses on routing dispatch and basic test helpers.

This sample addresses a distinct area: `Plug.Parsers` body decoding lifecycle, `Plug.Conn.Query` nested parameter semantics, parameter merging collision precedence, media type whitelist filtering, payload size limits, and custom parser extension points.

## Pinned Release

- `plug`: `1.20.3` (Hex package)
- Transitive dependencies: `mime` `2.0.7`, `plug_crypto` `2.2.0`, `telemetry` `1.4.2`

## Observed Behavior and Guarantees

### 1. Mandatory `:parsers` Option at Initialization Time
`Plug.Parsers.init/1` strictly requires a non-empty `:parsers` option at pipeline initialization. Passing an empty list or omitting `:parsers` immediately raises `ArgumentError: Plug.Parsers expects a set of parsers to be given in :parsers`.

### 2. URL-Encoded Parameter Decoding and Nested Brackets
`Plug.Parsers.URLENCODED` uses `Plug.Conn.Query.decode/1` to parse query strings and `application/x-www-form-urlencoded` payloads:
- Nested maps: `user[name]=Alice&user[contact][email]=alice@example.com` decodes into `%{"user" => %{"name" => "Alice", "contact" => %{"email" => "alice@example.com"}}}`.
- Empty bracket lists: `roles[]=admin&roles[]=editor` decodes into `%{"roles" => ["admin", "editor"]}`.
- Indexed brackets: `items[0]=first&items[1]=second` decodes into a map with string keys `%{"items" => %{"0" => "first", "1" => "second"}}` rather than an Elixir list.

### 3. Parameter Merging and Collision Precedence
`Plug.Conn.fetch_query_params/2` extracts URL query parameters into `conn.query_params` and populates `conn.params`. When `Plug.Parsers` executes, it extracts request body parameters into `conn.body_params` and merges `conn.query_params` and `conn.body_params` into `conn.params`.
When parameter keys collide between query and body payloads, body parameters take precedence in `conn.params`, while `conn.query_params` and `conn.body_params` retain their distinct, unmerged values.

### 4. Non-UTF8 Error Normalization
When an incoming urlencoded payload contains invalid UTF-8 byte sequences (e.g. byte 255 / `0xFF`), `Plug.Conn.Query` raises `Plug.Conn.InvalidQueryError`. `Plug.Parsers` traps this and normalizes it into `Plug.Parsers.BadEncodingError` with `plug_status: 400`.

### 5. Media Type Matching and Case-Insensitivity
`Plug.Parsers` extracts the media type from the incoming `content-type` header and matches it case-insensitively while ignoring header parameters such as `charset=utf-8` (e.g. `APPLICATION/X-WWW-FORM-URLENCODED; CHARSET=UTF-8` is correctly routed to `:urlencoded`).

### 6. Whitelist Pass-Through vs UnsupportedMediaTypeError
If a request content-type does not match any configured parser:
- If the media type matches an entry in the `:pass` list (e.g., `pass: ["*/*"]`, `pass: ["text/plain"]`, or `pass: ["application/*"]`), `Plug.Parsers` leaves `conn.body_params` as `%Plug.Conn.Unfetched{aspect: :body_params}` and passes the connection downstream without error.
- If the media type does not match `:pass`, `Plug.Parsers` raises `Plug.Parsers.UnsupportedMediaTypeError` with `plug_status: 415` and `media_type: "<unsupported_type>"`.

### 7. Request Body Length Limits
The `:length` option configures the maximum number of bytes read from the request body (default: `8_000_000` bytes). If the incoming body exceeds this limit, reading the body halts and `Plug.Parsers` raises `Plug.Parsers.RequestTooLargeError` with `plug_status: 413`.

### 8. Custom Parser Extension Lifecycle
Custom modules implementing the `Plug.Parsers` behaviour can be inserted into the `:parsers` pipeline. When `parse/5` is called:
- Returning `{:ok, parsed_map, conn}` sets `conn.body_params` and completes parsing.
- Returning `{:error, :too_large, conn}` raises `Plug.Parsers.RequestTooLargeError`.
- Returning `{:next, conn}` delegates handling to the next parser in the list.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"caseId":"case:sha256:94e4082c4671668a5266af9d053027e0580cc36f72fad92873e76ec24cb7211c","contract":["assert Plug.Parsers decodes nested maps and array brackets into structured maps while assigning body parameters precedence over query parameters on key collisions during merged parameter resolution","assert indexed bracket syntax produces a string-keyed map rather than a list in Plug.Conn.Query","assert Plug.Parsers.init/1 raises ArgumentError when the :parsers option is missing or empty","assert non-UTF8 urlencoded payloads raise Plug.Parsers.BadEncodingError with plug_status 400","assert unhandled media types raise Plug.Parsers.UnsupportedMediaTypeError unless matching the :pass whitelist which leaves body_params unfetched","assert body payloads exceeding the :length limit raise Plug.Parsers.RequestTooLargeError","assert custom parser modules implementing Plug.Parsers behaviour can return {:ok, ...}, {:error, :too_large, ...}, or delegate with {:next, ...}"],"goal":"Parse URL-encoded query and body payloads with Plug.Parsers, handle bracket and index nesting, enforce body length and media type constraints, and merge parameters with body precedence","kind":"HOW","packages":["pkg:hex/plug@1.20.3"],"schemaVersion":1,"symbols":["Plug.Parsers","Plug.Parsers.URLENCODED","Plug.Conn.Query","Plug.Conn.fetch_query_params"]},"contractCommand":["mix","test","--no-deps-check"],"environment":{"arch":"x64","ecosystem":"hex","executionContext":"elixir","language":"elixir","os":"linux","packageManager":"mix","runtime":"elixir","schemaVersion":1},"license":"MIT-0","packages":["pkg:hex/plug@1.20.3"],"schemaVersion":1,"symbols":["Plug.Parsers","Plug.Parsers.URLENCODED","Plug.Conn.Query","Plug.Conn.fetch_query_params"],"verifierAdapter":"hex@1"}
lib/csx_plug_parsers/csv_parser.ex
defmodule CsxPlugParsers.CsvParser do
  @moduledoc """
  Custom body parser implementing the `Plug.Parsers` behaviour for `text/csv` payloads.
  """
  @behaviour Plug.Parsers

  import Plug.Conn

  @impl true
  def init(opts), do: opts

  @impl true
  def parse(conn, "text", "csv", _headers, _opts) do
    case read_body(conn) do
      {:ok, body, conn} ->
        rows =
          body
          |> String.split("\n", trim: true)
          |> Enum.map(&String.split(&1, ","))

        {:ok, %{"_csv" => rows}, conn}

      {:more, _data, conn} ->
        {:error, :too_large, conn}
    end
  end

  def parse(conn, _type, _subtype, _headers, _opts) do
    {:next, conn}
  end
end
lib/csx_plug_parsers/pipeline.ex
defmodule CsxPlugParsers.Pipeline do
  @moduledoc """
  Plug pipeline demonstrating parameter parsing, media type dispatching, and error handling.
  """
  use Plug.Builder

  plug :fetch_query_params

  plug Plug.Parsers,
    parsers: [CsxPlugParsers.CsvParser, :urlencoded],
    pass: ["text/plain", "application/octet-stream"],
    length: 10_000

  plug :dispatch

  defp dispatch(conn, _opts) do
    case conn.path_info do
      ["params"] ->
        resp_data = inspect(%{
          query: conn.query_params,
          body: conn.body_params,
          params: conn.params
        })
        send_resp(conn, 200, resp_data)

      _ ->
        send_resp(conn, 404, "not found")
    end
  end
end
mix.exs
defmodule CsxPlugParsers.MixProject do
  use Mix.Project

  def project do
    [
      app: :csx_plug_parsers,
      version: "0.1.0",
      elixir: "~> 1.17",
      deps: deps()
    ]
  end

  def application do
    [
      extra_applications: [:logger]
    ]
  end

  defp deps do
    [
      {:plug, "1.20.3"}
    ]
  end
end
mix.lock
%{
  "mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
  "plug": {:hex, :plug, "1.20.3", "56c480c633ec2ce10140e236e15233bf576e1d323887d7c96711bd02ab5160db", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:plug_crypto, "~> 1.1.1 or ~> 1.2 or ~> 2.0", [hex: :plug_crypto, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4.3 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "be266aee1b8536ef6409d58cf39a3121319f0ec47cfa1b24024485aa0e76ad76"},
  "plug_crypto": {:hex, :plug_crypto, "2.2.0", "144014737daaf485407f5ed77daeaad74d651b216a28c87543f8cc7043f8efc8", [:mix], [], "hexpm", "83a95744ab1c75876542b6fab135fcc176280e0f301a111c1f757fddcec95d2c"},
  "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
test/contract_test.exs
defmodule CsxPlugParsers.ContractTest do
  use ExUnit.Case, async: true
  import Plug.Test
  import Plug.Conn

  alias CsxPlugParsers.Pipeline
  alias CsxPlugParsers.CsvParser

  test "Plug.Parsers decodes nested maps and array brackets into structured maps while assigning body parameters precedence over query parameters on key collisions during merged parameter resolution" do
    opts = Plug.Parsers.init(
      parsers: [:urlencoded],
      pass: ["*/*"]
    )

    query_str = "user[name]=Alice&user[contact][email]=alice@example.com&roles[]=admin&roles[]=editor"
    conn =
      conn(:post, "/users?source=web&roles=guest&user[name]=QueryAlice", query_str)
      |> put_req_header("content-type", "application/x-www-form-urlencoded")
      |> fetch_query_params()
      |> Plug.Parsers.call(opts)

    # 1. Query parameters remain isolated in query_params
    assert conn.query_params == %{
      "source" => "web",
      "roles" => "guest",
      "user" => %{"name" => "QueryAlice"}
    }

    # 2. Body parameters parsed into structured nested maps and lists
    assert conn.body_params == %{
      "roles" => ["admin", "editor"],
      "user" => %{
        "name" => "Alice",
        "contact" => %{"email" => "alice@example.com"}
      }
    }

    # 3. Merged conn.params: body parameters override query parameters on collision
    assert conn.params["source"] == "web"
    assert conn.params["roles"] == ["admin", "editor"]
    assert conn.params["user"]["name"] == "Alice"
    assert conn.params["user"]["contact"]["email"] == "alice@example.com"
  end

  test "indexed bracket syntax produces a string-keyed map rather than a list in Plug.Conn.Query" do
    # Empty bracket syntax produces an Elixir list
    list_params = Plug.Conn.Query.decode("items[]=first&items[]=second")
    assert list_params == %{"items" => ["first", "second"]}

    # Indexed bracket syntax produces a map keyed by index strings, not a list
    map_params = Plug.Conn.Query.decode("items[0]=first&items[1]=second")
    assert map_params == %{"items" => %{"0" => "first", "1" => "second"}}
  end

  test "Plug.Parsers.init/1 raises ArgumentError when the :parsers option is missing or empty" do
    assert_raise ArgumentError, ~r/Plug\.Parsers expects a set of parsers to be given in :parsers/, fn ->
      Plug.Parsers.init([])
    end

    assert_raise ArgumentError, ~r/Plug\.Parsers expects a set of parsers to be given in :parsers/, fn ->
      Plug.Parsers.init(parsers: nil)
    end
  end

  test "non-UTF8 urlencoded payloads raise Plug.Parsers.BadEncodingError with plug_status 400" do
    opts = Plug.Parsers.init(parsers: [:urlencoded])

    invalid_utf8_conn =
      conn(:post, "/submit", "name=valid&token=" <> <<255>>)
      |> put_req_header("content-type", "application/x-www-form-urlencoded")

    error =
      assert_raise Plug.Parsers.BadEncodingError, fn ->
        Plug.Parsers.call(invalid_utf8_conn, opts)
      end

    assert error.plug_status == 400
    assert error.message =~ "invalid UTF-8 on urlencoded params"
  end

  test "unhandled media types raise Plug.Parsers.UnsupportedMediaTypeError unless matching the :pass whitelist which leaves body_params unfetched" do
    strict_opts = Plug.Parsers.init(parsers: [:urlencoded], pass: [])

    unsupported_conn =
      conn(:post, "/upload", "<payload>test</payload>")
      |> put_req_header("content-type", "application/xml")

    error =
      assert_raise Plug.Parsers.UnsupportedMediaTypeError, fn ->
        Plug.Parsers.call(unsupported_conn, strict_opts)
      end

    assert error.plug_status == 415
    assert error.media_type == "application/xml"
    assert Exception.message(error) =~ "unsupported media type application/xml"

    # Whitelisted media type passes through without raising and leaves body_params unfetched
    pass_opts = Plug.Parsers.init(parsers: [:urlencoded], pass: ["application/*"])

    passed_conn =
      conn(:post, "/upload", "<payload>test</payload>")
      |> put_req_header("content-type", "application/xml")
      |> Plug.Parsers.call(pass_opts)

    assert %Plug.Conn.Unfetched{aspect: :body_params} = passed_conn.body_params
  end

  test "body payloads exceeding the :length limit raise Plug.Parsers.RequestTooLargeError" do
    opts = Plug.Parsers.init(parsers: [:urlencoded], length: 25)

    oversized_body = "key1=value1&key2=value2_exceeding_byte_limit"
    oversized_conn =
      conn(:post, "/submit", oversized_body)
      |> put_req_header("content-type", "application/x-www-form-urlencoded")

    error =
      assert_raise Plug.Parsers.RequestTooLargeError, fn ->
        Plug.Parsers.call(oversized_conn, opts)
      end

    assert error.plug_status == 413
  end

  test "custom parser modules implementing Plug.Parsers behaviour can return {:ok, ...}, {:error, :too_large, ...}, or delegate with {:next, ...}" do
    opts = Plug.Parsers.init(
      parsers: [CsvParser, :urlencoded],
      pass: ["*/*"]
    )

    # 1. Custom CSV parser handles text/csv
    csv_conn =
      conn(:post, "/upload", "name,email\nAlice,alice@example.com\nBob,bob@example.com")
      |> put_req_header("content-type", "text/csv")
      |> Plug.Parsers.call(opts)

    assert csv_conn.body_params == %{
      "_csv" => [["name", "email"], ["Alice", "alice@example.com"], ["Bob", "bob@example.com"]]
    }

    # 2. CsvParser delegates unrecognized content types via {:next, conn} to :urlencoded
    form_conn =
      conn(:post, "/submit", "status=active&count=42")
      |> put_req_header("content-type", "application/x-www-form-urlencoded")
      |> Plug.Parsers.call(opts)

    assert form_conn.body_params == %{"status" => "active", "count" => "42"}

    # 3. Pipeline integration end-to-end with case-insensitive headers
    pipeline_conn =
      conn(:post, "/params?page=2", "name,email\nCharlie,charlie@example.com")
      |> put_req_header("content-type", "TEXT/CSV; charset=utf-8")
      |> Pipeline.call([])

    assert pipeline_conn.status == 200
    assert pipeline_conn.body_params == %{
      "_csv" => [["name", "email"], ["Charlie", "charlie@example.com"]]
    }
    assert pipeline_conn.query_params == %{"page" => "2"}
    assert pipeline_conn.params["page"] == "2"
    assert pipeline_conn.params["_csv"] == [["name", "email"], ["Charlie", "charlie@example.com"]]
  end
end
test/test_helper.exs
ExUnit.start()

Seeder de origen

csx-seed