aboutsummaryrefslogtreecommitdiff
path: root/tests/test_moderation_policy.py
blob: 3421ba539be5da6b9ecca79417da0a62ccc586ab (plain) (blame)
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
61
62
63
64
65
66
67
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Domain normalization and receiver admission policy."""

from flask import Flask

from webmentions_ssg import db
from webmentions_ssg.models.moderation import AllowedDomain, BlockedDomain
from webmentions_ssg.moderation_policy import domain_from_url, rejection_reason


def test_domain_from_url() -> None:
    assert (
        domain_from_url("https://BÜCHER.example.:8443/post") == "xn--bcher-kva.example"
    )
    assert domain_from_url("https://[2001:db8::1]/post") == "2001:db8::1"
    assert domain_from_url("invalid") is None


def test_blocked_domain_matches_itself_and_subdomains_but_not_suffixes(
    app: Flask,
) -> None:
    with app.app_context():
        db.session.add(BlockedDomain(domain="example.org"))
        db.session.commit()
        for source in (
            "https://example.org/post",
            "https://blog.example.org/post",
            "https://A.blog.Example.ORG./post",
        ):
            assert rejection_reason(source) == "Source domain is blocked"
        for source in (
            "https://notexample.org/post",
            "https://example.org.evil/post",
            "https://other.net/post",
        ):
            assert rejection_reason(source) is None


def test_allowlist_is_fail_closed_and_blocklist_takes_precedence(app: Flask) -> None:
    app.config["ALLOWLIST_ENABLED"] = True
    with app.app_context():
        assert (
            rejection_reason("https://example.org/post")
            == "Source domain is not allowlisted"
        )
        db.session.add(AllowedDomain(domain="example.org"))
        db.session.commit()
        assert rejection_reason("https://blog.example.org/post") is None
        assert (
            rejection_reason("https://notexample.org/post")
            == "Source domain is not allowlisted"
        )
        db.session.add(BlockedDomain(domain="blog.example.org"))
        db.session.commit()
        assert (
            rejection_reason("https://blog.example.org/post")
            == "Source domain is blocked"
        )
        assert rejection_reason("https://example.org/post") is None


def test_rejection_reason_reports_invalid_source_hostname(app: Flask) -> None:
    with app.app_context():
        assert rejection_reason("http://[not-an-ip") == "Invalid source hostname"