CodeSampleX

Ejemplo

req 0.7.2: Handle Req defaults for redirect credential stripping, method rewrites, redirect limits, opt-in compression, and user-agent value validation

Muestra verificada para hex req 0.7.2: Handle Req defaults for redirect credential stripping, method rewrites, redirect limits, opt-in compression, and…

sha256:3f145e36efe27122e4ece7c6ac75d71229c265eb14001e46d2c75d0ba58c5e7c

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
Handle Req defaults for redirect credential stripping, method rewrites, redirect limits, opt-in compression, and user-agent value validation
Paquetes
Símbolos
  • Req.new
  • Req.Request.get_header
  • Req.Steps.redirect
  • Req.Steps.compressed
  • Req.Steps.put_user_agent
  • Req.TooManyRedirectsError
Entorno
elixir
Creado
2026-08-17T04:46:01Z

Contrato

  1. assert cross-origin HTTP redirects strip sensitive Authorization headers by default unless redirect_trusted: true is set
  2. assert same-origin redirects preserve Authorization headers while cross-origin redirects to a different host strip them
  3. assert 301, 302, and 303 redirects convert POST requests to GET and clear the body payload while 307 and 308 preserve POST method and body
  4. assert redirect defaults to true and following redirects can be disabled by setting redirect: false
  5. assert redirect loops halt and raise Req.TooManyRedirectsError when exceeding max_redirects default of 10
  6. assert compressed defaults to false and leaves accept-encoding unset, while compressed: true advertises supported encodings including gzip
  7. assert put_user_agent uses a Req version header by default and raises FunctionClauseError when user_agent: false is treated as a non-binary header value

Archivos

  • NOTES.md
  • csx.json
  • 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
`search_known_solution` returned a HIT for `pkg:hex/req@0.7.2` (`sha256:1a5be8dc134928a8238887f9504e70f60f67fb5fa956fd3fc577d86784ecfa1d` covering HTTP stubbing and `sha256:44ed518e27a03b5bcb2248c4e2644a12adf18d5288dd063d62acf4e74a458ee0` covering URL merging and path parameters). This sample proves a distinct set of public behaviors in Req: default option handling for cross-origin credential stripping, redirect status method transformations, redirect loop limits, and default request headers.

A naive assumption fails silently at runtime: cross-origin redirects strip bearer credentials unless explicitly trusted, and 301/302/303 rewrite a redirected `POST` to an empty `GET`. Req 0.7 also makes response compression opt-in; `compressed: true` adds `accept-encoding`, while `user_agent: false` is not a supported disable flag and fails when used as a non-binary header value.
csx.json
{"buildCommand":["mix","deps.compile","--no-deps-check"],"case":{"believed":"Req preserves Authorization headers across cross-origin redirects by default, retains the POST method when following 301 and 302 redirects, and sends no automatic accept-encoding headers unless compressed is requested.","caseId":"case:sha256:41f15f476c8135075f25b5e25afd74cb0b3ea29c8159af079a4e536723eaffcf","contract":["assert cross-origin HTTP redirects strip sensitive Authorization headers by default unless redirect_trusted: true is set","assert same-origin redirects preserve Authorization headers while cross-origin redirects to a different host strip them","assert 301, 302, and 303 redirects convert POST requests to GET and clear the body payload while 307 and 308 preserve POST method and body","assert redirect defaults to true and following redirects can be disabled by setting redirect: false","assert redirect loops halt and raise Req.TooManyRedirectsError when exceeding max_redirects default of 10","assert compressed defaults to false and leaves accept-encoding unset, while compressed: true advertises supported encodings including gzip","assert put_user_agent uses a Req version header by default and raises FunctionClauseError when user_agent: false is treated as a non-binary header value"],"goal":"Handle Req defaults for redirect credential stripping, method rewrites, redirect limits, opt-in compression, and user-agent value validation","kind":"HOW","packages":["pkg:hex/req@0.7.2","pkg:hex/plug@1.20.3","pkg:hex/jason@1.4.5"],"schemaVersion":1,"symbols":["Req.new","Req.Request.get_header","Req.Steps.redirect","Req.Steps.compressed","Req.Steps.put_user_agent","Req.TooManyRedirectsError"]},"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/req@0.7.2","pkg:hex/plug@1.20.3","pkg:hex/jason@1.4.5"],"schemaVersion":1,"symbols":["Req.new","Req.Request.get_header","Req.Steps.redirect","Req.Steps.compressed","Req.Steps.put_user_agent","Req.TooManyRedirectsError"],"verifierAdapter":"hex@1"}
mix.exs
defmodule CsxReqDefaults.MixProject do
  use Mix.Project

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

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

  defp deps do
    [
      {:req, "0.7.2"},
      {:plug, "1.20.3"},
      {:jason, "1.4.5"}
    ]
  end
end
mix.lock
%{
  "finch": {:hex, :finch, "0.23.0", "e3f9287ac25a8832f848b144c2b57346aac65b205e2e0629a52adfe6507fd837", [:mix], [{:mime, "~> 1.0 or ~> 2.0", [hex: :mime, repo: "hexpm", optional: false]}, {:mint, "~> 1.8", [hex: :mint, repo: "hexpm", optional: false]}, {:nimble_options, "~> 0.4 or ~> 1.0", [hex: :nimble_options, repo: "hexpm", optional: false]}, {:nimble_pool, "~> 1.1", [hex: :nimble_pool, repo: "hexpm", optional: false]}, {:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "80e58d3f936f57e3fdf404f83a3642897ae6d9fb642934e46da4d8fe761b99d5"},
  "hpax": {:hex, :hpax, "1.0.4", "777de5d433b0fbdc7c418159c8055910faa8047ffdb3d6b31098d2a46cd7685c", [:mix], [], "hexpm", "afc7cb142ebcc2d01ce7816190b98ce5dd49e799111b24249f3443d730f377ca"},
  "jason": {:hex, :jason, "1.4.5", "2e3a008590b0b8d7388c20293e9dcc9cf3e5d642fd2a114e4cbbb52e595d940a", [:mix], [{:decimal, "~> 1.0 or ~> 2.0 or ~> 3.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "b0c823996102bcd0239b3c2444eb00409b72f6a140c1950bc8b457d836b30684"},
  "mime": {:hex, :mime, "2.0.7", "b8d739037be7cd402aee1ba0306edfdef982687ee7e9859bee6198c1e7e2f128", [:mix], [], "hexpm", "6171188e399ee16023ffc5b76ce445eb6d9672e2e241d2df6050f3c771e80ccd"},
  "mint": {:hex, :mint, "1.9.3", "3337184d69179695c7a9f1714d92c11e629d36c8c037a21cf490131d3d150554", [:mix], [{:castore, "~> 0.1.0 or ~> 1.0", [hex: :castore, repo: "hexpm", optional: true]}, {:hpax, "~> 0.1.1 or ~> 0.2.0 or ~> 1.0", [hex: :hpax, repo: "hexpm", optional: false]}], "hexpm", "5f7c9342480c069dbbc4eeac3490303c9e01870ff01a7f1d29b6107054fc1e74"},
  "nimble_options": {:hex, :nimble_options, "1.1.1", "e3a492d54d85fc3fd7c5baf411d9d2852922f66e69476317787a7b2bb000a61b", [:mix], [], "hexpm", "821b2470ca9442c4b6984882fe9bb0389371b8ddec4d45a9504f00a66f650b44"},
  "nimble_pool": {:hex, :nimble_pool, "1.1.0", "bf9c29fbdcba3564a8b800d1eeb5a3c58f36e1e11d7b7fb2e084a643f645f06b", [:mix], [], "hexpm", "af2e4e6b34197db81f7aad230c1118eac993acc0dae6bc83bac0126d4ae0813a"},
  "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"},
  "req": {:hex, :req, "0.7.2", "364eae2e5f5c984f2dac6d71c07f8c8c89ce0bc49c4d746dacb7a306823020de", [:mix], [{:brotli, "~> 0.3.1", [hex: :brotli, repo: "hexpm", optional: true]}, {:finch, "~> 0.21", [hex: :finch, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}, {:mime, "~> 2.0.6 or ~> 2.1", [hex: :mime, repo: "hexpm", optional: false]}, {:nimble_csv, "~> 1.0", [hex: :nimble_csv, repo: "hexpm", optional: true]}, {:plug, "~> 1.0", [hex: :plug, repo: "hexpm", optional: true]}], "hexpm", "c9cdfa276b05d8db2a27fda5d233e6858b764d47189d76cbb186e130a871ae0b"},
  "telemetry": {:hex, :telemetry, "1.4.2", "a0cb522801dffb1c49fe6e30561badffc7b6d0e180db1300df759faa22062855", [:rebar3], [], "hexpm", "928f6495066506077862c0d1646609eed891a4326bee3126ba54b60af61febb1"},
}
test/contract_test.exs
defmodule CsxReqDefaultsTest do
  use ExUnit.Case, async: true

  test "cross-origin redirect strips Authorization by default, but preserves it on same-origin or with redirect_trusted: true" do
    plug = fn conn ->
      case {conn.host, conn.request_path} do
        {"auth.example.com", "/login"} ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://cdn.example.com/assets")
          |> Plug.Conn.send_resp(302, "redirect cross-origin")

        {"auth.example.com", "/internal"} ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://auth.example.com/assets")
          |> Plug.Conn.send_resp(302, "redirect same-origin")

        {"auth.example.com", "/assets"} ->
          auth_headers = Plug.Conn.get_req_header(conn, "authorization")

          conn
          |> Plug.Conn.put_resp_content_type("application/json")
          |> Plug.Conn.send_resp(200, Jason.encode!(%{origin: "same", auth: auth_headers}))

        {"cdn.example.com", "/assets"} ->
          auth_headers = Plug.Conn.get_req_header(conn, "authorization")

          conn
          |> Plug.Conn.put_resp_content_type("application/json")
          |> Plug.Conn.send_resp(200, Jason.encode!(%{origin: "cross", auth: auth_headers}))
      end
    end

    # 1. Cross-origin redirect with default redirect_trusted: false strips Authorization header
    resp_cross_default =
      Req.get!(
        url: "https://auth.example.com/login",
        auth: {:bearer, "token_secret_123"},
        plug: plug,
        retry: false
      )

    assert resp_cross_default.status == 200
    assert resp_cross_default.body == %{"origin" => "cross", "auth" => []}

    # 2. Same-origin redirect preserves Authorization header under default settings
    resp_same_default =
      Req.get!(
        url: "https://auth.example.com/internal",
        auth: {:bearer, "token_secret_123"},
        plug: plug,
        retry: false
      )

    assert resp_same_default.status == 200
    assert resp_same_default.body == %{"origin" => "same", "auth" => ["Bearer token_secret_123"]}

    # 3. Cross-origin redirect with explicit redirect_trusted: true preserves Authorization header
    resp_cross_trusted =
      Req.get!(
        url: "https://auth.example.com/login",
        auth: {:bearer, "token_secret_123"},
        redirect_trusted: true,
        plug: plug,
        retry: false
      )

    assert resp_cross_trusted.status == 200
    assert resp_cross_trusted.body == %{"origin" => "cross", "auth" => ["Bearer token_secret_123"]}
  end

  test "301, 302, and 303 redirects rewrite POST to GET and drop payload, whereas 307 and 308 preserve POST method and body" do
    plug = fn conn ->
      case conn.request_path do
        "/redirect-301" ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://api.example.com/target")
          |> Plug.Conn.send_resp(301, "")

        "/redirect-302" ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://api.example.com/target")
          |> Plug.Conn.send_resp(302, "")

        "/redirect-303" ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://api.example.com/target")
          |> Plug.Conn.send_resp(303, "")

        "/redirect-307" ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://api.example.com/target")
          |> Plug.Conn.send_resp(307, "")

        "/redirect-308" ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://api.example.com/target")
          |> Plug.Conn.send_resp(308, "")

        "/target" ->
          {:ok, body, conn} = Plug.Conn.read_body(conn)

          conn
          |> Plug.Conn.put_resp_content_type("application/json")
          |> Plug.Conn.send_resp(
            200,
            Jason.encode!(%{method: conn.method, received_body: body})
          )
      end
    end

    # 301 rewrites POST to GET and drops body
    resp_301 =
      Req.post!(
        url: "https://api.example.com/redirect-301",
        body: "payload_data",
        plug: plug,
        retry: false
      )

    assert resp_301.status == 200
    assert resp_301.body == %{"method" => "GET", "received_body" => ""}

    # 302 rewrites POST to GET and drops body
    resp_302 =
      Req.post!(
        url: "https://api.example.com/redirect-302",
        body: "payload_data",
        plug: plug,
        retry: false
      )

    assert resp_302.status == 200
    assert resp_302.body == %{"method" => "GET", "received_body" => ""}

    # 303 rewrites POST to GET and drops body
    resp_303 =
      Req.post!(
        url: "https://api.example.com/redirect-303",
        body: "payload_data",
        plug: plug,
        retry: false
      )

    assert resp_303.status == 200
    assert resp_303.body == %{"method" => "GET", "received_body" => ""}

    # 307 preserves POST method and preserves body payload
    resp_307 =
      Req.post!(
        url: "https://api.example.com/redirect-307",
        body: "payload_data",
        plug: plug,
        retry: false
      )

    assert resp_307.status == 200
    assert resp_307.body == %{"method" => "POST", "received_body" => "payload_data"}

    # 308 preserves POST method and preserves body payload
    resp_308 =
      Req.post!(
        url: "https://api.example.com/redirect-308",
        body: "payload_data",
        plug: plug,
        retry: false
      )

    assert resp_308.status == 200
    assert resp_308.body == %{"method" => "POST", "received_body" => "payload_data"}
  end

  test "redirect defaults to true and following redirects can be disabled or capped by max_redirects" do
    plug = fn conn ->
      case conn.request_path do
        "/redirect-step" ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://api.example.com/final")
          |> Plug.Conn.send_resp(302, "redirecting")

        "/final" ->
          Plug.Conn.send_resp(conn, 200, "final destination")

        "/loop" ->
          conn
          |> Plug.Conn.put_resp_header("location", "https://api.example.com/loop")
          |> Plug.Conn.send_resp(302, "looping")
      end
    end

    # Default redirect: true automatically follows to final destination
    resp_followed =
      Req.get!(
        url: "https://api.example.com/redirect-step",
        plug: plug,
        retry: false
      )

    assert resp_followed.status == 200
    assert resp_followed.body == "final destination"

    # Setting redirect: false returns the 302 response directly
    resp_unfollowed =
      Req.get!(
        url: "https://api.example.com/redirect-step",
        redirect: false,
        plug: plug,
        retry: false
      )

    assert resp_unfollowed.status == 302
    assert Req.Response.get_header(resp_unfollowed, "location") == ["https://api.example.com/final"]

    # Redirect loop exceeds max_redirects default (10) and raises Req.TooManyRedirectsError
    assert_raise Req.TooManyRedirectsError, ~r/too many redirects \(10\)/, fn ->
      Req.get!(
        url: "https://api.example.com/loop",
        plug: plug,
        retry: false
      )
    end

    # Custom max_redirects limit is respected
    assert_raise Req.TooManyRedirectsError, ~r/too many redirects \(3\)/, fn ->
      Req.get!(
        url: "https://api.example.com/loop",
        max_redirects: 3,
        plug: plug,
        retry: false
      )
    end
  end

  test "compressed is opt-in and user_agent expects a string rather than a boolean disable flag" do
    # Response decompression is opt-in in Req 0.7, so no accept-encoding header is added by default.
    req_default =
      Req.new(url: "https://api.example.com/info")
      |> Req.Steps.compressed()
      |> Req.Steps.put_user_agent()

    assert Req.Request.get_header(req_default, "accept-encoding") == []

    user_agent = Req.Request.get_header(req_default, "user-agent")
    assert user_agent != []
    assert Enum.any?(user_agent, &String.starts_with?(&1, "req/"))

    # Enabling compressed advertises gzip support.
    req_compressed =
      Req.new(url: "https://api.example.com/info", compressed: true)
      |> Req.Steps.compressed()

    assert Enum.any?(
             Req.Request.get_header(req_compressed, "accept-encoding"),
             &String.contains?(&1, "gzip")
           )

    # compressed: false leaves the compression header unset.
    req_disabled =
      Req.new(url: "https://api.example.com/info", compressed: false)
      |> Req.Steps.compressed()

    assert Req.Request.get_header(req_disabled, "accept-encoding") == []

    # user_agent is a header value option. Passing false is not a supported disable flag.
    assert_raise FunctionClauseError, fn ->
      Req.new(url: "https://api.example.com/info", user_agent: false)
      |> Req.Steps.put_user_agent()
    end
  end
end
test/test_helper.exs
ExUnit.start()

Seeder de origen

csx-seed