Skip to content

fix(keys): test collisions between generated routes and isolate cached identities safely #68

Closed

Description

@agustin18

P0 confirmed correctness / security-impact review (2026-11-20). fastapi-cache-stable==0.4.0 can reuse a cached response from a different FastAPI route when both handlers are distinct closures created by a factory but share __module__, __name__, no arguments and the same namespace. A maintainer agent reported: /a → {'value':'A'} MISS, /b → {'value':'A'} HIT instead of B. That HTTP test was reported externally, not replayed in this review; the identical key digest was independently reproduced from the exact published builder logic. This establishes a wrong-response hazard, not proof of arbitrary cross-tenant exploitation. Give it P0 priority ahead of feature train; assess a narrow 0.4.x correction when feasible, and do not change default key formats without a versioned migration/rollback strategy.

Context

default_key_builder still MD5-hashes {func.__module__}:{func.__name__}:{args}:{kwargs} (plus namespace), preserving the original fastapi-cache2 key identity. Two distinct closures made by a factory can share __module__ and __name__, identical parameters and namespace while their response depends on different captured state. The two closures do produce identical default keys whenever module, function name, args/kwargs and namespace match. A maintainer agent additionally reported an HTTP-level 0.4.0 reproduction (below). This is a confirmed cache-correctness defect; whether it permits cross-tenant/private data exposure in a concrete application remains unproven and requires a separate security impact check.

Related: upstream #491, our #53, #49.

Acceptance

  1. Make two real FastAPI routes using distinct factory closures with same function name/module but different captured data; test generated keys, MISS/HIT, content, namespace and headers, and explicit user/tenant separation where meaningful.
  2. Add golden fixtures for 0.2.2 → 0.4.0 default keys. Decide whether the closure issue is incorrect response replay, a cache-miss case, or just an unsupported caller configuration.
  3. First evaluate an immediately safe narrow, conservative mitigation for ambiguous factory routes and whether it fits a timely 0.4.x patch; also design explicit per-route namespaces / opt-in stable route-identity key builders with key migration guidance. Do not globally hash closure memory addresses or silently change existing default Redis keys.
  4. Threat-model the interaction with cache_authenticated, custom key_builder, Request bypass, Vary/header dependencies, and multi-process sharing.
  5. Incorrect response replay across routes is already confirmed and must be addressed before new 0.5.0 feature work. Separately test whether this can become a package-controlled tenant/privacy leak. For an actual security disclosure, use private GitHub security advisory coordination before publishing exploitation details. Do not silently change legacy keys across all endpoints.

Exit

Reproducible positive and negative integration tests, no old-key golden changes by default, and explicit migration/isolation documentation.

Activity

  1. added
    bug
    on Nov 20, 2026
  2. added 2 commits that reference this issue on Nov 20, 2026
  3. agustin18 commented on Nov 20, 2026

    @agustin18
    OwnerAuthor

    Implementation candidate for #68: draft PR #73, HEAD 19bb53b6d38f8c65a51efabdd1a0f3bc43a9bd01 (not merged/published). The published 0.4.0 remains affected.

    Design: scoped per-route SHA-256 partition only for generated/lambda FastAPI HTTP handlers using the exact legacy default_key_builder (host, HTTP method, mount root, request path, previous key). Other module-level/default keys and custom key builders are unchanged. Old shared generated-route MD5 entries are deliberately never read, while new keys keep the same namespace prefix and generated routes still cache (MISS/HIT). Invalid/missing ASGI path triggers a fail-closed bypass.

    Evidence: new InMemory HTTP and real standalone Redis integration tests verify distinct /a and /b closures (A MISS, B MISS, then independent HITs); seeded legacy poisoned key cannot replay; module-level key golden remains unchanged. Earlier first-head test run passed 315 tests but correctly failed 100% diff coverage because missing-path bypass lacked coverage; added a regression and reran. CI on updated head has shown real Redis and compatibility lanes passing; inspect exact latest CI before approval.

    Scope limits: This is a generated HTTP route fix, not proof of universal key uniqueness for direct non-ASGI decorated callables, two independently deployed apps using the same host/path/prefix, a custom builder, or hidden identity/locale/tenant state (#53). A confirmed arbitrary tenant disclosure is not claimed. Review the intentional factory-route cache-key rotation/migration and decide if a targeted 0.4.1 patch is preferable; no version bump, tag or publication has occurred. Keep #68 OPEN pending review/merge and appropriate release verification.

  4. agustin18 commented on Nov 20, 2026

    @agustin18
    OwnerAuthor

    New reproduction and fix iteration — functools.wraps (2026-11-20). Independent reviewer found the first #73 solution still failed when a factory used functools.wraps(module_level_template): /a → A MISS, /b → A HIT because __name__/__qualname__ were overwritten. This is a real blocker, not a harmless edge case. PR #73 has now been updated on branch fix/factory-route-cache-key-68 to also inspect actual function code co_freevars (unchanged by wraps). Added FastAPI integration assertions for wrapped /a and /b MISS/MISS/HIT/HIT, old-key non-replay, Host case normalization/different hosts, generated route method/root_path/path partition, FastAPICache.clear(namespace=...), and real Redis 7 integration using wrapped handlers with namespace clearing.

    Impact caveat: this also rotates keys for some ordinary module-level functions wrapped by closure decorators, because these are code closures despite module-level naming. Unwrapped module-level handlers and exported builder remain unchanged. Unvalidated Host can fragment the cache; document TrustedHostMiddleware. #53 hidden context remains open. Neither PR nor code change has been merged/published; latest CI must pass exact updated head before review.

  5. agustin18 commented on Nov 20, 2026

    @agustin18
    OwnerAuthor

    Reviewer blocker resolved in PR #73 on an exact tested HEAD (2026-11-20): 920997e6d3d0dcbc8dba18e707130aac6560aca2. The prior detector trusted __qualname__ and __name__; functools.wraps(template) overwrote those fields and allowed /a A MISS -> /b A HIT response replay. The revised detector also checks func.__code__.co_freevars and now distinguishes wrapped factory closures. Regression tests include wrapped HTTP routes MISS/MISS/HIT/HIT, poisoned old-cache key non-replay, path/HTTP method/root_path/host partition, case-insensitive Host spellings, named namespace clear in InMemory and real Redis 7.

    CI: PR #73 HEAD 50/50 checks PASS. Python 3.10 job: 321 passed / 18 skipped, 100% changed-line coverage; Redis 7 integration: 13 passed. Modern/legacy Python matrix, Redis client wheel/sdist metadata, lint, CodeQL and security audits passed.

    Compatibility/security review still needed: a module-level endpoint wrapped by an actual closure may now use a new scoped key; this is intentional to avoid reading potentially shared old entries. The exported legacy builder and unwrapped module-level keys remain unchanged. Host is normalized only for case; without TrustedHostMiddleware/edge validation arbitrary Host values can fragment cache storage. This is not universal tenant isolation (#53). PR remains OPEN, not merged, #68 remains OPEN, and v0.4.0 is still the latest publication. Evaluate scoped 0.4.1 patch after review; do not assume no other synthetic-function metadata patterns exist.

  6. agustin18 commented on Nov 20, 2026

    @agustin18
    OwnerAuthor

    Second reviewer blocker corrected — functools.wraps + default-bound value (2026-11-20). The previous co_freevars test did NOT catch:

    from functools import wraps
    async def template(): return {}
    def factory(value):
        @wraps(template)
        async def endpoint(value=value):
            return {"value": value}
        return endpoint

    co_freevars == () while __name__/__qualname__ are overwritten by @wraps, allowing /a → A MISS; /b → A HIT on earlier #73 HEAD. The current implementation in PR #73 detects explicit __wrapped__ metadata in addition to closure freevars, <locals> and lambda names. A direct getattr(func,"__wrapped__",None) is not None is sufficient; recursive inspect.unwrap gives no extra detection benefit for this boolean test and can add per-request traversal/cycle handling.

    Regression scope: InMemory HTTP checks for default-bound wraps factory /a → A MISS, /b → B MISS, then both HIT; old potentially contaminated cache entries skipped; module-level decorated-but-no-closure key rotation explicitly tested; Redis 7 integration parametrized for wrapped closure and wrapped default-bound handler, including named clear(namespace); existing method/Host/root_path/path partition and normal module-level key tests remain. Documentation now states any __wrapped__ module-level handler may intentionally rotate its key, even without freevars, and notes host validation/fragmentation limits.

    Exact HEAD 0f26788dac3eced92e96b81045920163696deabb: all 49/49 GitHub checks successful. Python 3.10: 325 passed, 18 skipped, 100% changed-line diff coverage; Redis 7: 14 passed; mypy: no issues. All additional Redis wheel/sdist profiles, CodeQL, security, lint and distribution inspection green. The interim code had legitimate mypy then Ruff test-assertion failures; fixed through isinstance(..., FunctionType) narrowing and reran full CI, no checks disabled.

    Status: PR #73 OPEN, not merged; #68 OPEN pending independent review and proper release decision. stable / v0.4.0 unchanged. #53 hidden request context/Vary stays open.

  7. agustin18 commented on Nov 20, 2026

    @agustin18
    OwnerAuthor

    Resolved by #73 and published in 0.4.1. Tag v0.4.1 points to release commit ed1000b; TestPyPI run 44771878983 and PyPI run 44772219414 succeeded. Wheel a68c770ebdd6dff06e7a6b282b71be1a60dc020b7d3f0b971c307a83489d708d and sdist e171db38e12b8a5b1815a5d781018b39d4af883be0d65ed01a6162cfeb0417af are recorded in docs/releases/RELEASE_STATUS_0.4.1.md. Factory/wraps/default-bound regressions pass. Residual Vary/hidden-context and Host-validation limits remain in #53 and the docs.

  8. added a commit that references this issue on Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugkeyssecurity

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions