Skip to content

template python3_raw_asgi - HTTPS - uvicorn does not get HTTP X-Forwarded-* headers #617

@matthieumarrast

Description

@matthieumarrast

Problem

Into an HTTPS context, our application (a fastapi) launched through uvicorn and the python3_raw_asgi template doesn't know that the protocol used by the client is HTTPS.
It causes redirections to HTTP instead of HTTPs because the fastapi has a redirection mechanism (http 307) for URLs with or without trailing slashes.

Sources: fastapi/fastapi#9328 (comment)
https://www.uvicorn.org/deployment/#running-behind-nginx

Uvicorn provided options to handle this:

-proxy-headers / --no-proxy-headers
                                  Enable/Disable X-Forwarded-Proto,
                                  X-Forwarded-For, X-Forwarded-Port to
                                  populate remote address info.
--forwarded-allow-ips TEXT      Comma separated list of IPs to trust with
                                  proxy headers. Defaults to the
                                  $FORWARDED_ALLOW_IPS environment variable if
                                  available, or '127.0.0.1'.

Solution

Always forward HTTP headers through uvicorn.

Before:

_cmd_and_args=uvicorn {debug_extra_options} --uds "{unix_socket_path}" --workers 1 {app_name}.application:app

After:

_cmd_and_args=uvicorn {debug_extra_options} --uds "{unix_socket_path}" --proxy-headers --forwarded-allow-ips="*" --workers 1 {app_name}.application:app

Tested succesfully in my HTTPS context.

We can also decide that it is the responsibility of the developer to add these options.
So this ticket can be used as a basis of knowledge.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions