rules:
  - id: auth.py.fastapi.session-hardcoded-secret
    languages:
      - python
    severity: ERROR
    message: |
      Starlette's `SessionMiddleware` is configured with a hard-coded
      `secret_key` string literal. 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.
    # Scoped to Starlette/FastAPI `SessionMiddleware`, added via
    # `app.add_middleware(SessionMiddleware, ..., secret_key="...")` or
    # instantiated directly. The `secret_key="..."` pattern matches ONLY a
    # string literal, so `secret_key=os.environ[...]`, a settings reference, or
    # `secrets.token_hex(...)` are NOT flagged. Obvious placeholder/`${ENV}`
    # template strings are dropped so docs stubs do not fire.
    patterns:
      - pattern-either:
          - pattern: $APP.add_middleware(SessionMiddleware, ..., secret_key="...", ...)
          - pattern: SessionMiddleware(..., secret_key="...", ...)
      - pattern-not-regex: 'secret_key\s*=\s*["'']\$\{?[A-Za-z_]+\}?["'']'
      - pattern-not-regex: 'secret_key\s*=\s*["'']<[^"'']*>["'']'
      - pattern-not-regex: '(?i)secret_key\s*=\s*["''](?:your[-_]|example|placeholder|xxx+|todo|changeme|change[-_]?me|replace|\.\.\.)'
    metadata:
      oauthlint-rule-id: AUTH-PY-FASTAPI-001
      oauthlint-doc-url: https://oauthlint.dev/rules/py-fastapi-session-hardcoded-secret
      category: security
      cwe: CWE-798
      owasp: A07:2021
      llm-prevalence: HIGH
      technology:
        - fastapi
        - starlette
      references:
        - https://www.starlette.io/middleware/#sessionmiddleware
        - https://cwe.mitre.org/data/definitions/798.html
