Skip to content

Commit

Permalink
Remove use of "pickle.loads()" to comply with security tools (#563)
Browse files Browse the repository at this point in the history
  • Loading branch information
Delgan committed Jan 21, 2022
1 parent f2d5133 commit 4b0070a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 14 deletions.
18 changes: 7 additions & 11 deletions loguru/_recattrs.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,14 @@ def __repr__(self):
return "(type=%r, value=%r, traceback=%r)" % (self.type, self.value, self.traceback)

def __reduce__(self):
# The traceback is not picklable so we need to remove it. Also, some custom exception
# values aren't picklable either. For user convenience, we try first to serialize it and
# we remove the value in case or error. As an optimization, we could have re-used the
# dumped value during unpickling, but this requires using "pickle.loads()" which is
# flagged as insecure by some security tools.
try:
pickled_value = pickle.dumps(self.value)
pickle.dumps(self.value)
except pickle.PickleError:
return (RecordException, (self.type, None, None))
else:
return (RecordException._from_pickled_value, (self.type, pickled_value, None))

@classmethod
def _from_pickled_value(cls, type_, pickled_value, traceback_):
try:
value = pickle.loads(pickled_value)
except pickle.PickleError:
return cls(type_, None, traceback_)
else:
return cls(type_, value, traceback_)
return (RecordException, (self.type, self.value, None))
28 changes: 25 additions & 3 deletions tests/test_add_option_enqueue.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,7 @@ def slow_sink(message):
assert err == "".join("%d\n" % i for i in range(10))


@pytest.mark.parametrize("arg", [NotPicklable(), NotUnpicklable()])
def test_logging_not_picklable_exception(arg):
def test_logging_not_picklable_exception():
exception = None

def sink(message):
Expand All @@ -202,7 +201,30 @@ def sink(message):
logger.add(sink, enqueue=True, catch=False)

try:
raise ValueError(arg)
raise ValueError(NotPicklable())
except Exception:
logger.exception("Oups")

logger.remove()

type_, value, traceback_ = exception
assert type_ is ValueError
assert value is None
assert traceback_ is None


@pytest.mark.xfail(reason="No way to safely deserialize exception yet")
def test_logging_not_unpicklable_exception():
exception = None

def sink(message):
nonlocal exception
exception = message.record["exception"]

logger.add(sink, enqueue=True, catch=False)

try:
raise ValueError(NotUnpicklable())
except Exception:
logger.exception("Oups")

Expand Down

0 comments on commit 4b0070a

Please sign in to comment.