Skip to content

design(cache): P1 corrupted cache data, serialization failures and safe fallback policy #112

Open

Description

@agustin18

Priority: P1 — design and tests before #96/#50

Explicitly define response caching behavior when backend bytes are corrupt, untrusted, no longer match a coder, or when encode/decode fails.

Decision matrix

  • Cache read succeeds but decode fails: distinguish invalid/corrupt entry from application serialization bug; decide fail-open recompute vs fail-closed, no accidental private replay and no infinite error loop.
  • Write/encode fails: returned response, cache header, exception policy, optional invalidate and error propagation (never suppress application correctness errors silently).
  • Backend unavailable: default policy and any opt-in fail-open semantics, bounded timeout, cancellation propagation and selective cleanup.
  • Trusted vs untrusted serialization: PickleCoder is unsafe on attacker-modifiable bytes; no auto-unpickle outside reviewed boundary.
  • No accidental leakage of raw cached values, keys, auth/session credentials, exception contents or high-cardinality labels to logs/observability.
  • Concurrency: multiple readers of bad bytes, in-flight refresh, same-key single-flight and cancellation, Redis reconnect, clear/overwrite races.
  • Deterministic negative tests for InMemory and installed Redis; optional coders follow explicit support matrix and defaults do not break legacy keys.
  • Document predictable behavior and recommended fixes with HTTP status/Cache-Control/ETag semantics in error cases.

Dependencies

RFC accepted before #96 and #50. Align with #99 multi-app lifecycle and #103 non-HTTP scope, rather than creating a second hidden global policy.

Design-first; no upload or new runtime code implicit in opening this issue.

Activity

  1. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    2026-11-23 source-level characterization to turn #112 into an actionable policy RFC (no runtime change yet):

    Current published behavior in fastapi_cache/decorator.py:

    • backend.get_with_ttl() raises an Exception → logs exception type and function/namespace, treats as MISS, recomputes endpoint. Cancellation (asyncio.CancelledError, a BaseException) normally propagates.
    • effective_coder.can_encode(result) returns false → bypasses write; encode(result) raises → propagates (no catch).
    • backend.set() raises an Exception → logs and returns the recomputed response with a MISS status and a generated ETag even though storage failed. Revalidation with matching ETag can return 304 in this branch.
    • decode_as_type(cached) raises → propagates, no selective deletion or fallback. Important ordering hazard: a matching If-None-Match can return 304 on the cached bytes before decode is attempted (lines 605–626): corrupt/undecodable data may be treated as valid for conditional requests. This deserves a deterministic negative test before any fail-open feature.
    • PickleCoder decodes pickle bytes and must be considered unsafe whenever the backend contents are not trustworthy. No automatic retry/unpickle under a recovery path.

    Proposed decisions for review, NOT yet accepted behavior:

    1. Keep general backend read error and write error policies distinct from a decode/coder error. Do not catch BaseException, swallow cancellation, or catch arbitrary endpoint bugs.
    2. Before returning a cache-driven HIT or 304, validate/decode the cached bytes. No ETag-only fast path on corrupt bytes. Fail-closed by default for decode errors until a narrow, explicit, opt-in invalid-entry recovery policy is approved; never silently unpickle attacker-owned data.
    3. If an opt-in fallback is approved: recompute exactly once per request with a safe, bounded invalidation strategy, and only on recognized coder-format errors. A failed invalidation must not create a retry/refresh loop. Do not replay a private response across identities, alter ordinary cache key digests or enable logging of raw keys/headers/payload.
    4. On failed backend write, make observable cache status truthful and explicitly specify ETag/304 semantics: an in-memory freshly calculated ETag must not be presented as proof of a persisted cache entry. Preserve response correctness when the cache is unavailable.
    5. Apply configuration through a future explicit app-scoped context (see design(app): isolate multiple FastAPI lifespans without breaking global cache API #99); non-HTTP use (design(cache): standalone application caching ergonomics without an incompatible API #103) must not depend on Response/ETag headers. Do not introduce another mutable process-global error-policy flag.
    6. Security tests: corrupt JSON/UTF-8, incompatible typed model, pickle trust boundary, backend read/write timeout or disconnection, simultaneous malformed reads, cancellation, invalidation errors, and If-None-Match on corrupt bytes; inspect that logs contain neither raw keys nor credentials. Use local InMemory and test-only standalone Redis, never destructive flush.

    Suggested implementation sequence: (a) approve the RFC, (b) add red/negative tests for existing premature-304 + malformed-cache behavior, (c) fix the smallest correctness defect independently, (d) only then consider opt-in fail-open and observability/single-flight. Do not mark #112 closed or approve #96/#50 based on this characterization alone.

  2. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    Follow-up correctness slice: Draft PR #124 now isolates one source-proven issue: in published 0.6.0, the cached-HIT path checked a matching If-None-Match and returned 304 before decode_as_type ran. The PR moves decode before that HTTP validator decision, and adds synthetic malformed JSON/UTF-8 plus valid-hit/304 tests. It preserves existing fail-closed decode-error semantics; it deliberately adds no fail-open retry, invalidation, policy flag or Redis change. A design-only failure policy RFC in the PR documents other unresolved decisions. Independent privacy/typed/PickleCoder review and exact-head CI remain required; keep #112 open.

  3. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    2026-11-23 #124 follow-up: Latest Draft PR #124, exact head 4ce2d9f6 on post-#122 stable, has 77/77 CI checks green. Added an explicit Pydantic v2 negative test: syntactically valid JSON with a matching ETag but an invalid typed field cannot return 304; it fails closed after typed decode. The security-review caveat remains: moving decode before 304 means conditional requests with PickleCoder now invoke unpickling on that path; never assume attacker-modifiable cache data are trusted. No invalidation, retries, opt-in fail-open or backend error policy has been adopted. Owner/security acceptance and full #112 matrix still pending; no release decision implied.

  4. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    Proposed narrow security/behavior decision for #124 — maintainer approval required

    Recommended narrow 0.7.x correction, NOT general recovery policy: on cache HIT, call the configured decoder/typed validator before comparing conditional If-None-Match and deciding HTTP 304. Valid bytes still produce HIT/304. Corrupt JSON, malformed UTF-8 or typed-invalid data still fail closed using the existing decoder exception behavior (no automatic key deletion, retry, backend fallback or recomputation). Keep current read/write/encode error policies pending a separate #112 matrix, and do not mask cancellation.

    Important threat boundary: a conditional request with PickleCoder now invokes unpickling where earlier it could short-circuit. Pickle remains unsafe for attacker-modifiable backend bytes: this fix is not a general secure-deserialization feature. The reviewer must explicitly accept this decoder-on-conditional-HIT effect or request a separate coder-policy design; do not call it a security GO by CI alone.

    Evidence: PR #124 exact post-#122 head 4ce2d9f6, 77/77 checks, malformed JSON/UTF-8/typed-negative HIT/304 tests and valid 304 preservation.

    Decision needed: maintainer/security reviewer ACCEPT or REJECT the narrow reorder plus Pickle trust limitation. Only then mark Draft ready/merge. Even if merged, keep #112 OPEN for approved corruption invalidation/retry policy, backend read/write exceptions, coder errors, privacy and concurrency/cancellation negative cases.

  5. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    Decisión técnica acotada para el candidato 0.7.0 — ACCEPT WITH TRUST BOUNDARY (2026-11-23)

    Tras revisión de las diferencias y pruebas de #124, se acepta para la rama de desarrollo que una respuesta cacheada solo puede producir HIT/304 después de que el coder valide/decodifique los bytes con éxito. Se preservan 304 válidos. JSON malformado, UTF-8 inválido y JSON sintácticamente válido pero tipado inválido siguen fallando de manera cerrada en vez de responder falso 304.

    Límite de seguridad aceptado, NO eliminado: PickleCoder deserializa bytes arbitrarios y, con este orden, también podría ejecutarse en una solicitud condicional antes cortocircuitada por el ETag. PickleCoder es solo para almacenamiento íntegro y de confianza. Si el backend puede ser alterado por un adversario, no se debe usar Pickle. Esta corrección no lo endurece, ni garantiza que un ETag autentique la entrada.

    No se aprueba invalidación/rehidratación automática, fail-open para corrupción, retrys, cambio de política backend.get/set, captura de BaseException, claves nuevas ni un nuevo flag global. Es un bugfix de orden exclusivamente, con error de decode propagado; no se presenta como política general segura ante fallos.

    Límites: #112 sigue abierto para la matriz completa de serialización, errores de backend, cancelación, concurrencia, métricas/redacción y eventual recuperación selectiva. La combinación con #123 necesita CI posterior a ambos merges y revisión de riesgo. Esto es decisión técnica de implementación bajo la solicitud actual, no una firma del mantenedor para publicar 0.7.0; no se crean tags ni releases.

  6. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    Post-merge checkpoint (2026-11-23): Narrow decode-before-ETag-304 change from #124 is MERGED into stable as 4dc66ad, after 77/77 exact-head checks with #123 already incorporated. Malformed JSON/UTF-8/typed-invalid cached bytes cannot return false 304; valid HIT/304 remains. Explicit PickleCoder trust boundary and no new error recovery policy apply. #112 remains OPEN for coder/backend error matrix, selective invalidation/recomputation, cancellation, concurrency, privacy/logging and real Redis outage tests. No 0.7.0 publication authorized.

  7. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    Reabierto para mantener honesta la trazabilidad de la release 0.7.0. #124 aceptó solo decode-before-304 conservando fallos de decode fail-closed y el riesgo de PickleCoder; aún faltan decisiones/evidencia para errores read/write, encode/decode, cancelaciones, concurrencia, redacción de logs y política de recuperación.

    Evitar afirmar cierre general por el merge acotado. Preparar casos negativos deterministas, Redis loopback y revisión independiente de límites; no habilitar fail-open, auto-invalidation ni política global sin revisión separada. #130 no cambia el runtime ni satisface este gate.

  8. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    0.7 serialization/error risk disposition proposed — external review needed

    PR #135 risk matrix records #124 decode-before-304 and #131 synthetic read/write, encode, cancellation, log-redaction tests; #133 adds no-retry Redis daemon outage characterization, not a general recovery API. Existing coder decode errors fail closed; PickleCoder must never decode attacker-modifiable bytes; failed writes may expose response ETag that does not attest storage. Hidden tenant/context and multiple app singleton remain unqualified.

    The prepromotion counterauditor should reproduce P0/P1 security/serialization issues, report the chosen 0.7 behavior and classify NOT RUN honestly. This does not close broad #112 or approve a universal fallback policy. Do not treat a docs CI PASS as release sign-off.

  9. agustin18 commented on Nov 23, 2026

    @agustin18
    OwnerAuthor

    0.7.0 final-candidate serialization/error risk disposition — CURRENT POLICY ACCEPTED WITH LIMITS

    Under the maintainer's explicit authorization, the following existing behavior is accepted only for source df884644f11eb0e36ae5d74721009fc8e4470c4b and its exact Phase B artifacts, subject to independent final review:

    • Default JsonCoder: corrupt JSON, invalid UTF-8 and typed-invalid cache entries fail closed. fix(cache): validate malformed HIT before conditional 304 #124 validates/decodes a cached HIT before a conditional HTTP 304; no false 304 on malformed data and no automatic invalidation/recomputation.
    • Explicit PickleCoder: uses pickle.loads; never use it when an attacker can modify cached bytes or the backing store. The decoder-before-304 fix can invoke unpickling on a conditional request that formerly short-circuited. Trusted storage is a strict precondition, not a library-provided guarantee.
    • Backend GET/SET, coder encode and cancellation: test(0.7): characterize backend failures and Redis client ownership #131 characterizes specific cases including logged exception types and cancellation propagation. There is no universal bounded-retry/fail-open guarantee, automatic corrupt-data recovery, single-flight, stale serving or new global error policy in 0.7.
    • Real outage: test(redis): exercise real disposable Redis 7.4 process outage and recovery #133 uses explicitly disabled Redis client retries. Latency with default redis-py retries is unqualified.
    • ETag on failed cache write: it identifies a representation; it is not evidence of persisted cache storage.

    Any reproducible exploitable package-owned P0/P1 or privacy regression is a NO-GO; an accepted limitation does not waive it. Keep #112 OPEN for comprehensive policy, concurrency and recovery work. Exact-artifact evidence: #126. No tag or registry approval.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions