// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The HPACK encoder, which never inserts into a dynamic table — by //! construction, because there is no table here to insert into. //! //! That is fully conformant. RFC 7541 §2.3.3 lets an encoder use the static //! table alone, and a decoder that is never sent a literal-with-incremental- //! indexing never grows a table to keep in step. What it buys is two things. //! //! The obvious one is that the entire class of eviction bugs cannot happen on //! the send side. The subtler one is that this type holds no state that has //! to survive a failed write: an encoder with a dynamic table that half-wrote //! a field section has a table the peer does not agree with, and the only //! cure for that is a new connection. //! //! What it costs is octets. A `server` or a `content-type` that is the same //! on every response is re-sent each time rather than becoming a one-octet //! index. Static indexing and Huffman coding still carry most of the win — a //! `:status: 200` is one octet either way — and the trade is deliberate. //! //! It allocates nothing and cannot fail except through the writer, which is //! what lets a field section be encoded outside the connection's write lock //! and in any order. const std = @import("std"); const protocol = @import("../../protocol.zig"); const Field = protocol.Field; const token = protocol.token; const hpack = @import("../hpack.zig"); const table = @import("table.zig"); const Writer = std.Io.Writer; const Encoder = @This(); /// A dynamic table size update this owes the peer, if any. /// /// The peer's `SETTINGS_HEADER_TABLE_SIZE` governs *our* table, and RFC 7541 /// §4.2 requires a change to be signalled at the start of the next field /// section. Since our table is permanently empty the value signalled is /// always zero — legal against any limit the peer could set, one octet, and /// it tells the peer's decoder it may free its copy. pending_size_update: ?u32 = 0, /// Names whose values are never put in any table — ours, which has none, and /// any intermediary's, which is what the never-indexed representation of /// §6.2.3 actually protects. §7.1.3 is the reasoning: a value an attacker can /// influence, sharing a compression context with a secret, is how the secret /// is recovered a byte at a time. sensitive: []const []const u8 = &.{ "authorization", "proxy-authorization", "cookie", "set-cookie", }, /// Called when the peer's SETTINGS arrives. Re-arms the size update, because /// a change to the limit is exactly what §4.2 requires to be signalled. /// /// `n` itself is not needed: the update signalled is always to zero, which /// is within any limit the peer could have set. pub fn setPeerTableSize(e: *Encoder, n: u32) void { _ = n; e.pending_size_update = 0; } test setPeerTableSize { var buffer: [8]u8 = undefined; var e: Encoder = .{ .pending_size_update = null }; e.setPeerTableSize(8192); var w: Writer = .fixed(&buffer); try e.encode(&w, &.{}); // A size update to zero, whatever the peer's new limit. try testing.expectEqualSlices(u8, &.{0x20}, w.buffered()); } /// Writes a whole field section, led by any dynamic table size update still /// owed to the peer. pub fn encode(e: *Encoder, out: *Writer, fields: []const Field) Writer.Error!void { if (e.pending_size_update) |size| { // §6.3, `001xxxxx`. Must come before any field in the section. try hpack.writeInt(out, 5, 0x20, size); e.pending_size_update = null; } for (fields) |f| try e.field(out, f.name, f.value); } test encode { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); var e: Encoder = .{}; try e.encode(&w, &.{ .{ .name = ":method", .value = "GET" }, .{ .name = ":path", .value = "/" }, }); // The size update the first section owes, then two static-table indices. try testing.expectEqualSlices(u8, &.{ 0x20, 0x82, 0x84 }, w.buffered()); } /// Writes one field. /// /// Names are folded to lower case on the way out, which RFC 9113 §8.2.1 /// requires and which `protocol.Headers` deliberately does not do — it keeps /// the spelling the handler used. The fold happens inside `writeString`, the /// last thing that touches the octets and the only place that can do it /// without a buffer. /// /// It does not write `pending_size_update`, which only `encode` does: a /// section assembled field by field with this alone leaves that owed. pub fn field(e: *Encoder, out: *Writer, name: []const u8, value: []const u8) Writer.Error!void { if (e.isSensitive(name)) { // §6.2.3, literal never indexed: `0001xxxx`. return e.literal(out, 0x10, name, value); } if (table.findStatic(name, value)) |index| { // §6.1, indexed field: `1xxxxxxx`. One octet for the whole field. return hpack.writeInt(out, 7, 0x80, index); } // §6.2.2, literal without indexing: `0000xxxx`. return e.literal(out, 0x00, name, value); } test field { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); var e: Encoder = .{}; try e.field(&w, ":status", "200"); try testing.expectEqualSlices(u8, &.{0x88}, w.buffered()); // A field never writes the pending size update; only `encode` does. try testing.expectEqual(@as(?u32, 0), e.pending_size_update); } fn literal(e: *Encoder, out: *Writer, high_bits: u8, name: []const u8, value: []const u8) Writer.Error!void { _ = e; if (table.findStaticName(name)) |index| { try hpack.writeInt(out, 4, high_bits, index); } else { try hpack.writeInt(out, 4, high_bits, 0); try hpack.writeString(out, name, true); } try hpack.writeString(out, value, false); } fn isSensitive(e: *const Encoder, name: []const u8) bool { for (e.sensitive) |s| { if (token.eqlIgnoreCase(s, name)) return true; } return false; } const testing = std.testing; fn roundTrip(fields: []const Field) !void { const gpa = testing.allocator; var buffer: [4096]u8 = undefined; var w: Writer = .fixed(&buffer); var encoder: Encoder = .{}; try encoder.encode(&w, fields); var scratch: [4096]u8 = undefined; var decoder: hpack.Decoder = .init(4096, &scratch, .{}); defer decoder.deinit(gpa); var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); var got: std.ArrayList(Field) = .empty; try decoder.decode(gpa, arena_state.allocator(), buffer[0..w.end], &got); try testing.expectEqual(fields.len, got.items.len); for (fields, got.items) |want, have| { // Names come back folded, which is not a loss: RFC 9113 §8.2.1 // requires it on the wire. var folded: [128]u8 = undefined; const lower = std.ascii.lowerString(folded[0..want.name.len], want.name); try testing.expectEqualStrings(lower, have.name); try testing.expectEqualStrings(want.value, have.value); } } test "what this encoder and the decoder say to each other" { try roundTrip(&.{}); try roundTrip(&.{.{ .name = ":status", .value = "200" }}); try roundTrip(&.{ .{ .name = ":status", .value = "404" }, .{ .name = "content-type", .value = "text/plain; charset=utf-8" }, .{ .name = "content-length", .value = "13" }, }); // The mixed-case spelling the library itself produces, in `sendStatus` // and `redirect`. try roundTrip(&.{ .{ .name = "Content-Type", .value = "text/plain" }, .{ .name = "Location", .value = "/elsewhere" }, }); // A name in no table at all, and an empty value. try roundTrip(&.{ .{ .name = "x-made-up-entirely", .value = "" }, .{ .name = "x-another", .value = "and a value with spaces" }, }); // Values that Huffman coding does not shrink. try roundTrip(&.{.{ .name = "x-binary", .value = "\x00\x01\x02\xfe\xff" }}); } test "a field in the static table costs one octet" { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); var encoder: Encoder = .{ .pending_size_update = null }; try encoder.field(&w, ":method", "GET"); // RFC 7541 C.2.4 writes exactly this for `:method: GET`. try testing.expectEqualSlices(u8, &.{0x82}, buffer[0..w.end]); w = .fixed(&buffer); try encoder.field(&w, ":status", "200"); try testing.expectEqualSlices(u8, &.{0x88}, buffer[0..w.end]); } test "an indexed name and a literal value" { var buffer: [64]u8 = undefined; var w: Writer = .fixed(&buffer); var encoder: Encoder = .{ .pending_size_update = null }; // `:path` is index 4, and `/sample/path` is not a value in the table. RFC // 7541 C.2.2 writes this as `04 0c /sample/path` without Huffman; this // encoder Huffman-codes the value when that is shorter, so the length // differs while the representation does not. try encoder.field(&w, ":path", "/sample/path"); try testing.expectEqual(@as(u8, 0x04), buffer[0]); try testing.expect(buffer[1] & 0x80 != 0); // Huffman } test "a sensitive field is never indexed" { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); var encoder: Encoder = .{ .pending_size_update = null }; try encoder.field(&w, "authorization", "Bearer hunter2"); // `0001xxxx`, the representation that asks every intermediary not to put // this value in a table either. try testing.expectEqual(@as(u8, 0x10), buffer[0] & 0xf0); // And `set-cookie` too, which is in the static table with an empty value // and would otherwise take the indexed-name path. w = .fixed(&buffer); try encoder.field(&w, "Set-Cookie", "a=1"); try testing.expectEqual(@as(u8, 0x10), buffer[0] & 0xf0); } test "the size update comes first, once" { var buffer: [128]u8 = undefined; var w: Writer = .fixed(&buffer); var encoder: Encoder = .{}; try encoder.encode(&w, &.{.{ .name = ":status", .value = "200" }}); // `001` with a five-bit value of zero, then the field. try testing.expectEqualSlices(u8, &.{ 0x20, 0x88 }, buffer[0..w.end]); // Not repeated on the next section. w = .fixed(&buffer); try encoder.encode(&w, &.{.{ .name = ":status", .value = "200" }}); try testing.expectEqualSlices(u8, &.{0x88}, buffer[0..w.end]); // Until the peer changes its mind about the table size. encoder.setPeerTableSize(0); w = .fixed(&buffer); try encoder.encode(&w, &.{.{ .name = ":status", .value = "200" }}); try testing.expectEqualSlices(u8, &.{ 0x20, 0x88 }, buffer[0..w.end]); } test "nothing this encoder writes grows the decoder's table" { // The claim in the module comment, checked: after a hundred sections the // peer's dynamic table is still empty, so there is no eviction for the // two ends to disagree about. const gpa = testing.allocator; var scratch: [4096]u8 = undefined; var decoder: hpack.Decoder = .init(4096, &scratch, .{}); defer decoder.deinit(gpa); var encoder: Encoder = .{}; for (0..100) |i| { var buffer: [256]u8 = undefined; var w: Writer = .fixed(&buffer); var value_buf: [32]u8 = undefined; const value = try std.fmt.bufPrint(&value_buf, "value-{d}", .{i}); try encoder.encode(&w, &.{ .{ .name = ":status", .value = "200" }, .{ .name = "x-counter", .value = value }, }); var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); var got: std.ArrayList(Field) = .empty; try decoder.decode(gpa, arena_state.allocator(), buffer[0..w.end], &got); try testing.expectEqual(@as(u32, 0), decoder.table_.size); } }