Skip to content

HTTP/3 (QUIC) foundation: Phase 8 (Connection lifecycle)#27885

Draft
quaesitor-scientiam wants to merge 41 commits into
vlang:masterfrom
quaesitor-scientiam:http3-quic-connection-lifecycle
Draft

HTTP/3 (QUIC) foundation: Phase 8 (Connection lifecycle)#27885
quaesitor-scientiam wants to merge 41 commits into
vlang:masterfrom
quaesitor-scientiam:http3-quic-connection-lifecycle

Conversation

@quaesitor-scientiam

@quaesitor-scientiam quaesitor-scientiam commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Summary

Draft PR tracking Phase 8 of HTTP/3/QUIC support (#27675), continuing from
the completed Phase 7 work in #27884 (loss detection and NewReno congestion
control). This branch starts from #27884's tip, since idle-timeout reset
timing and the draining-state ping-pong guard both need to reason about
ack-eliciting sends/receives, a concept Phase 7's loss detection already
tracks.

This is a work-in-progress, opened as a draft so the work is
visible/discoverable while in progress. It will be retargeted to master
directly once #27680, #27877, #27880, #27881, #27882, and #27884 merge;
until then it necessarily also contains their commits.

See vlib/net/quic/PROGRESS.md
for the exact phase-by-phase checklist.

Scope

  • idle_timeout.v — effective idle timeout is the min of the two peers'
    non-zero max_idle_timeout transport parameters, where 0 means "no
    timeout" (not literally zero) — all 4 combinations (both zero, one zero,
    neither zero) need distinct handling. Reset on an ack-eliciting packet
    RECEIVED or ANY packet SENT — a deliberate asymmetry, not "any packet
    either direction".
  • connection_close.v — CONNECTION_CLOSE with a transport error code vs.
    an application error code are distinct wire variants (RFC 9000 §19.19);
    closing/draining state to prevent an infinite CONNECTION_CLOSE
    ping-pong (RFC 9000 §10.2's rate-limited-retransmission-on-receipt
    vs. draining's fully silent no-response).
  • stateless_reset.v — recognized only as a fallback once normal AEAD
    decryption has already failed, never as a first-choice interpretation;
    immediate ungraceful teardown, no draining period. Scoped-down
    NEW_CONNECTION_ID handling: record stateless-reset tokens for matching
    purposes without implementing full connection ID rotation/migration.
  • ecn.v — no OS-level ECN socket option exists in V today, so ECN
    validation always resolves to failed/unsupported (a spec-legal fallback,
    RFC 9000 §13.4.2) rather than being ignored outright; received ACK
    frames' ECN counts are still parsed without erroring, just never trigger
    an ECN-based congestion response.
  • pmtu.v — pinned to the 1200-byte RFC 9000 §14.1 safe minimum, no
    active DPLPMTUD probing in v1 (a legitimate, spec-sanctioned
    conservative choice). Connection migration (RFC 9000 §9) stays
    explicitly out of scope.

Test plan

  • Idle-timeout min-of-non-zero-or-infinite across all 4 combinations
    (both zero, local-only zero, peer-only zero, neither zero) —
    test_effective_idle_timeout_all_four_zero_nonzero_combinations.
  • Idle-timeout reset asymmetry: an ack-eliciting RECEIVE resets it, a
    non-ack-eliciting receive does not, but ANY send does —
    test_idle_timeout_state_reset_asymmetry.
  • CONNECTION_CLOSE closing-state rate-limited retransmission on
    receipt vs. draining-state fully silent behavior —
    test_connection_close_tracker_closing_rate_limited_retransmission,
    test_connection_close_tracker_draining_is_fully_silent.
  • Stateless reset matched only via a token previously recorded for
    the exact connection ID queried, never fabricated
    (test_is_stateless_reset_recognized_only_via_a_matching_token).
    The "only after a decrypt failure" ordering itself is a caller
    contract documented on is_stateless_reset — there's no real
    packet-processing pipeline yet to integration-test that ordering
    against (arrives with Phase 9's QuicConn).
  • ECN counts parsed from a received ACK frame without erroring, and
    is_validated() confirmed to always report false regardless of
    what was recorded (including a non-zero ECN-CE count) —
    test_ecn_state_parses_counts_without_erroring_and_never_validates.
  • Runtime assertion that fits_within_pmtu stays pinned at exactly
    1200 bytes with no active probing path —
    test_fits_within_pmtu_runtime_assertion_at_1200_bytes.
  • All new/modified code passing under ./vnew test <path> — 36/36
    files in vlib/net/quic/.
  • ./vnew fmt -w applied to all touched .v files.

/vreview (full A-G pass) found and fixed one issue before commit: a real
integer-overflow bug. max_idle_timeout is a peer-supplied
transport-parameter varint that transport_parameters.v accepts with NO
upper bound (up to the full 2^62-1 varint range) — effective_idle_timeout
originally multiplied it directly by time.millisecond, which overflows
the i64 backing time.Duration for any peer value above ~9.2 trillion
ms, silently producing a nonsensical (possibly negative) timeout: a
hostile or buggy peer could self-inflict a near-immediate teardown, or
effectively disable the idle timeout altogether. Fixed by clamping to the
exact mathematically-necessary bound (derived from time.infinite, i.e.
i64::MAX nanoseconds, not an arbitrary policy number) before scaling;
regression test feeds the maximum possible QUIC varint (2^62-1) through
both the one-sided and both-sided paths and confirms a large-but-finite,
strictly positive Duration comes back.

🧙 Built with WOZCODE

quaesitor-scientiam and others added 30 commits July 6, 2026 21:39
…ves)

Adds QUIC varint codec, packet number encode/reconstruct (RFC 9000 §17.1 +
Appendix A), and long/short header parsing (RFC 9000 §17.2/17.3) as the first
buildable pieces of an HTTP/3 implementation (tracking issue vlang#27675).

Adds P-256 ECDH to crypto.ecdsa and a new crypto.rsa_pss module (RSA-PSS
sign/verify), both needed for the QUIC-scoped TLS 1.3 handshake landing in
Phase 2 — this repo implements that handshake from scratch in pure V rather
than patching vendored mbedTLS, which has no QUIC support in any released
version (see the tracking issue for the full comparison).

Confirms mbedTLS's X.509 parse/verify functions work standalone (no
mbedtls_ssl_context), and that the existing Windows CI OpenSSL coverage
already exercises the exact dependency this work adds.

/vreview caught and fixed two real bugs before this landed: a wire-integer
truncation in parse_long_header's token_len handling, and a minor OpenSSL
leak in the new PublicKey.from_uncompressed_bytes.

See vlib/net/quic/PROGRESS.md for exact phase-by-phase status and what's
next, for anyone continuing this work.

Co-Authored-By: WOZCODE <contact@withwoz.com>
…01 §5.2)

Adds initial_secrets.v: the fixed QUIC v1 Initial salt, HKDF-Expand-Label
(RFC 8446 §7.1 — the shared derivation primitive Phase 2b/2c and Phase 3
will all reuse), and derive_initial_secrets computing the client/server
Initial secrets from a connection's client-chosen DCID.

Verified against RFC 9001 Appendix A.1's own published test vectors,
obtained directly from the raw RFC text (the WebFetch summarizer corrupted
several hex values when first attempted — caught via an odd-hex-digit-count
self-check, not trusted). Also chain-tests hkdf_expand_label against the
same appendix's quic key/iv/hp derivations for extra coverage of the
primitive itself, without adding any Phase 3 packet-protection code.

/vreview: no findings — small, side-effect-free, no concurrency/unsafe/
C-interop surface in this file.
Adds tls13_keyschedule.v: the full Early -> Handshake -> Master secret
chain (derive_early_secret, derive_handshake_secrets,
derive_application_secrets, derive_secret for Derive-Secret itself), plus
synthetic_client_hello1_hash for RFC 8446 §4.4.1's HelloRetryRequest
transcript rule. exporter_master_secret/resumption_master_secret are
intentionally omitted (v1 uses neither TLS exporters nor 0-RTT).

Verified against RFC 8448 §3's published intermediate secrets (independent
of the RFC 9001 vectors Phase 2a uses), including an end-to-end chained
test and an independent recomputation proving Transcript-Hash covers only
raw handshake message bytes with no record-layer framing. All vectors
extracted programmatically from the raw RFC text, not hand-transcribed,
after catching WebFetch's summarizer corrupt hex constants during Phase 2a.

Phase-R verified: swapped the client/server hs-traffic labels, confirmed
the RFC vector tests catch it, then restored.

/vreview: no findings — pure, side-effect-free, no concurrency/unsafe/
C-interop surface in this file.
…r commit)

Content was written and reviewed alongside the Phase 2b commit
(786ee01) but got unstaged before that commit landed. Same content,
separate commit.
Adds tls13_messages.v: generic TLS 1.3 handshake message wire framing
(HandshakeType enum restricted to the real RFC 8446 SS B.3 v1.3 set,
encode_handshake_message/parse_handshake_message), and the Finished message
MAC (RFC 8446 SS 4.4.4) via compute_finished_verify_data/verify_finished,
using crypto.hmac.equal for constant-time peer-data comparison.

Verified against an extended RFC 8448 SS 3 trace (EncryptedExtensions/
Certificate/CertificateVerify bytes added to the existing ClientHello/
ServerHello vectors, needed to compute the real transcript hash the
server's Finished authenticates). First extraction attempt was silently
corrupted by RFC page-break footer text ("[Page 7]", "January 2019")
landing inside the Certificate line range and being parsed as hex bytes;
caught via a byte-count mismatch and a failed end-to-end cross-check before
trusting the vector.

Phase-R verified: forced verify_finished to always return true, confirmed
three negative tests (tampered data, wrong base secret, stale transcript
checkpoint) all caught it, then restored the real constant-time comparison.

Remaining Phase 2c work (quic_transport_parameters, ClientHello/ServerHello/
Certificate construction+parsing, the client state machine) tracked in
PROGRESS.md, not yet started.

/vreview: no findings.
…load

Adds transport_parameters.v: all 17 RFC 9000 SS18.2 transport parameters
(including the nested preferred_address struct) as a single
QuicTransportParameters struct using Optional fields so "absent" stays
distinct from "present with a default/zero value" -- applying the spec's
stated defaults is deferred to whichever later phase actually consumes
these values.

decode_transport_parameters ignores unrecognized parameter IDs per RFC 9000
SS7.4.2's MUST (also exercises the SS18.1 grease pattern), validates
ack_delay_exponent/max_udp_payload_size/max_ack_delay/
active_connection_id_limit against the spec's own bounds (accept+reject
boundary-pair tests for all four), and rejects duplicate parameter IDs (a
defensive addition beyond an explicit RFC citation, Phase-R verified).

This is the first Phase 2 file that parses a loop of peer-controlled wire
bytes, so particular attention went to the length-bounds check: it
validates in u64 space before any truncating cast to int, the same pattern
already fixed once in Phase 1's header.v (a crafted oversized varint length
silently wrapping past a 32-bit int bounds check) -- confirmed not
reintroduced here.

Scope note: this file covers only the RFC 9000 SS18 "Transport Parameters"
sequence itself (the extension_data). The outer TLS extension_type=0x39 +
length-prefix wrapping, and the initial_source_connection_id-vs-packet-
header-SCID cross-check, are later work (ClientHello/EncryptedExtensions
and Phase 9's QuicConn respectively).

/vreview: no findings.
Adds tls13_client_hello.v: build_client_hello constructs a complete TLS 1.3
ClientHello (RFC 8446 SS4.1.2) -- legacy_version 0x0303, empty
legacy_session_id (RFC 9001 SS8.4 prohibits TLS 1.3 middlebox
compatibility mode over QUIC), a single cipher suite
(TLS_AES_128_GCM_SHA256), and six extensions: server_name,
supported_versions, supported_groups (secp256r1 only), signature_algorithms
(ECDSA P-256 + RSA-PSS), key_share (Phase 1's P-256 ECDH), and
quic_transport_parameters (wrapping Phase 2c part 2's payload).

Verified via two exact RFC 8448 SS3 cross-checks (supported_versions, and
server_name with hostname "server") -- real sub-structures RFC 8448's own
ClientHello happens to share byte-for-byte with ours despite the overall
messages differing (x25519 vs our P-256, no QUIC extension there) -- plus
hand-derived structural tests for the P-256-specific extensions and a
full-message structural round trip using a real generated ECDH key.

/vreview caught and fixed a real gap: QuicTransportParameters deliberately
doesn't reject the four server-only fields itself (documented as "the
client-side caller's job" in transport_parameters.v) -- build_client_hello
is that caller and hadn't actually done it, so a caller could silently
produce a ClientHello violating RFC 9000 SS18.2's "a client MUST NOT
include any server-only transport parameter." Fixed with four explicit
checks, one per field; Phase-R verified by deliberately mixing up which
field one check tested and confirming exactly the corresponding test (and
no other) failed.

Also traced through a potential wire-integer overflow in the key_share/
server_name extension encoders (the same bug class already fixed once in
Phase 1's header.v) -- confirmed unreachable: the outer encode_extension
length check is a strict superset of the inner field's own overflow
condition, so it always catches oversized input first. Not a finding, but
worth the record given that bug class's history in this codebase.

/vreview: 1 finding, fixed (see above).
Adds tls13_server_hello.v: generic TLS extension-list parsing
(parse_extension_list/find_extension, RFC 8446 SS4.2, duplicate-extension
rejection mirroring transport_parameters.v's duplicate-ID rejection for
the analogous QUIC TLV sequence). parse_server_hello returns a
ParsedHelloRetryRequest | ParsedServerHello sum type, distinguished by RFC
8446 SS4.1.3's magic Random value -- independently verified via a live
SHA-256 computation of "HelloRetryRequest", not just transcribed from the
RFC text. Validates every statically-checkable RFC 8446 SS4.1.3 MUST.
parse_encrypted_extensions rejects early_data (0-RTT not offered).

Verified against RFC 8448 SS3's own ServerHello for the happy path, plus
hand-built HRR (with and without cookie) and error-path tests. Phase-R
verified the HRR-vs-ServerHello discrimination itself (not just that both
shapes parse), by forcing the branch and confirming the RFC-vector test
catches it.

/vreview caught and fixed a real gap: the real-ServerHello key_share branch
didn't reject an empty key_exchange, even though RFC 8446 SS4.2.8's
opaque key_exchange<1..2^16-1> requires at least 1 byte -- the parallel
check already existed for the cookie extension but was missed here. Fixed
with an explicit check, Phase-R verified.

Deferred to Phase 2c's still-pending state machine (needs connection-level
state this parsing layer doesn't have): second-HRR rejection, and
cross-checking EncryptedExtensions/cipher_suite/selected_version/key_share
group against what was actually offered rather than fixed v1 values.

/vreview: 1 finding, fixed (see above).
…arsing

Adds tls13_certificate.v: parse_certificate (RFC 8446 SS4.4.2 --
certificate_request_context + a non-empty CertificateEntry chain, each a
non-empty DER cert_data plus per-entry extensions), parse_certificate_verify
(RFC 8446 SS4.4.3 -- algorithm validated against v1's own fixed offered
set, signature bytes), and certificate_verify_signed_content (RFC 8446
SS4.4.3's exact 64-byte-pad + context-string + separator +
transcript-hash construction).

Verified byte-for-byte against RFC 8446's own CertificateVerify worked
example (transcript hash = 32 bytes of 0x01), extracted programmatically
and independently reconstructed before use. Phase-R verified the
algorithm-allowlist check.

/vreview caught and fixed an over-strict check: this file initially
rejected a zero-length CertificateVerify signature, but RFC 8446 SS4.4.3
declares opaque signature<0..2^16-1> -- zero is syntactically legal,
unlike cert_data<1..2^24-1> and key_exchange<1..2^16-1> (real minimums of
1, correctly enforced elsewhere in this file and in tls13_server_hello.v).
No real implementation ever sends an empty signature, so this wasn't an
active interop break, but it was inconsistent with this file's own
exact-RFC-fidelity approach -- removed, test now asserts acceptance at
that boundary instead.

Deliberately NOT yet built, as its own next step: the actual mbedTLS X.509
chain validation and mbedtls_pk_verify_ext signature verification this
parsed data feeds into.

/vreview: 1 finding, fixed (see above).
Adds net.mbedtls/x509_standalone.v: build_certificate_chain/
verify_certificate_chain/free_certificate_chain, standalone (no
mbedtls_ssl_context, same discipline as Phase 0's x509_standalone_test.v).
New public API added to net.mbedtls rather than net.quic reimplementing C
bindings -- matches how net.http's TLS clients already depend on
net.mbedtls instead of duplicating it. net.quic/tls13_certificate_chain.v
wraps this for a ParsedCertificate.

Every C-interop calling convention verified against mbedTLS's actual
vendored source (x509_crt.c), not memory: DER certs need their exact
length, not the +1 NUL-terminator convention this module's PEM helpers
use (a real out-of-bounds read otherwise, though only source-verified,
since mbedTLS's DER parser tolerates a too-long buflen for well-formed
input and no test can observe the difference); mbedtls_x509_crt_parse_der
always copies its input; repeated parse calls on the same chain correctly
append via a walk-to-tail-and-link algorithm (also source-verified only --
no second real test cert exists yet to exercise a genuine multi-cert
chain functionally).

/vreview caught and fixed two real issues: (1)
VerifiedCertificateChain.free() was double-free-prone on a second call --
the exact class of bug SSLConn.shutdown() already guards against with a
documented comment, a sibling that should have been checked first; fixed
with a mut receiver that nulls the pointer after freeing (also only
reasoning-verified, same as above -- a double-free this size doesn't
reliably crash this platform's allocator either way). (2)
verify_certificate_chain's CA-bundle parse check used `< 0`, inconsistent
with every other PEM-parsing call site in net.mbedtls (`!= 0`) -- a real
gap, since mbedtls_x509_crt_parse can return a positive count of certs
that failed to parse within an otherwise-valid bundle; `< 0` would have
silently accepted that. Fixed to `!= 0`.

Also resolves the plan's flagged open question about mbedTLS's PSS
salt-length semantics, ahead of building the code that needs it: checked
the vendored mbedtls_config.h -- MBEDTLS_USE_PSA_CRYPTO is disabled, so
mbedtls_pk_verify_ext's "salt length not verified under PSA crypto" caveat
doesn't apply here. No rsa_pss module fallback needed.

Deliberately not yet built: the mbedtls_pk_verify_ext CertificateVerify
signature verification itself (needs a small C shim to safely extract the
leaf cert's embedded public key, following the established
mbedtls_helpers.h pattern), and CertificateRequest rejection.

/vreview: 2 findings, both fixed (see above).
…cation

Adds mbedtls_pk_verify_ext-based signature checking, completing the last
unbuilt piece of Certificate/CertificateVerify handling before the client
state machine. net.mbedtls gains get_leaf_public_key/verify_ecdsa_signature/
verify_rsa_pss_signature (x509_standalone.v) plus a v_mbedtls_x509_crt_get_pk
C shim (mbedtls_helpers.h) to safely extract a parsed cert's embedded public
key. net.quic's VerifiedCertificateChain gains
verify_certificate_verify_signature, dispatching CertificateVerify's
algorithm to the matching digest and feeding
certificate_verify_signed_content's already-tested RFC 8446 §4.4.3
construction.

RSA-PSS salt length is pinned to the exact digest length per RFC 8446
§4.2.3, confirmed real (not a PSA-crypto no-op) by reading rsa.c and
cross-checked against mbedTLS's own TLS 1.3 code doing the identical thing.
Tested with a genuine RSA-PSS sign+verify round trip using the repo's
existing self-signed test cert's matching private key (real cryptography,
not just reasoning about C-binding correctness); no EC key exists anywhere
in this repo, so ECDSA is tested only via rejecting an incompatible key
type, documented as an honest coverage gap.

/vreview caught and fixed a real bug: calling
verify_certificate_verify_signature on an already-freed chain dereferenced
a garbage near-null pointer (UB) instead of erroring cleanly. Phase-R
confirmed a real, reliable segfault via an isolated probe before fixing;
closed with a nil guard and a permanent regression test.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Adds Tls13ClientHandshake, wiring ClientHello construction through the
client's own Finished message: process_server_hello (real ECDHE + Handshake
secret derivation, handling both ServerHello and HelloRetryRequest),
process_encrypted_extensions (transport-parameter extraction +
initial_source_connection_id cross-check), process_certificate_or_request
(chain verification, CertificateRequest rejection), process_certificate_verify
(signature check against the transcript checkpoint Certificate left behind),
and process_finished (server Finished verification, Application secret
derivation, client's own Finished). TlsAlert + tls_alert_to_quic_error
implement RFC 9001 §4.8's alert-to-CONNECTION_CLOSE mapping; every fatal
path carries the mapped code via error_with_code.

Second-HelloRetryRequest rejection is implemented; a first HRR is reported
as explicitly not-yet-implemented rather than half-built, since it needs a
cookie extension build_client_hello doesn't speak yet.

Tested end-to-end with a genuine fake TLS 1.3 server: real ECDHE, real
RSA-PSS CertificateVerify signing, real Finished HMACs computed
independently and cross-checked against the client's own output — both
sides agreeing, not just "didn't crash". Certificate chain trust itself
isn't exercised end-to-end (no CA-flagged test cert exists in this repo,
same gap as Phase 2c part 6); one test asserts the expected propagated
failure, another installs an already-verified chain directly to test the
remaining steps independently.

/vreview caught and fixed two bugs: free() had no idempotency guard, and a
second call double-freed the ephemeral ECDHE key (Phase-R confirmed a real,
reliable crash, unlike this codebase's other double-free discussions);
and certificate_request_context's RFC 8446 §4.4.2 must-be-empty requirement
was parsed but never checked. Both have regression tests confirmed to fail
on the pre-fix code.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Adds vlib/net/quic/testdata/tls13_vectors/: a real QUIC+TLS 1.3 handshake
captured from Cloudflare quiche (cloudflare/quiche-qns, pinned by digest
via quic-interop-runner's published image reference), running client +
server + tcpdump in Docker with SSLKEYLOGFILE set (undocumented but
functional for quiche, confirmed empirically). Decrypted and dissected
with tshark 4.6.6 using the keylog; extract_handshake.py reconstructs each
handshake message's exact raw bytes from tshark's PDML tree, cross-checked
against tshark's own independently-reported size for every message before
being trusted (this caught two real bugs in the extraction script itself,
documented in the README).

tls13_quiche_vector_test.v parses every real captured message with this
module's own production functions and validates exactly what a standard
keylog capture can prove: message parsing against an independent
implementation's real wire bytes; a real ECDSA P-256 CertificateVerify
signature verifying successfully (closing the gap Phase 2c's own signature
work documented — no EC private key exists anywhere in this repo, so
x509_standalone_signature_test.v could only exercise ECDSA rejection,
never a genuine accepted signature); and both directions' real Finished
MACs using the keylog's real traffic secrets. Documents honestly what
this capture does NOT prove (the Early/Handshake Secret HKDF chain itself,
which needs the raw ECDHE shared secret a standard keylog doesn't export —
already covered separately via RFC 8448's worked values).

Directory structure follows this repo's own crypto/blake2b/testdata/
convention rather than inventing a new one.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Implements RFC 9001 §5: QuicPacketProtectionKeys derivation, AEAD
encrypt/decrypt with a full-packet-number nonce, and combined
protect_packet/unprotect_packet helpers that hard-code the correct
encrypt-then-sample-then-mask ordering.

/vreview found and fixed two gaps: unprotect_header was missing the
RFC 9000 §17.2/§17.3.1 Reserved Bits validation, and
packet_protection_nonce indexed its iv parameter with no length
check (unlike the sibling hp_key check on the same struct), risking
a panic instead of a clean error. Both have regression tests.

Includes a known-answer test against a real Client Initial packet
extracted directly from the same quiche pcap capture Phase 2c used.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Adds frame.v (PADDING/PING/ACK/CRYPTO/CONNECTION_CLOSE, RFC 9000 §19),
crypto_stream.v (per-level CRYPTO frame reassembly tolerating
out-of-order/overlapping retransmissions, RFC 9000 §19.6), coalesce.v
(datagram splitting via Length-field walking, RFC 9000 §12.2),
retry.v (client-side Retry Integrity Tag, RFC 9001 §5.8, fixed
key/nonce cross-checked against RFC text and quiche's own source),
and version_negotiation.v (RFC 9000 §6.2 client-side handling).

/vreview found and fixed three gaps: split_coalesced_datagram
misread trailing UDP-level padding as a bogus packet (neither
parse_long_header nor parse_short_header validated the Fixed Bit,
header.v now does); parse_ack_frame sized an allocation off an
unvalidated attacker-controlled ack_range_count (DoS vector); and
CryptoStreamReassembler had no cap on the number of out-of-order
fragments a peer could accumulate. All three have regression tests,
Phase-R-verified against the pre-fix code.

Includes a capstone integration test tying Phases 2+3+4 together:
a real ClientHello, framed, protected, "transmitted" over an
in-memory buffer, and fully reversed back to the original bytes.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Adds packet_number_space.v (three independent packet number spaces,
Initial/Handshake/Application Data, RFC 9000 §12.3), handshake_confirm.v
(complete vs. confirmed checkpoints and their independent key-discard
triggers, RFC 9001 §4.1.2/§4.9), and key_update.v (1-RTT key phase
rotation, receive side, RFC 9001 §6).

/vreview found and fixed one gap: note_successful_decrypt trusted
resolve-time is_new_update/is_previous_phase flags that go stale if a
caller resolves more than one packet before committing either (e.g.
two packets from the same coalesced datagram) — a second commit could
re-promote an already-current phase as a second genuine update,
permanently desynchronizing decryption. Fixed by re-deriving the
classification fresh from the packet's real phase bit against current
state at commit time. Has a regression test, Phase-R-verified against
the pre-fix code.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Extends frame.v with all stream-related frames (STREAM, RESET_STREAM,
STOP_SENDING, MAX_DATA, MAX_STREAM_DATA, MAX_STREAMS, DATA_BLOCKED,
STREAM_DATA_BLOCKED, STREAMS_BLOCKED). Adds stream.v (stream ID
categories, send/recv state machines, QuicStreamSet), stream_reassembly.v
(per-stream offset-ordered reassembly with final-size reconciliation,
mirroring Phase 4's crypto_stream.v), and flow_control.v (connection-
and stream-level windows, the RFC 9000 §4.1 initial-limit naming
inversion resolved in one place).

/vreview found and fixed a real design footgun: QuicStream.send/recv
were Optional value fields, so mutating the unwrapped copy via
note_data()/note_size_known() silently didn't persist unless the
caller remembered to reassign it back. Fixed by switching to nilable
pointers (matching Tls13ClientHandshake.verified_chain's established
convention) before any real caller could hit it. Also fixed two
mechanical V-compiler quirks: match on a repeated array-index
expression stops reliably narrowing a sum type past a certain variant
count (affected two pre-existing tests too), and a stale "type 0x08
unimplemented" test now that Phase 6 implements STREAM frames there.

Includes the plan's own named integration test: three interleaved
streams (client bidi, server-initiated uni, second client bidi) with
connection-level flow control tracked across all three.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Implements RFC 9002's loss detection and congestion control as a
self-contained, directly unit-testable algorithmic core (no event loop
wiring yet — that's Phase 9's QuicConn job):

- rtt.v: RttEstimator (RFC 9002 §5.3) — distinct first-sample-seeds vs.
  subsequent-sample-EWMA formulas, ACK Delay unconditionally ignored for
  Initial/Handshake spaces, max_ack_delay clamp gated on handshake
  confirmation, and the ack_delay-never-pushes-below-min_rtt guard.
- loss_detection.v: QuicLossDetectionTimer — three independent per-space
  LossDetectionSpaceState (packet numbering is per-space, RFC 9000 §12.3)
  plus a single connection-wide RTT estimator/pto_count/PTO timer, sourced
  from whichever space's own deadline is earliest (pto_time_and_space) —
  the PTO timer is deliberately NOT per-space, the opposite mistake from
  treating packet numbers as connection-global. Packet-threshold OR
  time-threshold loss detection (RFC 9002 §6.1), persistent-congestion
  detection (§7.6.2).
- congestion_control.v: NewRenoCongestionControl (RFC 9002 Appendix B) —
  slow start / congestion avoidance, ordinary-loss ssthresh halving, a
  distinctly harsher persistent-congestion collapse, single-reaction-per-
  recovery-episode via in_congestion_recovery.

/vreview (full A-G pass) found and fixed two issues before this commit:
(1) is_in_slow_start() shortcut to `ssthresh == none` instead of RFC
9002's actual `congestion_window < ssthresh` — these diverge after a
persistent-congestion collapse, which resets cwnd to kMinimumWindow while
leaving the larger ssthresh untouched, so cwnd can legitimately fall back
below an already-set ssthresh and must re-enter slow start. (2) A real
DoS: on_ack_received iterated each ACK range's [smallest, largest] span
directly, but largest_acknowledged/first_ack_range are independent wire
varints (RFC 9000 §19.3) — a tiny, well-formed ACK frame can legally claim
a range spanning up to 2^62-1 packet numbers with no relationship to the
frame's own wire size. Fixed by iterating sent_packets (bounded by what
we actually have outstanding) and testing range membership instead;
regression test constructs a 2^62-spanning range and confirms the call
still completes and resolves correctly.

31/31 net.quic test files pass under ./vnew.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Implements RFC 9000's connection-lifecycle mechanics as self-contained,
directly unit-testable state:

- idle_timeout.v: effective_idle_timeout resolves §10.1's min-of-non-zero
  rule across all 4 zero/non-zero combinations (0 means "no timeout", not
  literally zero). IdleTimeoutState tracks the asymmetric reset rule: an
  ack-eliciting RECEIVE restarts it, a non-ack-eliciting receive does not,
  but ANY send does.
- connection_close.v: ConnectionCloseTracker — active -> closing (may
  still send a rate-limited CONNECTION_CLOSE retransmission, §10.2.1) ->
  draining (received the peer's CONNECTION_CLOSE; MUST NOT send anything
  at all, §10.2.2, a one-way absorbing state).
- stateless_reset.v: StatelessResetTracker records tokens keyed by
  connection ID; is_stateless_reset is documented as callable only after
  normal AEAD decryption has already failed (§10.3.1 — never a
  first-choice interpretation), comparing the trailing 16 bytes via
  crypto.internal.subtle's constant-time compare.
- ecn.v: EcnState parses/records a peer's reported ECN counts without
  erroring, but is_validated() always reports false in v1 — no OS-level
  ECN socket option exists in V today, a spec-legal fallback (§13.4.2).
- pmtu.v: pinned to the existing 1200-byte safe minimum (reusing
  congestion_control.v's max_datagram_size), no active DPLPMTUD probing.

/vreview (full A-G pass) found and fixed one issue before this commit: a
real integer-overflow bug. max_idle_timeout is a peer-supplied transport-
parameter varint with no upper bound of its own (transport_parameters.v
accepts up to the full 2^62-1 range) — effective_idle_timeout originally
multiplied it directly by time.millisecond, overflowing the i64 backing
time.Duration for any peer value above ~9.2 trillion ms, silently
producing a nonsensical (possibly negative) timeout. Fixed by clamping to
the exact mathematically-necessary bound (derived from time.infinite)
before scaling; regression test feeds the maximum QUIC varint (2^62-1)
through both paths and confirms a large-but-finite, strictly positive
Duration comes back.

36/36 net.quic test files pass under ./vnew.

Co-Authored-By: WOZCODE <contact@withwoz.com>
parse_version_negotiation (header.v) and find_extension
(tls13_server_hello.v) were flagging CI's report-missing-fn-doc check on
PR vlang#27680. No behavior change -- doc comments only.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Root cause of PR vlang#27680's msvc-windows/tcc-windows CI failures: both jobs
run on windows-2022, unlike gcc-windows (windows-2025), and windows-2022
does not ship the OpenSSL-Win64 dev package that vlib/crypto/ecdsa/
ecdsa.c.v and vlib/crypto/rsa_pss/rsa_pss.c.v already expect via their
hardcoded #flag windows search paths -- confirmed via CI logs:
  - msvc-windows: `LINK : fatal error LNK1104: cannot open file
    'crypto.lib'` (no import library to link against)
  - tcc-windows: exit code -1073741515 (STATUS_DLL_NOT_FOUND) at runtime
    (TCC's linker is more lenient and produces an exe, but the DLL isn't
    discoverable at runtime)
Every net.quic test file fails as a side effect, since the module
transitively imports crypto.ecdsa/crypto.rsa_pss for the QUIC handshake's
ECDHE key exchange.

Fix: install OpenSSL via choco (which lands at the exact
C:/Program Files/OpenSSL-Win64 path ecdsa.c.v/rsa_pss.c.v already check)
in both jobs, and add its bin/ directory to PATH so the runtime DLL is
discoverable too -- addressing both the MSVC link-time and TCC run-time
failure modes with one step. No application code changes.

Co-Authored-By: WOZCODE <contact@withwoz.com>
quaesitor-scientiam and others added 11 commits July 21, 2026 00:40
The previous commit (3524f88) guessed the choco openssl package
deploys to C:\Program Files\OpenSSL-Win64\ -- confirmed wrong by the
actual CI run: choco's log shows "Deployed to 'C:\Program Files\OpenSSL\'"
(no -Win64 suffix), which is the SECOND of ecdsa.c.v/rsa_pss.c.v's two
hardcoded #flag windows fallback paths, not the first. Point the
verification/PATH-append step at the path choco actually uses.

Co-Authored-By: WOZCODE <contact@withwoz.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant