Skip to content

Commit

Permalink
Handle unexpected xml parsing errors more gracefully (#349)
Browse files Browse the repository at this point in the history
* updates `parse_aggregate_report_xml` to not raise an unhandled
  exception on parsing errors
* adds an empty xml file to the aggregate test samples
* adds test for coverage
* Resolves #348
  • Loading branch information
drawks authored Sep 8, 2022
1 parent 9d739cc commit 84a7386
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
13 changes: 8 additions & 5 deletions parsedmarc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,14 @@ def parse_aggregate_report_xml(xml, ip_db_path=None, offline=False,
xmltodict.parse(xml)["feedback"]
except Exception as e:
errors.append("Invalid XML: {0}".format(e.__str__()))
tree = etree.parse(
BytesIO(xml.encode('utf-8')),
etree.XMLParser(recover=True, resolve_entities=False))
s = etree.tostring(tree)
xml = '' if s is None else s.decode('utf-8')
try:
tree = etree.parse(
BytesIO(xml.encode('utf-8')),
etree.XMLParser(recover=True, resolve_entities=False))
s = etree.tostring(tree)
xml = '' if s is None else s.decode('utf-8')
except Exception:
xml = u'<a/>'

try:
# Replace XML header (sometimes they are invalid)
Expand Down
Empty file added samples/empty.xml
Empty file.
5 changes: 5 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@ def testAggregateSamples(self):
print("\n")
print(parsedmarc.parsed_aggregate_reports_to_csv(parsed_report))

def testEmptySample(self):
"""Test empty/unparasable report"""
with self.assertRaises(parsedmarc.InvalidDMARCReport):
parsedmarc.parse_report_file('samples/empty.xml')

def testForensicSamples(self):
"""Test sample forensic/ruf/failure DMARC reports"""
sample_paths = glob("samples/forensic/*.eml")
Expand Down

0 comments on commit 84a7386

Please sign in to comment.