metwork-framework / mfserv

metwork/mfserv module
http://metwork-framework.org
BSD 3-Clause "New" or "Revised" License
12 stars 6 forks source link

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

Open matthieumarrast opened 8 months ago

matthieumarrast commented 8 months ago

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: https://github.com/tiangolo/fastapi/discussions/9328#discussioncomment-8242245 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.

thebaptiste commented 8 months ago

618 let the developer choose between adding these options or not