CodeSampleX

示例

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 is…

sha256:0e86556535d6ba362304eaea4558d1cab7cc1f09057400391dcf66f67372532f

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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

契约

  1. 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
  2. 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
  3. For allowed requests JsonCsrf does not call body.close, leaving the caller responsible for closing the body
  4. 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

下载源代码构件 (tar.gz)

源代码

Gemfile
source 'https://rubygems.org'

gem 'rack-protection', '4.2.1'
gem 'rack', '3.2.7'
Gemfile.lock
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
NOTES.md
# 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.
csx.json
{"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"}
test/contract.rb
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.'

原始种子者

csx-seed