SearchBook a call

RESEARCH / PAPERS

published

curl_reap 2.0: a 38-finding transport audit and TLS/HTTP2 benchmark study

Adversarial 38-finding transport audit of curl_reap, pure-Python TLS 1.3 and HTTP/2 architecture, and baseline vs. 2.0 benchmarks against curl_cffi.

Before building curl_reap 2.0, we ran an adversarial correctness audit against its 1.x transport (http.py, h2engine.py, tls.py, aio.py, cache.py) and benchmarked it head-to-head against curl_cffi 0.16.3 and Python’s standard library http.client. As explored in Fingerprints below HTTP, the wire identity of an HTTP client is decided below the application layer—in TLS ClientHello byte layouts and HTTP/2 preface frames—where Python’s standard ssl module and hyper-h2 defaults cannot impersonate modern browsers.

The 10 October 2026 audit uncovered 38 distinct defects (11 P1 wrong-result bugs, 11 P2 robustness defects, and 16 P3 protocol, memory, and API gaps), every one backed by a running reproduction script. Combined with baseline profiling, those findings shaped curl_reap 2.0’s pure-Python TLS 1.3 client (curl_reap/_tls/), custom HTTP/2 framing (curl_reap/_h2/), and hardened transport. Below are the full protocol findings, the 2.0 architectural changes, and the exact before-and-after benchmark measurements.

Facts at a glance:

  • Audit date & scope: 10 October 2026 on branch feat/beyond-curl-cffi, covering http.py, h2engine.py, tls.py, aio.py, and cache.py without modifying source code during the audit.
  • Reproducibility: 41 standalone reproduction scripts built on a shared harness (FakeSocket, GeneratorSocket for synthetic 70 MB bodies, an in-process hyper-h2 server behind H2PipeSocket, and a raw loopback TCP server).
  • Finding breakdown: 38 open findings—11 P1, 11 P2, and 16 P3—plus 19 protocol behaviors verified correct and two earlier September items (B13 POST retry gating and B28 cookie path boundary) confirmed fixed.
  • Benchmark environment: Apple M3 Pro (11 cores, macOS 26.3 arm64), Python 3.12.12, OpenSSL 3.6.5, curl_cffi 0.16.3 (libcurl/8.21.0-IMPERSONATE, BoringSSL, nghttp2/1.63.0), cryptography 50.0.2, h2 4.4.1, hpack 4.2.0.
  • Headline benchmark shifts (1.1.0 → 2.0.0): 5 MB streaming/body transfer jumped 29.3x from 121.3 MB/s (0.05x curl_cffi) to 3,554.5 MB/s (1.20x curl_cffi); HTTP/2 fixed its bad=1000 gzip-decoding failure while rising from 3,079 to 3,280 req/s; fresh pure-Python TLS 1.3 handshakes traded throughput (1,639 → 1,011 conn/s, 0.958 ms p50) for byte-faithful browser ClientHello and JA4/peetprint parity.

The 38-finding transport audit

Every finding below was reproduced against the pre-2.0 transport and recorded with file-and-line evidence.

P1 findings: wrong results, corrupted files, and RFC violations (11)

ID Subsystem Defect and measured reproduction
F02 Cookies (http.py:434) SimpleCookie drops any Set-Cookie carrying Partitioned (on live youtube.com, 6 of 8 cookies—including YSC, VISITOR_INFO1_LIVE, and VISITOR_PRIVACY_METADATA—were silently discarded) and turns unknown valued attributes (Priority=High) into phantom cookies replayed on subsequent requests.
F-B2 HTTP/2 decode (http.py:1012) _h2_exchange never invoked _decode_content, returning raw \x1f\x8b gzip bytes in .content, .text, and download() files even though every profile advertised Accept-Encoding: gzip, deflate.
F04 HTTP/2 flow control (h2engine.py:90) send_data pushed the full request body in a single call. A 16,385-byte POST raised a raw h2.exceptions.FrameTooLargeError (above the 16,384-byte max_outbound_frame_size), and a 70,000-byte POST raised FlowControlError (above the 65,535-byte window), bypassing TransportError and retry logic.
F05 HTTP/2 GOAWAY (http.py:952) Connections remained marked reusable = True after receiving GOAWAY in the same recv as StreamEnded; the next GET on the pooled socket crashed with an unretried raw h2.exceptions.ProtocolError (ConnectionState.CLOSED).
F06 HTTP/2 PUSH_PROMISE (h2engine.py:122) Event handling never filtered on event.stream_id == stream_id and left ENABLE_PUSH=1. A server push stream’s END_STREAM (200 text/css, b'PUSHED-CSS') was returned as the response to a /page request whose real answer was 404 text/html.
F07 HTTP/2 downloads (http.py:953) download() over HTTP/2 buffered the entire response in memory (60 MB peak traced heap for a 20 MB download vs. a 256 KB buffer on HTTP/1.1) and failed at 67,108,865 bytes against the 64 MiB cap (_MAX_BODY_BYTES).
F01 Multi-member gzip (http.py:248) One-shot zlib.decompress and _StreamDecoder.feed both stopped after the first gzip member and ignored unused_data, truncating b'first-member-second-member' to b'first-member-' in both buffered and download() paths.
F03 Redirect Location (http.py:769) Decoding raw UTF-8 Location bytes as latin-1 before urljoin and UTF-8 percent-encoding double-encoded /caf\xc3\xa9 into /caf%C3%83%C2%A9.
F08 DiskCache atomicity (cache.py:87) DiskCache.set truncated the body file in place before swapping metadata and used a fixed temp filename; concurrent reader/writer threads produced 771 torn reads (status 200 with 0-byte body) in 1.5 s.
F09 Download overwrite (http.py:786) download() committed any non-redirect body via os.replace without checking status. After three 503 responses, a 19 KB dataset.csv was overwritten with <h1>maintenance</h1> and returned without raising.
F12 Proxy CONNECT (http.py:695) _authority omitted default port 443, sending CONNECT example.com HTTP/1.1 instead of host:port as mandated by RFC 9110 section 9.3.6 (rejected by strict proxies such as Squid).

P2 findings: pooling, deadlines, TLS exceptions, and HTTP framing (11)

  • F-B14 (Stale and unbounded pool): _acquire performed no socket liveness probe before reuse (turning server-closed keep-alive into a TransportError on POST and a 0.52 s retry backoff on GET) and never reaped or capped idle sockets (40 idle sockets remained after 40 parallel GETs).
  • F-B15 (Per-op timeout vs. request deadline): timeout=0.5 reset on every socket operation and every redirect hop; a dribbled 10-byte body took 3.03 s and five 0.35 s redirect hops plus drip took 4.81 s without timing out.
  • F-B16 (Unbounded HTTP/1.1 bodies): Unlike HTTP/2, none of the three HTTP/1.1 framing paths enforced a response size cap, buffering 73,400,320 bytes (70 MiB) into memory.
  • F38 (Raw TLS errors): _acquire ran outside the try block that wraps OSError/ssl.SSLError, so certificate verification failures (self-signed.badssl.com, expired.badssl.com) and handshake timeouts escaped as raw ssl.SSLCertVerificationError, ssl.SSLError, or TimeoutError rather than TransportError.
  • F37 (Excess bytes poisoning): Bytes arriving past Content-Length stayed in _BufferedSocket.buffer, poisoning the next pooled request with malformed HTTP status line 'EXTRAHTTP/1.1 200 OK'.
  • F10 (HEAD + 303 rewrite): A 303 redirect after HEAD was unconditionally rewritten to GET, downloading a 5,000-byte body contrary to RFC 9110 section 15.4.4.
  • F11 (Profile header suppression): Passing headers={'Accept-Encoding': None} stripped the None sentinel before merging profile headers, leaving Accept-Encoding and Accept-Language on the wire.
  • F13 (Malformed Content-Length in download): download() called raw int() without catching errors, raising ValueError instead of TransportError.
  • F14 (Uncapped Retry-After): Retry-After: inf or 1e400 crashed time.sleep with OverflowError, while Retry-After: 99999999 attempted a multi-year sleep.
  • F-B20a and F-B20d (HTTP/2 close & redirect sinks): Session.close() never called H2Protocol.close() (no GOAWAY sent), and download() over HTTP/2 wrote redirect bodies to disk before evaluating max_redirects.

P3 findings: desync edges, memory doubling, and fingerprint gaps (16)

Sixteen lower-severity findings exposed classic HTTP edge cases and maintenance debt:

  • Framing and security edges: _release checked _closed outside its lock, leaking live sockets into a cleared pool (F30); 101 Switching Protocols responses were pooled as HTTP/1.1 (F27); chunked trailers were folded into buffered headers—allowing a trailer to inject Content-Encoding or Location contrary to RFC 9110 section 6.5.1—while streaming dropped them (F21); non-chunked Transfer-Encoding fell through undecoded contrary to RFC 9112 section 6.1 (F31); Connection was checked with string equality instead of token parsing, pooling Connection: close, foo (F32); Secure cookies from plain http origins were accepted contrary to RFC 6265bis section 5.5 (F35); Unicode hostnames failed to match punycode Domain attributes and _origin checks (F15); and int() accepted Content-Length: 1_0, +10, and chunk sizes 0x5 (F16), a well-known proxy desynchronization surface.
  • Memory, concurrency, and API consistency: _RawResponse eagerly decoded .text on construction, pushing peak traced heap on a 40 MB application/octet-stream GET to 121 MB (F24); download() reported saved_to metadata even when 204/304/unfollowed-302 wrote no file (F18); HTTP/2 response.headers['set-cookie'] kept only the last value (F23); AsyncSession cancellation could not interrupt the worker thread and left sockets open after close() (F29); CaseInsensitiveHeaders was O(n) per lookup (F-B24); profile vs. impersonate conflicts differed between Session() and request() (F-B26); dead code left Profile.alpn_protocols unread (F-B30); and the fingerprint table lacked br/zstd, 13 curl_cffi 0.16.3 targets, and browser HTTP/2 pseudo-header order (m,s,a,p instead of Chrome’s m,a,s,p) (F-FP).

Nineteen behaviors passed audit verification without defects, including Content-Length + Transfer-Encoding precedence (chunked wins), 1xx interim skipping, HEAD/304 body suppression, non-pooling of HTTP/1.0, IDNA Host and IPv6 bracketing, 303/307 redirect body semantics, withholding Secure cookies over plain HTTP, verify in the pool key, and HTTP/2 WINDOW_UPDATE on both stream and connection windows for 300 KB responses.

curl_reap 2.0 transport architecture

The audit showed that patching OpenSSL and hyper-h2 around the edges could not close the core wire gap. Standard-library ssl emits an OpenSSL-shaped ClientHello (JA4 t13d913h2_... against Chrome’s t13d1516h2_8daaf6152771_806a8c22fdea) with no control over extension ordering, GREASE, TLS 1.3 cipher order, supported groups, or post-quantum ML-KEM key shares. Meanwhile, hyper-h2 always emits all six default SETTINGS (1:4096;2:1;...|00|0|m,s,a,p against Chrome’s 1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p) and cannot match nghttp2’s HPACK representations.

Rather than binding C curl-impersonate (which reintroduces per-platform C toolchains and locks fingerprint updates to binary releases), curl_reap 2.0 adopts a pure-Python protocol stack over cryptography>=42, hpack>=4, and brotli>=1.1:

  • Native TLS 1.3 client (curl_reap/_tls/): a sans-IO TLSClient plus blocking TLSSocket and AsyncTLSSocket drivers that emit byte-faithful ClientHellos from data templates—including real X25519MLKEM768 hybrid key shares, compressed certificates, ALPS, ECH GREASE, HelloRetryRequest, KeyUpdate, PSK resumption (SessionCache), and cryptography.x509.verification hostname/IP validation. Servers negotiating TLS 1.2 raise TLS12Negotiated and fall back automatically to OpenSSL (Session(tls='auto')), reported in Response.tls_backend.
  • Custom HTTP/2 framing (curl_reap/_h2/): replaces h2engine.py with H2Connection and H2Spec templates over hpack Huffman tables, emitting per-browser SETTINGS, WINDOW_UPDATE, HEADERS priority/flags, pseudo-header order, and nghttp2-identical HPACK encoding. It enforces stream-ID filtering, refuses PUSH_PROMISE (ENABLE_PUSH=0), chunks outbound bodies against both stream and connection flow-control windows, streams DATA directly to sinks without buffering, sends GOAWAY on close(), and marks stream_id > last_stream_id retryable.
  • Hardened core modules: dedicated exceptions.py (CurlECode-compatible hierarchy under RequestException/TransportError), O(1) multi-value headers.py, RFC 6265bis cookies.py supporting Partitioned and rejecting Secure cookies over http, per-family multipart.py, and socks.py (socks4/4a/5/5h).
  • Transport invariants: HTTP/2 enabled by default (Session(http2=True)), bounded keep-alive pools (10 idle per key, 60 s TTL, select liveness probe, empty-buffer guard), whole-request deadlines across redirects, 64 MiB cap for buffered bodies (uncapped for stream=True and download()), 2xx-only atomic download() commits, unconditional host:port CONNECT, lazy .text, all 56 curl_cffi 0.16.3 targets plus legacy aliases, and reap doctor [target] for live JA3/JA4/peetprint/Akamai verification.

Benchmarks: baseline 1.1.0 vs. post-2.0

Both benchmark runs used the same local loopback harness (bench/bench.py) on an Apple M3 Pro (11 cores, macOS 26.3 arm64), Python 3.12.12, OpenSSL 3.6.5, and curl_cffi 0.16.3. Every server ran in-process on 127.0.0.1 with a self-signed ECDSA P-256 CA and server TLS session tickets enabled; each scenario ran 20 warm-up requests followed by 3 timed runs, reporting medians. HTML bodies were 20,480 bytes (4,828 bytes gzip); large bodies were 5,242,880 bytes identity.

Throughput and latency comparison

Scenario Metric curl_reap 1.1.0 (2026-10-10) curl_reap 2.0.0 (2026-10-11) curl_cffi 0.16.3 (2026-10-11) http.client floor (2026-10-11) 2.0 reap / cffi
A. HTTP/1.1 keep-alive, 1 conn, 2000 × 20 KB gzip req/s 12,949 9,795 7,389 14,184 1.33x
p50 / p99 ms 0.076 / 0.098 0.099 / 0.144 0.132 / 0.206 0.069 / 0.097
B. HTTP/1.1 keep-alive, 16 threads × 300 GET req/s 10,676 7,594 4,271 11,758 1.78x
p50 / p99 ms 1.413 / 3.108 2.061 / 3.617 3.634 / 6.729 1.272 / 2.953
C. HTTPS fresh conns, 300 × 1 GET (Connection: close) conn/s 1,639 1,011 2,085 1,311 0.48x
p50 / p99 ms 0.601 / 0.970 0.958 / 1.460 0.452 / 0.843 0.731 / 1.294
D. HTTPS keep-alive, 1 conn, 2000 × 20 KB gzip req/s 11,349 8,034 6,944 12,215 1.16x
p50 / p99 ms 0.086 / 0.114 0.120 / 0.182 0.139 / 0.211 0.081 / 0.105
E. HTTP/2 keep-alive (ALPN h2), 1000 × 20 KB gzip req/s 3,079 (bad=1000) 3,280 (bad=0) 4,377 n/a 0.75x
p50 / p99 ms 0.317 / 0.631 0.296 / 0.531 0.221 / 0.428 n/a
F. HTTP/1.1 keep-alive, 50 × 5 MB identity body MB/s 121.3 3,554.5 2,967.4 12,154.0 1.20x
p50 / p99 ms 41.246 / 42.211 1.333 / 1.971 1.589 / 2.759 0.368 / 0.875

(For reference, curl_cffi 0.16.3 scored 7,468 req/s on A, 4,238 req/s on B, 2,179 conn/s on C, 6,979 req/s on D, 4,401 req/s on E, and 2,468.9 MB/s on F during the 10 October baseline run.)

Reading the trade-offs

Four concrete conclusions fall out of the baseline-to-2.0 delta:

  1. Lazy .text erased a 20x bottleneck on large bodies (Scenario F): in 1.1.0, content.decode("utf-8", "replace") inside _RawResponse.__init__ burned 36.5 ms of every 41.2 ms response—even for binary payloads. Making .text lazy raised throughput from 121.3 MB/s to 3,554.5 MB/s (p50 down from 41.246 ms to 1.333 ms), overtaking curl_cffi (2,967.4 MB/s) at 1.20x.
  2. HTTP/2 became both correct and faster (Scenario E): baseline 1.1.0 failed every single HTTP/2 response (bad=1000) because it returned raw gzip bytes. Replacing hyper-h2 with curl_reap/_h2/ fixed content decoding (bad=0) while improving throughput from 3,079 to 3,280 req/s (p50 0.296 ms vs. 0.317 ms, narrowing the gap to nghttp2 from 0.70x to 0.75x) and achieving exact Akamai fingerprint parity.
  3. Keep-alive and threaded throughput remain ahead of curl_cffi (Scenarios A, B, D): adding liveness checks, strict headers, RFC 6265bis cookies, and deadline accounting reduced raw loopback request rates relative to 1.1.0 (e.g., 12,949 → 9,795 req/s on A; 11,349 → 8,034 req/s on D), yet 2.0.0 still outperforms curl_cffi across all three scenarios—1.33x on single-connection HTTP/1.1, 1.16x on HTTPS keep-alive, and 1.78x under 16-thread contention (7,594 vs. 4,271 req/s, where curl_cffi degrades below its own sequential rate).
  4. Pure-Python TLS 1.3 pays ~0.36 ms extra on fresh handshakes (Scenario C): fresh HTTPS connections dropped from 1,639 conn/s (0.601 ms p50 via OpenSSL) to 1,011 conn/s (0.958 ms p50 via native Python TLS 1.3), compared with BoringSSL’s 2,085 conn/s (0.452 ms p50). That ~1 ms handshake budget matches the 2.0 design estimate and is paid once per new connection in exchange for exact browser ClientHello, JA4, peetprint, and ML-KEM parity without compiled BoringSSL forks.

Scope boundaries and limitations

  • Not in scope for 2.0: HTTP/3 (QUIC, raising NotImplementedError), CAPTCHA or anti-bot bypass, TLS 1.2 inside the native Python engine (handled by automatic OpenSSL fallback), and constant-time cryptographic guarantees in the Python record layer.
  • Loopback vs. WAN latency: all six benchmark scenarios measure CPU and transport overhead over 127.0.0.1 with zero network RTT; on internet connections where round-trip times are tens of milliseconds, the sub-millisecond fresh-handshake difference in Scenario C is a small fraction of total latency, whereas HTTP/2 correctness, pool liveness, and lazy .text dominate real workloads.
  • Async transport architecture: AsyncSession remains thread-backed over the synchronous transport in 2.0 (asyncio.to_thread), while the sans-IO _tls and _h2 cores lay the groundwork for a native asyncio transport in a later release.

Sources

  • docs/design/audit-2026-10-10.md (curl_reap repository, 38-finding transport audit and 41 reproduction scripts)
  • docs/design/beyond-curl-cffi.md (curl_reap repository, 2.0 architecture contract, frozen 11 October 2026)
  • bench/BASELINE.md (curl_reap 1.1.0 benchmark and cProfile hot-spot analysis, 10 October 2026)
  • bench/AFTER-2.0.md (curl_reap 2.0.0 post-rewrite benchmark, 11 October 2026)
  • curl_reap project documentation and Fingerprints below HTTP

← All papers