diff --git a/conftest.py b/conftest.py index 62064338e..7f2863637 100644 --- a/conftest.py +++ b/conftest.py @@ -1,5 +1,16 @@ import pytest from django_webtest import DjangoTestApp, WebTestMixin +from rest_framework.throttling import AnonRateThrottle + + +@pytest.fixture(autouse=True) +def sem_limite_de_requisicoes_da_api(monkeypatch): + """ + Nos testes, todas as requisições anônimas vêm do mesmo endereço e o + histórico do limite fica no cache entre um teste e outro. Os testes do + limite (sapl/api/tests/test_api_abuso.py) definem a própria taxa. + """ + monkeypatch.setattr(AnonRateThrottle, 'THROTTLE_RATES', {'anon': None}) class OurTestApp(DjangoTestApp): diff --git a/drfautoapi/drfautoapi.py b/drfautoapi/drfautoapi.py index 2b2c0481e..c68511463 100644 --- a/drfautoapi/drfautoapi.py +++ b/drfautoapi/drfautoapi.py @@ -149,18 +149,37 @@ class ApiFilterSetMixin(FilterSet): except: return queryset - def filter_o(self, queryset, name, value): - fields = list(map(str.strip, value.split(','))) - + def get_ordering_fields(self): + """ + Campos aceitos em `o`: os campos concretos do próprio model (pelo + nome ou pela coluna, como tipo_id), exceto os ocultos. + """ hidden = self.get_hidden_fields() - if any(f.lstrip('-') in hidden for f in fields): - return queryset + fields = {'pk'} + for f in self._meta.model._meta.concrete_fields: + if f.name not in hidden: + fields |= {f.name, f.attname} + return fields - try: - return queryset.order_by(*fields) - except: + def filter_o(self, queryset, name, value): + """ + Ordena pelos campos informados, separados por vírgula, com "-" para + ordem decrescente. O parâmetro é ignorado se algum campo não estiver + em get_ordering_fields: caminhos para outros models (a__b) e campos + ocultos permitiriam deduzir valores que não aparecem na resposta, e + "?" ordena aleatoriamente, o que é caro. + """ + fields = [f.strip() for f in value.split(',') if f.strip()] + if not fields: return queryset + allowed = self.get_ordering_fields() + for f in fields: + if (f[1:] if f.startswith('-') else f) not in allowed: + return queryset + + return queryset.order_by(*fields) + @classmethod def get_fields(cls): model = cls._meta.model diff --git a/sapl/api/pagination.py b/sapl/api/pagination.py index 67aecd7f5..b1de53996 100644 --- a/sapl/api/pagination.py +++ b/sapl/api/pagination.py @@ -1,5 +1,7 @@ from django.core.paginator import EmptyPage +from django.db.models.query import QuerySet from rest_framework import pagination +from rest_framework.exceptions import ValidationError from rest_framework.response import Response @@ -8,11 +10,30 @@ class StandardPagination(pagination.PageNumberPagination): page_size_query_param = 'page_size' max_page_size = 100 + # get_all=true devolve a lista inteira, sem paginar. Sem login, só + # quando o total não passa deste limite. A página pública de + # parlamentares usa get_all para legislaturas e parlamentares. + get_all_max_anonimo = 500 + def paginate_queryset(self, queryset, request, view=None): if request.query_params.get('get_all', '').lower() == 'true': + if not request.user.is_authenticated: + self.verifica_limite_get_all(queryset) return None return super().paginate_queryset(queryset, request, view=view) + def verifica_limite_get_all(self, queryset): + limite = self.get_all_max_anonimo + if isinstance(queryset, QuerySet): + total = queryset[:limite + 1].count() + else: + total = len(queryset) + + if total > limite: + raise ValidationError({'detail': ( + f'Sem autenticação, get_all=true só pode ser usado com até ' + f'{limite} registros. Use a paginação (page e page_size).')}) + def get_paginated_response_schema(self, schema): r = { 'type': 'object', diff --git a/sapl/api/serializers.py b/sapl/api/serializers.py index d623dc563..acab5f9f1 100644 --- a/sapl/api/serializers.py +++ b/sapl/api/serializers.py @@ -46,16 +46,29 @@ class SaplSerializerMixin(DrfAutoApiSerializerMixin): return hidden def get_metadata(self, obj) -> dict: - try: - metadata = Metadata.objects.get( - content_type=ContentType.objects.get_for_model( - obj._meta.model), - object_id=obj.id - ).metadata - except: - metadata = {} - finally: - return metadata + """ + Numa listagem, busca de uma vez os metadados de todos os objetos da + lista, em vez de uma query por objeto. O resultado fica no contexto + do serializer raiz, compartilhado por toda a resposta. + """ + content_type = ContentType.objects.get_for_model(obj._meta.model) + cache = self.context.setdefault('_sapl_metadata', {}).setdefault( + content_type.id, {}) + + if obj.pk not in cache: + pks = {obj.pk} + if isinstance(self.parent, serializers.ListSerializer) and \ + self.parent.instance is not None: + pks |= {o.pk for o in self.parent.instance + if o.pk not in cache} + + encontrados = dict(Metadata.objects.filter( + content_type=content_type, object_id__in=pks + ).values_list('object_id', 'metadata')) + for pk in pks: + cache[pk] = encontrados.get(pk, {}) + + return cache[obj.pk] def get_link_detail_backend(self, obj) -> str: try: diff --git a/sapl/api/tests/test_api_abuso.py b/sapl/api/tests/test_api_abuso.py new file mode 100644 index 000000000..caeed8b38 --- /dev/null +++ b/sapl/api/tests/test_api_abuso.py @@ -0,0 +1,213 @@ +import datetime + +import pytest +from django.contrib.contenttypes.models import ContentType +from django.db import connection +from django.test.utils import CaptureQueriesContext +from model_bakery import baker +from rest_framework.throttling import AnonRateThrottle + +from sapl.api.pagination import StandardPagination +from sapl.api.tests.conftest import resultados +from sapl.base.models import Metadata +from sapl.parlamentares.models import (Legislatura, Mandato, Parlamentar, + Partido) + +URL_LEGISLATURA = '/api/parlamentares/legislatura/' +URL_PARTIDO = '/api/parlamentares/partido/' +URL_MANDATO = '/api/parlamentares/mandato/' + + +@pytest.fixture +def legislaturas(db): + return [baker.make(Legislatura, numero=n, + data_inicio=datetime.date(2000 + 4 * n, 1, 1), + data_fim=datetime.date(2003 + 4 * n, 12, 31), + data_eleicao=datetime.date(1999 + 4 * n, 10, 1)) + for n in range(1, 4)] + + +@pytest.fixture +def limite_get_all(monkeypatch): + monkeypatch.setattr(StandardPagination, 'get_all_max_anonimo', 2) + + +# get_all + + +@pytest.mark.django_db(transaction=False) +def test_get_all_anonimo_dentro_do_limite_devolve_lista(api, legislaturas): + """Usado pela página pública de parlamentares (frontend/parlamentar).""" + response = api().get(URL_LEGISLATURA, {'get_all': 'true'}) + + assert response.status_code == 200 + assert isinstance(response.json(), list) + assert len(response.json()) == 3 + + +@pytest.mark.django_db(transaction=False) +def test_get_all_anonimo_acima_do_limite_e_recusado( + api, legislaturas, limite_get_all): + response = api().get(URL_LEGISLATURA, {'get_all': 'true'}) + + assert response.status_code == 400 + assert 'page_size' in response.json()['detail'] + + +@pytest.mark.django_db(transaction=False) +def test_get_all_anonimo_em_action_acima_do_limite_e_recusado( + api, legislaturas, limite_get_all): + legislatura = legislaturas[0] + for _ in range(3): + baker.make(Mandato, legislatura=legislatura, + data_inicio_mandato=legislatura.data_inicio, + data_fim_mandato=legislatura.data_fim) + + url = f'{URL_LEGISLATURA}{legislatura.pk}/parlamentares/' + assert api().get(url, {'get_all': 'true'}).status_code == 400 + + +@pytest.mark.django_db(transaction=False) +def test_get_all_autenticado_nao_tem_limite( + api, usuario, legislaturas, limite_get_all): + response = api(usuario('operador')).get( + URL_LEGISLATURA, {'get_all': 'true'}) + + assert response.status_code == 200 + assert len(response.json()) == 3 + + +@pytest.mark.django_db(transaction=False) +def test_paginacao_continua_limitada_sem_get_all(api, legislaturas, + limite_get_all): + response = api().get(URL_LEGISLATURA, {'page_size': 2}) + + assert response.status_code == 200 + assert response.json()['pagination']['total_entries'] == 3 + assert len(resultados(response)) == 2 + + +# metadata + + +def _partidos_com_metadata(quantidade): + content_type = ContentType.objects.get_for_model(Partido) + partidos = baker.make(Partido, _quantity=quantidade) + for partido in partidos[::2]: + baker.make(Metadata, content_type=content_type, + object_id=partido.pk, metadata={'sigla_tse': partido.pk}) + return partidos + + +def _queries(client, url, params): + with CaptureQueriesContext(connection) as queries: + response = client.get(url, params) + assert response.status_code == 200 + return len(queries), response + + +@pytest.mark.django_db(transaction=False) +def test_metadata_nao_faz_uma_query_por_objeto(api): + _partidos_com_metadata(30) + + com_2, _ = _queries(api(), URL_PARTIDO, {'page_size': 2}) + com_30, _ = _queries(api(), URL_PARTIDO, {'page_size': 30}) + get_all, _ = _queries(api(), URL_PARTIDO, {'get_all': 'true'}) + + assert com_30 == com_2 + assert get_all <= com_2 + + +@pytest.mark.django_db(transaction=False) +def test_metadata_continua_correto(api): + partidos = _partidos_com_metadata(5) + id__in = ','.join(str(p.pk) for p in partidos) + + for params in ({'page_size': 5}, {'get_all': 'true'}): + response = api().get(URL_PARTIDO, {'id__in': id__in, **params}) + metadata = {p['id']: p['metadata'] for p in resultados(response)} + assert metadata == { + p.pk: ({'sigla_tse': p.pk} if i % 2 == 0 else {}) + for i, p in enumerate(partidos)} + + detalhe = api().get(f'{URL_PARTIDO}{partidos[0].pk}/').json() + assert detalhe['metadata'] == {'sigla_tse': partidos[0].pk} + + +# ordenação (o) + + +@pytest.fixture +def mandatos(db): + """Ordem padrão (por parlamentar) diferente da ordem por CPF.""" + ana = baker.make(Parlamentar, nome_parlamentar='Ana', cpf='99999999999') + bruno = baker.make(Parlamentar, nome_parlamentar='Bruno', + cpf='11111111111') + return [baker.make(Mandato, parlamentar=ana), + baker.make(Mandato, parlamentar=bruno)] + + +def _ordem(response): + assert response.status_code == 200 + return [m['id'] for m in resultados(response)] + + +@pytest.mark.django_db(transaction=False) +@pytest.mark.parametrize('o', [ + 'parlamentar__cpf', + '-parlamentar__data_nascimento', + 'parlamentar__user__password', + '?', + 'campo_inexistente', + 'id,parlamentar__cpf', +]) +def test_ordenacao_so_aceita_campos_do_proprio_model(api, mandatos, o): + padrao = _ordem(api().get(URL_MANDATO)) + + assert _ordem(api().get(URL_MANDATO, {'o': o})) == padrao + + +@pytest.mark.django_db(transaction=False) +def test_ordenacao_por_campos_do_proprio_model(api, mandatos): + ana, bruno = mandatos + + assert _ordem(api().get(URL_MANDATO, {'o': '-id'})) == [bruno.pk, ana.pk] + assert _ordem(api().get(URL_MANDATO, {'o': 'pk'})) == [ana.pk, bruno.pk] + assert _ordem(api().get( + URL_MANDATO, {'o': '-parlamentar_id, id'})) == [bruno.pk, ana.pk] + assert _ordem(api().get( + URL_MANDATO, {'o': '-parlamentar'})) == [bruno.pk, ana.pk] + + +# throttling + + +@pytest.fixture +def limite_requisicoes(monkeypatch): + monkeypatch.setattr(AnonRateThrottle, 'THROTTLE_RATES', {'anon': '3/min'}) + + +@pytest.mark.django_db(transaction=False) +def test_requisicoes_anonimas_sao_limitadas(api, legislaturas, + limite_requisicoes): + client = api() + status = [client.get(URL_LEGISLATURA).status_code for _ in range(4)] + + assert status == [200, 200, 200, 429] + + +@pytest.mark.django_db(transaction=False) +def test_requisicoes_autenticadas_nao_sao_limitadas( + api, usuario, legislaturas, limite_requisicoes): + client = api(usuario('operador')) + + assert {client.get(URL_LEGISLATURA).status_code + for _ in range(5)} == {200} + + +@pytest.mark.django_db(transaction=False) +@pytest.mark.parametrize('url', ['/health/', '/ready/', '/version/']) +def test_health_check_nao_e_limitado(api, limite_requisicoes, url): + client = api() + + assert 429 not in {client.get(url).status_code for _ in range(5)} diff --git a/sapl/api/views_health.py b/sapl/api/views_health.py index bd7e6eaad..b15380b4f 100644 --- a/sapl/api/views_health.py +++ b/sapl/api/views_health.py @@ -24,6 +24,7 @@ def _format_plain(ok: bool) -> HttpResponse: class HealthzView(APIView): authentication_classes = [] permission_classes = [] + throttle_classes = [] logger = logging.getLogger(__name__) @@ -50,6 +51,7 @@ class HealthzView(APIView): class ReadyzView(APIView): authentication_classes = [] permission_classes = [] + throttle_classes = [] logger = logging.getLogger(__name__) @@ -84,6 +86,7 @@ class ReadyzView(APIView): class AppzVersionView(APIView): authentication_classes = [] permission_classes = [] + throttle_classes = [] logger = logging.getLogger(__name__) diff --git a/sapl/settings.py b/sapl/settings.py index 5936f0f23..76cd1c54b 100644 --- a/sapl/settings.py +++ b/sapl/settings.py @@ -186,6 +186,23 @@ REST_FRAMEWORK = { "rest_framework.filters.SearchFilter", 'django_filters.rest_framework.DjangoFilterBackend', ), + + # Limita as requisições anônimas à API por cliente. Usuários + # autenticados (sessão ou token) não são limitados. Para desativar, + # use API_THROTTLE_ANON vazio. + "DEFAULT_THROTTLE_CLASSES": ( + "rest_framework.throttling.AnonRateThrottle", + ), + "DEFAULT_THROTTLE_RATES": { + "anon": config('API_THROTTLE_ANON', default='300/min') or None, + }, + # O cliente é identificado pelo X-Forwarded-For. Com o número de proxies + # reversos à frente do SAPL (o nginx da imagem conta como um), usa-se o + # endereço acrescentado pelo proxy mais externo, que o cliente não + # consegue forjar. Sem valor, vale o padrão do DRF (o cabeçalho inteiro). + "NUM_PROXIES": config( + 'API_NUM_PROXIES', default='', + cast=lambda v: int(v) if str(v).strip() else None), } DRFAUTOAPI = {