Skip to content

lkrequest-py v0.3.0

Latest

Choose a tag to compare

@ezxlabs-admin ezxlabs-admin released this 20 Nov 10:55

Built on the Rust library's 0.3.0, it adds the Chrome 158 fingerprint, caps on
the retries and connections of one request and a summary of what each request
did, a deadline for a body that stops arriving and deadlines that can be turned
off, a lifetime for cached TLS sessions, complete profile bundles, compressed
WebSocket messages and proxy credentials worked out from a 407's challenges.
The Rust library's other changes show on the wire: requests sent at once to an
origin no connection is open to share the one being set up, where each dialed
its own; TLS 1.2 sessions are resumed, by ticket or session ID, until they
expire; the Firefox presets no longer stall HTTP/2 downloads of more than 128
KiB; the Firefox and Safari presets complete the P-521 handshakes they offer;
and a server that accepts permessage-deflate gets compressed messages. Of the
bindings' own changes, quic_fingerprint="chrome_158" sends the ClientHello
Chrome sends inside QUIC rather than its TCP one.

Three changes are visible from Python and worth reading before upgrading: an
HTTP/2 connection whose first request fails is no longer tried again over
HTTP/1.1, and a request whose pooled connection the server closed is no longer
sent again, unless h2_fallback_h1 and retry_on_connection_close turn that
back on; total_timeout now defaults to 120 seconds and also bounds the reading
of a streamed body, so a longer download needs a deadline that fits it; and a
host Hsts.dynamic() learns covers its subdomains only with
includeSubDomains and is forgotten when its max-age runs out.

🚀 Features

  • Chrome 158 Fingerprint — Added Client.chrome_158() / BlockingClient.chrome_158(), the "chrome_158" name for tls_profile= / h2_profile= / quic_profile=, and TlsProfile.chrome_158(), TlsProfile.chrome_158_quic(), H2Profile.chrome_158(), QuicProfile.chrome_158(). Captured from Chrome 158.0.8127.37 on Windows, it matches Chrome 157 throughout: the TCP and QUIC ClientHellos differ only in their name, and the H2, QUIC and HTTP/3 profiles, the header order and the protocol policy are Chrome 157's. The capture confirmed the HTTP/2 and HTTP/3 SETTINGS and the navigation and favicon priority; timing, loss recovery, resumption and 0-RTT carry over from Chrome 157 without being observed again. Like Chrome 152 to 157, it carries Trust Anchor Identifiers, so the trust_anchor_* options apply to it. The default fingerprint stays Chrome 155.
  • Profile Bundles — inherited from upstream 0.3.0. lkrequest.export_preset_json(name) writes a browser preset out as a complete profile bundle, lkrequest's v2 preset JSON: its TLS, QUIC TLS, HTTP/2 and QUIC profiles, header and cookie order, protocol policy and session-cache partitioning. Client.from_preset_json(json, tcp_fingerprint=None) and Client.from_preset_file(path, tcp_fingerprint=None), on BlockingClient too, build a client from one, edited or of your own, as Client.<name>() builds one from a preset; a bundle has no TCP fingerprint, so it is given alongside. The Rust library validates a bundle as it reads it, up to 1 MiB, and one it refuses raises ValueError naming the reason and the JSON pointer of the value at fault, such as UnknownField at /runtime/surprise or a protocol policy whose axes contradict one another.
  • Attempt Limits, And What A Request Did — inherited from upstream 0.3.0. The new AttemptLimits(extra_http_attempts=..., connect_attempts=...) caps, for one request, the HTTP submissions beyond its first and its redirects — retries and recoveries — and the TCP and QUIC connections it starts; reusing a pooled connection, or waiting for one being set up, starts none. Give it as attempt_limits= to a client, to session() or to a single request: a session or request inherits the cap above it and can only lower it, and one above raises ValueError, from session() for a session and before anything is sent for a request. The caps turn no retry on and replace no timeout, and concurrent requests count separately. Every Response and StreamingResponse, and the exception of a request that failed, now has attempt_summary, a dict of what the request did: its HTTP submissions, the extra ones among them, redirects, recoveries and connection starts, its outcome, why a recovery it could have made was refused, and the limits in effect, each with the scope that set it. Clients and sessions read their limits back as attempt_limits and effective_attempt_limits.
  • How Long A TLS Session Is Cached — Client(tls_session_cache_ttl=...) and BlockingClient(tls_session_cache_ttl=...) set how many seconds a cached TLS session lives before it is no longer resumed, over TLS 1.2, TLS 1.3 and QUIC alike: by default an hour for TLS 1.2, counted from the session's first full handshake, and seven days for TLS 1.3 and QUIC, which is also the most it can be. A shorter lifetime from the server still wins, and 0 caches nothing. The read-only tls_session_cache_ttl reads the setting back, None for the defaults, and tls_session_cache_enabled says whether sessions are cached at all, which TlsSessionResumptionPolicy.DISABLED or a lifetime of zero turns off.
  • A Deadline For A Body That Stops Arriving, And Deadlines Turned Off — Client(read_idle_timeout=...) and BlockingClient(read_idle_timeout=...) end a request whose response body, buffered or streamed, goes that many seconds without anything arriving, with TimeoutError; it is off unless set, and reads back in timeouts. Any of the client's timeouts — dns_timeout, tcp_connect_timeout, tls_handshake_timeout, ttfb_timeout, total_timeout, quic_connect_timeout and read_idle_timeout — now takes math.inf to turn that deadline off, which reads back as None; before, every one of them had a deadline whatever was given, and infinity raised ValueError. Together they suit a long download: total_timeout=math.inf, read_idle_timeout=30.0. A request's own timeout= still takes a finite number of seconds.
  • Compressed WebSocket Messages — inherited from upstream. ws_connect(..., extensions=["permessage-deflate; client_max_window_bits"]), the offer Chrome makes, now gives a connection that compresses and decompresses its messages once the server accepts the offer, with context takeover, fragmented messages and client windows of 9 to 15 bits; a message that decompresses to more than 64 MiB fails the connection. Before, the offer could be made but every compressed message the server sent failed to be received. Compression is used only when offered, so a connection that offers nothing is unchanged. The handshake now fails with RequestError when the server accepts an extension other than permessage-deflate, more than one, or deflate parameters that match no offer, where the frames used to be read plain regardless.
  • Proxy Credentials Worked Out From A 407's Challenges — inherited from upstream 0.3.0. ProxyConfig.with_custom_auth() takes on_challenge=, a function given the proxy's Proxy-Authenticate values, each whole and in the order sent, that answers a 407 in place of authorize, for a scheme such as Digest that works its credential out from the challenge. It runs on the thread setting the connection up, which waits for it, once for the CONNECT the challenge prompts. None, an exception or anything but a string declines the challenge, and the request fails with a ProxyError whose proxy_error_kind is "authentication_required"; an exception is logged as a warning. Like authorize, it must be a plain function: an async def, or anything that cannot be called, raises TypeError.

🔧 Changes

  • Recovery Only When Asked For — inherited from upstream 0.3.0. h2_fallback_h1 and retry_on_connection_close now default to False on both clients, where both were on: an HTTP/2 connection whose first request fails is no longer tried again over HTTP/1.1, whose fingerprint is not the browser's, and a request whose pooled connection the server has closed fails instead of going out again on a new connection. Pass True for either to have it back; neither overrides the method's idempotency or a body that cannot be sent twice. The new read-only retry_on_connection_close reads the setting back, beside h2_fallback_h1. One effect to look out for: HTTP/2 forbids the headers Connection, Keep-Alive, Proxy-Connection, Transfer-Encoding, Upgrade and a TE other than trailers. A request given one still sends it, now with a warning logged, and a strict server fails the request, which used to fall back to HTTP/1.1 and succeed; header sets copied from a browser's HTTP/1.1 request often carry Connection: keep-alive.
  • Two Minutes For A Whole Request, Streaming Included — inherited from upstream 0.3.0. total_timeout now defaults to 120 seconds, where it was 60, and bounds the whole request: connecting, redirects, retries and their backoff, and now the reading of a streamed body too, which it did not bound before. A streamed download that takes longer fails part way with TimeoutError, so give such a download a total_timeout, or a timeout= of its own, that fits it, or total_timeout=math.inf and a read_idle_timeout (see A Deadline For A Body That Stops Arriving, And Deadlines Turned Off above). A retry no longer starts a deadline of its own.

🐞 Fixes

  • Concurrent Requests Share The Connection Being Set Up — inherited from upstream. Requests sent at once to an origin no connection was open to each dialed one of their own: 50 at once made 50 TCP and TLS connections, where a browser makes one, and with max_connections_per_session set, every request beyond the cap failed with session connection limit reached. They now wait for the first connection and share it once it turns out to speak HTTP/2, so 50 or 100 at once make one connection and none fails. Over HTTP/1.1, which cannot share a connection, they still dial in parallel.
  • A Learned HSTS Host Expires, And Covers Subdomains Only When Told To — inherited from upstream. Hsts.dynamic() upgraded every subdomain of a host it had learned from a Strict-Transport-Security header, whether the header said includeSubDomains or not, and never forgot a host, however short its max-age. A learned host now covers its subdomains only with includeSubDomains, and is forgotten once its max-age runs out; a header with a malformed or repeated directive is ignored. Hosts given in seed= cover their subdomains and do not expire, as before, until a valid header replaces or removes them. Hsts.static_() is unchanged.
  • One Call Per CONNECT For A Proxy Credential Function — inherited from upstream. On a 407, the function given to ProxyConfig.with_custom_auth() was called once more than there were CONNECT requests, the extra answer thrown away, so a one-time token was used up for nothing. It is now called once for each CONNECT sent; returning None for the one a challenge prompts gives up with a ProxyError whose proxy_error_kind is "authentication_required".
  • Firefox Downloads No Longer Stall Over HTTP/2 — inherited from upstream. The Firefox presets sent no WINDOW_UPDATE for a stream, so a response of more than 128 KiB over HTTP/2 stopped arriving once the server had used up the stream's window, and the request hung until a timeout. The window is now replenished from what has been received, which also corrects when the other presets send theirs.
  • TLS 1.2 Sessions Are Resumed — inherited from upstream. A TLS 1.2 session could be resumed once, never by session ID, and not at all from a server that gave its ticket a lifetime of 0, as Go's servers do, so the connections after the first made full handshakes where a browser resumes. A TLS 1.2 session is now kept for reuse until it expires, an hour at most from its first handshake, as in Chrome, and resumed by ticket or by session ID, the Safari presets, which send no session_ticket extension, included. A ticket offer carries a fresh random session ID, and a session is dropped after a fatal TLS error. TLS 1.3 tickets are still used once.
  • More TLS 1.2 Servers Connect — inherited from upstream, whose TLS engine was reworked. Over TLS 1.2 it now speaks the four ECDHE-ECDSA CBC suites, encrypt-then-MAC (firefox_133 failed CBC connections with bad_record_mac), RSA-PSS with SHA-384 and SHA-512, ECDSA with a key on a curve other than the key exchange's, and a ServerHello split across records. The three 3DES suites safari_26 offers work when a server picks one, where the handshake failed. With verify on, a handshake signed with RSA/SHA-1, ECDSA/SHA-1 or ECDSA/SHA-512 is verified rather than refused, except ECDSA/SHA-1 with a P-384 key.
  • A Protocol Race Leaves Out The Side Turned Off — inherited from upstream. With HttpIntent.AcquireH3WhenViable, a RacePolicy(enable_quic=False) went over QUIC alone, and with ReuseExistingProtocol, enable_tcp=False went over TCP. The side a RacePolicy turns off now takes no part.
  • A Finished Request Sends Nothing More — inherited from upstream. Every way a request goes out — buffered or streamed, redirects, recovery, a TCP-versus-QUIC race — now asks one authority whether it may send, so a request that has completed or been cancelled cannot go out again, and the losing TCP side of a race cannot send a streamed request through an HTTP/2 connection it has just pooled, using up its one-time body.
  • Hardening In The Dependencies — inherited from upstream. A malformed DNS response of 12 bytes declaring 65,535 questions made the bundled Hickory parser allocate 5.5 MiB; its first allocation is now capped. The fingerprinting Quinn fork has upstream's fixes for QUIC Initial tokens, MAX_STREAM_DATA limits and truncated datagrams on Unix, and a QUIC connection whose TLS setup fails now releases its connection IDs instead of using up a shared endpoint's.
  • P-521 Handshakes For The Firefox And Safari Presets — inherited from upstream. The Firefox presets and safari_18 offer P-521, the secp521r1 group and the ecdsa_secp521r1_sha512 signature scheme, and safari_26 the group, but a server that took them up failed the handshake on the client's side: a P-521 certificate with unsupported handshake signature algorithm: 0x0603 over TLS 1.3, and over TLS 1.2 with handshake signature verification failed for 0x0403, the server having signed with SHA-256 as TLS 1.2 allows on any curve; a P-521 key exchange with HRR requested unsupported group: 0x0019 or unsupported ECDHE curve. These handshakes now complete, and a certificate chain a P-521 CA signed verifies. The Chrome presets offer no P-521, as Chrome does not, so a server that will use nothing else still refuses them.
  • A TLS Alert After The Handshake Is A TlsError That Names It — inherited from upstream, with the class from the bindings. Over TLS 1.3 a server can refuse a request once the handshake is over, as one that wants a client certificate does with certificate_required, the client having sent none. The request failed with a RequestError whose message changed from one try to the next (channel closed, operation was canceled, connection error) and never named the alert, and now and then it waited until ttfb_timeout. It now fails at once with a TlsError, TLS alert from server: fatal alert: certificate_required (116), whose tls_alert names the alert, phase is "http_request" and retryable is False. A connection error a TLS alert caused is a TlsError in the same way; a ProxyError or a timeout keeps its class.
  • HTTP/3 Responses Say Which Connection They Came Over — inherited from upstream. The diagnostics of a request over HTTP/3 had only ttfb_ms, total_ms and protocol: dns_ms, remote_addr and cipher_suite were None, and nothing timed the QUIC handshake. They are now given, remote_addr and cipher_suite on a pooled connection too, and the new key quic_ms times the QUIC handshake of a connection the request opened, as tls_ms does a TLS one. tcp_ms and tls_ms stay None over HTTP/3, as quic_ms does over TCP.
  • quic_fingerprint="chrome_158" Sends Chrome's QUIC ClientHello — a name given to quic_fingerprint= was looked up among the TLS presets, so "chrome_158" sent inside QUIC the ClientHello Chrome 158 sends over TCP, TLS 1.2 cipher suites and ML-DSA signature algorithms included, which Chrome never sends over QUIC, and the names of the QUIC-TLS presets, such as "chrome_158_quic", raised ValueError. A preset's name now stands for the ClientHello that preset sends over QUIC, as Client.<name>() does: TlsProfile.chrome_158_quic() for "chrome_158", Chrome 146's for Chrome 144 to 149, and, as before, the TLS profile itself for the presets without a QUIC ClientHello of their own (Chrome 131, Firefox, Safari). The QUIC-TLS presets can be named as well, as "chrome_158_quic", and a TlsProfile is used as given.