TypeError / secure

Lightweight modern Python library to add security headers (CSP, HSTS, etc.) to Django, Flask, FastAPI, and more. Secure defaults or fully customizable.
MIT License
900 stars 27 forks source link

Server header is not overridden #22

Closed lsmith77 closed 2 months ago

lsmith77 commented 1 year ago

I am using the following in a FastAPI project

server = secure.Server().set("Secure")

But the result is:

server: uvicorn
server: Secure

ie. it does not override the server header but simply adds another one.

nashyeung commented 1 year ago

I just got the same problem. Turns out it is uvicorn that injects the server header unconditionally. You can run uvicorn with the --no-server-header option to disable this header. Ref: https://www.uvicorn.org/settings/#http

lsmith77 commented 1 year ago

In my case I fixed it now using

    uvicorn.run(
        app,
        host="0.0.0.0",
        port=8000,
        server_header=False,
    )
cak commented 7 months ago

Thanks @lsmith77 and @nashyeung! I'll add this to the documentation.

alexmaurizio commented 3 months ago

I'll just point out in this issue that if you use Uvicorn VIA Gunicorn (eg: as a Uvicorn-Worker), this setting is not passed so it's impossible to override, unless subclassing the worker itself. This is not a problem with Secure.py but with Uvicorn/Gunicorn combo.

Refer here -> https://github.com/encode/uvicorn/issues/1436 | https://github.com/encode/uvicorn/discussions/1435

cak commented 2 months ago

Hi everyone,

Thanks for raising this issue! As @nashyeung and @lsmith77 mentioned, Uvicorn injects the Server header by default. If you're using Secure.py and want to override the Server header, you’ll need to disable Uvicorn's default behavior.

You can do this by using the --no-server-header option when running Uvicorn or setting server_header=False in the uvicorn.run() method:

uvicorn.run(
    app,
    host="0.0.0.0",
    port=8000,
    server_header=False,  # Disable the default Uvicorn Server header
)

Additionally, as @alexmaurizio pointed out, if you're using Uvicorn via Gunicorn, this setting is not passed through unless you subclass the worker. This is a limitation of the Uvicorn-Gunicorn combo, not of Secure.py.

This information has been added to the documentation for the upcoming v1.0.0 release. Thanks again for your contributions!