CodeSampleX

Exemplo

rack-protection 4.2.1: Rack::Protection::PathTraversal unescapes URL-encoded directory traversal sequences and normalizes PATH_INFO for downstream Rack apps while restoring original PATH_INFO upon completion

Amostra verificada para gem rack-protection 4.2.1: Rack::Protection::PathTraversal unescapes URL-encoded directory traversal sequences and normalizes…

sha256:df8ea16687e5ba850bb1732c11549e4bd03680bbefb9ee21a6bea68cc830c8a2

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 gem

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
Rack::Protection::PathTraversal unescapes URL-encoded directory traversal sequences and normalizes PATH_INFO for downstream Rack apps while restoring original PATH_INFO upon completion
Pacotes
Símbolos
  • Rack::Protection::PathTraversal
Ambiente
ruby
Criado
2026-08-17T14:38:56Z

Contrato

  1. Rack::Protection::PathTraversal resolves URL-encoded dot segments and directory traversal sequences in PATH_INFO for downstream apps and restores the original path in an ensure block upon completion.
  2. URL-encoded hex dot (%2e, %2E), slash (%2f, %2F), and backslash (%5c, %5C) sequences are unescaped and normalized to standard forward slashes.
  3. Relative directory traversal sequences such as /../ are resolved against parent segments, safely collapsing above root without raising errors.
  4. Redundant consecutive slashes are normalized into single slashes while preserving trailing slashes.
  5. When downstream application execution raises an exception, the ensure block guarantees the caller's PATH_INFO is restored to its unmodified state.
  6. Empty or nil PATH_INFO values pass through without modification.

Arquivos

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

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

Código-fonte

Gemfile
source "https://rubygems.org"

gem "rack-protection", "4.2.1"
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-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::PathTraversal PATH_INFO Normalization and Restoration

## Search Result
`search_known_solution` returned existing published samples for `rack-protection` covering session hijacking opt-in (`sha256:211d7395fda74de66490b727f70e99004de2ff33d235445d7c9a625f290745c2`), header casing differences (`sha256:54af8c0cb5ec887a12fc56af91226ed4576b60f9249d8282e6065d700f8465eb`), and CookieTossing state pollution (`sha256:de525c5063edd41b2129d8989415035efd382bbaa6dd7d0fd59f815fd6c16e71`). No existing sample proves `Rack::Protection::PathTraversal` normalization semantics.

## Pinned Release
`rack-protection` 4.2.1 pinned via `Gemfile` and `Gemfile.lock`.

## Observed Behaviour
`Rack::Protection::PathTraversal` intercepts incoming requests and sanitizes `env['PATH_INFO']` before delegating to downstream Rack applications:
1. URL-encoded dot (`%2e` / `%2E`), slash (`%2f` / `%2F`), and backslash (`%5c` / `%5C`) escapes are unescaped and converted to standard forward slashes.
2. Relative directory traversal components (`/../`) are resolved against parent segments without escaping root boundaries (traversals above root safely collapse to root-relative paths).
3. Redundant dot segments (`/./`) and multiple consecutive slashes (`///`) are collapsed into single slashes while preserving any trailing slash.
4. The middleware wraps downstream application execution in an `ensure` block that restores `env['PATH_INFO']` to its original uncleaned value upon return, even if downstream application execution raises an exception.
5. Empty strings and `nil` values for `PATH_INFO` pass through unmodified.
csx.json
{"case":{"caseId":"case:sha256:0aad297a3b48b0fb1aa7932716a30635f7bf9539098aa2d448d6be5eb5a47106","contract":["Rack::Protection::PathTraversal resolves URL-encoded dot segments and directory traversal sequences in PATH_INFO for downstream apps and restores the original path in an ensure block upon completion.","URL-encoded hex dot (%2e, %2E), slash (%2f, %2F), and backslash (%5c, %5C) sequences are unescaped and normalized to standard forward slashes.","Relative directory traversal sequences such as /../ are resolved against parent segments, safely collapsing above root without raising errors.","Redundant consecutive slashes are normalized into single slashes while preserving trailing slashes.","When downstream application execution raises an exception, the ensure block guarantees the caller's PATH_INFO is restored to its unmodified state.","Empty or nil PATH_INFO values pass through without modification."],"goal":"Rack::Protection::PathTraversal unescapes URL-encoded directory traversal sequences and normalizes PATH_INFO for downstream Rack apps while restoring original PATH_INFO upon completion","kind":"HOW","packages":["pkg:gem/rack-protection@4.2.1"],"schemaVersion":1,"symbols":["Rack::Protection::PathTraversal"]},"contractCommand":["ruby","test/contract.rb"],"environment":{"arch":"x64","ecosystem":"gem","executionContext":"ruby","language":"ruby","os":"linux","packageManager":"gem","runtime":"ruby","schemaVersion":1},"license":"MIT-0","packages":["pkg:gem/rack-protection@4.2.1"],"schemaVersion":1,"symbols":["Rack::Protection::PathTraversal"],"verifierAdapter":"rubygems@1"}
test/contract.rb
# frozen_string_literal: true

require 'rack/protection'

def assert_equal(expected, actual, message = nil)
  return if expected == actual

  msg = message ? "#{message} - " : ''
  raise "#{msg}Expected #{expected.inspect}, got #{actual.inspect}"
end

def assert(condition, message = 'Assertion failed')
  raise message unless condition
end

# Downstream Rack application that captures the PATH_INFO received from middleware
received_paths = []
app = lambda do |env|
  received_paths << env['PATH_INFO']
  [200, { 'content-type' => 'text/plain' }, [env['PATH_INFO'] || '']]
end

middleware = Rack::Protection::PathTraversal.new(app)

# 1. Primary contract: URL-encoded traversal sequences are sanitized for downstream app
# and the original PATH_INFO is restored on return via the ensure block.
env1 = { 'PATH_INFO' => '/public/%2e%2e/secret' }
status1, _, body1 = middleware.call(env1)

assert_equal 200, status1, 'Request succeeds with status 200'
assert_equal '/secret', body1.first, 'Downstream app sees sanitized PATH_INFO without traversal'
assert_equal '/public/%2e%2e/secret', env1['PATH_INFO'], 'Original PATH_INFO is restored on the env hash'

# 2. Case-insensitive URL-encoded hex characters (%2E, %2F, %5C) and backslashes are normalized
env2 = { 'PATH_INFO' => '/public/%2E%2E/%2Fsecret/%5Cconfig' }
_, _, body2 = middleware.call(env2)
assert_equal '/secret/config', body2.first, 'Unescapes uppercase hex dot/slash/backslash into standard slashes'
assert_equal '/public/%2E%2E/%2Fsecret/%5Cconfig', env2['PATH_INFO'], 'Caller env is restored'

# 3. Relative directory traversal segments (/../) collapse parent segments safely
env3 = { 'PATH_INFO' => '/api/v1/users/../../v2/settings' }
_, _, body3 = middleware.call(env3)
assert_equal '/api/v2/settings', body3.first, 'Resolves relative /../ segments against parent components'

# 4. Root-level directory traversal attempts safely collapse at root level without error
env4 = { 'PATH_INFO' => '/%2e%2e/%2e%2e/admin/dashboard' }
_, _, body4 = middleware.call(env4)
assert_equal '/admin/dashboard', body4.first, 'Traversals beyond root collapse to root-relative path'

# 5. Redundant dot segments and multiple consecutive slashes are normalized
env5 = { 'PATH_INFO' => '///assets/./js///bundle.js' }
_, _, body5 = middleware.call(env5)
assert_equal '/assets/js/bundle.js', body5.first, 'Collapses consecutive slashes and redundant dot segments'

# 6. Trailing slash is preserved when present
env6 = { 'PATH_INFO' => '/docs/api/../guide/' }
_, _, body6 = middleware.call(env6)
assert_equal '/docs/guide/', body6.first, 'Preserves trailing slash on normalized directory paths'

# 7. Ensure block guarantees restoration even when downstream app raises an exception
error_app = lambda do |_env|
  raise StandardError, 'Downstream application failure'
end
error_middleware = Rack::Protection::PathTraversal.new(error_app)
env7 = { 'PATH_INFO' => '/foo/%2e%2e/bar' }
begin
  error_middleware.call(env7)
  raise 'Expected downstream error was not raised'
rescue StandardError => e
  assert_equal 'Downstream application failure', e.message, 'Caught expected downstream error'
end
assert_equal '/foo/%2e%2e/bar', env7['PATH_INFO'], 'PATH_INFO is restored even after exception in downstream app'

# 8. Empty and nil PATH_INFO values pass through without error
env8 = { 'PATH_INFO' => '' }
_, _, body8 = middleware.call(env8)
assert_equal '', body8.first, 'Empty string PATH_INFO passes through'
assert_equal '', env8['PATH_INFO'], 'Empty string PATH_INFO remains unmodified'

env9 = { 'PATH_INFO' => nil }
_, _, body9 = middleware.call(env9)
assert_equal '', body9.first, 'Nil PATH_INFO passes through'
assert env9['PATH_INFO'].nil?, 'Nil PATH_INFO remains nil'

puts 'All Rack::Protection::PathTraversal contract assertions passed.'

Seeder de origem

csx-seed