Skip to content

Commit f5c304a

Browse files
fix(event_handler): propagate UnauthorizedException and await async class-based middlewares (#8633)
* fix(event_handler): propagate UnauthorizedException from per-event AppSync Events resolvers The per-event resolvers (`aggregate=False`) catch every exception and turn it into a per-event error payload. `UnauthorizedException` is a control-flow signal rather than a payload: re-raise it so AppSync denies the whole operation. Both the sync and the async paths now behave like the aggregate and subscribe resolvers. Signed-off-by: SuellenQAQ <sulun6693485@163.com> * fix(event_handler): await async handlers in class-based middlewares `AsyncMiddlewareFrame` only awaited middlewares that are themselves coroutine functions. A `BaseMiddlewareHandler` subclass with an `async def handler` is not a coroutine function, so the frame returned the coroutine and the response leaked through un-awaited. Detect the class-based `handler` too and await whatever the middleware returns. Also return a short-circuiting middleware's own response in `wrap_middleware_async` instead of raising IndexError when the next middleware was never called. Signed-off-by: SuellenQAQ <sulun6693485@163.com> * test(event_handler): cover async class-based middlewares and short-circuiting Added tests for class-based async middleware and sync short-circuit behavior. Signed-off-by: SuellenQAQ <sulun6693485@163.com> * test(event_handler): cover UnauthorizedException propagation in per-event resolvers Add tests for handling unauthorized exceptions in AppSync events. Signed-off-by: SuellenQAQ <sulun6693485@163.com> --------- Signed-off-by: SuellenQAQ <sulun6693485@163.com> Co-authored-by: Leandro Damascena <lcdama@amazon.pt>
1 parent 272a612 commit f5c304a

4 files changed

Lines changed: 172 additions & 4 deletions

File tree

‎aws_lambda_powertools/event_handler/events_appsync/appsync_events.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,9 @@ def _process_publish_event_sync_resolver(
254254
try:
255255
result_return = resolver["func"](payload=event.get("payload"))
256256
results.append({"id": event.get("id"), "payload": result_return})
257+
except UnauthorizedException:
258+
# Authorization failures must fail the whole request, same as the aggregate path
259+
raise
257260
except Exception as error:
258261
logger.debug(f"Failed to process event number {idx}")
259262
error_return = {"id": event.get("id"), "error": self._format_error_response(error)}
@@ -314,6 +317,12 @@ async def _call_publish_event_async_resolver(
314317
# this will become useful when we support exception handling in AppSync resolver
315318
# Aggregate results and exceptions, then filter them out
316319
results = await asyncio.gather(*tasks, return_exceptions=True)
320+
321+
# Authorization failures must fail the whole request, same as the aggregate path
322+
for result in results:
323+
if isinstance(result, UnauthorizedException):
324+
raise result
325+
317326
response_async.extend(
318327
[
319328
(

‎aws_lambda_powertools/event_handler/middlewares/async_utils.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,10 @@ def run_middleware() -> None:
9898
# If middleware raised before calling next, propagate immediately
9999
if not next_app_holder:
100100
thread.join()
101-
raise middleware_error_holder[0]
101+
if middleware_error_holder:
102+
raise middleware_error_holder[0]
103+
# Middleware short-circuited without calling next: return its own response
104+
return middleware_result_holder[0] if middleware_result_holder else None
102105

103106
# Resolve the async next_handler on the event-loop
104107
real_response = await next_handler(next_app_holder[0])
@@ -159,8 +162,18 @@ async def __call__(self, app: ApiGatewayResolver) -> dict | tuple | Response:
159162

160163
extra_kwargs = _resolve_extra_middleware_kwargs(app, self.current_middleware)
161164

162-
if inspect.iscoroutinefunction(self.current_middleware):
163-
return await self.current_middleware(app, self.next_middleware, **extra_kwargs)
165+
# Class-based middlewares expose their logic through `handler`, which may be a coroutine
166+
# function even though the instance itself is not
167+
middleware_handler = getattr(self.current_middleware, "handler", None)
168+
is_async_middleware = inspect.iscoroutinefunction(
169+
self.current_middleware,
170+
) or inspect.iscoroutinefunction(middleware_handler)
171+
172+
if is_async_middleware:
173+
result = self.current_middleware(app, self.next_middleware, **extra_kwargs)
174+
if inspect.iscoroutine(result):
175+
result = await result
176+
return result
164177

165178
loop = asyncio.get_running_loop()
166179

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import pytest
2+
3+
from aws_lambda_powertools.event_handler import AppSyncEventsResolver
4+
from aws_lambda_powertools.event_handler.events_appsync.exceptions import UnauthorizedException
5+
from tests.functional.utils import load_event
6+
7+
8+
class LambdaContext:
9+
def __init__(self):
10+
self.function_name = "test-func"
11+
self.memory_limit_in_mb = 128
12+
self.invoked_function_arn = "arn:aws:lambda:eu-west-1:809313241234:function:test-func"
13+
self.aws_request_id = "52fdfc07-2182-154f-163f-5f0f9a621d72"
14+
15+
def get_remaining_time_in_millis(self) -> int:
16+
return 1000
17+
18+
19+
@pytest.fixture(scope="module")
20+
def lambda_context() -> LambdaContext:
21+
return LambdaContext()
22+
23+
24+
@pytest.fixture(scope="module")
25+
def mock_event():
26+
return load_event("appSyncEventsEvent.json")
27+
28+
29+
def test_publish_events_throw_unauthorized_exception_without_aggregate(lambda_context, mock_event):
30+
"""UnauthorizedException raised in a per-event resolver must not be swallowed.
31+
32+
When aggregate=False, each event is handled independently and any other exception is
33+
turned into a per-event error payload. Authorization failures are the exception: they
34+
must fail the whole request, otherwise a denied caller receives a successful response.
35+
"""
36+
# GIVEN a publish event with a single event
37+
mock_event["info"]["operation"] = "PUBLISH"
38+
mock_event["info"]["channel"]["path"] = "/default/test"
39+
mock_event["events"] = [
40+
{"id": "123", "payload": {"data": "test data"}},
41+
]
42+
43+
# GIVEN an AppSyncEventsResolver with a per-event resolver that denies access
44+
app = AppSyncEventsResolver()
45+
46+
@app.on_publish(path="/default/*")
47+
def handle_events(payload):
48+
raise UnauthorizedException
49+
50+
# WHEN we resolve the event
51+
# THEN the exception must propagate to the caller
52+
with pytest.raises(UnauthorizedException):
53+
app.resolve(mock_event, lambda_context)
54+
55+
56+
def test_async_publish_events_throw_unauthorized_exception_without_aggregate(lambda_context, mock_event):
57+
"""UnauthorizedException raised in an async per-event resolver must not be swallowed."""
58+
# GIVEN a publish event with a single event
59+
mock_event["info"]["operation"] = "PUBLISH"
60+
mock_event["info"]["channel"]["path"] = "/default/test"
61+
mock_event["events"] = [
62+
{"id": "123", "payload": {"data": "test data"}},
63+
]
64+
65+
# GIVEN an AppSyncEventsResolver with an async per-event resolver that denies access
66+
app = AppSyncEventsResolver()
67+
68+
@app.async_on_publish(path="/default/*")
69+
async def handle_events(payload):
70+
raise UnauthorizedException
71+
72+
# WHEN we resolve the event
73+
# THEN the exception must propagate to the caller
74+
with pytest.raises(UnauthorizedException):
75+
app.resolve(mock_event, lambda_context)
76+
77+
78+
def test_publish_events_throw_unauthorized_exception_with_multiple_events(lambda_context, mock_event):
79+
"""A single denied event must fail the whole batch, even when other events succeed."""
80+
# GIVEN a publish event with two events
81+
mock_event["info"]["operation"] = "PUBLISH"
82+
mock_event["info"]["channel"]["path"] = "/default/test"
83+
mock_event["events"] = [
84+
{"id": "123", "payload": {"data": "test data"}},
85+
{"id": "456", "payload": {"data": "more test data"}},
86+
]
87+
88+
# GIVEN an AppSyncEventsResolver that allows the first event and denies the second one
89+
app = AppSyncEventsResolver()
90+
calls = []
91+
92+
@app.on_publish(path="/default/*")
93+
def handle_events(payload):
94+
calls.append(payload)
95+
if len(calls) == 2:
96+
raise UnauthorizedException
97+
return {"processed": True}
98+
99+
# WHEN we resolve the event
100+
# THEN the exception must propagate to the caller
101+
with pytest.raises(UnauthorizedException):
102+
app.resolve(mock_event, lambda_context)

‎tests/functional/event_handler/required_dependencies/test_async_middleware_frame.py‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
ProxyEventType,
99
Response,
1010
)
11-
from aws_lambda_powertools.event_handler.middlewares import NextMiddleware
11+
from aws_lambda_powertools.event_handler.middlewares import BaseMiddlewareHandler, NextMiddleware
1212
from aws_lambda_powertools.event_handler.middlewares.async_utils import AsyncMiddlewareFrame, wrap_middleware_async
1313
from tests.functional.utils import load_event
1414

@@ -87,3 +87,47 @@ async def next_handler(app: ApiGatewayResolver):
8787
# THEN the exception propagates
8888
with pytest.raises(ValidationError, match="invalid request"):
8989
asyncio.run(frame(app))
90+
91+
92+
class AsyncClassMiddleware(BaseMiddlewareHandler):
93+
async def handler(self, app: ApiGatewayResolver, next_middleware: NextMiddleware) -> Response:
94+
response = await next_middleware(app)
95+
response.headers["x-async-middleware"] = "true"
96+
return response
97+
98+
99+
def test_class_based_async_middleware_is_awaited():
100+
# GIVEN a class-based middleware whose handler is a coroutine function
101+
app = _make_app()
102+
103+
async def next_handler(app: ApiGatewayResolver):
104+
await asyncio.sleep(0)
105+
return Response(200, content_types.TEXT_HTML, "ok")
106+
107+
frame = AsyncMiddlewareFrame(current_middleware=AsyncClassMiddleware(), next_middleware=next_handler)
108+
109+
# WHEN calling the frame
110+
response = asyncio.run(frame(app))
111+
112+
# THEN the handler is awaited instead of returning a coroutine
113+
assert isinstance(response, Response)
114+
assert response.headers["x-async-middleware"] == "true"
115+
116+
117+
def test_wrap_middleware_async_sync_short_circuit_returns_response():
118+
# GIVEN a sync middleware that returns a response without calling next()
119+
app = _make_app()
120+
121+
def short_circuit_middleware(app, next_middleware):
122+
return Response(401, content_types.APPLICATION_JSON, '{"message": "denied"}')
123+
124+
async def next_handler(app):
125+
raise AssertionError("next middleware should not be called")
126+
127+
wrapped = wrap_middleware_async(short_circuit_middleware, next_handler)
128+
129+
# WHEN calling the wrapped middleware
130+
response = asyncio.run(wrapped(app))
131+
132+
# THEN its own response is returned instead of raising IndexError
133+
assert response.status_code == 401

0 commit comments

Comments
 (0)