Recursos · 63

Caché HTTP: proteger respuestas personalizadas

Separar cachés compartidos, privados y de aplicaciones, inspeccionar claves, revalidación e invalidación después de cambios en los derechos de acceso.

Actualizado · 7 min

Pasillo seguro de servidores y redes sin personal Ilustración editorial generada con IA

Lo que esta guía ayuda a lograr

  • Capas de inventario
  • Elige retención
  • Inspeccionar claves
  • Revalidación y cambio de ejercicio

Comprobación rápida

  • ¿Sin caché significa que no se retiene nada?
  • ¿Vary protege los derechos de acceso?
  • ¿Se deben almacenar en caché todas las API?

Método paso a paso

  1. 1

    Capas de inventario

    Listado de cachés de navegador, CDN, proxy, trabajador de servicio y aplicaciones. Clasificar respuestas públicas y personalizadas. Una política HTTP no describe automáticamente el almacenamiento en caché implementado en el código.

    Entregable: diagrama de capas y propietarios.

  2. 2

    Elige retención

    RFC 9111 distingue directivas: no-cache requiere validación antes de su reutilización, no-store prohíbe el almacenamiento HTTP relevante y privado no calificado excluye el almacenamiento compartido. Ninguno por sí solo garantiza la confidencialidad del sistema.

    Entregable: política de retención por respuesta.

  3. 3

    Inspeccionar claves

    Verificar método, URI y dimensiones cambiando una representación. Variar los campos de solicitud de preocupaciones; no es autorización. Busque lenguaje omitido, negociación de formato y contexto de cuenta en las capas de aplicación.

    Entregable: claves y pruebas de separación.

  4. 4

    Revalidación y cambio de ejercicio

    Pruebe respuestas nuevas y obsoletas, actualizaciones de datos y derechos revocados. Inspeccione ETag, validación condicional y comportamiento de origen no disponible. Una respuesta que antes era correcta puede volverse confidencial después de la revocación.

    Entregable: trazas de antes y después.

  5. 5

    Rejugar con dos cuentas

    Utiliza identidades y marcadores ficticios. Solicitudes alternativas al mismo URI con cachés frías y calientes. Verifique el cierre de sesión, los enlaces directos y el inicio de sesión sin registrar tokens reales.

    Entregable: pruebas negativas y estrategia de invalidación.

Medir también la frescura de la caché

Ejemplo ficticio: estos datos no describen clientes ni resultados observados.

Situación

Dos lecturas son rápidas, pero una sigue mostrando disponibilidad antigua después de cambiar la fuente.

Comprobar

Comparar valor, versión, lugar de lectura y tiempo desde el cambio. Probar invalidación, caducidad y consulta de origen según el contrato del sistema.

Actuar

Definir la frescura aceptable por uso y vigilar discrepancias. Una latencia menor no demuestra coherencia de los datos servidos.

Hoja de cálculo reutilizable

Complete con sus observaciones autorizadas. Estos campos son una plantilla de trabajo, no resultados observados.

CampoInformación a registrar
RespuestaPúblico o personalizado; dimensiones
CapaCaché, propietario y clave
PolíticaRetención, frescura y validación
PruebaRelato ficticio, cambio y observación

Ejemplo trabajado ficticio

Situación ilustrativa

Ejemplo ficticio: una CDN reutiliza una respuesta de perfil en el mismo URI para dos cuentas de prueba.

Decisión y pruebas esperadas

El escenario detecta fugas, examina políticas y claves y luego se reproduce después de la corrección y la revocación de acceso.

Distinguir los mecanismos

MecanismoPropósitoVerificación o limitación
sin cachéPermitir almacenamiento con validación requeridaNo leerlo como sin almacenamiento
Privado no calificadoExcluir almacenamiento en caché compartidoNo lo leas como garantía de confidencialidad
sin tiendaImpedir el almacenamiento HTTP relevanteVerificar cachés e historial de aplicaciones por separado

Indicadores de gestión

IndicadorQué midePrimera acción
Separación de cuentasNingún marcador de otra cuentaInspeccionar cuerpo, enlaces y metadatos
Edad y validaciónReutilización coherente con políticaCaducidad de la prueba y origen no disponible
Retraso de invalidaciónTiempo hasta representación corregidaNombre cada capa aún obsoleta

Errores comunes

  • No leerlo como sin almacenamiento
  • No lo leas como garantía de confidencialidad
  • Verificar cachés e historial de aplicaciones por separado

Preguntas frecuentes

¿Sin caché significa que no se retiene nada?

No. Requiere validación antes de su reutilización; no prohíbe el almacenamiento como lo hace el no almacenamiento.

¿Vary protege los derechos de acceso?

No. Participa en la selección de representación; la autorización permanece separada.

¿Se deben almacenar en caché todas las API?

No. Los beneficios dependen del costo, la frescura y el riesgo. Las respuestas confidenciales pueden justificar evitar cachés compartidos.

ETag, caché HTTP y actualizaciones concurrentes

Las notas detalladas de esta edición están disponibles en inglés.

ETag: revalidate responses and prevent lost updates

An ETag is an opaque validator for the selected representation. It compares versions; it is neither authorisation nor an access token, and it need not be a file hash. Personalised responses require separate decisions about access, cache selection and HTTP conditions.

Local teaching model: a representation already exists; at most one conditional field contains a single ETag or *. GET, HEAD and PUT are covered. Tag lists, date validators, ranges, creation, combined conditions and the already-succeeded modification exception are excluded. No network call, storage or state change occurs; this does not test your API.

Laboratorio de red ficticio sin personas, con equipos sobre una mesa oscura iluminada en ámbar. Ilustración editorial generada con IA
Generated conceptual scene: a fictional empty network laboratory. It shows neither a real facility nor a protocol measurement.

Strong and weak ETag comparison serve different purposes

If-Match requires strong comparison: neither tag may start with W/. If-None-Match uses weak comparison, matching the opaque values regardless of W/. Values remain case-sensitive. The * wildcard checks representation existence here, not a particular version.

Strong and weak ETag comparison serve different purposes
Current tagReceived tagStrong comparisonWeak comparison
"v1""v1"MatchesMatches
"v1"W/"v1"Does not matchMatches
W/"v1"W/"v1"Does not matchMatches
"v1""v2"Does not matchDoes not match
"v1""V1"Does not matchDoes not match

Simulate an HTTP decision without contacting a server

The six parameters yield 432 combinations. Requiring a conditional field and selecting 204 for successful PUT are policies of this fictional scenario. Requiring any condition does not prevent every lost update: If-Match: * compares no version.

Model decision : 304

304: If-None-Match finds a weak match for GET or HEAD. Reuse the stored representation under cache rules with the revalidation metadata.

304 and 204: no response content.

Request excerpt

GET /demo/resource HTTP/1.1
Host: api.example.test
If-None-Match: W/"v1"

Response excerpt

HTTP/1.1 304 Not Modified
Date: Thu, 22 Oct 2026 00:00:00 GMT
ETag: "v1"
Cache-Control: private, no-cache

Fictional HTTP/1.1 excerpts for reading: bodies are omitted even where allowed. api.example.test is an example domain. The date is fixed. This model does not update the ETag after PUT; the separate walkthrough follows successive versions.

Ten reproducible situations

Ten reproducible situations
Fictional situationCondition and expected outcomeInterpretation
Read using a weak tagGET · "v1"
If-None-Match: W/"v1" → 304

Access allowed · Conditional field optional

W/"v1" and "v1" match weakly.
Different client versionGET · "v1"
If-None-Match: "v2" → 200

Access allowed · Conditional field optional

The client needs the selected representation.
HEAD revalidationHEAD · "v1"
If-None-Match: "v1" → 304

Access allowed · Conditional field optional

The status can be 304; the response has no content.
Write based on an old versionPUT · "v2"
If-Match: "v1" → 412

Access allowed · Conditional field optional

Read again and resolve the conflict before retrying.
Weak tag with If-MatchPUT · "v1"
If-Match: W/"v1" → 412

Access allowed · Conditional field optional

Strong comparison rejects a weak tag.
Required condition absent on PUTPUT · "v1"
none → 428

Access allowed · Conditional field required

428 follows the policy announced by this API.
Access denied despite matching tagGET · "v1"
If-None-Match: "v1" → 403

Access denied · Conditional field optional

Authorisation precedes HTTP conditions.
Write on the correct versionPUT · "v1"
If-Match: "v1" → 204

Access allowed · Conditional field required

The model accepts PUT and selects a 204 success.
If-None-Match: * on existing dataPUT · "v1"
If-None-Match: * → 412

Access allowed · Conditional field optional

The wildcard matches any existing representation.
If-Match: * on existing dataPUT · W/"v1"
If-Match: * → 204

Access allowed · Conditional field required

The wildcard passes even with a weak current tag: it does not protect a version.

Four rules for a personalised response

Four rules for a personalised response
Response fieldHTTP effect within this scopeEvidence to retain
Cache-Control: no-cacheUnqualified no-cache permits storage, but any reuse needs successful validation with the origin server.Observe a conditional round trip; do not read no-cache as a storage prohibition.
Cache-Control: no-storeForbids storage by private and shared HTTP caches. It is not a general privacy guarantee.Also review logs, history, screenshots and application storage.
Cache-Control: privateUnqualified private forbids storage by a shared cache; a private cache may store under the other constraints.Distinguish browser, proxy and CDN. A directive does not replace access checks.
VaryAdds the named request fields to selection of a stored response. It does not decide who may access a resource.Test relevant variants. Do not assume a cookie or Authorization automatically prevents all caching.

Useful API acceptance evidence

  • Expected request and status: method, test resource, access rights, conditional field and current ETag. Use fictional data and remove secrets.
  • Observed response: status, ETag, Date, Cache-Control, Vary and no content for HEAD, 204 or 304. A 304 must carry the required metadata that would have accompanied the 200.
  • Concurrency: verify that a stale write fails without changing the resource; retain the conflict-resolution decision. Do not blindly replace the ETag and resend the same write.

Follow the two-client conflict →

Primary references and limits

The standards define HTTP conditions and caching. The ten cases, laboratory and two-client walkthrough are original illustrations. Displayed results are calculated by this local model, not measurements of this site or your infrastructure.

References reviewed

Referencias oficiales

Las referencias respaldan el método. Adapte los controles a su contexto; no constituyen certificación. Los títulos de referencia originales y los documentos fuente pueden estar en otro idioma.

Referencias consultadas el .