From 74295b5d8cd5aa0c92ccc5aa665a134a775d85ed Mon Sep 17 00:00:00 2001 From: Edward Oliveira Date: Mon, 30 Nov 2026 15:32:06 -0300 Subject: [PATCH] =?UTF-8?q?Ignora=20If-Unmodified-Since=20sem=20data=20e?= =?UTF-8?q?=20varia=20a=20resposta=20por=20usu=C3=A1rio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Sem data de atualização, o If-Unmodified-Since é ignorado em vez de responder 412 (RFC 9110, 13.1.4) - Respostas com validadores mandam Vary: Authorization, Cookie, porque os campos visíveis dependem das permissões de quem pede - nginx: CORS aceita If-None-Match e If-Unmodified-Since e expõe ETag e Last-Modified Co-Authored-By: Claude Opus 5.5 --- docker/config/nginx/sapl.conf | 8 ++++---- sapl/api/tests/test_api_last_modified.py | 23 +++++++++++++++++++++++ sapl/api/views.py | 10 +++++++++- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/docker/config/nginx/sapl.conf b/docker/config/nginx/sapl.conf index ce5171a00..2018ae9e3 100644 --- a/docker/config/nginx/sapl.conf +++ b/docker/config/nginx/sapl.conf @@ -22,15 +22,15 @@ server { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, HEAD, OPTIONS'; - add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Origin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; - add_header 'Access-Control-Expose-Headers' 'Access-Control-Allow-Origin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; + add_header 'Access-Control-Allow-Headers' 'Access-Control-Allow-Origin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,If-None-Match,If-Unmodified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; + add_header 'Access-Control-Expose-Headers' 'Access-Control-Allow-Origin,XMLHttpRequest,Accept,Authorization,Cache-Control,Content-Type,DNT,ETag,If-Modified-Since,Keep-Alive,Last-Modified,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; # handle the browser's preflight steps if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, HEAD, OPTIONS'; - add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; - add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range'; + add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,If-None-Match,If-Unmodified-Since,Cache-Control,Content-Type,Content-Range,Range'; + add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,ETag,Last-Modified'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; diff --git a/sapl/api/tests/test_api_last_modified.py b/sapl/api/tests/test_api_last_modified.py index 63bfaa217..88d36e178 100644 --- a/sapl/api/tests/test_api_last_modified.py +++ b/sapl/api/tests/test_api_last_modified.py @@ -194,6 +194,27 @@ def test_last_modified_do_detalhe(api, usuario): assert response.status_code == 412 +@pytest.mark.parametrize('url', [ + pytest.param(URL_MATERIA, id='data-nula'), + pytest.param(URL_TRAMITACAO, id='sem-campo-de-data'), +]) +def test_if_unmodified_since_sem_data_e_ignorado(api, usuario, url): + if url == URL_MATERIA: + obj = baker.make(MateriaLegislativa) + atualizado_em(obj, None) + else: + obj = baker.make(Tramitacao) + admin = api(usuario('admin', is_superuser=True)) + detalhe = f'{url}{obj.pk}/' + + response = admin.get(detalhe, HTTP_IF_UNMODIFIED_SINCE=HTTP_ANTES) + assert response.status_code == 200 + + response = admin.patch(detalhe, {}, format='json', + HTTP_IF_UNMODIFIED_SINCE=HTTP_ANTES) + assert response.status_code == 200 + + def test_detalhe_busca_o_objeto_uma_vez(api): materia = baker.make(MateriaLegislativa) pelo_id = f'"{MateriaLegislativa._meta.db_table}"."id" = {materia.pk}' @@ -216,6 +237,8 @@ def test_respostas_com_validadores_pedem_revalidacao(api): assert response.status_code == 200, url diretivas = {d.strip() for d in response['Cache-Control'].split(',')} assert {'private', 'no-cache'} <= diretivas, url + vary = {v.strip().lower() for v in response['Vary'].split(',')} + assert {'authorization', 'cookie'} <= vary, url @pytest.fixture diff --git a/sapl/api/views.py b/sapl/api/views.py index 09fbe4661..440380465 100644 --- a/sapl/api/views.py +++ b/sapl/api/views.py @@ -7,7 +7,8 @@ from django.core.exceptions import ValidationError as DjangoValidationError from django.db.models import Count, Max, Q, Sum from django.http import (Http404, HttpResponse, HttpResponseNotModified, JsonResponse) -from django.utils.cache import get_conditional_response, patch_cache_control +from django.utils.cache import (get_conditional_response, patch_cache_control, + patch_vary_headers) from django.utils.http import http_date, parse_etags from rest_framework.authtoken.models import Token from rest_framework.decorators import api_view, permission_classes @@ -103,6 +104,10 @@ class LastModifiedMixin: raise _RespostaCondicional(HttpResponseNotModified()) return + if self._last_modified is None: + # Sem data, o If-Unmodified-Since é ignorado (RFC 9110, 13.1.4) + return + response = get_conditional_response( request, last_modified=self._last_modified) if response is not None: @@ -132,6 +137,9 @@ class LastModifiedMixin: # Sem isso, o navegador pode reaproveitar a resposta sem # revalidar, por um tempo estimado a partir do Last-Modified patch_cache_control(response, private=True, no_cache=True) + # Os campos visíveis dependem das permissões de quem pede: um + # cache com mais de um usuário não pode reaproveitar a resposta + patch_vary_headers(response, ('Authorization', 'Cookie')) return response def get_object(self):