CodeSampleX

샘플

rack-test 2.2.0: Handle Rack::Test header HTTP_ double-prefixing, 308 redirect method mutation, query array flattening, and cookie comma truncation

검증된 샘플 — gem rack-test 2.2.0: Handle Rack::Test header HTTP_ double-prefixing, 308 redirect method mutation, query array flattening, and cookie comma…

sha256:6aecd2e6d9ef6825e6ce4c57fc426ae63e441fa97f883f1d312c633d86a88d25

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
1
선언된 환경 ruby linux x64 ruby ruby rubygems

검증 실행 환경

환경 컨트랙트 단계 실행일
ruby 3 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-16
ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 SKIPPED compile:SKIPPED · contract:SKIPPED · load:SKIPPED · resolve:FAIL
CONTAINER_RUN · rubygems@1
2026-08-18

케이스

HOW
목표
Handle Rack::Test header HTTP_ double-prefixing, 308 redirect method mutation, query array flattening, and cookie comma truncation
패키지
심벌
  • Rack::Test::Methods
  • Rack::Test::Session#header
  • Rack::Test::Session#follow_redirect!
  • Rack::Test::Utils.build_nested_query
  • Rack::Test::UploadedFile.new
  • Rack::Test::CookieJar
환경
ruby
생성일
2026-08-16T16:46:17Z

컨트랙트

  1. Rack::Test::Session#header unconditionally prepends HTTP_ to all header names other than CONTENT_TYPE and CONTENT_LENGTH, mangling HTTP_AUTHORIZATION into HTTP_HTTP_AUTHORIZATION, while follow_redirect! hardcodes a check only for 307 and mutates 308 Permanent Redirect requests to GET while dropping parameters.
  2. Passing nil in GET params encodes as a bare key parsed back as nil, empty string encodes as key= parsed as empty string, empty array encodes as key[]= parsed as [""], and nested 2D arrays are flattened into a 1D query string
  3. In multipart POST requests, nil parameters are coerced to empty strings in form parts and empty arrays produce no parts at all, omitting the key from parsed parameters
  4. Rack::Test::Cookie splits Set-Cookie headers on commas, truncating cookie values containing commas at the first comma, and scopes paths using start_with? matching prefixes beyond directory boundaries

파일

  • Gemfile
  • Gemfile.lock
  • NOTES.md
  • csx.json
  • src/app.rb
  • test/contract.rb

소스 아티팩트 내려받기 (tar.gz)

소스

Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

gem "rack", "3.2.7"
gem "rack-test", "2.2.0"
gem "minitest", "~> 5.25"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    minitest (5.27.0)
    rack (3.2.7)
    rack-test (2.2.0)
      rack (>= 1.3)

PLATFORMS
  x64-mingw-ucrt

DEPENDENCIES
  minitest (~> 5.25)
  rack (= 3.2.7)
  rack-test (= 2.2.0)

BUNDLED WITH
   2.6.9
NOTES.md
# Notes on `rack-test` Header Normalization, 308 Redirect Handling, and Input Edge Serialization

## 1. What `search_known_solution` answered

`search_known_solution` returned existing samples for `rack-test`:
- `sha256:5e6ad6f64fb23b10442b9867c77cd2600b9b4f64391a51a71c223bc4a3fe78f3` ("Manage Rack::Test type serialization boundaries across JSON Hash payloads, query parameter type coercion, multipart symbol keys, and CookieJar security scopes")
- `sha256:a495a264fa6e8265c86934c8789b1337aa1c808e0661fc7e43c8522913cd660a` ("Show that Rack::Test only honored secure cookies when the `Secure` attribute is parsed case-insensitively in 2.2.0.")
- `sha256:e873d35fe6c381482a9e0eccc77adc87a49c7dd3a71b3a34b647cabceb3360a5` ("Demonstrate that `Rack::Test::Cookie` now reads mixed-case cookie attributes when scoping cookies.")

This contract targets a distinct set of traps in `rack-test`:
1. `Rack::Test::Session#header` double-prefixing headers that already begin with `HTTP_` (e.g. `header("HTTP_AUTHORIZATION", ...)` setting `HTTP_HTTP_AUTHORIZATION`).
2. `follow_redirect!` hardcoding a check for status 307 only, silently converting 308 Permanent Redirects from POST to GET and dropping the payload.
3. Query parameter boundary behaviors in `Rack::Test::Utils.build_nested_query` (flattening 2D arrays to 1D, `nil` vs `""` serialization, and empty array mutating to `[""]`).
4. `Rack::Test::Cookie` truncating cookie values containing commas at the first comma delimiter and matching paths via prefix `start_with?`.

## 2. How the wrong version fails

- **Loud failures**:
  - Authenticated endpoints fail with 401 Unauthorized because `header("HTTP_AUTHORIZATION", "Bearer ...")` writes `HTTP_HTTP_AUTHORIZATION` to the Rack environment, leaving `HTTP_AUTHORIZATION` nil.
  - Endpoints expecting 2D matrices raise `TypeError` or `NoMethodError` when indexing `params["matrix"][row][col]` because `Rack::Test` flattens nested arrays into a 1D list.
  - Endpoints handling 308 redirects fail with 404 or 405 Method Not Allowed because `follow_redirect!` issues a GET request with empty parameters instead of replaying the POST request.

- **Silent failures with green build**:
  - `header("X-Nil", nil)` removes the header from the session environment, while `header("X-Empty", "")` preserves an empty string header `HTTP_X_EMPTY = ""`.
  - In multipart requests with `UploadedFile`, passing `nil_val: nil` silently arrives as `""` (empty string) in the Rack application, whereas in urlencoded requests it arrives as `nil`.
  - In multipart requests, passing `empty_arr: []` produces no form parts, causing `params.key?("empty_arr")` to evaluate to `false`, whereas in urlencoded requests it produces `[""]`.
  - `Set-Cookie: tag=val1,val2; path=/` silently truncates the cookie value to `val1` in `CookieJar`.
  - Cookies scoped to `path=/admin` are silently sent to `/administrator` because cookie path checking uses `uri.path.start_with?(path)`.
csx.json
{"case":{"believed":"Calling header with a header name already starting with HTTP_ sets the Rack environment key directly, and follow_redirect! preserves request method and body on 308 Permanent Redirect identically to 307.","caseId":"case:sha256:7fde51a4a389f725a52f2edfc817633b5f7d3ff78a71160e265fb4e15c37bb73","contract":["Rack::Test::Session#header unconditionally prepends HTTP_ to all header names other than CONTENT_TYPE and CONTENT_LENGTH, mangling HTTP_AUTHORIZATION into HTTP_HTTP_AUTHORIZATION, while follow_redirect! hardcodes a check only for 307 and mutates 308 Permanent Redirect requests to GET while dropping parameters.","Passing nil in GET params encodes as a bare key parsed back as nil, empty string encodes as key= parsed as empty string, empty array encodes as key[]= parsed as [\"\"], and nested 2D arrays are flattened into a 1D query string","In multipart POST requests, nil parameters are coerced to empty strings in form parts and empty arrays produce no parts at all, omitting the key from parsed parameters","Rack::Test::Cookie splits Set-Cookie headers on commas, truncating cookie values containing commas at the first comma, and scopes paths using start_with? matching prefixes beyond directory boundaries"],"goal":"Handle Rack::Test header HTTP_ double-prefixing, 308 redirect method mutation, query array flattening, and cookie comma truncation","kind":"HOW","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::Methods","Rack::Test::Session#header","Rack::Test::Session#follow_redirect!","Rack::Test::Utils.build_nested_query","Rack::Test::UploadedFile.new","Rack::Test::CookieJar"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"rubygems","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7"],"schemaVersion":1,"symbols":["Rack::Test::Methods","Rack::Test::Session#header","Rack::Test::Session#follow_redirect!","Rack::Test::Utils.build_nested_query","Rack::Test::UploadedFile.new","Rack::Test::CookieJar"],"verifierAdapter":"rubygems@1"}
src/app.rb
# frozen_string_literal: true

require "rack"
require "json"

module RackTestDomainEdgeApp
  class Application
    def call(env)
      req = Rack::Request.new(env)

      case req.path_info
      when "/query"
        payload = {
          query_string: req.query_string,
          params: req.params
        }
        [200, { "content-type" => "application/json" }, [JSON.generate(payload)]]

      when "/headers"
        payload = {
          http_authorization: env["HTTP_AUTHORIZATION"],
          http_http_authorization: env["HTTP_HTTP_AUTHORIZATION"],
          content_type: env["CONTENT_TYPE"],
          content_length: env["CONTENT_LENGTH"],
          http_content_disposition: env["HTTP_CONTENT_DISPOSITION"],
          http_x_empty: env["HTTP_X_EMPTY"],
          http_x_nil: env["HTTP_X_NIL"]
        }
        [200, { "content-type" => "application/json" }, [JSON.generate(payload)]]

      when "/redirect_307"
        [307, { "location" => "/destination" }, [""]]

      when "/redirect_308"
        [308, { "location" => "/destination" }, [""]]

      when "/destination"
        body_content = env["rack.input"] ? env["rack.input"].read : ""
        env["rack.input"]&.rewind
        payload = {
          method: req.request_method,
          body: body_content,
          params: req.params,
          referer: env["HTTP_REFERER"]
        }
        [200, { "content-type" => "application/json" }, [JSON.generate(payload)]]

      when "/multipart"
        file_part = req.params["file"]
        file_meta = if file_part.is_a?(Hash)
                      {
                        filename: file_part[:filename],
                        type: file_part[:type],
                        size: file_part[:tempfile]&.size
                      }
                    end
        payload = {
          content_type: req.content_type,
          file: file_meta,
          nil_val: req.params["nil_val"],
          empty_str: req.params["empty_str"],
          has_empty_arr: req.params.key?("empty_arr"),
          empty_arr: req.params["empty_arr"]
        }
        [200, { "content-type" => "application/json" }, [JSON.generate(payload)]]

      when "/cookies/set"
        [200, {
          "content-type" => "text/plain",
          "set-cookie" => "tag=val1,val2; path=/\nempty_val=; path=/\nscoped=admin_only; path=/admin"
        }, ["cookies_set"]]

      when "/cookies/echo", "/admin", "/administrator"
        payload = {
          path: req.path_info,
          cookies: req.cookies
        }
        [200, { "content-type" => "application/json" }, [JSON.generate(payload)]]

      else
        [404, { "content-type" => "text/plain" }, ["not found"]]
      end
    end
  end
end
test/contract.rb
# frozen_string_literal: true

require "minitest/autorun"
require "rack"
require "rack/test"
require "json"
require "stringio"

require_relative "../src/app"

class RackTestContractTest < Minitest::Test
  include Rack::Test::Methods

  def app
    RackTestDomainEdgeApp::Application.new
  end

  def test_header_prefixing_and_nil_deletion
    # 1. header() unconditionally prepends HTTP_ unless name is CONTENT_TYPE or CONTENT_LENGTH
    header "HTTP_AUTHORIZATION", "Bearer token_abc"
    header "Content-Type", "application/json"
    header "Content-Disposition", "inline"
    header "X-Empty", ""
    header "X-Nil", "to_be_deleted"
    header "X-Nil", nil

    get "/headers"
    assert_equal 200, last_response.status

    data = JSON.parse(last_response.body)
    # Proves HTTP_AUTHORIZATION is NOT set directly, but mangled into HTTP_HTTP_AUTHORIZATION
    assert_nil data["http_authorization"]
    assert_equal "Bearer token_abc", data["http_http_authorization"]

    # Proves CONTENT_TYPE is exempt from HTTP_ prefix
    assert_equal "application/json", data["content_type"]

    # Proves other Content-* headers receive HTTP_ prefix
    assert_equal "inline", data["http_content_disposition"]

    # Proves empty string preserves header as "", while nil deletes it from session env
    assert_equal "", data["http_x_empty"]
    assert_nil data["http_x_nil"]
  end

  def test_query_parameter_domain_boundaries_and_array_flattening
    # 2. Query serialization of nil, empty string, empty array, empty hash, nested 2D array, and unicode
    get "/query", {
      "nil_param" => nil,
      "empty_str" => "",
      "empty_arr" => [],
      "empty_hash" => {},
      "matrix" => [["row1_col1", "row1_col2"], ["row2_col1", "row2_col2"]],
      "ユーザー" => "山田 太郎"
    }

    assert_equal 200, last_response.status
    data = JSON.parse(last_response.body)
    params = data["params"]

    # nil encodes as bare key without '=', parsed back as nil
    assert_nil params["nil_param"]

    # empty string encodes with '=', parsed as ""
    assert_equal "", params["empty_str"]

    # empty array encodes as "empty_arr[]=", parsed as an array containing one empty string
    assert_equal [""], params["empty_arr"]

    # empty hash produces no query tokens, omitted entirely from params
    refute params.key?("empty_hash")

    # nested 2D array is flattened to 1D array by build_nested_query
    assert_equal ["row1_col1", "row1_col2", "row2_col1", "row2_col2"], params["matrix"]

    # Unicode keys and values are UTF-8 percent-encoded and parsed correctly
    assert_equal "山田 太郎", params["ユーザー"]
  end

  def test_redirect_method_and_payload_preservation_307_vs_308
    # 3. HTTP 307 preserves POST method and body, whereas HTTP 308 mutates to GET and drops body
    post "/redirect_307", { "action" => "create_record" }
    assert_equal 307, last_response.status
    follow_redirect!

    res_307 = JSON.parse(last_response.body)
    assert_equal "POST", res_307["method"]
    assert_equal "create_record", res_307["params"]["action"]
    assert_equal "action=create_record", res_307["body"]

    post "/redirect_308", { "action" => "create_record" }
    assert_equal 308, last_response.status
    follow_redirect!

    res_308 = JSON.parse(last_response.body)
    assert_equal "GET", res_308["method"]
    assert_equal({}, res_308["params"])
    assert_equal "", res_308["body"]
  end

  def test_multipart_versus_urlencoded_empty_and_nil_handling
    # 4. In multipart mode (presence of UploadedFile), nil becomes "" and empty array is dropped
    uploaded_file = Rack::Test::UploadedFile.new(
      StringIO.new("sample content"),
      "text/plain",
      original_filename: "sample.txt"
    )

    post "/multipart", {
      "file" => uploaded_file,
      "nil_val" => nil,
      "empty_str" => "",
      "empty_arr" => []
    }

    assert_equal 200, last_response.status
    data = JSON.parse(last_response.body)

    assert_equal "sample.txt", data["file"]["filename"]
    # In multipart, nil value generates a form part with empty body, parsed as ""
    assert_equal "", data["nil_val"]
    assert_equal "", data["empty_str"]
    # In multipart, empty array generates no form parts, so the key is absent
    assert_equal false, data["has_empty_arr"]
    assert_nil data["empty_arr"]
  end

  def test_cookie_comma_truncation_and_path_prefix_scoping
    # 5. Cookie value with comma is truncated at first comma, and path scoping uses start_with?
    clear_cookies
    get "/cookies/set"
    assert_equal 200, last_response.status

    # Cookie with value "val1,val2" is split on comma, storing only "val1"
    assert_equal "val1", current_session.cookie_jar["tag"]
    assert_equal "", current_session.cookie_jar["empty_val"]

    # Cookie with path="/admin" is sent to both "/admin" and "/administrator"
    get "/admin"
    data_admin = JSON.parse(last_response.body)
    assert_equal "admin_only", data_admin["cookies"]["scoped"]

    get "/administrator"
    data_admin_prefix = JSON.parse(last_response.body)
    assert_equal "admin_only", data_admin_prefix["cookies"]["scoped"]

    # But not sent to root /cookies/echo
    get "/cookies/echo"
    data_root = JSON.parse(last_response.body)
    refute data_root["cookies"].key?("scoped")
  end
end

오리진 시더

csx-seed