Why AI tools produce this: AI coding tools generate this anti-pattern by default, it appears in a large share of AI-written auth code.
Why this matters
That key signs every session cookie: anyone who reads the source or a leaked repo can forge a session and impersonate any user, a complete authentication bypass (CWE-798). This is a common AI-generated shortcut, where a literal secret is inlined so the sample "just works" and is never externalized.
Load the key from the environment or a secret manager instead, e.g. app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"]), and generate it with a CSPRNG such as secrets.token_hex(32). Rotate the leaked secret out of source control.
import osimport secretsfrom fastapi import FastAPIfrom starlette.middleware.sessions import SessionMiddlewareapp = FastAPI()# Loaded from the environment.# ok: auth.py.fastapi.session-hardcoded-secretapp.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"])# Settings reference.# ok: auth.py.fastapi.session-hardcoded-secretapp.add_middleware(SessionMiddleware, secret_key=settings.session_secret)# Generated with a CSPRNG.# ok: auth.py.fastapi.session-hardcoded-secretapp.add_middleware(SessionMiddleware, secret_key=secrets.token_hex(32))# Obvious placeholder / env template — not a real secret.# ok: auth.py.fastapi.session-hardcoded-secretapp.add_middleware(SessionMiddleware, secret_key="${SESSION_SECRET}")# ok: auth.py.fastapi.session-hardcoded-secretapp.add_middleware(SessionMiddleware, secret_key="changeme")
Suppressing this rule
If a finding is a genuine false positive, scope the suppression to the exact line and leave a reason, never disable the rule project-wide. Disable directives are line-scoped by design.