aboutsummaryrefslogtreecommitdiff
path: root/webmentions_ssg/source_policy.py
blob: 2c62527e64d203c58d8ef6cf88d8c166eb23492b (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
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause

"""Admission policy for incoming Webmention source hostnames."""

import ipaddress

import sqlalchemy as sa
from flask import current_app

from .extensions import db
from .hostname import normalize_hostname
from .models import AllowedSource, BlockedSource


def source_domain_from_url(source: str) -> str | None:
    """Extract and canonicalize the source hostname without a network request."""
    try:
        return normalize_hostname(source, from_url=True)
    except ValueError:
        return None


def has_matching_domain(
    model: type[AllowedSource | BlockedSource], domain: str
) -> bool:
    """Match the hostname itself and parent domains, never partial labels."""
    candidates = [domain]
    # An IP address can only match itself, not a suffix of its textual form.
    try:
        ipaddress.ip_address(domain)
    except ValueError:
        parts = domain.split(".")
        candidates.extend(".".join(parts[i:]) for i in range(1, len(parts)))

    return (
        db.session.scalar(
            sa.select(model.id).where(model.domain.in_(candidates)).limit(1)
        )
        is not None
    )


def source_rejection_reason(source: str) -> str | None:
    """Return the reason a source cannot be received, or None when accepted.

    The blocklist always wins. In allowlist mode an empty allowlist rejects
    every source. The database, not a stale per-worker cache, is consulted.
    """
    if (domain := source_domain_from_url(source)) is None:
        return "Invalid source hostname"

    if has_matching_domain(BlockedSource, domain):
        return "Source domain is blocked"

    if current_app.config["SOURCE_ALLOWLIST_ENABLED"] and not has_matching_domain(
        AllowedSource, domain
    ):
        return "Source domain is not allowlisted"

    return None