from urllib.parse import urlencode
from urllib.request import Request, urlopen

from tests.support.local_target import local_template_target


def _submit(target: str, value: str) -> str:
    request = Request(
        f"{target}/apply",
        data=urlencode({"name": value}).encode(),
        method="POST",
    )
    with urlopen(request, timeout=2) as response:
        return response.read().decode()


def test_vulnerable_target_exposes_a_repeatable_template_primitive() -> None:
    with local_template_target() as target:
        assert _submit(target.url, "{{7*7}}") == "Application received for 49"
        assert _submit(target.url, "{{6*7}}") == "Application received for 42"
        assert target.flag in _submit(target.url, "{{config}}")
        assert target.flag in _submit(target.url, "{{config.FLAG}}")


def test_hardened_target_reflects_template_syntax_without_evaluating_it() -> None:
    with local_template_target(vulnerable=False) as target:
        response = _submit(target.url, "{{config.FLAG}}")

    assert response == "Application received for {{config.FLAG}}"
    assert target.flag not in response
