Skip to content

Commit 5bfccb6

Browse files
justinchubyCopilot
andauthored
Harden GGUF metadata array header parsing (#625)
## Summary - validate GGUF metadata tables before invoking `gguf.GGUFReader` - bound array counts by remaining encoded bytes and a 1,000,000-element safety cap - fast-skip fixed-width arrays and safely bound nested/string arrays - share validation with remote architecture header preflight while preserving big-endian files and continuation shards - add adversarial coverage for huge counts, truncation, nested arrays, and the valid cap boundary ## Tests - `python -m pytest src/mobius/integrations/gguf/_reader_test.py src/mobius/integrations/gguf/_builder_test.py -q --tb=short` - `python -m pytest src/mobius/integrations/gguf/_reader_test.py src/mobius/integrations/gguf/_builder_test.py src/mobius/integrations/gguf/_shard_set_test.py src/mobius/integrations/gguf/_preflight_test.py -q --tb=short` - `python -m pytest src/mobius/integrations/gguf/_docs_test.py -q --tb=short` - `python -m pytest tests/build_graph_test.py tests/cli_test.py src/ -q -k "not phi4mm and not apply_weights_unknown" --tb=short -n auto` - `lintrunner f --output oneline src/mobius/integrations/gguf/_header.py src/mobius/integrations/gguf/_reader.py src/mobius/integrations/gguf/_reader_test.py src/mobius/integrations/gguf/_builder.py src/mobius/integrations/gguf/_builder_test.py` Follow-up to review comment #586 (comment). Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent aec175f commit 5bfccb6

5 files changed

Lines changed: 315 additions & 91 deletions

File tree

‎src/mobius/integrations/gguf/_builder.py‎

Lines changed: 4 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import logging
2121
import math
2222
import re
23-
import struct
2423
from collections import Counter
2524
from collections.abc import Callable, Collection, Iterable, Mapping
2625
from pathlib import Path
@@ -49,6 +48,7 @@
4948
ShardedGGUFNotSupportedError,
5049
UnsupportedGGUFArchitectureError,
5150
)
51+
from mobius.integrations.gguf._header import _gguf_architecture_from_header
5252
from mobius.integrations.gguf._spec import Support
5353

5454
_HUB_PREFLIGHT_TRANSPORT_ERRORS: tuple[type[BaseException], ...] = (OSError,)
@@ -70,20 +70,6 @@
7070
)
7171
_NEMOTRON_H_MOE_ARCHITECTURE = "nemotron_h_moe"
7272
_GGUF_HEADER_RANGE_BYTES = 16 * 1024 * 1024
73-
_GGUF_ARCHITECTURE_KEY = b"general.architecture"
74-
_GGUF_SCALAR_WIDTHS = {
75-
0: 1, # UINT8
76-
1: 1, # INT8
77-
2: 2, # UINT16
78-
3: 2, # INT16
79-
4: 4, # UINT32
80-
5: 4, # INT32
81-
6: 4, # FLOAT32
82-
7: 1, # BOOL
83-
10: 8, # UINT64
84-
11: 8, # INT64
85-
12: 8, # FLOAT64
86-
}
8773

8874

8975
def _summarize_nemotron_h_moe_layout(
@@ -401,82 +387,9 @@ def _preflight_hf_gguf(api: HfApi, repo_id: str, filename: str) -> None:
401387

402388
def _gguf_architecture_from_header_prefix(data: bytes, *, source: str) -> str:
403389
"""Read ``general.architecture`` from a bounded GGUF header prefix."""
404-
if len(data) < 24 or data[:4] != b"GGUF":
405-
raise ValueError(f"{source!r} does not begin with a valid GGUF header.")
406-
version = struct.unpack_from("<I", data, 4)[0]
407-
if version not in {2, 3}:
408-
raise ValueError(f"{source!r} uses unsupported GGUF version {version}.")
409-
410-
def read_uint32(offset: int) -> tuple[int, int]:
411-
end = offset + 4
412-
if end > len(data):
413-
raise ValueError(f"{source!r} has a truncated GGUF metadata header.")
414-
return struct.unpack_from("<I", data, offset)[0], end
415-
416-
def read_uint64(offset: int) -> tuple[int, int]:
417-
end = offset + 8
418-
if end > len(data):
419-
raise ValueError(f"{source!r} has a truncated GGUF metadata header.")
420-
return struct.unpack_from("<Q", data, offset)[0], end
421-
422-
def read_string(offset: int) -> tuple[bytes, int]:
423-
length, offset = read_uint64(offset)
424-
end = offset + length
425-
if end > len(data):
426-
raise ValueError(f"{source!r} has a truncated GGUF metadata string.")
427-
return data[offset:end], end
428-
429-
def skip_value(value_type: int, offset: int, *, depth: int = 0) -> int:
430-
width = _GGUF_SCALAR_WIDTHS.get(value_type)
431-
if width is not None:
432-
end = offset + width
433-
if end > len(data):
434-
raise ValueError(f"{source!r} has a truncated GGUF metadata value.")
435-
return end
436-
if value_type == 8:
437-
_, offset = read_string(offset)
438-
return offset
439-
if value_type != 9:
440-
raise ValueError(f"{source!r} uses unknown GGUF metadata type {value_type}.")
441-
if depth >= 8:
442-
raise ValueError(f"{source!r} has excessively nested GGUF metadata arrays.")
443-
element_type, offset = read_uint32(offset)
444-
count, offset = read_uint64(offset)
445-
if count > len(data):
446-
raise ValueError(f"{source!r} declares an impossible GGUF metadata array size.")
447-
for _ in range(count):
448-
offset = skip_value(element_type, offset, depth=depth + 1)
449-
return offset
450-
451-
kv_count = struct.unpack_from("<Q", data, 16)[0]
452-
if kv_count > len(data):
453-
raise ValueError(f"{source!r} declares an impossible GGUF metadata entry count.")
454-
offset = 24
455-
architecture_values: list[bytes] = []
456-
for _ in range(kv_count):
457-
key, offset = read_string(offset)
458-
value_type, offset = read_uint32(offset)
459-
if key == _GGUF_ARCHITECTURE_KEY:
460-
if value_type != 8:
461-
raise ValueError(
462-
f"{source!r} encodes general.architecture with GGUF type "
463-
f"{value_type}, expected string type 8."
464-
)
465-
value, offset = read_string(offset)
466-
architecture_values.append(value)
467-
else:
468-
offset = skip_value(value_type, offset)
469-
470-
if len(architecture_values) != 1:
471-
raise ValueError(
472-
f"{source!r} must contain exactly one general.architecture metadata entry, "
473-
f"found {len(architecture_values)}."
474-
)
475-
value = architecture_values[0]
476-
try:
477-
return value.decode("utf-8")
478-
except UnicodeDecodeError as error:
479-
raise ValueError(f"{source!r} has a non-UTF-8 general.architecture value.") from error
390+
architecture = _gguf_architecture_from_header(data, source=source)
391+
assert architecture is not None
392+
return architecture
480393

481394

482395
def _preflight_hf_gguf_file(

‎src/mobius/integrations/gguf/_builder_test.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7418,6 +7418,87 @@ def test_structural_header_parser_rejects_duplicate_architecture_entries(self) -
74187418
source="duplicate.gguf",
74197419
)
74207420

7421+
def test_structural_header_parser_rejects_array_above_safety_limit(self) -> None:
7422+
from mobius.integrations.gguf._builder import (
7423+
_gguf_architecture_from_header_prefix,
7424+
)
7425+
7426+
count = 1_000_001
7427+
padding_entry = (
7428+
struct.pack("<Q", len(b"padding"))
7429+
+ b"padding"
7430+
+ struct.pack("<IIQ", 9, 0, count)
7431+
+ bytes(count)
7432+
)
7433+
data = (
7434+
b"GGUF"
7435+
+ struct.pack("<IQQ", 3, 0, 2)
7436+
+ padding_entry
7437+
+ _gguf_header_prefix("llama")[24:]
7438+
)
7439+
with pytest.raises(ValueError, match=r"1000001.*safety limit of 1000000"):
7440+
_gguf_architecture_from_header_prefix(data, source="oversized-array.gguf")
7441+
7442+
def test_structural_header_parser_rejects_truncated_fixed_width_array(self) -> None:
7443+
from mobius.integrations.gguf._builder import (
7444+
_gguf_architecture_from_header_prefix,
7445+
)
7446+
7447+
array_entry = (
7448+
struct.pack("<Q", len(b"padding"))
7449+
+ b"padding"
7450+
+ struct.pack("<IIQ", 9, 4, 2)
7451+
+ b"\x00" * 7
7452+
)
7453+
data = b"GGUF" + struct.pack("<IQQ", 3, 0, 1) + array_entry
7454+
with pytest.raises(
7455+
ValueError,
7456+
match=r"truncated GGUF metadata array.*requiring at least 8 bytes.*7 remaining",
7457+
):
7458+
_gguf_architecture_from_header_prefix(data, source="truncated-array.gguf")
7459+
7460+
def test_structural_header_parser_rejects_truncated_nested_array(self) -> None:
7461+
from mobius.integrations.gguf._builder import (
7462+
_gguf_architecture_from_header_prefix,
7463+
)
7464+
7465+
nested_array = struct.pack("<IQ", 0, 2**63)
7466+
array_entry = (
7467+
struct.pack("<Q", len(b"padding"))
7468+
+ b"padding"
7469+
+ struct.pack("<IIQ", 9, 9, 1)
7470+
+ nested_array
7471+
)
7472+
data = b"GGUF" + struct.pack("<IQQ", 3, 0, 1) + array_entry
7473+
with pytest.raises(
7474+
ValueError,
7475+
match=r"truncated GGUF metadata array.*9223372036854775808 elements",
7476+
):
7477+
_gguf_architecture_from_header_prefix(data, source="nested-array.gguf")
7478+
7479+
def test_structural_header_parser_accepts_array_at_safety_limit(self) -> None:
7480+
from mobius.integrations.gguf._builder import (
7481+
_gguf_architecture_from_header_prefix,
7482+
)
7483+
7484+
count = 1_000_000
7485+
padding_entry = (
7486+
struct.pack("<Q", len(b"padding"))
7487+
+ b"padding"
7488+
+ struct.pack("<IIQ", 9, 0, count)
7489+
+ bytes(count)
7490+
)
7491+
data = (
7492+
b"GGUF"
7493+
+ struct.pack("<IQQ", 3, 0, 2)
7494+
+ padding_entry
7495+
+ _gguf_header_prefix("llama")[24:]
7496+
)
7497+
assert (
7498+
_gguf_architecture_from_header_prefix(data, source="boundary-array.gguf")
7499+
== "llama"
7500+
)
7501+
74217502
def test_exact_companion_preflight_rejects_unresolved_mutable_revision(self) -> None:
74227503
from mobius.integrations.gguf._builder import (
74237504
_preflight_hf_mmproj_companion_file,
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Bounded structural validation for GGUF metadata headers."""
5+
6+
from __future__ import annotations
7+
8+
import struct
9+
from typing import Any
10+
11+
_GGUF_ARCHITECTURE_KEY = b"general.architecture"
12+
_GGUF_MAX_METADATA_ARRAY_DEPTH = 8
13+
_GGUF_MAX_METADATA_ARRAY_ELEMENTS = 1_000_000
14+
_GGUF_MAX_METADATA_ENTRIES = 1_000_000
15+
_GGUF_SCALAR_WIDTHS = {
16+
0: 1, # UINT8
17+
1: 1, # INT8
18+
2: 2, # UINT16
19+
3: 2, # INT16
20+
4: 4, # UINT32
21+
5: 4, # INT32
22+
6: 4, # FLOAT32
23+
7: 1, # BOOL
24+
10: 8, # UINT64
25+
11: 8, # INT64
26+
12: 8, # FLOAT64
27+
}
28+
_GGUF_STRING = 8
29+
_GGUF_ARRAY = 9
30+
31+
32+
def _gguf_architecture_from_header(
33+
data: Any,
34+
*,
35+
source: str,
36+
require_architecture: bool = True,
37+
) -> str | None:
38+
"""Validate a GGUF metadata table and return its architecture when present."""
39+
size = len(data)
40+
if size < 24 or data[0:4] != b"GGUF":
41+
raise ValueError(f"{source!r} does not begin with a valid GGUF header.")
42+
43+
little_version = struct.unpack_from("<I", data, 4)[0]
44+
if little_version in {2, 3}:
45+
byte_order = "<"
46+
version = little_version
47+
else:
48+
version = struct.unpack_from(">I", data, 4)[0]
49+
if version not in {2, 3}:
50+
raise ValueError(f"{source!r} uses unsupported GGUF version {little_version}.")
51+
byte_order = ">"
52+
53+
def read_uint32(offset: int) -> tuple[int, int]:
54+
end = offset + 4
55+
if end > size:
56+
raise ValueError(f"{source!r} has a truncated GGUF metadata header.")
57+
return struct.unpack_from(f"{byte_order}I", data, offset)[0], end
58+
59+
def read_uint64(offset: int) -> tuple[int, int]:
60+
end = offset + 8
61+
if end > size:
62+
raise ValueError(f"{source!r} has a truncated GGUF metadata header.")
63+
return struct.unpack_from(f"{byte_order}Q", data, offset)[0], end
64+
65+
def read_string_span(offset: int) -> tuple[int, int, int]:
66+
length, offset = read_uint64(offset)
67+
end = offset + length
68+
if end > size:
69+
raise ValueError(
70+
f"{source!r} has a truncated GGUF metadata string: "
71+
f"declares {length} bytes with only {size - offset} remaining."
72+
)
73+
return offset, end, end
74+
75+
def minimum_value_width(value_type: int) -> int:
76+
width = _GGUF_SCALAR_WIDTHS.get(value_type)
77+
if width is not None:
78+
return width
79+
if value_type == _GGUF_STRING:
80+
return 8
81+
if value_type == _GGUF_ARRAY:
82+
return 12
83+
raise ValueError(f"{source!r} uses unknown GGUF metadata type {value_type}.")
84+
85+
def skip_value(value_type: int, offset: int, *, depth: int = 0) -> int:
86+
width = _GGUF_SCALAR_WIDTHS.get(value_type)
87+
if width is not None:
88+
end = offset + width
89+
if end > size:
90+
raise ValueError(f"{source!r} has a truncated GGUF metadata value.")
91+
return end
92+
if value_type == _GGUF_STRING:
93+
_, _, offset = read_string_span(offset)
94+
return offset
95+
if value_type != _GGUF_ARRAY:
96+
raise ValueError(f"{source!r} uses unknown GGUF metadata type {value_type}.")
97+
if depth >= _GGUF_MAX_METADATA_ARRAY_DEPTH:
98+
raise ValueError(f"{source!r} has excessively nested GGUF metadata arrays.")
99+
100+
element_type, offset = read_uint32(offset)
101+
count, offset = read_uint64(offset)
102+
element_width = minimum_value_width(element_type)
103+
remaining = size - offset
104+
if count > remaining // element_width:
105+
raise ValueError(
106+
f"{source!r} has a truncated GGUF metadata array: declares {count} "
107+
f"elements requiring at least {count * element_width} bytes with only "
108+
f"{remaining} remaining."
109+
)
110+
if count > _GGUF_MAX_METADATA_ARRAY_ELEMENTS:
111+
raise ValueError(
112+
f"{source!r} declares {count} GGUF metadata array elements, exceeding "
113+
f"the safety limit of {_GGUF_MAX_METADATA_ARRAY_ELEMENTS}."
114+
)
115+
116+
if element_type in _GGUF_SCALAR_WIDTHS:
117+
return offset + count * element_width
118+
for _ in range(count):
119+
offset = skip_value(element_type, offset, depth=depth + 1)
120+
return offset
121+
122+
kv_count = struct.unpack_from(f"{byte_order}Q", data, 16)[0]
123+
if kv_count > _GGUF_MAX_METADATA_ENTRIES:
124+
raise ValueError(
125+
f"{source!r} declares {kv_count} GGUF metadata entries, exceeding "
126+
f"the safety limit of {_GGUF_MAX_METADATA_ENTRIES}."
127+
)
128+
# Every entry needs an 8-byte key length, a 4-byte type, and at least
129+
# one value byte. Reject impossible counts before entering the loop.
130+
if kv_count > (size - 24) // 13:
131+
raise ValueError(
132+
f"{source!r} has a truncated GGUF metadata table for {kv_count} entries."
133+
)
134+
135+
offset = 24
136+
architecture_values: list[bytes] = []
137+
for _ in range(kv_count):
138+
key_start, key_end, offset = read_string_span(offset)
139+
value_type, offset = read_uint32(offset)
140+
is_architecture = (
141+
key_end - key_start == len(_GGUF_ARCHITECTURE_KEY)
142+
and data[key_start:key_end] == _GGUF_ARCHITECTURE_KEY
143+
)
144+
if is_architecture:
145+
if value_type != _GGUF_STRING:
146+
raise ValueError(
147+
f"{source!r} encodes general.architecture with GGUF type "
148+
f"{value_type}, expected string type {_GGUF_STRING}."
149+
)
150+
value_start, value_end, offset = read_string_span(offset)
151+
architecture_values.append(bytes(data[value_start:value_end]))
152+
else:
153+
offset = skip_value(value_type, offset)
154+
155+
if not architecture_values and not require_architecture:
156+
return None
157+
if len(architecture_values) != 1:
158+
raise ValueError(
159+
f"{source!r} must contain exactly one general.architecture metadata entry, "
160+
f"found {len(architecture_values)}."
161+
)
162+
try:
163+
return architecture_values[0].decode("utf-8")
164+
except UnicodeDecodeError as error:
165+
raise ValueError(f"{source!r} has a non-UTF-8 general.architecture value.") from error

0 commit comments

Comments
 (0)