Пример
rack-test 2.2.0: Configure Rack::Test session host defaults, secure cookie URI requirements, multi-session isolation, restore_state header leaks, and symbol XHR flags
Проверенный пример — gem rack-test 2.2.0: Configure Rack::Test session host defaults, secure cookie URI requirements, multi-session isolation, restore_state…
sha256:8a39d61a043d3d3266b938f3aee80a49ca9a57038e54bbe3d199bef1a92695bd
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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- Цель
- Configure Rack::Test session host defaults, secure cookie URI requirements, multi-session isolation, restore_state header leaks, and symbol XHR flags
- Пакеты
- Символы
-
- Rack::Test::Methods
- Rack::Test::Session#set_cookie
- Rack::Test::Session#default_host
- Rack::Test::Methods#with_session
- Rack::Test::Session#restore_state
- Rack::Test::Session#after_request
- Rack::Test::CookieJar
- Окружение
- ruby
- Создан
- 2026-08-17T02:45:45Z
Контракт
- assert calling set_cookie with a secure attribute without an explicit URI object silently drops the cookie because default URI lacks an HTTPS scheme, while passing a URI string raises NoMethodError
- assert defining default_host on the test harness sets HTTP_HOST on relative requests and isolates host-only cookies from requests targeting other hosts
- assert with_session isolates cookie jars, session headers, and request history across distinct named clients
- assert restore_state rolls back last_request, last_response, and cookie_jar but leaves session env headers mutated
- assert passing xhr: true requires a Symbol key in request env to set HTTP_X_REQUESTED_WITH while string keys are ignored
- assert after_request registers callbacks that execute in order after response parsing with access to last_response
Файлы
- 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
# Rack::Test Session Configuration and Environment Contract
## 1. What `search_known_solution` answered
`search_known_solution` returned sample `sha256:b6e08189aff9762145b13c9da3005e5280f936fd2c9e33822f7436a47fdc8cea` ("Manage Rack::Test per-request CGI environment keys, session header persistence, JSON string Content-Type defaults, UploadedFile multipart symbol params, and redirect method preservation").
This sample focuses on `Rack::Test` session configuration, host defaults, secure cookie URI requirements, multi-session isolation, state restoration scope, and XHR environment keys.
## 2. What a model would have written instead
- Called `set_cookie("token=secret; secure")` in test setup expecting the session to store the secure cookie and send it on HTTPS requests.
- Passed a URL string as the second argument to `set_cookie` (e.g. `set_cookie("token=secret; secure", "https://api.example.test/")`), expecting `Rack::Test` to parse the string URL.
- Assumed `restore_state` rolls back all session state including headers configured via `header(...)`.
- Passed `{ "xhr" => true }` with a string key to simulate AJAX requests.
- Expected cookies set on `default_host` to be sent when requesting absolute URIs on other hosts.
## 3. How the wrong version fails
- **Loud failures**:
- `set_cookie("token=secret; secure", "https://api.example.test/")` with a String URI raises `NoMethodError: undefined method 'host' for an instance of String` because `Cookie#initialize` assumes `uri` is already a `URI` instance.
- Calling `restore_state` directly on a test instance including `Rack::Test::Methods` raises `NoMethodError: undefined method 'restore_state'` because it is a `Rack::Test::Session` method not delegated by `Methods`.
- **Silent failures with green build**:
- `set_cookie("token=secret; secure")` without an explicit `URI` object silently drops the cookie from `cookie_jar` because the default URI (`//api.example.test/`) has a `nil` scheme, failing `Cookie#valid?`.
- Mutating session headers via `header(...)` inside `restore_state` silently leaks headers to subsequent test requests outside the block.
- Passing `{ "xhr" => true }` with a string key silently leaves `HTTP_X_REQUESTED_WITH` unset while `env[:xhr]` with a symbol key works as intended.
{"case":{"believed":"Calling set_cookie with a secure attribute on a session stores the cookie in the jar for HTTPS requests and accepts a URI string.","caseId":"case:sha256:24b4c1bf5fa6ac0079d80d8cc927f89f796669e0d48aae5d07f4454f44ca5193","contract":["assert calling set_cookie with a secure attribute without an explicit URI object silently drops the cookie because default URI lacks an HTTPS scheme, while passing a URI string raises NoMethodError","assert defining default_host on the test harness sets HTTP_HOST on relative requests and isolates host-only cookies from requests targeting other hosts","assert with_session isolates cookie jars, session headers, and request history across distinct named clients","assert restore_state rolls back last_request, last_response, and cookie_jar but leaves session env headers mutated","assert passing xhr: true requires a Symbol key in request env to set HTTP_X_REQUESTED_WITH while string keys are ignored","assert after_request registers callbacks that execute in order after response parsing with access to last_response"],"goal":"Configure Rack::Test session host defaults, secure cookie URI requirements, multi-session isolation, restore_state header leaks, and symbol XHR flags","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#set_cookie","Rack::Test::Session#default_host","Rack::Test::Methods#with_session","Rack::Test::Session#restore_state","Rack::Test::Session#after_request","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#set_cookie","Rack::Test::Session#default_host","Rack::Test::Methods#with_session","Rack::Test::Session#restore_state","Rack::Test::Session#after_request","Rack::Test::CookieJar"],"verifierAdapter":"rubygems@1"}
# frozen_string_literal: true
require "rack"
require "json"
module RackTestConfigContract
class RecordingApp
attr_reader :last_recorded
def initialize
@last_recorded = nil
end
def call(env)
req = Rack::Request.new(env)
@last_recorded = {
method: req.request_method,
path: req.path_info,
host: req.host,
port: req.port,
scheme: req.scheme,
ssl: req.ssl?,
cookies: req.cookies,
http_host: env["HTTP_HOST"],
http_x_role: env["HTTP_X_ROLE"],
http_x_tenant: env["HTTP_X_TENANT"],
http_x_extra: env["HTTP_X_EXTRA"],
http_x_requested_with: env["HTTP_X_REQUESTED_WITH"],
raw_xhr: env["xhr"],
rack_test_flag: env["rack.test"]
}
case req.path_info
when "/set-secure-cookie"
[
200,
{
"content-type" => "text/plain",
"set-cookie" => "app_sec=token_secret; secure; path=/"
},
["Secure cookie issued"]
]
when "/set-host-cookie"
[
200,
{
"content-type" => "text/plain",
"set-cookie" => "host_only=val1; path=/"
},
["Host cookie issued"]
]
when "/session-auth"
user_id = req.params["user_id"] || "101"
[
200,
{
"content-type" => "text/plain",
"set-cookie" => "user_id=#{user_id}; path=/"
},
["Authenticated"]
]
else
[
200,
{ "content-type" => "application/json" },
[JSON.generate(@last_recorded)]
]
end
end
end
end
# frozen_string_literal: true
require "minitest/autorun"
require "rack"
require "rack/test"
require "uri"
require_relative "../src/app"
class RackTestConfigContractTest < Minitest::Test
include Rack::Test::Methods
attr_reader :app_instance
def app
@app_instance ||= RackTestConfigContract::RecordingApp.new
end
def default_host
"api.example.test"
end
def setup
@app_instance = RackTestConfigContract::RecordingApp.new
end
# 1. Secure cookies: set_cookie requires explicit URI object, drops scheme-less default URI,
# string URIs raise NoMethodError, and transmission is strictly scoped to HTTPS.
def test_set_cookie_with_secure_flag_requires_explicit_uri_instance_and_drops_unqualified_or_insecure_cookies
# Naive assumption: set_cookie("token=secret; secure") stores the cookie in the session jar.
# Reality: default URI is //api.example.test/ (scheme nil). Cookie#valid? checks uri.scheme == 'https',
# which is false, so CookieJar#merge silently drops the cookie entirely.
set_cookie "token=secret; secure"
assert_nil current_session.cookie_jar["token"]
# Passing a URI string instead of a URI instance raises NoMethodError (Cookie#initialize calls uri.host)
assert_raises(NoMethodError) do
set_cookie "token=secret; secure", "https://api.example.test/"
end
# Passing a URI instance allows CookieJar to validate the https scheme and accept the cookie
set_cookie "token=secret; secure", URI.parse("https://api.example.test/")
assert_equal "secret", current_session.cookie_jar["token"]
# Over HTTP, the secure cookie is excluded from HTTP_COOKIE header
get "/inspect"
assert_nil app_instance.last_recorded[:cookies]["token"]
# Over HTTPS, the secure cookie matches and is transmitted
get "https://api.example.test/inspect"
assert_equal "secret", app_instance.last_recorded[:cookies]["token"]
# App issuing Set-Cookie: ...; secure over HTTP is rejected by CookieJar
get "/set-secure-cookie"
assert_nil current_session.cookie_jar["app_sec"]
# App issuing Set-Cookie: ...; secure over HTTPS is accepted into CookieJar
get "https://api.example.test/set-secure-cookie"
assert_equal "token_secret", current_session.cookie_jar["app_sec"]
end
# 2. default_host configuration sets HTTP_HOST on relative requests and scopes host-only cookies
def test_default_host_configuration_sets_http_host_and_scopes_host_only_cookies
# Session initialized with default_host from test harness
assert_equal "api.example.test", current_session.default_host
# Relative paths resolve to default_host
get "/inspect"
assert_equal "api.example.test", app_instance.last_recorded[:host]
assert_equal "api.example.test", app_instance.last_recorded[:http_host]
# Host-only cookie set on default_host
get "/set-host-cookie"
assert_equal "val1", current_session.cookie_jar["host_only"]
# Relative request receives the host-only cookie
get "/inspect"
assert_equal "val1", app_instance.last_recorded[:cookies]["host_only"]
# Request targeting a different host overrides HTTP_HOST and excludes host-only cookie
get "http://other.example.test/inspect"
assert_equal "other.example.test", app_instance.last_recorded[:host]
assert_equal "other.example.test", app_instance.last_recorded[:http_host]
assert_nil app_instance.last_recorded[:cookies]["host_only"]
# Explicit HTTP_HOST env key overrides header for relative requests
get "/inspect", {}, { "HTTP_HOST" => "custom.example.test" }
assert_equal "custom.example.test", app_instance.last_recorded[:http_host]
end
# 3. with_session isolates cookie jars, session headers, and request history
def test_with_session_isolates_session_cookies_headers_and_history_for_multi_client_flows
header "X-Role", "guest"
get "/session-auth", "user_id" => "101"
assert_equal "101", current_session.cookie_jar["user_id"]
assert_equal "guest", app_instance.last_recorded[:http_x_role]
initial_request = last_request
# Isolated admin session
with_session(:admin) do
# Cookies and headers from default session are absent
assert_nil current_session.cookie_jar["user_id"]
get "/inspect"
assert_nil app_instance.last_recorded[:http_x_role]
# Admin session sets its own headers and cookies
header "X-Role", "admin"
get "/session-auth", "user_id" => "999"
assert_equal "999", current_session.cookie_jar["user_id"]
assert_equal "admin", app_instance.last_recorded[:http_x_role]
end
# Returning to default session restores original cookies, headers, and last_request
assert_equal "101", current_session.cookie_jar["user_id"]
assert_same initial_request, last_request
get "/inspect"
assert_equal "guest", app_instance.last_recorded[:http_x_role]
end
# 4. restore_state rolls back cookies, response, and after_request hooks, but LEAKS mutated session @env headers
def test_restore_state_restores_cookies_and_history_but_leaks_session_env_headers
header "X-Tenant", "primary"
get "/inspect"
assert_equal "primary", app_instance.last_recorded[:http_x_tenant]
baseline_request = last_request
# restore_state is a Session method not delegated by Methods module
current_session.restore_state do
# Mutating headers inside restore_state modifies session @env
header "X-Tenant", "mutated"
header "X-Extra", "transient"
set_cookie "temp_cookie=active"
get "/inspect"
assert_equal "mutated", app_instance.last_recorded[:http_x_tenant]
assert_equal "transient", app_instance.last_recorded[:http_x_extra]
assert_equal "active", current_session.cookie_jar["temp_cookie"]
end
# Cookie jar and last_request are restored to pre-block state
assert_nil current_session.cookie_jar["temp_cookie"]
assert_same baseline_request, last_request
# Session headers (@env) were NOT restored, leaking mutations to subsequent requests
get "/inspect"
assert_equal "mutated", app_instance.last_recorded[:http_x_tenant]
assert_equal "transient", app_instance.last_recorded[:http_x_extra]
end
# 5. xhr flag requires Symbol key :xhr; String key "xhr" is ignored
def test_xhr_flag_requires_symbol_key_in_request_env
# Symbol key :xhr triggers HTTP_X_REQUESTED_WITH header generation
get "/inspect", {}, { xhr: true }
assert_equal "XMLHttpRequest", app_instance.last_recorded[:http_x_requested_with]
# String key "xhr" is ignored by Rack::Test and leaves HTTP_X_REQUESTED_WITH unset
get "/inspect", {}, { "xhr" => true }
assert_nil app_instance.last_recorded[:http_x_requested_with]
assert_equal true, app_instance.last_recorded[:raw_xhr]
end
# 6. after_request callback lifecycle and execution order
def test_after_request_callback_execution_order_and_access_to_last_response
execution_log = []
current_session.after_request do
execution_log << "hook_1:#{last_response.status}"
end
current_session.after_request do
execution_log << "hook_2:#{last_request.path_info}"
end
get "/inspect"
assert_equal ["hook_1:200", "hook_2:/inspect"], execution_log
end
end