szn

Bug 484 — expandTruncateInto slice-out-of-bounds panic on malformed UTF-8

484. Trailing lead byte in a status value crashes the server

Severity: CRITICAL (server panic on untrusted bytes) Status: ✅ FIXED Files: src/format.zig:735-768

Problem

expandTruncateInto truncates a status-format value to n characters:

var idx: usize = 0;
while (idx < value.len) {
    const len = std.unicode.utf8ByteSequenceLength(value[idx]) catch 1;
    if (count >= n) break;
    count += 1;
    idx += len;
}
...
try out.appendSlice(allocator, value[0..idx]);

utf8ByteSequenceLength validates only the lead byte. If value ends with a truncated sequence (e.g. a trailing 0xC3 with its continuation byte missing), len comes back 2, idx overshoots value.len, and value[0..idx] panics with a slice-out-of-bounds. The negative branch has the same shape: k overshoots before value[k..].

The values come from ctx.get() — status variables like pane_title, which the child process controls via OSC sequences. A child emitting a truncated UTF-8 sequence in its title crashes the server on the next status render. Any pane in any session can trigger it.

Proposed Fix

Clamp before slicing:

idx = @min(idx, value.len);
try out.appendSlice(allocator, value[0..idx]);

(same for k in the negative branch), or iterate with std.unicode.Utf8View so malformed sequences decode as U+FFFD instead of overshooting. A regression test should feed a value ending in 0xC3 / 0xE2 0x82 through the truncation path.

Resolution

expandTruncateInto in src/format.zig clamps idx, j, and k to value.len using @min(idx + len, value.len) during iteration, and explicitly clamps indices before slicing value[0..idx] and value[k..].

Tests: expandTruncateInto with malformed UTF-8 does not panic — bug #484 tests positive and negative truncation on truncated 2-byte (\xC3) and 3-byte (\xE2\x82) sequences.