샘플
rack-protection 4.2.1: Rack::Protection::JsonCsrf calls app.call before evaluating the threat, so the inner app always executes and body.close is called on the upstream body object when the request is denied
검증된 샘플 — gem rack-protection 4.2.1: Rack::Protection::JsonCsrf calls app.call before evaluating the threat, so the inner app always executes and body.close…
sha256:0e86556535d6ba362304eaea4558d1cab7cc1f09057400391dcf66f67372532f
이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다.
통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다.
MIT-0
실행 증거
선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.
- 증거 기준
- 서명된 컨트랙트 통과
- 검증 영수증
- 2
- 빌드한 서명 키
- 2
선언된 환경
ruby linux x64 ruby ruby bundler
검증 실행 환경
| 환경 | 컨트랙트 | 단계 | 실행일 |
|---|---|---|---|
| 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- 목표
- Rack::Protection::JsonCsrf calls app.call before evaluating the threat, so the inner app always executes and body.close is called on the upstream body object when the request is denied
- 심벌
-
- Rack::Protection::JsonCsrf
- Rack::Protection::JsonCsrf#call
- Rack::Protection::JsonCsrf#has_vector?
- Rack::Protection::JsonCsrf#close_body
- Rack::Protection::JsonCsrf#react_and_close
- 환경
- ruby
- 생성일
- 2026-08-17T02:45:21Z
컨트랙트
- JsonCsrf#call invokes app.call(env) unconditionally before deciding whether to deny, so the inner application executes — and its side effects occur — even when the middleware ultimately returns 403
- When JsonCsrf denies a request it calls body.close() on the object returned by the inner app, consuming the resource before the 403 response is passed upstream; the outer caller never receives that body
- For allowed requests JsonCsrf does not call body.close, leaving the caller responsible for closing the body
- JsonCsrf inspects the response Content-Type header, not the request method or Content-Type; a POST that returns text/html from a cross-origin referrer is not blocked
파일
- Gemfile
- Gemfile.lock
- NOTES.md
- csx.json
- test/contract.rb
소스
source 'https://rubygems.org'
gem 'rack-protection', '4.2.1'
gem 'rack', '3.2.7'
GEM
remote: https://rubygems.org/
specs:
base64 (0.3.0)
logger (1.7.0)
rack (3.2.7)
rack-protection (4.2.1)
base64 (>= 0.1.0)
logger (>= 1.6.0)
rack (>= 3.0.0, < 4)
PLATFORMS
ruby
x64-mingw-ucrt
DEPENDENCIES
rack (= 3.2.7)
rack-protection (= 4.2.1)
CHECKSUMS
base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
bundler (4.0.18) sha256=02d9a17429de1847b4e0c9f27a9ee4b20c0a74c0a641b4e77195d6019e3618ac
logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7
rack-protection (4.2.1) sha256=cf6e2842df8c55f5e4d1a4be015e603e19e9bc3a7178bae58949ccbb58558bac
BUNDLED WITH
4.0.18
# rack-protection: JsonCsrf body lifecycle
## What search_known_solution found
The search returned no exact match for this specific behavior. The closest
local hit was `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b`,
which covers testing a Sinatra 4 app with rack-test in the same process
(no server, getting params). That angle is already published.
## The trap
Most protection middleware in rack-protection short-circuits the pipeline:
`accepts?` is called, and if it returns false the inner app never runs.
`JsonCsrf` does not follow this pattern. Its `call` method invokes
`app.call(env)` unconditionally to obtain a response, reads the
`content-type` header from that response, and only then decides whether to
deny. Two things follow from this:
1. The inner application always executes. Any side effect — writing a
database record, queueing a job, charging a card — has already happened
by the time JsonCsrf returns 403. There is no way to distinguish a
blocked from an allowed request inside the inner app.
2. When denying, `JsonCsrf` calls `body.close` on whatever the inner app
returned before returning its own 403 body. An IO-backed body
(`File`, `Rack::File`, a streaming enumerator wrapping a database
cursor) is closed by the middleware, not by the Rack server's normal
response finalization path. For allowed requests JsonCsrf does nothing
with the body, so the caller remains responsible for closing it.
The check is on the **response** `content-type`, not on the request method
or the request `content-type`. A POST that returns `text/html` passes. A
GET that returns `application/json` from a cross-origin referrer (no
`Origin` header) is blocked.
## How the wrong version fails
The behaviour described here is present in rack-protection 4.x and in
earlier 3.x releases; the `JsonCsrf` class has used the
post-call inspection pattern since it was introduced. A model that assumes
the middleware blocks *before* the inner app runs will write code that
appears to work — the 403 is returned correctly in tests — but leaks side
effects on every blocked request and leaks open IO handles whenever the
body object is IO-backed. The build stays green; nothing fails loudly.
The mistake is discovered only when a staging log shows the inner handler
ran twice: once for an attacker's probe and once for the real request.
{"case":{"believed":"Protection middleware short-circuits the request pipeline before the inner app runs, so an app behind JsonCsrf only executes when the request is allowed","caseId":"case:sha256:a02765b84383b912338e2886bdbca9971617b7e8ce66a762f88a6277e47ac877","contract":["JsonCsrf#call invokes app.call(env) unconditionally before deciding whether to deny, so the inner application executes — and its side effects occur — even when the middleware ultimately returns 403","When JsonCsrf denies a request it calls body.close() on the object returned by the inner app, consuming the resource before the 403 response is passed upstream; the outer caller never receives that body","For allowed requests JsonCsrf does not call body.close, leaving the caller responsible for closing the body","JsonCsrf inspects the response Content-Type header, not the request method or Content-Type; a POST that returns text/html from a cross-origin referrer is not blocked"],"goal":"Rack::Protection::JsonCsrf calls app.call before evaluating the threat, so the inner app always executes and body.close is called on the upstream body object when the request is denied","kind":"HOW","packages":["pkg:gem/rack-protection@4.2.1"],"schemaVersion":1,"symbols":["Rack::Protection::JsonCsrf","Rack::Protection::JsonCsrf#call","Rack::Protection::JsonCsrf#has_vector?","Rack::Protection::JsonCsrf#close_body","Rack::Protection::JsonCsrf#react_and_close"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundler","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/rack-protection@4.2.1"],"schemaVersion":1,"symbols":["Rack::Protection::JsonCsrf","Rack::Protection::JsonCsrf#call","Rack::Protection::JsonCsrf#has_vector?","Rack::Protection::JsonCsrf#close_body","Rack::Protection::JsonCsrf#react_and_close"],"verifierAdapter":"rubygems@1"}
require 'rack/protection'
require 'rack/mock'
require 'stringio'
# Rack::Protection::JsonCsrf blocks JSON CSRF attacks differently from other
# protection middleware: it calls app.call(env) first to get the response,
# inspects the Content-Type header, and THEN decides to deny.
#
# Consequence 1: the inner app always executes — side effects happen even
# for blocked requests.
# Consequence 2: when denying, JsonCsrf calls body.close() on whatever the
# inner app returned, consuming / closing the resource before the 403 is
# passed upstream. The caller never sees that body object.
# ---- helpers ----------------------------------------------------------------
def make_stack(app)
Rack::Builder.new do
use Rack::Protection::JsonCsrf
run app
end.to_app
end
SAFE_ENV = {
'REQUEST_METHOD' => 'GET',
'PATH_INFO' => '/api/items',
'HTTP_HOST' => 'example.com',
'rack.input' => StringIO.new(''),
'rack.errors' => StringIO.new
}.freeze
# A cross-origin referrer with no Origin header triggers JsonCsrf
THREAT_ENV = SAFE_ENV.merge(
'HTTP_REFERER' => 'http://attacker.example.net/page'
)
XHR_THREAT_ENV = THREAT_ENV.merge(
'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest'
)
# ---- Contract 1 ------------------------------------------------------------
# JsonCsrf calls app.call BEFORE evaluating whether to deny; the inner app
# always executes, including for requests that ultimately return 403.
puts 'Contract 1: inner app executes even for denied requests'
inner_call_count = 0
app1 = ->(_env) {
inner_call_count += 1
[200, {'content-type' => 'application/json'}, ['[]']]
}
stack1 = make_stack(app1)
# Blocked request
status1, = stack1.call(THREAT_ENV.dup)
raise "Expected 403, got #{status1}" unless status1 == 403
raise "Inner app must run even for blocked request" unless inner_call_count == 1
# Safe XHR request (same threat env, but XHR bypasses the check)
status1b, = stack1.call(XHR_THREAT_ENV.dup)
raise "Expected 200 for XHR, got #{status1b}" unless status1b == 200
raise "Inner app must run for allowed request too" unless inner_call_count == 2
puts " PASS: inner_call_count=#{inner_call_count} after one blocked + one allowed request"
# ---- Contract 2 ------------------------------------------------------------
# When JsonCsrf denies a request, it calls body.close() on the upstream body
# object — the resource is consumed/closed before the 403 is returned to the
# Rack server. The caller (Rack server) never receives that body.
puts 'Contract 2: JsonCsrf closes the upstream body on denial'
body_closed = false
app2 = ->(_env) {
body = Object.new
body.define_singleton_method(:each) { |&b| b.call('{"items":[]}') }
body.define_singleton_method(:close) { body_closed = true }
[200, {'content-type' => 'application/json'}, body]
}
stack2 = make_stack(app2)
status2, _headers2, returned_body = stack2.call(THREAT_ENV.dup)
raise "Expected 403, got #{status2}" unless status2 == 403
raise "body.close must be called by JsonCsrf when denying" unless body_closed
# The returned body from the middleware is its OWN denial body, not the app body
denial_content = returned_body.map(&:itself).join
raise "Denial body must not be empty" if denial_content.empty?
puts " PASS: body_closed=#{body_closed}, denial body='#{denial_content}'"
# ---- Contract 3 ------------------------------------------------------------
# For allowed requests, JsonCsrf does NOT close the body — the caller is
# responsible. This is the flip side: body.close is NOT called for safe requests.
puts 'Contract 3: body.close is NOT called for allowed requests'
body_closed3 = false
app3 = ->(_env) {
body = Object.new
body.define_singleton_method(:each) { |&b| b.call('{}') }
body.define_singleton_method(:close) { body_closed3 = true }
[200, {'content-type' => 'application/json'}, body]
}
stack3 = make_stack(app3)
status3, = stack3.call(XHR_THREAT_ENV.dup)
raise "Expected 200, got #{status3}" unless status3 == 200
raise "body.close must NOT be called for allowed requests" if body_closed3
puts " PASS: body_closed3=#{body_closed3} for allowed request (caller owns the body)"
# ---- Contract 4 ------------------------------------------------------------
# JsonCsrf only inspects the RESPONSE Content-Type, not the request Content-Type.
# A GET request returning application/json from a cross-origin referrer is blocked.
# A POST request returning text/html is NOT blocked even from cross-origin.
puts 'Contract 4: JsonCsrf checks response Content-Type, not request method'
app4 = ->(_env) {
# return HTML regardless of what was requested
[200, {'content-type' => 'text/html'}, ['<html></html>']]
}
stack4 = make_stack(app4)
# POST with cross-origin referrer, but response is HTML — should pass
post_env = THREAT_ENV.merge('REQUEST_METHOD' => 'POST',
'rack.input' => StringIO.new('data=x'))
status4, = stack4.call(post_env)
raise "HTML response must not be blocked, got #{status4}" unless status4 == 200
puts " PASS: HTML response from cross-origin POST is not blocked (status=#{status4})"
puts
puts 'All contracts passed.'