Skip to content

Commit 0a06331

Browse files
authored
Python: Detect invalid magic when instantiating SeekingReader (#971)
### Public-Facing Changes Python: Detect invalid magic when instantiating `SeekingReader` ### Description Attempts to read the magic bytes when instantiating a `SeekingReader`, leading to an exception when the stream is not from a valid mcap file Resolves FG-4787
1 parent 7719727 commit 0a06331

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

python/mcap/mcap/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "1.1.0"
1+
__version__ = "1.1.1"

python/mcap/mcap/reader.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
Schema,
3535
Statistics,
3636
)
37-
from .stream_reader import MAGIC_SIZE, StreamReader, breakup_chunk
37+
from .stream_reader import MAGIC_SIZE, StreamReader, breakup_chunk, read_magic
3838
from .summary import Summary
3939

4040

@@ -249,6 +249,7 @@ def __init__(
249249
decoder_factories: Iterable[DecoderFactory] = (),
250250
):
251251
super().__init__(decoder_factories=decoder_factories)
252+
read_magic(ReadDataStream(stream, calculate_crc=False))
252253
self._stream = stream
253254
self._validate_crcs = validate_crcs
254255
self._summary: Optional[Summary] = None

python/mcap/tests/test_reader.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import pytest
88

99
from mcap.decoder import DecoderFactory
10-
from mcap.exceptions import DecoderNotFoundError
10+
from mcap.exceptions import DecoderNotFoundError, InvalidMagic
1111
from mcap.reader import McapReader, NonSeekingReader, SeekingReader, make_reader
1212
from mcap.records import Channel, Message, Schema
1313
from mcap.writer import IndexType, Writer
@@ -238,3 +238,17 @@ def test_no_summary_not_seeking(tmpdir: Path):
238238
assert len(list(NonSeekingReader(f).iter_attachments())) == 1
239239
with open(filepath, "rb") as f:
240240
assert len(list(NonSeekingReader(f).iter_metadata())) == 1
241+
242+
243+
def test_detect_invalid_initial_magic(tmpdir: Path):
244+
filepath = tmpdir / "invalid_magic.mcap"
245+
with open(filepath, "w") as f:
246+
f.write("some bytes longer than the initial magic bytes")
247+
248+
with open(filepath, "rb") as f:
249+
with pytest.raises(InvalidMagic):
250+
SeekingReader(f)
251+
252+
with open(filepath, "rb") as f:
253+
with pytest.raises(InvalidMagic):
254+
NonSeekingReader(f).get_header()

0 commit comments

Comments
 (0)