CodeSampleX

Exemplo

sinatra 4.2.1: Demonstrate how Sinatra's route pass mechanism preserves response status codes, headers, cookies, and params mutations across route conditions and fallback handlers

Amostra verificada para gem sinatra 4.2.1: Demonstrate how Sinatra's route pass mechanism preserves response status codes, headers, cookies, and params…

sha256:9daef5c538d2e6e18aa5a87d9fe4391e249631bdca6f5967cce7845f633e1c30

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
2
Ambiente declarado ruby linux x64 ruby ruby bundle

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · rubygems@1
2026-08-18

Caso

HOW
Objetivo
Demonstrate how Sinatra's route pass mechanism preserves response status codes, headers, cookies, and params mutations across route conditions and fallback handlers
Pacotes
Símbolos
  • Sinatra::Base#pass
  • Sinatra::Base#condition
  • Sinatra::Base#status
  • Sinatra::Base#headers
  • Sinatra::Response#set_cookie
  • Sinatra::Base#params
Ambiente
ruby
Criado
2026-08-16T17:02:11Z

Contrato

  1. Calling pass retains any HTTP status code, response headers, cookies, and params mutations made by the passed route rather than resetting the response state for the fallback handler.
  2. assert a fallback route returning a string inherits the non-200 HTTP status code set before pass when the fallback does not explicitly assign status
  3. assert response headers and cookies set by a passed route are preserved in the final HTTP response
  4. assert route conditions are evaluated in sequence on the shared request instance and accumulate headers across evaluations
  5. assert route parameters mutated before pass remain accessible in subsequent matching route handlers
  6. assert calling pass when no downstream route matches yields a 404 response with X-Cascade: pass while still preserving headers and cookies set before pass

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

Gemfile
source "https://rubygems.org"

gem "sinatra", "4.2.1"
gem "rack-test", "2.2.0"
gem "minitest", "~> 5.25"
Gemfile.lock
GEM
  remote: https://rubygems.org/
  specs:
    base64 (0.3.0)
    logger (1.7.0)
    minitest (5.27.0)
    mustermann (3.1.1)
    rack (3.2.7)
    rack-protection (4.2.1)
      base64 (>= 0.1.0)
      logger (>= 1.6.0)
      rack (>= 3.0.0, < 4)
    rack-session (2.1.2)
      base64 (>= 0.1.0)
      rack (>= 3.0.0)
    rack-test (2.2.0)
      rack (>= 1.3)
    sinatra (4.2.1)
      logger (>= 1.6.0)
      mustermann (~> 3.0)
      rack (>= 3.0.0, < 4)
      rack-protection (= 4.2.1)
      rack-session (>= 2.0.0, < 3)
      tilt (~> 2.0)
    tilt (2.8.0)

PLATFORMS
  ruby
  x64-mingw-ucrt
  x86_64-linux

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

BUNDLED WITH
   2.6.9
NOTES.md
# Sinatra Route Pass and Response State Persistence

## Prior Solutions Found in Network Search

A search of known solutions returned existing coverage for Sinatra 4 behavior:
- `sha256:cb16ec9117c9887155c2792e1e4607e740fe8c584754b3d6136855be6762490b`: In-process testing with rack-test, host authorization in development, params precedence (route vs form vs query), splat arrays, default 404 pages vs `halt 404`, and `halt` vs `return` in `before` filters.
- `sha256:6e3c39259c903ef98aa1a3a0b9b3c1dad0a3af159e7e3d689ce10e03f43cf009`: Error handling dispatch, status code handlers, and route return value coercion.
- `sha256:6fe2e76b77d6bce49055c7040cb3e0a61454a28c849849a68c088f2e767143fc`: Route-level halt interaction with registered 404 error handlers.

This sample addresses a distinct interaction: the stateful behavior of Sinatra's `pass` mechanism across custom route conditions and fallback route handlers.

## Failure Mode

Fails silently with a green build: code assuming that calling `pass` rolls back intermediate response modifications will unintentionally leak non-200 HTTP statuses, custom headers, cookies, and mutated params into downstream fallback handlers and 404 cascade responses.

## Technical Details

Sinatra instantiates the `Sinatra::Base` application class once per request. Filters, route conditions, and matching route blocks execute within this single mutable instance context:
1. When a route handler modifies `status`, `headers`, `response.set_cookie`, `params`, or instance variables and subsequently invokes `pass`, Sinatra catches the internal throw and advances to the next candidate route without rolling back the response or request state.
2. If a downstream fallback route completes by returning a string without explicitly specifying `status`, the previously assigned HTTP status code (e.g. `202`) is retained rather than resetting to `200`.
3. If no subsequent route matches, Sinatra cascades to a 404 status (`X-Cascade: pass`), but any headers and cookies set in the passed route remain in the final response.
4. Route conditions (`condition`) execute in declaration order against the shared instance, so any header assignments or instance variables created during condition checks persist across all evaluated routes.
csx.json
{"case":{"believed":"Calling pass inside a matched route handler discards intermediate modifications to the HTTP status code, response headers, cookies, and request params before dispatching to subsequent matching routes.","caseId":"case:sha256:a2f0108d9494484ea39d69d45f269ef5c1fbe3af0fb0686e46ac2e4d9ab456d9","contract":["Calling pass retains any HTTP status code, response headers, cookies, and params mutations made by the passed route rather than resetting the response state for the fallback handler.","assert a fallback route returning a string inherits the non-200 HTTP status code set before pass when the fallback does not explicitly assign status","assert response headers and cookies set by a passed route are preserved in the final HTTP response","assert route conditions are evaluated in sequence on the shared request instance and accumulate headers across evaluations","assert route parameters mutated before pass remain accessible in subsequent matching route handlers","assert calling pass when no downstream route matches yields a 404 response with X-Cascade: pass while still preserving headers and cookies set before pass"],"goal":"Demonstrate how Sinatra's route pass mechanism preserves response status codes, headers, cookies, and params mutations across route conditions and fallback handlers","kind":"HOW","packages":["pkg:gem/sinatra@4.2.1","pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7","pkg:gem/rack-protection@4.2.1","pkg:gem/mustermann@3.1.1"],"schemaVersion":1,"symbols":["Sinatra::Base#pass","Sinatra::Base#condition","Sinatra::Base#status","Sinatra::Base#headers","Sinatra::Response#set_cookie","Sinatra::Base#params"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"bundle","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/sinatra@4.2.1","pkg:gem/rack-test@2.2.0","pkg:gem/rack@3.2.7","pkg:gem/rack-protection@4.2.1","pkg:gem/mustermann@3.1.1"],"schemaVersion":1,"symbols":["Sinatra::Base#pass","Sinatra::Base#condition","Sinatra::Base#status","Sinatra::Base#headers","Sinatra::Response#set_cookie","Sinatra::Base#params"],"verifierAdapter":"rubygems@1"}
src/app.rb
require "sinatra/base"

# In Sinatra, route blocks and condition blocks do not run in isolated sandbox
# scopes. Instead, Sinatra dispatches each incoming request by instantiating
# the Sinatra::Base subclass once per request and executing matching filters,
# conditions, and route blocks within that identical context instance.
#
# When a route decides it cannot completely satisfy a request and calls `pass`,
# control flow returns to Sinatra's routing loop to find the next matching route.
# However, Sinatra does not perform any rollback or snapshot-restore on the
# response object (Sinatra::Response), the request params (Sinatra::IndifferentHash),
# or the application instance variables.
#
# Consequently:
#   1. An HTTP status code explicitly set via `status <code\>` remains assigned to
#      the response. If a subsequent fallback route returns a body without explicitly
#      setting a status, Sinatra preserves that earlier status rather than defaulting to 200.
#   2. Response headers and cookies added before calling `pass` persist in `response.headers`.
#   3. Mutations made to `params` remain visible in subsequent route handlers.
#   4. Custom route conditions run sequentially on the shared instance, so any headers
#      or instance variables set during condition checks accumulate.
#   5. If every candidate route calls `pass` and no route handles the request,
#      Sinatra produces a 404 response with `X-Cascade: pass`, but retains any
#      headers and cookies assigned prior to `pass`.

class PassRoutingApp < Sinatra::Base
  # Permit rack-test default host in test runs
  set :host_authorization, permitted_hosts: []

  # Custom route condition: checks header and records evaluation side-effects
  set(:role) do |expected|
    condition do
      @evaluated_roles ||= []
      @evaluated_roles << expected
      headers["X-Condition-Checked-#{expected}"] = "true"
      env["HTTP_X_ROLE"] == expected
    end
  end

  # Route 1: Matches /items/:id for clients with the 'member' role.
  # Modifies response status, headers, cookies, params, and instance variables,
  # then delegates to subsequent routes when params[:id] is 'deferred'.
  get "/items/:id", :role => "member" do
    status 202
    headers "X-Route-Attempted" => "member-route"
    response.set_cookie("attempted_route", "member")
    params[:enriched_by] = "member_route"
    @audit_trail = ["member_route_entered"]

    pass if params[:id] == "deferred"

    "handled by member route"
  end

  # Route 2: Matches /items/:id for clients with the 'admin' role.
  # Condition evaluation fails for non-admins, but its condition block already ran.
  get "/items/:id", :role => "admin" do
    "handled by admin route"
  end

  # Route 3: Fallback route matching /items/:id without any role conditions.
  # Returns a response body string without calling `status`.
  get "/items/:id" do
    @audit_trail ||= []
    @audit_trail << "fallback_route_entered"
    "fallback body: id=#{params[:id]}, enriched=#{params[:enriched_by]}"
  end

  # Route 4: Sets status, headers, and cookies, then calls pass with no downstream handler.
  get "/pass-to-unmatched" do
    status 201
    headers "X-Passed-Header" => "persists-on-404"
    response.set_cookie("passed_cookie", "persists-on-404")
    pass
  end
end
test/contract.rb
require "minitest/autorun"
require "rack/test"
require_relative "../src/app"

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

  def app
    PassRoutingApp
  end

  def test_pass_retains_status_headers_cookies_and_params_in_fallback_route
    # Calling pass inside a route transfers execution to the next matching
    # route handler without rolling back response mutations or param updates.
    header "X-Role", "member"
    get "/items/deferred"

    # Status 202 set in the passed route persists because the fallback route
    # returns a body string without explicitly calling status.
    assert_equal 202, last_response.status

    # Fallback route body was executed and read the mutated param key
    assert_equal "fallback body: id=deferred, enriched=member_route", last_response.body

    # Response headers set before pass persist in the final response
    assert_equal "member-route", last_response.headers["x-route-attempted"]

    # Cookies set before pass persist in the final response
    assert_includes last_response.headers["set-cookie"], "attempted_route=member"

    # Condition checks ran on the shared context instance and their header side-effects accumulated
    assert_equal "true", last_response.headers["x-condition-checked-member"]
    assert_equal "true", last_response.headers["x-condition-checked-admin"]
  end

  def test_direct_route_without_pass_bypasses_downstream_conditions
    header "X-Role", "member"
    get "/items/direct"

    assert_equal 202, last_response.status
    assert_equal "handled by member route", last_response.body
    assert_equal "member-route", last_response.headers["x-route-attempted"]
    assert_equal "true", last_response.headers["x-condition-checked-member"]

    # Because Route 1 satisfied the request without calling pass, downstream route conditions never executed
    refute last_response.headers.key?("x-condition-checked-admin")
  end

  def test_pass_with_no_subsequent_match_yields_404_cascade_with_persisted_headers_and_cookies
    get "/pass-to-unmatched"

    # When all matching routes call pass, Sinatra cascades to a 404 response
    assert_equal 404, last_response.status
    assert_equal "pass", last_response.headers["x-cascade"]

    # Headers and cookies configured before calling pass remain attached to the 404 response
    assert_equal "persists-on-404", last_response.headers["x-passed-header"]
    assert_includes last_response.headers["set-cookie"], "passed_cookie=persists-on-404"
  end
end

Seeder de origem

csx-seed