all repos — rastro @ 303f75c7f98bcf857e2ef49ec4c4489ce9eb333b

BitTorrent tracker!

tests/unit/test_normalize_ssrf.py (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
"""Normalization and SSRF unit tests."""

from __future__ import annotations

import pytest
from app.services.normalize import (
    NormalizationError,
    normalize_tracker_url,
    parse_tracker_list_text,
)
from app.services.ssrf import assert_safe_destination, is_blocked_hostname, is_public_ip


def test_parse_blank_lines_and_duplicates():
    body = "udp://a.example:80/announce\n\n\nudp://a.example:80/announce\nhttp://b.example:80/announce\n"
    items = parse_tracker_list_text(body)
    assert items == [
        "udp://a.example:80/announce",
        "http://b.example:80/announce",
    ]


def test_normalize_basic_and_idna():
    n = normalize_tracker_url("HTTPS://EXEMPLO.COM:443/announce")
    assert n.scheme == "https"
    assert n.hostname == "exemplo.com"
    assert n.port == 443
    assert n.canonical_url == "https://exemplo.com:443/announce"

    n2 = normalize_tracker_url("http://bücher.example/announce")
    assert "xn--" in n2.hostname
    assert n2.scheme == "http"


def test_reject_credentials_and_bad_port():
    with pytest.raises(NormalizationError):
        normalize_tracker_url("http://user:pass@host.example:80/announce")
    with pytest.raises(NormalizationError):
        normalize_tracker_url("udp://host.example:99999/announce")


def test_unsupported_ws():
    n = normalize_tracker_url("wss://tracker.example/announce")
    assert n.unsupported is True


def test_ssrf_blocks_private_and_metadata():
    assert is_public_ip("8.8.8.8")
    assert not is_public_ip("127.0.0.1")
    assert not is_public_ip("10.0.0.1")
    assert not is_public_ip("192.168.1.1")
    assert not is_public_ip("169.254.169.254")
    assert not is_public_ip("::1")
    assert not is_public_ip("fc00::1")
    assert is_blocked_hostname("localhost")
    assert is_blocked_hostname("metadata.google.internal")
    with pytest.raises(ValueError):
        assert_safe_destination("evil.example", ["127.0.0.1"])
    with pytest.raises(ValueError):
        assert_safe_destination("localhost", ["8.8.8.8"])