Skip to content

Commit

Permalink
ensure correct propagation of BlockingRequest inside nested asm reque…
Browse files Browse the repository at this point in the history
…st contexts
  • Loading branch information
christophe-papazian committed May 2, 2024
1 parent 87cadb0 commit 7cd5645
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
8 changes: 8 additions & 0 deletions ddtrace/appsec/_asm_request_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from ddtrace.appsec._iast._utils import _is_iast_enabled
from ddtrace.appsec._utils import get_triggers
from ddtrace.internal import core
from ddtrace.internal._exceptions import BlockingException
from ddtrace.internal.constants import REQUEST_PATH_PARAMS
from ddtrace.internal.logger import get_logger
from ddtrace.settings.asm import config as asm_config
Expand Down Expand Up @@ -140,6 +141,7 @@ def __init__(self):
env = ASM_Environment(True)

self._id = _DataHandler.main_id
self._root = not in_context()
self.active = True
self.execution_context = core.ExecutionContext(__name__, **{"asm_env": env})

Expand Down Expand Up @@ -393,6 +395,12 @@ def asm_request_context_manager(
if resources is not None:
try:
yield resources
except BlockingException as e:
# ensure that the BlockingRequest that is never raised outside a context
# is also never propagated outside the context
core.set_item(WAF_CONTEXT_NAMES.BLOCKED, e.args[0])
if not resources._root:
raise
finally:
_end_context(resources)
else:
Expand Down
17 changes: 17 additions & 0 deletions tests/appsec/appsec/test_asm_request_context.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pytest

from ddtrace.appsec import _asm_request_context
from ddtrace.internal._exceptions import BlockingException
from tests.utils import override_global_config


Expand Down Expand Up @@ -94,3 +95,19 @@ def test_asm_request_context_manager():
assert _asm_request_context.get_headers() == {}
assert _asm_request_context.get_value("callbacks", "block") is None
assert not _asm_request_context.get_headers_case_sensitive()


def test_blocking_exception_correctly_propagated():
with override_global_config({"_asm_enabled": True}):
with _asm_request_context.asm_request_context_manager():
witness = 0
with _asm_request_context.asm_request_context_manager():
witness = 1
raise BlockingException({}, "rule", "type", "value")
# should be skipped by exception
witness = 3
# should be also skipped by exception
witness = 4
# no more exception there
# ensure that the exception was raised and caught at the end of the last context manager
assert witness == 1

0 comments on commit 7cd5645

Please sign in to comment.