Пример
rack-test 2.2.0: Manage Rack::Test type serialization boundaries across JSON Hash payloads, query parameter type coercion, multipart symbol keys, and CookieJar security scopes
Проверенный пример — gem rack-test 2.2.0: Manage Rack::Test type serialization boundaries across JSON Hash payloads, query parameter type coercion, multipart…
sha256:5fe3699ec9450e25104ae03ae89602c44a28ffdbdf87748819f7f3de86bdc4bc
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
MIT-0
Свидетельства выполнения
Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.
- Основа свидетельства
- Подписанный контракт пройден
- Квитанции проверки
- 2
- Ключи подписи, собравшие его
- 2
Заявленная среда
ruby linux x64 ruby ruby rubygems
Среды запусков проверки
| Окружение | Контракт | Этапы | Запуск |
|---|---|---|---|
| ruby 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-17 |
| ruby 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · rubygems@1 |
2026-08-18 |
Кейс
HOW- Цель
- Manage Rack::Test type serialization boundaries across JSON Hash payloads, query parameter type coercion, multipart symbol keys, and CookieJar security scopes
- Пакеты
- Символы
-
- Rack::Test::Methods
- Rack::Test::Session#header
- Rack::Test::Session#get
- Rack::Test::Session#post
- Rack::Test::UploadedFile.new
- Rack::Test::CookieJar
- Окружение
- ruby
- Создан
- 2026-08-17T02:45:45Z
Контракт
- assert posting a Hash with application/json Content-Type sends a form-urlencoded query string and fails JSON parsing unless explicitly passed as a serialized JSON string
- assert primitive Hash parameter types are coerced to strings, nil is preserved as nil, empty arrays mutate to an array containing an empty string, and empty hashes are omitted from params
- assert URI query string and params Hash merge overwrites scalar keys but appends array elements together
- assert UploadedFile triggers multipart encoding with symbol-keyed descriptor hashes while unwrapped IO objects are stringified into urlencoded form data
- assert CookieJar silently ignores Secure cookies received over plain HTTP, filters Secure cookies from HTTP requests, and scopes non-domain cookies to the exact host
Файлы
- Gemfile
- Gemfile.lock
- NOTES.md
- csx.json
- src/app.rb
- test/contract.rb
Исходный код
source "https://rubygems.org"
gem "rack-test", "2.2.0"
gem "rack", "3.2.7"
gem "minitest", "5.27.0"
GEM
remote: https://rubygems.org/
specs:
minitest (5.27.0)
rack (3.2.7)
rack-test (2.2.0)
rack (>= 1.3)
PLATFORMS
ruby
x64-mingw-ucrt
DEPENDENCIES
minitest (= 5.27.0)
rack (= 3.2.7)
rack-test (= 2.2.0)
CHECKSUMS
bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
minitest (5.27.0) sha256=2d3b17f8a36fe7801c1adcffdbc38233b938eb0b4966e97a6739055a45fa77d5
rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7
rack-test (2.2.0) sha256=005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463
BUNDLED WITH
4.0.18
# Notes on `pkg:gem/rack-test` Type & Serialization Boundaries
## 1. What `search_known_solution` answered
`search_known_solution` returned a match for sample `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b` ("Test a Sinatra 4 app with rack-test in the same process, with no server, and get the params, filter and 404 behaviour right instead of guessing it"). That sample evaluated Sinatra 4 framework integrations (modular versus classic base classes, HostAuthorization middleware blocking requests with 403, parameter precedence between route captures, query strings, and form bodies, filter halting with `halt` versus `return`, and custom 404 views).
This sample focuses directly on `rack-test` type coercion, payload serialization, multipart structures, parameter merging, and CookieJar RFC 6265 security boundaries.
## 2. What a model would have written instead
- Assumed setting `header "Content-Type", "application/json"` causes `post "/api", { user: { name: "Alice" } }` to serialize the Ruby Hash into JSON.
- Assumed Ruby types in `params` (integers, symbols, booleans, `nil`, empty arrays, and empty hashes) preserve their types and shapes inside the Rack application.
- Assumed passing query parameters via `params` in a `GET` request replaces any query parameters with the same name in the URI path.
- Expected `Rack::Test::UploadedFile` to be parsed inside the application as an `UploadedFile` instance or a Hash with String keys (e.g. `params["avatar"]["filename"]`), or assumed passing a raw `File` / `StringIO` in `params` triggers multipart upload.
- Assumed `Rack::Test::CookieJar` accepts `Secure` cookies received over plain `http://` or transmits `Secure` cookies over insecure requests.
## 3. How the wrong version fails
- **Loud failures**:
- Downstream endpoints or middleware parsing JSON with `JSON.parse(request.body.read)` raise `JSON::ParserError` because `Rack::Test` sends form-urlencoded data (`user[name]=Alice`) when `params` is a `Hash`, even with `application/json` Content-Type.
- **Silent failures with green build**:
- `header "Content-Type", "application/json"` with Hash params leaves `req.params` empty (`{}`) in Rack, causing controller parameters to silently be missing.
- Passing `empty_arr: []` in `params` silently arrives as `[""]` (an array containing an empty string) rather than `[]`.
- Passing `empty_hash: {}` in `params` silently disappears from `params` (`nil`) rather than arriving as `{}`.
- Passing `tags: ["a", "b"]` in `params` when the URI already has `tags[]=old` silently merges and appends them to `["old", "a", "b"]` instead of replacing the array.
- Accessing `req.params["avatar"]["filename"]` returns `nil` because Rack parses multipart upload descriptors with Symbol keys (`[:filename]`, `[:tempfile]`, `[:type]`) despite form fields having String keys.
- Passing a raw `StringIO` or `File` in `params` silently stringifies the Ruby object (`raw_io=%23%3CStringIO%3A...`) instead of uploading the content.
- Setting a `Secure` cookie over plain `http://` is silently ignored by `CookieJar` and never persisted.
{"case":{"believed":"Passing a Hash payload to Rack::Test request methods with a JSON Content-Type header automatically serializes the body as JSON.","caseId":"case:sha256:7df08ccd5f09e60e2528a72d9ca1ccc378bd0c22c38c51dbab5c3111c6815162","contract":["assert posting a Hash with application/json Content-Type sends a form-urlencoded query string and fails JSON parsing unless explicitly passed as a serialized JSON string","assert primitive Hash parameter types are coerced to strings, nil is preserved as nil, empty arrays mutate to an array containing an empty string, and empty hashes are omitted from params","assert URI query string and params Hash merge overwrites scalar keys but appends array elements together","assert UploadedFile triggers multipart encoding with symbol-keyed descriptor hashes while unwrapped IO objects are stringified into urlencoded form data","assert CookieJar silently ignores Secure cookies received over plain HTTP, filters Secure cookies from HTTP requests, and scopes non-domain cookies to the exact host"],"goal":"Manage Rack::Test type serialization boundaries across JSON Hash payloads, query parameter type coercion, multipart symbol keys, and CookieJar security scopes","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#get","Rack::Test::Session#post","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#get","Rack::Test::Session#post","Rack::Test::UploadedFile.new","Rack::Test::CookieJar"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "rack"
require "json"
module RackTestBoundaryApp
class Application
attr_reader :last_request_data
def initialize
@last_request_data = nil
end
def call(env)
req = Rack::Request.new(env)
raw_body = ""
if env["rack.input"]
raw_body = env["rack.input"].read
env["rack.input"].rewind
end
json_payload = nil
json_error = nil
if req.media_type == "application/json" && !raw_body.empty?
begin
json_payload = JSON.parse(raw_body)
rescue JSON::ParserError => e
json_error = e.class.name
end
end
@last_request_data = {
method: req.request_method,
scheme: req.scheme,
host: req.host,
path: req.path_info,
query_string: req.query_string,
params: req.params,
cookies: req.cookies,
content_type: req.content_type,
media_type: req.media_type,
raw_body: raw_body,
json_payload: json_payload,
json_error: json_error
}
case req.path_info
when "/set-secure-cookie"
[
200,
{
"content-type" => "application/json",
"set-cookie" => [
"session_id=plain_abc; path=/",
"secure_token=sec_xyz; path=/; secure",
"host_only=val1; path=/",
"domain_scoped=val2; domain=.example.org; path=/"
]
},
[JSON.generate({ status: "cookies_set" })]
]
else
[
200,
{ "content-type" => "application/json" },
[JSON.generate({ status: "ok" })]
]
end
end
end
end
# frozen_string_literal: true
require "minitest/autorun"
require "rack"
require "rack/test"
require "json"
require "stringio"
require_relative "../src/app"
class RackTestSerializationBoundaryTest < Minitest::Test
include Rack::Test::Methods
attr_reader :app_instance
def app
@app_instance ||= RackTestBoundaryApp::Application.new
end
def setup
@app_instance = RackTestBoundaryApp::Application.new
end
# 1. JSON header + Hash params sends urlencoded body rather than JSON
def test_posting_hash_with_json_content_type_sends_urlencoded_body_and_fails_json_parsing
# Believed: Setting Content-Type application/json serializes Hash params as JSON.
# Reality: Rack::Test always runs build_nested_query on Hash params, sending form-encoded
# string "user[name]=Alice&user[active]=true". Because media_type is application/json,
# Rack skips form parsing (params is empty) and JSON parsing fails.
header "Content-Type", "application/json"
post "/api/users", { user: { name: "Alice", active: true } }
assert_equal "application/json", app_instance.last_request_data[:content_type]
assert_equal "user[name]=Alice&user[active]=true", app_instance.last_request_data[:raw_body]
assert_equal({}, app_instance.last_request_data[:params])
assert_equal "JSON::ParserError", app_instance.last_request_data[:json_error]
assert_nil app_instance.last_request_data[:json_payload]
# Explicit JSON string serialization is required for proper JSON payloads:
post "/api/users", JSON.generate({ user: { name: "Alice", active: true } })
assert_nil app_instance.last_request_data[:json_error]
assert_equal({ "user" => { "name" => "Alice", "active" => true } }, app_instance.last_request_data[:json_payload])
header "Content-Type", nil
end
# 2. Primitive type coercion and empty collection mutation across query params
def test_hash_param_types_are_coerced_to_strings_and_empty_collections_mutate_shape
# Naive assumption: Ruby types (integers, symbols, booleans, empty collections) are preserved.
# Reality:
# - Integers, booleans, symbols become strings.
# - nil becomes a key with nil value.
# - Empty Array [] becomes an array containing an empty string [""]!
# - Empty Hash {} is completely omitted from params!
get "/search", {
int_val: 42,
bool_val: true,
sym_val: :filter,
nil_val: nil,
empty_arr: [],
empty_hash: {}
}
recorded = app_instance.last_request_data[:params]
assert_equal "42", recorded["int_val"]
assert_equal "true", recorded["bool_val"]
assert_equal "filter", recorded["sym_val"]
assert_nil recorded["nil_val"]
assert_equal [""], recorded["empty_arr"]
assert_nil recorded["empty_hash"]
end
# 3. URI query string and params Hash merge semantics
def test_uri_query_and_params_merge_overwrites_scalars_but_appends_arrays
# Merging query string from URI path with params Hash:
# Scalar keys: later value overwrites earlier value.
# Array keys: later values are appended to existing array instead of replacing it.
get "/items?page=1&tags[]=first", { page: 2, tags: ["second", "third"] }
recorded = app_instance.last_request_data[:params]
assert_equal "2", recorded["page"]
assert_equal ["first", "second", "third"], recorded["tags"]
end
# 4. Multipart UploadedFile symbol keys vs raw IO stringification
def test_uploaded_file_produces_symbol_keys_while_raw_io_is_stringified
# UploadedFile triggers multipart encoding where file params have Symbol keys:
uploaded = Rack::Test::UploadedFile.new(
StringIO.new("avatar data"),
"image/png",
original_filename: "avatar.png"
)
post "/upload", { title: "Profile", user: { avatar: uploaded } }
assert_match(%r{\Amultipart/form-data; boundary=}, app_instance.last_request_data[:content_type])
assert_equal "Profile", app_instance.last_request_data[:params]["title"]
avatar_param = app_instance.last_request_data[:params]["user"]["avatar"]
assert_instance_of Hash, avatar_param
assert_nil avatar_param["filename"]
assert_equal "avatar.png", avatar_param[:filename]
assert_equal "image/png", avatar_param[:type]
assert_equal "avatar data", avatar_param[:tempfile].read
# Passing raw StringIO without UploadedFile does not upload; it stringifies the Ruby object:
post "/upload-raw", { raw_io: StringIO.new("unwrapped") }
assert_equal "application/x-www-form-urlencoded", app_instance.last_request_data[:content_type]
assert_match(%r{\Araw_io=%23%3CStringIO%3A}, app_instance.last_request_data[:raw_body])
end
# 5. Cookie security and domain boundaries
def test_cookie_jar_enforces_scheme_and_domain_boundaries
# Setting Secure cookie over plain HTTP is ignored by CookieJar
get "http://example.org/set-secure-cookie"
assert_nil current_session.cookie_jar["secure_token"]
# Setting Secure cookie over HTTPS is accepted
get "https://example.org/set-secure-cookie"
assert_equal "sec_xyz", current_session.cookie_jar["secure_token"]
# Insecure request to example.org receives plain cookies, but NOT the Secure cookie
get "http://example.org/inspect"
assert_equal({ "domain_scoped" => "val2", "host_only" => "val1", "session_id" => "plain_abc" }, app_instance.last_request_data[:cookies])
# Secure request to example.org receives all cookies including Secure cookie
get "https://example.org/inspect"
assert_equal({ "domain_scoped" => "val2", "host_only" => "val1", "secure_token" => "sec_xyz", "session_id" => "plain_abc" }, app_instance.last_request_data[:cookies])
# Subdomain receives domain-scoped cookie, but host-only cookie is omitted
get "https://sub.example.org/inspect"
assert_equal({ "domain_scoped" => "val2" }, app_instance.last_request_data[:cookies])
end
end