Skip to content

lkrequest-py v0.2.2

Choose a tag to compare

@ezxlabs-admin ezxlabs-admin released this 25 Sep 14:07
· 5 commits to main since this release

Adds streaming uploads, the Chrome 153, Chrome 154 and Firefox 156 fingerprints,
experimental MASQUE (CONNECT-UDP) proxies and address-family control with dial
target overrides, makes text() usable on the non-UTF-8 web, and picks up three
upstream fixes: a connection-pool bug that made every request re-dial whenever
HTTP/3 fell back to HTTP/2, a QPACK bug that made HTTP/3 connections built from
the Chrome presets unusable after their first request against servers such as
LiteSpeed, and HTTP/3 never reaching an IPv6 address. Six behaviour changes are
worth reading before upgrading: what text() does with bytes it cannot decode,
the exception json() raises, the order of the Cookie header, the QUIC GREASE
fields the Chromium presets now randomize per connection, the default port for a
portless HTTP proxy URL, and the encoding of ProxyConfig.identity().

🚀 Features

  • Streaming Uploads — Added body_stream= and content_length= to post, put, patch, delete, request and send_streaming on both clients, uploading without holding the body in memory. body_stream accepts a file-like object (read(n)), any iterable of bytes, or — on the async client — an async iterable; the blocking client rejects an async iterable up front, since it has no event loop to drive it. Omit content_length for an unknown-length body: HTTP/1.1 then uses chunked framing, HTTP/2 and HTTP/3 send DATA frames with no Content-Length. A supplied length is exact, so a source that ends short or runs long fails the request. Chunk boundaries are passed through untouched rather than re-chunked, because they are visible on the wire as DATA frame sizes. The source is single-use: neither an automatic retry, a protocol fallback, nor a redirect that must preserve the body can replay it.
  • HTTP/2 Dispatch Batching — Added Client(h2_dispatch_batch_size=...) and a matching read-only property, capping how many ready HTTP/2 requests are coalesced into one driver write turn. The default of 1 keeps each request in its own write, which is the shape the browser presets were captured with; batching is faster but observable, so it is opt-in. 0 is rejected with ValueError.
  • Readable Cookie Attributes — Added session.get_cookies_with_attrs(url) and session.get_all_cookies() on both clients, returning Cookie objects carrying name, value, domain, host_only, path, secure, http_only, same_site, expires and is_persistent. get_cookies() returns (name, value) pairs, which cannot tell apart two cookies sharing a name at different paths — the jar holds both, and only the attributes say which is which. These are what a caller needs to hand a jar to a browser automation context, to persist a login and know which cookies are session-only, and to answer why a cookie the jar holds was not sent. get_cookies_with_attrs is scoped to a URL like get_cookies; get_all_cookies spans every domain, which is the view to persist. Cookie is hashable, so two jars can be diffed with set operations. get_all_cookies lists cookies oldest first, which is the order to write them back in: combined with the Cookie ordering fix below, a jar saved and restored reproduces the same headers on the wire.
  • Address Family Selection — Added Client(ip_family="any" | "ipv4" | "ipv6") on both clients, backed by upstream's address-family policy. On a dual-stack host the OS resolver orders IPv6 ahead of IPv4 (RFC 6724), so a target publishing an AAAA record is reached over IPv6 whenever IPv6 happens to work; "ipv4" or "ipv6" keeps every address this process dials — the target, the proxy's own address, a SOCKS5 UDP relay, QUIC — within one family, which is what keeps a session from leaving over two families and presenting two source addresses to the target. "ipv6" also refuses IPv4-mapped addresses (::ffff:a.b.c.d). The default "any" is the previous behaviour. An address outside the family raises an error that names the ip_family setting (LkConnectionError, or ProxyError for the proxy's own address) instead of falling back — not even to a direct connection under proxy_fallback_direct=True — and an unknown value raises ValueError. Composes with dns= and with system_dns_cache_ttl=. A proxy that resolves the target itself — HTTP CONNECT, socks5h or MASQUE handed a hostname — still picks the family it dials; connect_to hands it an address instead.
  • Dial Target Overrides — Added Client(connect_to={"host:port": "ip:port"}) on both clients: requests to that origin dial the given address, while the URL, TLS SNI and certificate name, Host, cookies and connection pooling keep the original host. It applies to direct, proxied and HTTP/3 connections, ahead of Alt-Svc / SVCB endpoints, and never to the proxy's own address; through an HTTP CONNECT proxy the CONNECT line carries the address, which is how to decide the family a proxy dials. An IPv6 host or address goes in brackets ("[::1]:8443", "[2001:db8::1]:443"). The mapping is fixed — nothing re-resolves or refreshes it. A malformed entry, a zero port, one origin listed twice (Example.com and example.com count as the same), or an address ip_family excludes raises ValueError when the client is built.
  • Chrome 153 Fingerprint — Added Client.chrome_153() / BlockingClient.chrome_153(), the "chrome_153" name for tls_profile= / h2_profile= / quic_profile=, and TlsProfile.chrome_153(), TlsProfile.chrome_153_quic(), H2Profile.chrome_153(), QuicProfile.chrome_153(). Captured from Chrome 153.0.8010.37 on Windows. Against Chrome 152 the TLS shape is the same except for the shuffled trust-anchor list (extension 0xca34), which narrows from 32 identifiers to 28; H2 is unchanged; the QUIC ClientHello keeps the nine classic signature algorithms and sends no TLS GREASE slots. Nothing switches over on its own — an existing client keeps the preset it names.
  • Chrome 154 And Firefox 156 Fingerprints — Added Client.chrome_154() / BlockingClient.chrome_154(), the "chrome_154" name for tls_profile= / h2_profile= / quic_profile=, and TlsProfile.chrome_154(), TlsProfile.chrome_154_quic(), H2Profile.chrome_154(), QuicProfile.chrome_154(). Captured from Chrome 154.0.8037.58 on Windows: the TCP and QUIC ClientHellos, H2, the QUIC transport parameters and the Initial-packet generation rules all match Chrome 153, so only the profile name differs. The capture never received a QUIC response, so the H3 SETTINGS and request priority carry over from Chrome 153's completed navigation instead of being observed anew. Added Client.firefox_156() / BlockingClient.firefox_156(), the "firefox_156" name for tls_profile= / h2_profile=, and TlsProfile.firefox_156(), H2Profile.firefox_156(). Captured from Firefox 156.0.1 on Windows: against Firefox 147 the TLS profile drops two ECDSA CBC suites (0xc009, 0xc00a) and both FFDHE groups (256, 257), and its ECH GREASE switches to AES-128-GCM with a fixed 240-byte payload; H2 is unchanged. Like the other Firefox presets it carries no QUIC profile and turns HTTP/3 off — upstream captured Firefox 156's QUIC Initial but cannot yet reproduce every field of it — so there is no "firefox_156" QUIC name. As before, an existing client keeps the preset it names.
  • Chromium GREASE Generation For The QUIC Presets — inherited from upstream, and it changes the wire for existing presets, not just Chrome 153. Three fields are now generated per connection the way Chromium generates them, instead of being fixed by the profile: the reserved HTTP/3 SETTINGS id and value plus the control-stream GREASE frame (every Chrome QuicProfile, the generic chrome included); the reserved QUIC transport parameter ids, now spanning the full 62-bit range with 0–15 byte payloads and a randomized GREASE version position; and the Initial packet layout, with CRYPTO data split and shuffled and PING/PADDING interleaved (both on Chrome 146 and 150–154). Two connections from one client therefore no longer look byte-identical in those fields — which is what real Chrome does, and the reason a fixed value was a fingerprint of its own. A QuicProfile loaded from JSON is unaffected: the three flags default to off, so a serialized or hand-built profile keeps its previous behaviour.
  • MASQUE Proxies (Experimental) — experimental upstream and here: MasqueConfig, the masque= / tunnel_probe= parameters and the behaviour of masque:// routes may change in any release without a deprecation period, and interoperability has been checked only against test proxies, not against independent production MASQUE deployments. Behind the new masque build feature, which implies quic-h3 and is compiled into the published wheels; it does nothing unless a masque:// proxy is used. A masque:// proxy (port 443 by default) carries the QUIC connection to the target inside an RFC 9298 CONNECT-UDP tunnel over an HTTP/3 connection to the proxy; the target is named in the tunnel request, so DNS resolves proxy-side as with socks5h. Added MasqueConfig for the hop to the proxy — server_name, ca_cert (PEM file) / ca_cert_pem, use_native_certs, verify, and the two tunnel-lifecycle knobs tunnel_idle_timeout (default 120 s, None never retires an idle tunnel) and max_idle_tunnels (default 256, 0 removes the cap) — passed as Client(masque=...) on both clients. Its trust settings are deliberately independent of the client's verify / ca_cert*, which govern the origin: relaxing one hop for debugging never relaxes the other. A PEM bundle that is malformed or holds no certificate raises ValueError instead of leaving the trust store unchanged. HealthCheckConfig gained tunnel_probe and masque: a TCP connect proves nothing about a MASQUE proxy, so by default the health check skips those proxies — neither credited nor blacklisted — and with tunnel_probe=True it opens a real CONNECT-UDP tunnel to the check's target instead. Upstream skips the probe with only a log line when no outer configuration is given; here both arrive in one call, so tunnel_probe=True without masque= raises ValueError rather than silently never probing. MASQUE carries UDP only: HTTP/1.1 and HTTP/2 requests through it raise ProxyError, a failed tunnel never falls back to a direct connection even with proxy_fallback_direct=True, and a MASQUE proxy cannot be a chain hop. The connection to the proxy is not a browser fingerprint (the tunneled one to the origin is), and DNS-discovered ECH configs and H3 hints are unavailable on this route.
  • Proxy Credentials Beyond Username/Password — Added ProxyConfig.with_http_auth(scheme, credentials) for a static HTTP credential sent as-is (Bearer, Preshared, …), ProxyConfig.with_user_pass(username, password), and ProxyConfig.with_auth_header("proxy-authorization" | "authorization") to choose the header it travels in: RFC 9298 leaves proxy authentication unspecified, and MASQUE deployments disagree on the field. Each returns a new config and replaces any credential already set. An HTTP credential on a SOCKS5 proxy, which has nowhere to carry it, raises ValueError. Works for HTTP CONNECT proxies as well as MASQUE.

🐞 Fixes

  • The Cookie Header Follows Chrome's Order — inherited from upstream, and visible on the wire. The jar iterated a hash map, so the Cookie header order was arbitrary and differed between two sessions holding the same cookies; cookie_order pinned only the names it listed, and the relative order of same-name cookies at different paths stayed random. Cookies are now sorted as Chrome's CookieMonster sorts them: longer paths first, then older cookies first. Re-setting a cookie to the same value keeps its age, a new value makes it a new cookie, and removed or expired cookies do not disturb the order. This also makes the documented order of get_cookie(), get_cookies() and get_cookie_values() (longest path first) actually true — it was not. Upstream verified the result against Chrome 153.0.8010.47 on the wire: the same Set-Cookie sequence produced an identical Cookie header from both.
  • Enums Are Hashable Again — HttpVersion, HttpIntent, PreferredHttpVersion, Idempotency, BrokenQuicPolicy and WsMessage raised TypeError: unhashable type when used as a dict key or put in a set, which is the obvious way to map a member onto something. They declared equality without a matching hash, and CPython answers that by setting __hash__ = None. Equality is unchanged, including the integer comparisons (HttpVersion.H2 == 2). Still unhashable, pending a Hash derive upstream: Layers, NegotiabilityFloor, H2DataFramePolicy, TlsSessionResumptionPolicy, TlsSessionCachePartitionPolicy and NetworkPartitionContext.
  • set_cookie_raw On The Blocking Session — the blocking Session was missing it, although the async one had it and upstream's blocking session supported it all along. Since set_cookie_with_attrs accepts neither Expires nor SameSite, blocking callers had no way to set those two attributes at all.
  • text() Decodes The Declared Charset — Response.text() decoded UTF-8 unconditionally, so a charset=gbk body — or Big5, Shift_JIS, EUC-KR, any of the legacy web — was unreachable through it even though encoding reported the charset correctly. The failure was also misleading: it surfaced as TypeError: function takes exactly 5 arguments (1 given), because the error path constructed a UnicodeDecodeError from a single string and that exception requires five. text() now decodes with the charset from Content-Type, resolved against the WHATWG Encoding Standard as a browser resolves it, falling back to UTF-8 when none is declared or the label is unusable. text(encoding=...) overrides it for a charset the server omitted or got wrong; that argument is looked up in Python's own codec registry, so Python spellings the web standard does not list (latin-1, utf-8-sig, cp936) work as written, and an unknown codec raises LookupError just as bytes.decode would. Bytes that cannot be decoded become U+FFFD instead of raising, matching requests and httpx — reach for content when the exact bytes matter. A BOM is stripped and, where it contradicts the declared charset, believed over it. That is the browser rule and it goes further than requests and httpx, which strip nothing and always let the header win: stripping keeps an invisible U+FEFF from silently defeating json.loads and startswith (requests.json() fails outright on a BOM-prefixed UTF-8 body), and believing the BOM is almost always right, since a UTF-8 BOM read as the declared charset is garbage no real document opens with. The visible consequence is that a charset=gbk response whose body starts with a UTF-8 BOM decodes as UTF-8. The streaming responses' text() (StreamingResponse and BlockingStreamingResponse) now decodes the same way and takes the same encoding= argument; it used to decode strict UTF-8 whatever the header said, and raised RequestError on any other body.
  • Exceptions Can Cross A Process Boundary — every exception class failed to pickle, so a worker in a ProcessPoolExecutor, multiprocessing pool or task queue could not report one to its parent: the real error was replaced by PicklingError: Can't pickle <class '_lkrequest.TimeoutError'>: import of module '_lkrequest' failed, losing the message and no longer matching except lkrequest.RequestError. pickle stores a class by name — it imports __module__ and looks up __qualname__ there — and the classes named _lkrequest, which is not importable on its own, since the extension lives inside the lkrequest package. They now report __module__ = "lkrequest", which also makes repr() show the path callers actually import from. One class had a second, independent problem: ProxyError reported itself as LkProxyError, a name the package does not export, so the lookup failed even once the module resolved. Names are now pinned to the exported ones by a test.
  • json() Failures Are Now RequestErrors — a body that is not JSON raised the stdlib json.JSONDecodeError, which is not a RequestError, so except lkrequest.RequestError missed it and retry logic needed a separate case for it. It now raises lkrequest.JsonDecodeError, which subclasses both RequestError and json.JSONDecodeError, so either except catches it and existing code written against the stdlib exception keeps working. It carries the stdlib exception's msg, doc, pos, lineno and colno.
  • HTTP/3 Fallback No Longer Loses The Connection Pool — with HTTP/3 enabled (the default), an origin whose QUIC was unreachable re-established TCP and TLS for every request: the fallback pooled its HTTP/2 connection, but the pool lookup for Http3WithFallback only ever searched for an HTTP/3 connection and never saw it. There was no error, only latency — roughly a 3× slowdown against affected origins, which include any host advertising Alt-Svc h3 from a network where UDP is blocked.
  • HTTP/3 Connections Survive The QPACK Dynamic Table — inherited from upstream. Every Chrome QuicProfile, the generic chrome included, advertises a 64 KiB QPACK dynamic table as Chrome does, but the client could decode only static-table references. Against a server whose encoder takes up that offer — LiteSpeed does, and so does anything built on ls-qpack — the first request on an HTTP/3 connection succeeded and every later one failed with QPACK_DECOMPRESSION_FAILED, taking the connection down each time, so HTTP/3 connections were never reused. The client now builds the dynamic table from the server's encoder stream, holds a response until the entries it references have arrived, and acknowledges on the QPACK decoder stream as Chrome does. The SETTINGS on the wire are unchanged.
  • HTTP/3 Reaches IPv6 Addresses — inherited from upstream. The QUIC endpoint was bound to the IPv4 wildcard only, so every HTTP/3 connection to an IPv6 address failed before a packet was sent: with http3_only=True the request raised, and under the default policy it fell back to HTTP/2 and marked the origin's QUIC broken. On a network with IPv6, a dual-stack site whose AAAA record sorted first therefore never got HTTP/3. The client now keeps a separate IPv6 endpoint.
  • Portless HTTP Proxy URLs Default To Port 80 — proxy="http://proxy.example.com" previously defaulted to 8080, which is a common proxy port but not the scheme's default. It now resolves to 80, as the URL says. Spell the port out (http://proxy.example.com:8080) if 8080 was what you relied on. https:// proxies are unaffected (443 either way).
  • ProxyConfig.identity() Encoding Changed — the pooling and failure-tracking key is now a JSON array of ordered hops, each carrying protocol, host, port and a credential fragment, replacing the user@host:port / a>b>c form. The old encoding could not tell socks5 from socks5h, so two chains that resolve hostnames at different hops shared one cooldown entry. The fragment is null without credentials, "user:<name>" for a username/password (never the password), and an opaque fingerprint for an HTTP credential, so two tokens on one gateway do not share a key. Treat the value as an opaque key; use str(config) for something human-readable.
  • Direct TCP Connections Disable Nagle By Default — interactive HTTP benefits from TCP_NODELAY, so it is now on unless a fingerprint sets it off explicitly (TcpFingerprint(tcp_nodelay=False)).
  • Streaming Responses Honour Request Middleware And HSTS — send_streaming skipped both. Request middleware now runs in the same order as on the buffered path, followed by the session's HSTS URL upgrade, and the response updates HSTS state. Full-body response middleware still does not run, since there is no full body to hand it.
  • Replay Safety Across A Protocol Switch — a request that changed protocol mid-flight could be retried even though the earlier attempt may already have reached the server. Retry eligibility is now tracked through the switch.
  • Faster HTTP/2 Request Processing — upstream reworked the HTTP/2 driver's write path and HPACK encoder. No API change, and the default dispatch batch size keeps the wire shape identical.