Skip to content

Commit

Permalink
Improve error messages on malformed keys
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthiasValvekens committed Mar 27, 2024
1 parent 6871e2b commit 296dd3b
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
10 changes: 8 additions & 2 deletions pyhanko/pdf_utils/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -1259,7 +1259,7 @@ def read_from_stream(
tmp = stream.read(2)
if tmp != b"<<":
raise PdfReadError(
"Dictionary read error at byte %s: "
"Dictionary read error at byte 0x%s: "
"stream must begin with '<<'" % hex(stream.tell())
)
data = {}
Expand All @@ -1270,7 +1270,13 @@ def read_from_stream(
stream.read(1)
break
stream.seek(-1, os.SEEK_CUR)
key = read_object(stream, container_ref)
try:
key = NameObject.read_from_stream(stream)
except Exception as ex:
raise PdfReadError(
"Failed to read dictionary key at byte 0x%s; expected PDF name"
% hex(stream.tell())
) from ex
read_non_whitespace(stream)
stream.seek(-1, os.SEEK_CUR)
value = read_object(stream, container_ref)
Expand Down
17 changes: 17 additions & 0 deletions pyhanko_tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from pyhanko.pdf_utils.incremental_writer import IncrementalPdfFileWriter
from pyhanko.pdf_utils.layout import BoxConstraints, BoxSpecificationError
from pyhanko.pdf_utils.metadata.model import DocumentMetadata
from pyhanko.pdf_utils.misc import PdfReadError
from pyhanko.pdf_utils.reader import (
HistoricalResolver,
PdfFileReader,
Expand Down Expand Up @@ -1521,6 +1522,22 @@ def test_parse_comments(input_str):
assert result['/C'] == '/D'


@pytest.mark.parametrize(
'input_str',
[
'<</2 0 R>>',
'<</Name 0 0>>',
'<<(blah) 0>>',
],
)
def test_parse_malformed_dictionary(input_str):
strm = BytesIO(input_str.strip().encode('utf8'))
with pytest.raises(PdfReadError, match="Failed to read dictionary key"):
generic.DictionaryObject.read_from_stream(
strm, container_ref=generic.Reference(1, 0, pdf=None)
)


NONEXISTENT_XREF_PATH = os.path.join(
PDF_DATA_DIR, 'minimal-with-nonexistent-refs.pdf'
)
Expand Down

0 comments on commit 296dd3b

Please sign in to comment.