cellos-supervisor 0.5.1

CellOS execution-cell runner — boots cells in Firecracker microVMs or gVisor, enforces narrow typed authority, emits signed CloudEvents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! HPACK decoder — stateful per-connection.
//!
//! Phase 3g extends P3c's stateless one-shot decoder to a full HPACK
//! decoder with:
//!
//! 1. Dynamic table state (RFC 7541 §4.1, §4.2, §4.4).
//! 2. Huffman literal decoding (RFC 7541 §5.2 + Appendix B).
//! 3. CONTINUATION-fragmented header block reassembly (driven by the
//!    parent `h2` module — the decoder itself works on already-reassembled
//!    blocks).
//!
//! The public surface is a single struct [`HpackDecoder`] whose
//! [`HpackDecoder::decode_block`] consumes a whole header-block fragment
//! (the concatenation of HEADERS + 0..n CONTINUATION payloads, padding +
//! priority already stripped by the frame layer) and returns the
//! `:authority` if one was found.

pub mod dynamic_table;
pub mod huffman;
pub mod integer;
pub mod static_table;
pub mod string;

use super::error::H2ParseError;
use dynamic_table::DynamicTable;
use integer::decode_integer;
use static_table::{STATIC_INDEX_AUTHORITY, STATIC_TABLE_MAX};
use string::decode_string;

/// RFC 7540 §6.5.2 default `SETTINGS_HEADER_TABLE_SIZE`.
pub const DEFAULT_HEADER_TABLE_SIZE: usize = 4096;

/// Stateful HPACK decoder with a per-connection dynamic table.
///
/// The same instance is fed all header-block fragments seen on a single
/// h2c connection — both intra-frame (CONTINUATION reassembly) AND
/// inter-stream (different request HEADERS on the same connection share
/// the same dynamic table per RFC 7541 §2.3.1).
pub struct HpackDecoder {
    dynamic_table: DynamicTable,
}

impl Default for HpackDecoder {
    fn default() -> Self {
        Self::new()
    }
}

impl HpackDecoder {
    /// Construct a fresh decoder with the RFC 7540 default table size.
    pub fn new() -> Self {
        Self {
            // Cannot fail: DEFAULT_HEADER_TABLE_SIZE < MAX_TABLE_SIZE.
            dynamic_table: DynamicTable::new(DEFAULT_HEADER_TABLE_SIZE)
                .expect("default table size is within bound"),
        }
    }

    /// Reset dynamic table to empty (e.g. on connection close — caller
    /// dropping the decoder is equivalent).
    #[allow(dead_code)] // the proxy drops the decoder per connection; provided for API completeness
    pub fn reset(&mut self) {
        self.dynamic_table = DynamicTable::new(DEFAULT_HEADER_TABLE_SIZE)
            .expect("default table size is within bound");
    }

    /// Decode a single header block fragment. Returns the first
    /// `:authority` value found in the block; `Ok(None)` if the block
    /// parsed cleanly but contained no `:authority` (caller emits
    /// `l7_h2_authority_missing`).
    ///
    /// The decoder also returns metadata about *how* the authority was
    /// extracted so the caller can pick the right reason code:
    /// [`AuthorityProvenance`].
    pub fn decode_block(&mut self, block: &[u8]) -> Result<Option<DecodedAuthority>, H2ParseError> {
        let mut cursor = block;
        let mut found: Option<DecodedAuthority> = None;

        while !cursor.is_empty() {
            let first = cursor[0];

            if first & 0b1000_0000 != 0 {
                // 1xxxxxxx — Indexed Header Field (RFC 7541 §6.1).
                let (index, rest) = decode_integer(cursor, 7)?;
                cursor = rest;
                let (name, value) = self
                    .dynamic_table
                    .lookup(index)
                    .ok_or(H2ParseError::HpackInvalidIndex { index })?;
                if found.is_none() && eq_authority(name.as_bytes()) && !value.is_empty() {
                    let provenance = if index <= STATIC_TABLE_MAX {
                        // Static index 1's value is empty (handled above);
                        // any other static index that matches `:authority`
                        // by name doesn't exist (only row 1 names it). So
                        // a non-empty value here means the encoder used a
                        // name-only static reference + value — but
                        // Indexed-Header-Field carries no separate value.
                        // Practically unreachable; classify as static.
                        AuthorityProvenance::StaticIndexed
                    } else {
                        AuthorityProvenance::DynamicIndexed
                    };
                    found = Some(DecodedAuthority {
                        value: normalise_authority(value.as_bytes()),
                        provenance,
                    });
                }
                continue;
            }

            if first & 0b1100_0000 == 0b0100_0000 {
                // 01xxxxxx — Literal Header Field with Incremental Indexing
                // (RFC 7541 §6.2.1). Adds an entry to the dynamic table.
                let (name, value, name_index, value_was_huffman, after) =
                    self.parse_literal(cursor, 6)?;
                cursor = after;
                let is_authority = if name_index == 0 {
                    eq_authority(name.as_bytes())
                } else {
                    name_index == STATIC_INDEX_AUTHORITY
                        || self
                            .dynamic_table
                            .lookup(name_index)
                            .map(|(n, _)| eq_authority(n.as_bytes()))
                            .unwrap_or(false)
                };
                if found.is_none() && is_authority && !value.is_empty() {
                    let provenance = match (name_index, value_was_huffman) {
                        (_, true) => AuthorityProvenance::Huffman,
                        (0, false) => AuthorityProvenance::StaticLiteral,
                        (i, false) if i <= STATIC_TABLE_MAX => AuthorityProvenance::StaticLiteral,
                        (_, false) => AuthorityProvenance::DynamicIndexed,
                    };
                    found = Some(DecodedAuthority {
                        value: normalise_authority(value.as_bytes()),
                        provenance,
                    });
                }
                // Insert into dynamic table per §6.2.1.
                let stored_name = if name_index == 0 {
                    name
                } else {
                    self.dynamic_table
                        .lookup(name_index)
                        .ok_or(H2ParseError::HpackInvalidIndex { index: name_index })?
                        .0
                        .to_string()
                };
                self.dynamic_table.insert(stored_name, value);
                continue;
            }

            if first & 0b1111_0000 == 0b0000_0000 || first & 0b1111_0000 == 0b0001_0000 {
                // 0000xxxx — Literal Header Field without Indexing (§6.2.2)
                // 0001xxxx — Literal Header Field Never Indexed     (§6.2.3)
                let (name, value, name_index, value_was_huffman, after) =
                    self.parse_literal(cursor, 4)?;
                cursor = after;
                let is_authority = if name_index == 0 {
                    eq_authority(name.as_bytes())
                } else {
                    name_index == STATIC_INDEX_AUTHORITY
                        || self
                            .dynamic_table
                            .lookup(name_index)
                            .map(|(n, _)| eq_authority(n.as_bytes()))
                            .unwrap_or(false)
                };
                if found.is_none() && is_authority && !value.is_empty() {
                    let provenance = if value_was_huffman {
                        AuthorityProvenance::Huffman
                    } else if name_index == 0 || name_index <= STATIC_TABLE_MAX {
                        AuthorityProvenance::StaticLiteral
                    } else {
                        AuthorityProvenance::DynamicIndexed
                    };
                    found = Some(DecodedAuthority {
                        value: normalise_authority(value.as_bytes()),
                        provenance,
                    });
                }
                // No table mutation for §6.2.2 / §6.2.3.
                continue;
            }

            if first & 0b1110_0000 == 0b0010_0000 {
                // 001xxxxx — Dynamic Table Size Update (RFC 7541 §6.3).
                let (new_max, rest) = decode_integer(cursor, 5)?;
                cursor = rest;
                let new_max_usize =
                    usize::try_from(new_max).map_err(|_| H2ParseError::MalformedHeaders)?;
                self.dynamic_table.update_max_size(new_max_usize)?;
                continue;
            }

            // Unrecognised top-bit pattern.
            return Err(H2ParseError::MalformedHeaders);
        }

        Ok(found)
    }

    /// Parse a literal header field (representation classes §6.2.1, §6.2.2,
    /// §6.2.3). `prefix_bits` is 6 (incremental-indexing) or 4 (no-indexing
    /// / never-indexed). Returns the literal name (string — empty if
    /// referenced by index), value, name-reference index (0 = literal),
    /// whether the value was Huffman-coded, and the slice after.
    fn parse_literal<'a>(
        &mut self,
        buf: &'a [u8],
        prefix_bits: u32,
    ) -> Result<(String, String, u64, bool, &'a [u8]), H2ParseError> {
        let (name_index, rest) = decode_integer(buf, prefix_bits)?;
        let (name, after_name) = if name_index == 0 {
            let (n, r) = decode_string(rest)?;
            (n, r)
        } else {
            (String::new(), rest)
        };
        let value_was_huffman = !after_name.is_empty() && (after_name[0] & 0x80) != 0;
        let (value, after_value) = decode_string(after_name)?;
        Ok((name, value, name_index, value_was_huffman, after_value))
    }
}

/// Where the `:authority` value came from. Drives the proxy's reason-code
/// selection so the audit trail differentiates static-table refs (P3c
/// behaviour, attacker simplicity), dynamic-table refs (Phase 3g — adversary
/// must establish prior context), and Huffman literals (Phase 3g — adversary
/// uses encoder-side compression).
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum AuthorityProvenance {
    /// Decoded from a static-table index reference (HPACK indexed-header
    /// representation pointing at index ≤ 61). Same path P3c covered.
    StaticIndexed,
    /// Decoded from a literal whose value was a raw (non-Huffman) octet
    /// string AND whose name was either literal or referenced the static
    /// table. Same path P3c covered.
    StaticLiteral,
    /// Decoded from a dynamic-table indexed reference (HPACK index ≥ 62)
    /// OR a literal whose name pointed at the dynamic table. Phase 3g
    /// extension — required prior incremental-indexing entries to populate
    /// the dynamic table.
    DynamicIndexed,
    /// Decoded from a literal whose value was Huffman-coded. Phase 3g
    /// extension — required RFC 7541 Appendix B static Huffman code.
    Huffman,
}

/// `:authority` extracted from a header block, with provenance metadata.
#[derive(Debug, Clone)]
pub struct DecodedAuthority {
    pub value: String,
    pub provenance: AuthorityProvenance,
}

/// Case-insensitive `:authority` match.
fn eq_authority(name: &[u8]) -> bool {
    if name.len() != b":authority".len() {
        return false;
    }
    name.iter()
        .zip(b":authority".iter())
        .all(|(a, b)| a.eq_ignore_ascii_case(b))
}

/// Produce the canonical RFC 3986 host form of an `:authority` value:
/// strip the optional `:port` suffix (preserving IPv6 brackets), strip a
/// trailing dot, and lowercase. Mirrors `http::normalise_host_value` so
/// the allowlist matcher sees the same shape across protocols.
pub(crate) fn normalise_authority(raw: &[u8]) -> String {
    let trimmed = trim_ascii(raw);
    let host = if trimmed.first() == Some(&b'[') {
        if let Some(close) = trimmed.iter().position(|&b| b == b']') {
            &trimmed[..=close]
        } else {
            trimmed
        }
    } else if let Some(colon) = trimmed.iter().position(|&b| b == b':') {
        &trimmed[..colon]
    } else {
        trimmed
    };
    let mut s = String::from_utf8_lossy(host).to_string();
    s.make_ascii_lowercase();
    if s.ends_with('.') {
        s.pop();
    }
    s
}

fn trim_ascii(s: &[u8]) -> &[u8] {
    let mut start = 0;
    while start < s.len() && (s[start] == b' ' || s[start] == b'\t') {
        start += 1;
    }
    let mut end = s.len();
    while end > start && (s[end - 1] == b' ' || s[end - 1] == b'\t') {
        end -= 1;
    }
    &s[start..end]
}

#[cfg(test)]
mod tests {
    use super::*;

    fn lit_indexed_name(name_index: u8, value: &str) -> Vec<u8> {
        let mut out = Vec::new();
        out.push(0x40 | (name_index & 0x3F));
        out.push(value.len() as u8); // 7-bit length, no Huffman
        out.extend_from_slice(value.as_bytes());
        out
    }

    fn lit_indexed_name_huffman(name_index: u8, value: &str) -> Vec<u8> {
        let mut out = Vec::new();
        out.push(0x40 | (name_index & 0x3F));
        let payload = huffman::encode(value);
        assert!(payload.len() < 0x7F);
        out.push(0x80 | payload.len() as u8);
        out.extend_from_slice(&payload);
        out
    }

    #[test]
    fn extracts_authority_via_static_literal() {
        let mut d = HpackDecoder::new();
        let block = lit_indexed_name(1, "api.example.com");
        let result = d.decode_block(&block).unwrap().unwrap();
        assert_eq!(result.value, "api.example.com");
        assert_eq!(result.provenance, AuthorityProvenance::StaticLiteral);
        // The literal-with-incremental-indexing path adds to the dynamic table.
        assert_eq!(d.dynamic_table.entry_count(), 1);
    }

    #[test]
    fn extracts_authority_via_huffman_literal() {
        let mut d = HpackDecoder::new();
        let block = lit_indexed_name_huffman(1, "api.example.com");
        let result = d.decode_block(&block).unwrap().unwrap();
        assert_eq!(result.value, "api.example.com");
        assert_eq!(result.provenance, AuthorityProvenance::Huffman);
    }

    #[test]
    fn extracts_authority_via_dynamic_table_reference() {
        let mut d = HpackDecoder::new();
        // First block: incremental-index :authority = "api.example.com".
        // The decoder also returns the authority from this block.
        let block1 = lit_indexed_name(1, "api.example.com");
        let r1 = d.decode_block(&block1).unwrap().unwrap();
        assert_eq!(r1.value, "api.example.com");
        // Second block: indexed-header-field at dynamic index 62 (the
        // entry we just added).
        let block2 = vec![0x80 | 62];
        let r2 = d.decode_block(&block2).unwrap().unwrap();
        assert_eq!(r2.value, "api.example.com");
        assert_eq!(r2.provenance, AuthorityProvenance::DynamicIndexed);
    }

    #[test]
    fn rejects_invalid_dynamic_index() {
        let mut d = HpackDecoder::new();
        // Indexed-header at dynamic index 62 with empty dynamic table.
        let block = vec![0x80 | 62];
        let err = d.decode_block(&block).unwrap_err();
        assert!(matches!(err, H2ParseError::HpackInvalidIndex { .. }));
    }

    #[test]
    fn dynamic_table_size_update_is_honoured() {
        let mut d = HpackDecoder::new();
        // Update to 0 → table cleared.
        let block = vec![0x20]; // 001 00000 → size 0
        d.decode_block(&block).unwrap();
        assert_eq!(d.dynamic_table.max_size(), 0);
    }

    #[test]
    fn block_with_no_authority_returns_none() {
        let mut d = HpackDecoder::new();
        // Indexed-header-field at static index 2 (`:method GET`) — not
        // :authority.
        let block = vec![0x80 | 2];
        let result = d.decode_block(&block).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn literal_with_incremental_indexing_persists_across_blocks() {
        let mut d = HpackDecoder::new();
        // Add entry via incremental indexing — name is literal "x-custom".
        let mut block1 = Vec::new();
        block1.push(0x40); // 01000000 — name literal follows
        block1.push(8);
        block1.extend_from_slice(b"x-custom");
        block1.push(5);
        block1.extend_from_slice(b"value");
        d.decode_block(&block1).unwrap();
        assert_eq!(d.dynamic_table.entry_count(), 1);
        // Reference it as dynamic index 62.
        let (name, value) = d.dynamic_table.lookup(62).unwrap();
        assert_eq!(name, "x-custom");
        assert_eq!(value, "value");
    }
}