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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
"""Authenticated domain moderation views and operations."""
from http import HTTPStatus
from typing import cast
import sqlalchemy as sa
from flask import abort, current_app, flash, redirect, render_template, url_for
from flask.typing import ResponseReturnValue
from flask_login import login_required
from sqlalchemy.exc import IntegrityError
from ..extensions import db
from ..forms.admin import ConfirmActionForm
from ..forms.moderation import ModerateDomainForm
from ..models.moderation import AllowedDomain, BlockedDomain
from .blueprint import webmentions_bp
MODERATION_DOMAIN_MODELS = {"blocked": BlockedDomain, "allowed": AllowedDomain}
def block_domains(domains: set[str]) -> int:
"""Persist distinct source domains, tolerating concurrent blocklist inserts.
Savepoints isolate unique-constraint races so one preexisting entry cannot
prevent other selected domains from being blocked.
"""
existing = set(
db.session.scalars(
sa.select(BlockedDomain.domain).where(BlockedDomain.domain.in_(domains))
)
)
added = 0
for domain in sorted(domains - existing):
try:
with db.session.begin_nested():
db.session.add(BlockedDomain(domain=domain))
db.session.flush()
except IntegrityError:
# A concurrent admin action has already blocked this hostname.
continue
added += 1
db.session.commit()
return added
@webmentions_bp.get("/moderation")
@login_required
def moderation() -> ResponseReturnValue:
"""Manage blocklist and allowlist entries used by the receiver."""
return render_template(
"moderation.html",
title="Source domain rules",
blocked=db.session.scalars(
sa.select(BlockedDomain).order_by(BlockedDomain.domain)
).all(),
allowed=db.session.scalars(
sa.select(AllowedDomain).order_by(AllowedDomain.domain)
).all(),
allowlist_enabled=current_app.config["ALLOWLIST_ENABLED"],
)
@webmentions_bp.post("/moderation/<kind>/add")
@login_required
def moderation_domain_add(kind: str) -> ResponseReturnValue:
"""Validate and add a normalized hostname to the selected domain list."""
if (model := MODERATION_DOMAIN_MODELS.get(kind)) is None:
abort(HTTPStatus.NOT_FOUND)
form = ModerateDomainForm()
if not form.validate_on_submit():
abort(HTTPStatus.BAD_REQUEST)
domain = cast(str, form.domain.data)
if db.session.scalar(sa.select(model.id).where(model.domain == domain)) is None:
db.session.add(model(domain=domain))
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
flash(f"Source domain {domain} added to {kind} list.", "success")
return redirect(url_for("webmentions.moderation"))
@webmentions_bp.post("/moderation/<kind>/<int:entry_id>/delete")
@login_required
def moderation_domain_delete(kind: str, entry_id: int) -> ResponseReturnValue:
"""Remove a rule; unblocked domains become eligible for submissions again."""
if (model := MODERATION_DOMAIN_MODELS.get(kind)) is None:
abort(HTTPStatus.NOT_FOUND)
if not ConfirmActionForm().validate_on_submit():
abort(HTTPStatus.BAD_REQUEST)
entry = db.get_or_404(model, entry_id)
domain = entry.domain
db.session.delete(entry)
db.session.commit()
flash(f"Source domain {domain} removed from {kind} list.", "success")
return redirect(url_for("webmentions.moderation"))
|