From f84a020c15608ead833161e752c8e5c8addf0917 Mon Sep 17 00:00:00 2001 From: Edward Oliveira Date: Mon, 3 Aug 2026 14:51:58 -0300 Subject: [PATCH] Sanitiza HTML/JavaScript nos campos TextField (stored XSS) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Os ~71 campos models.TextField do SAPL guardavam texto livre sem nenhuma sanitização, e a renderização os tratava como HTML confiável em 142 pontos (|safe, {% autoescape off %}). Qualquer usuário com permissão de edição conseguia gravar Ciente') == 'Ciente' + assert sanitize_html('Encaminhado ao setor') == \ + 'Encaminhado ao setor' + assert sanitize_html('') == '' + assert sanitize_html('
a
b
') == 'ab' + + +def test_plain_escapa_caracteres_especiais(): + assert sanitize_html('Valor < 10 & prazo > 5') == \ + 'Valor < 10 & prazo > 5' + + +def test_plain_preserva_quebras_de_linha(): + # get_field_display converte \n em
depois de sanitizar + assert sanitize_html('linha1\nlinha2') == 'linha1\nlinha2' + + +def test_valores_vazios_atravessam(): + assert sanitize_html('') == '' + assert sanitize_html(None) is None + assert sanitize_html('', rich=True) == '' + + +@pytest.mark.parametrize('valor', [ + 'Ciente', + 'Valor < 10 & prazo > 5', + 'Encaminhado ao setor', + 'texto & cia', +]) +def test_plain_e_idempotente(valor): + """Propriedade da qual dependem as duas camadas (pre_save + renderização). + + Se sanitizar duas vezes não fosse estável, o valor gravado seria + re-escapado a cada exibição. + """ + uma_vez = sanitize_html(valor) + assert sanitize_html(uma_vez) == uma_vez + + +@pytest.mark.parametrize('valor', [ + 'Portal', + '

centro

', + '
c
', + 'ok', +]) +def test_rich_e_idempotente(valor): + uma_vez = sanitize_html(valor, rich=True) + assert sanitize_html(uma_vez, rich=True) == uma_vez + + +def test_rich_preserva_links(): + saida = sanitize_html( + 'Portal', + rich=True) + assert 'href="https://camara.gov.br"' in saida + assert 'target="_blank"' in saida + assert 'rel="noopener noreferrer"' in saida + assert '>Portal' in saida + + assert 'href="/materia/123"' in sanitize_html( + 'Matéria', rich=True) + assert 'href="mailto:a@b.c"' in sanitize_html( + 'mail', rich=True) + + +def test_rich_remove_href_perigosa_mas_mantem_o_texto(): + saida = sanitize_html( + 'clique', rich=True) + assert 'javascript' not in saida + assert 'clique' in saida + + +def test_rich_remove_script_e_manipuladores_de_evento(): + saida = sanitize_html('ok', rich=True) + assert saida == 'ok' + + assert 'onclick' not in sanitize_html( + 'x', rich=True) + assert 'onerror' not in sanitize_html( + '', rich=True) + + +def test_rich_preserva_formatacao_do_tinymce(): + """Protege contra regressão visual no conteúdo já cadastrado.""" + assert 'style="text-align: center;"' in sanitize_html( + '

centro

', rich=True) + + saida = sanitize_html( + '
c
', rich=True) + assert '' in saida and 'colspan="2"' in saida + + assert sanitize_html('', rich=True) == \ + '' + + +def test_sanitize_scope(): + assert sanitize_scope(TramitacaoAdministrativo, 'texto') == 'plain' + assert sanitize_scope(ExpedienteSessao, 'conteudo') == 'rich' + assert sanitize_scope(LexmlProvedor, 'xml') == 'exempt' + + +def test_sanitize_field_respeita_isencao(): + xml = 'y' + assert sanitize_field(LexmlProvedor, 'xml', xml) == xml + + +@pytest.mark.django_db +def test_pre_save_sanitiza_campo_simples(): + t = baker.make(TramitacaoAdministrativo, + texto='Ciente ok') + t.refresh_from_db() + assert t.texto == 'Ciente ok' + + +@pytest.mark.django_db +def test_pre_save_sanitiza_campo_rico_preservando_html(): + e = baker.make(ExpedienteSessao, + conteudo='x' + 'l') + e.refresh_from_db() + assert '' + p = baker.make(LexmlProvedor, xml=xml) + p.refresh_from_db() + assert p.xml == xml + + +@pytest.mark.django_db +def test_get_field_display_nao_devolve_script(): + t = TramitacaoAdministrativo(texto='Ciente') + __, display = get_field_display(t, 'texto') + assert 'legado') + t.refresh_from_db() + assert t.texto == 'legado' + + __, display = get_field_display(t, 'texto') + assert '