Skip to content

h2: HPACK encoder table diverges when an encoded HEADERS block is dropped unsent #1627

Closed

Description

@FlorentinDUBOIS

Found by the adversarial review of #1625 (#1604's ordered output), plus a second path found while fixing #1622. Both paths predate those PRs.

Mechanism

The connection's HPACK encoder changes its dynamic table while it encodes, not when the block reaches the wire. The in-tree encoder's Representation::Proxy encodes an unknown name with incremental indexing (0x40) and calls DynamicTable::insert right away (Encoder::encode_field, lib/src/protocol/mux/hpack/encoder.rs). A dynamic-table-size update is committed to the table in the same way. The encoding happens in kawa.prepare, through H2BlockConverter (lib/src/protocol/mux/converter.rs). The HEADERS/CONTINUATION frames then wait in the stream's kawa.out until a later transmit sends them.

RFC 7541 §4 / RFC 9113 §4.3 make that table connection state: every header block the encoder produced must reach the peer, in order. Two paths drop an encoded block without sending it, and the tables then diverge silently. A later block names a dynamic index that the peer's decoder resolves to another entry, or cannot resolve at all.

Path 1: a removed stream drops its encoded, unsent HEADERS

  1. A stream's response HEADERS is prepared: entries are inserted into the encoder table.
  2. The write that would send it takes 0 bytes, so the stream is parked. The block can also sit behind a DATA frame a partial write cut, for example as trailers.
  3. The stream is removed before its next transmit: a peer RST_STREAM, end_stream, expiry, prune_inactive_streams_while_closing, or any other remove_dead_stream caller. Its kawa.out goes with it.
  4. The next stream's HEADERS indexes the entries the dropped block inserted.

#1625 does not change this. Its ordered output only keeps the frames the wire has already started, and a block that has not started is dropped whole. That is harmless for framing, but it is still an HPACK side effect. #1625's LIFECYCLE.md invariant 28 and h2_output.rs module doc say so explicitly.

Path 2: an oversized header block is discarded after encoding

H2BlockConverter::check_header_capacity (converter.rs) clears self.out when it exceeds MAX_HEADER_LIST_SIZE, and the stream is aborted with a RST. By then the size-update prefix and the incremental-indexing insertions of the fields already encoded have changed the encoder table. The peer never sees any of it.

Reproduction (path 1)

Measured red on main at 771c9e90 on 2026-09-27, and on #1625's branch. The test goes in lib/src/protocol/mux/h2.rs's tests module and uses the PacedSocket fixture from #1601. It is not committed.

  • Two requests are read.
  • A 404 default answer is set on both.
  • A writable() runs with a socket that takes 0 bytes: stream 1's HEADERS is encoded and parked.
  • A peer RST_STREAM(1) is read, which removes stream 1.
  • The socket is unthrottled and the connection driven.

The peer's single decoder then fails on stream 3's block:

assertion `left == right` failed: the peer must decode stream 3's block with its own table
  left: [(3, false)]
 right: [(3, true)]
#[test]
fn hpack_repro_unsent_headers_block_dropped_on_removal() {
    let pool = make_pool_for_invariant_16();
    let (socket, _peer) = connected_socket();
    let mut connection = H2Shell::new(
        Ulid::generate(),
        PacedSocket { stream: socket, budget: 0, wire: Vec::new(), inbound: std::collections::VecDeque::new() },
        Position::Server,
        &mut PoolBufferSource::new(Rc::downgrade(&pool)),
        H2FloodConfig::default(), H2ConnectionConfig::default(),
        Duration::from_secs(30), None, Duration::from_secs(30),
        Some((H2StreamId::Zero, 9)),
        Ready::READABLE | Ready::WRITABLE | Ready::HUP | Ready::ERROR,
    ).expect("pool");
    connection.core.state = H2State::Header;
    let mut context = test_context(&pool);
    let mut router = Router::new(Duration::from_secs(30), Duration::from_secs(30));
    let mut peer_encoder = crate::protocol::mux::hpack::Encoder::new();
    for stream_id in [1u32, 3] {
        let block = peer_encoder.encode([
            (&b":method"[..], &b"GET"[..]), (&b":scheme"[..], &b"https"[..]),
            (&b":authority"[..], &b"example.com"[..]), (&b":path"[..], &b"/repro"[..]),
        ]);
        let mut frame = (block.len() as u32).to_be_bytes()[1..].to_vec();
        frame.push(1);
        frame.push(parser::FLAG_END_STREAM | parser::FLAG_END_HEADERS);
        frame.extend_from_slice(&stream_id.to_be_bytes());
        frame.extend_from_slice(&block);
        connection.socket.inbound.extend(frame);
    }
    for _ in 0..8 {
        connection.core.readiness.event.insert(Ready::READABLE);
        connection.readable(&mut context, EndpointClient(&mut router));
    }
    let answers = context.listener.borrow().get_answers().clone();
    let open: Vec<GlobalStreamId> = connection.core.stream_table.streams().values().copied().collect();
    for gid in open {
        crate::protocol::mux::answers::set_default_answer(
            &mut context.streams[gid], &mut connection.core.readiness, 404, &answers.borrow());
    }
    connection.core.readiness.event.insert(Ready::WRITABLE);
    connection.writable(&mut context, EndpointClient(&mut router)); // stream 1 encoded, 0 bytes sent
    connection.socket.inbound.extend(b"\x00\x00\x04\x03\x00\x00\x00\x00\x01\x00\x00\x00\x08"); // RST_STREAM(1)
    for _ in 0..4 {
        connection.core.readiness.event.insert(Ready::READABLE);
        connection.readable(&mut context, EndpointClient(&mut router));
    }
    connection.socket.budget = usize::MAX;
    for _ in 0..16 {
        connection.core.readiness.event.insert(Ready::WRITABLE);
        if connection.core.readiness.filter_interest().is_writable() {
            connection.writable(&mut context, EndpointClient(&mut router));
        }
        connection.core.readiness.event.insert(Ready::READABLE);
        if connection.core.readiness.filter_interest().is_readable() {
            connection.readable(&mut context, EndpointClient(&mut router));
        }
    }
    let mut decoder = crate::protocol::mux::hpack::Decoder::new();
    let mut seen = Vec::new();
    for (kind, _, stream_id, payload) in peer_frames(&connection.socket.wire).unwrap() {
        if kind == 1 {
            seen.push((stream_id, decoder.decode_with_cb(&payload, |_, _| {}).is_ok()));
        }
    }
    assert_eq!(seen, vec![(3, true)], "the peer must decode stream 3's block with its own table");
}

Path 2 has no reproduction yet. It needs a response whose encoded block exceeds MAX_HEADER_LIST_SIZE after it has inserted at least one entry, followed by a second response that indexes that entry.

Options

  1. Encode at send time, as HAProxy (h2s_snd_fhdrs, straight into mbuf) and h2 (FramedWrite::buffer, which encodes a Frame::Headers into its output buffer when it is buffered for the wire) both do. The table only changes for a block that is committed. This is structural, but it moves HPACK encoding out of kawa.prepare in converter.rs.
  2. Commit an encoded block regardless of its stream. When a stream with encoded, unsent HEADERS/CONTINUATION frames is removed, have the connection's ordered output queue (fix(mux-h2): send every committed frame whole through one ordered output queue #1625's H2Output) adopt them, so they still reach the peer. The peer then receives HEADERS on a closed stream, which RFC 9113 §5.1 lets it ignore while still processing it for HPACK (§4.3), as HAProxy does for a refused stream's field block. Path 2 would need the aborted block's representations re-emitted, or its insertions reverted.
  3. Encode without indexing for blocks that may be dropped. This avoids the side effect, at the cost of compression.

Option 1 fixes both paths at once. Option 2 is local to the removal path.

Activity

  1. FlorentinDUBOIS commented on Sep 28, 2026

    @FlorentinDUBOIS
    CollaboratorAuthor

    Scope correction: Router, and with it every backend connection in Router::backends, belongs to a single Mux session (field Mux::router, lib/src/protocol/mux/mod.rs). An H2 backend connection is therefore shared only by the streams of one frontend connection, never between distinct client TCP connections. Any cross-user impact requires an intermediary (a CDN or load balancer, for example) that multiplexes several users over one frontend connection to sozu.

    For this issue: the field substitution is still real within that session. A block dropped on one stream shifts the peer's dynamic table for every later block on the same connection, so a later stream of the same frontend connection can silently decode another stream's fields: between two requests of the same client, or between two users behind the same intermediary.

  2. added a commit that references this issue on Sep 28, 2026
    d516191
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions