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

Add support for proxypass middleware #248

Closed
signebedi opened this issue Jun 11, 2024 · 1 comment
Closed

Add support for proxypass middleware #248

signebedi opened this issue Jun 11, 2024 · 1 comment

Comments

@signebedi
Copy link
Owner

Werkzeug allowed us to do this in one line of code, but I'm not sure if starlette can do the same...

@signebedi
Copy link
Owner Author

Based on https://pypi.org/project/fastapi-proxiedheadersmiddleware/, we might be able to use the following code:

from typing import List, Tuple

from starlette.types import ASGIApp, Receive, Scope, Send

Headers = List[Tuple[bytes, bytes]]


class ProxiedHeadersMiddleware:
    """
    A middleware that modifies the request to ensure that FastAPI uses the
    X-Forwarded-* headers when creating URLs used to reference this application.

    We are very permissive in allowing all X-Forwarded-* headers to be used, as
    we know that this API will be published behind the API Gateway, and is
    therefore not prone to redirect hijacking.

    """

    def __init__(self, app: ASGIApp):
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
        scope["headers"] = self.remap_headers(scope.get("headers", {}))

        await self.app(scope, receive, send)
        return

    def remap_headers(self, source: Headers) -> Headers:
        """
        Map X-Forwarded-Host to host and X-Forwarded-Prefix to prefix.

        """

        source = dict(source)

        if b'x-forwarded-host' in source:
            source.update({b'host': source[b'x-forwarded-host']})
            source.pop(b'x-forwarded-host')

        if b'x-forwarded-prefix' in source:
            source.update({
                b'host': source[b'host'] + source[b'x-forwarded-prefix']
            })
            source.pop(b'x-forwarded-prefix')

        source = [(k, v) for k, v in source.items()]

        return source

Source https://gitlab.developers.cam.ac.uk/uis/devops/lib/fastapi-proxiedheadersmiddleware/-/blob/main/fastapi_proxiedheadersmiddleware/__init__.py?ref_type=heads

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