Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle comma separated X-Forwarded-port #303

Open
rleyton opened this issue Sep 1, 2023 · 0 comments
Open

Handle comma separated X-Forwarded-port #303

rleyton opened this issue Sep 1, 2023 · 0 comments

Comments

@rleyton
Copy link

rleyton commented Sep 1, 2023

X-Forwarded-port can sometimes be comma separated. Mangum assumes it's only ever a singular int, which cases a ValueError exception.

Summary of the issue, and draft PR to address follows.

Background

I've a FastAPI service deployed with Mangum, running as a Lambda. The following stack trace occurred:

[ERROR] ValueError: invalid literal for int() with base 10: '443,80'
Traceback (most recent call last):
  File "/opt/python/lib/python3.9/site-packages/datadog_lambda/wrapper.py", line 214, in __call__
    self.response = self.func(event, context, **kwargs)
  File "/opt/python/aws_lambda_powertools/logging/logger.py", line 385, in decorate
    @functools.wraps(lambda_handler)
  File "/opt/python/lib/python3.9/site-packages/ddtrace/contrib/aws_lambda/patch.py", line 115, in __call__
    self.response = self.func(*args, **kwargs)
  File "/opt/python/aws_lambda_powertools/logging/logger.py", line 402, in decorate
    return lambda_handler(event, context, *args, **kwargs)
  File "/opt/python/mangum/adapter.py", line 82, in __call__
    http_cycle = HTTPCycle(handler.scope, handler.body)
  File "/opt/python/mangum/handlers/api_gateway.py", line 104, in scope
    "server": get_server_and_port(headers),
  File "/opt/python/mangum/handlers/utils.py", line 24, in get_server_and_port
    server = (server_name, int(server_port))

x-forwarded-port was 443,80, shown in API Gateway logs (some elements redacted):

apigateway-request-headers

Upstream request

API Gateway is being called by a component that sits behind two reverse proxies (Cloudfront and nginx). In making requests of our API Gateway it includes headers, including the X-forwarded-port.

nginx workaround

Adding a rule, as a temporary fix, to nginx to masks the problem:

        proxy_set_header X-Forwarded-Port "";

PR with fix

I've drafted #304 with a fix to utils.py to handle a comma-separated list of port values inX-Forwarded-Port

Notes

  • It takes the first port value in the list, which maps to the first encountered port.
  • I'm not sure which is 'best' in this situation. It may be preferable to take the last (most recent port).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant