Skip to content

Handle comma separated X-Forwarded-port #303

@rleyton

Description

@rleyton

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).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions