Run isolated spam filter checks on mail receivers
This commit is contained in:
1 parent
ca9543ee0a
commit
042406b2aa
10 files changed
+653
-6
No files matched your search
@@ -2533,6 +2533,28 @@ show the journal's delivery state and enhanced status code when present.
|
|||||||
The journal search is limited to the selected domain on the configured
|
The journal search is limited to the selected domain on the configured
|
||||||
mail receiver. Header analysis runs without contacting the mail node.
|
mail receiver. Header analysis runs without contacting the mail node.
|
||||||
|
|
||||||
|
### Check the incoming spam filter
|
||||||
|
|
||||||
|
On **Mail diagnostics**, select a managed mail domain and choose
|
||||||
|
**Run filter check**. The check runs on the same local or linked mail
|
||||||
|
receiver that provisions mailboxes for the panel. Keep linked receivers
|
||||||
|
at the same Coulobre release. The report identifies the receiver, shows
|
||||||
|
the expected and observed decisions, and lists scores, thresholds and
|
||||||
|
matching rules for the two synthetic messages.
|
||||||
|
|
||||||
|
The direct check covers SpamAssassin's local rules. It uses a transient
|
||||||
|
unprivileged service with a read-only system, private temporary storage
|
||||||
|
and no network access. Bayesian learning and online checks are disabled.
|
||||||
|
The messages never enter Postfix or reach a mailbox. The check is
|
||||||
|
unavailable when SpamAssassin is absent, including mail nodes that only
|
||||||
|
use Rspamd for signing. The panel retains the summary for one hour.
|
||||||
|
[SpamAssassin GTUBE](https://spamassassin.apache.org/gtube/)
|
||||||
|
|
||||||
|
For an end-to-end check of the SMTP listener, milter and mailbox delivery,
|
||||||
|
follow the [SpamAssassin test procedure](#filter-incoming-mail-with-spamassassin)
|
||||||
|
with a designated test mailbox. Run that procedure separately from the
|
||||||
|
direct filter check.
|
||||||
|
|
||||||
## Check and provision mail DNS
|
## Check and provision mail DNS
|
||||||
|
|
||||||
Open **Check mail DNS** under **Mail domains**. The check reads MX and
|
Open **Check mail DNS** under **Mail domains**. The check reads MX and
|
||||||
|
|||||||
@@ -1,4 +1,12 @@
|
|||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
from django import forms
|
from django import forms
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.db import transaction
|
||||||
|
from django.http import Http404
|
||||||
|
from django.shortcuts import get_object_or_404, redirect
|
||||||
|
from django.urls import reverse
|
||||||
|
from django.utils import timezone
|
||||||
from django.utils.decorators import method_decorator
|
from django.utils.decorators import method_decorator
|
||||||
from django.views.decorators.cache import never_cache
|
from django.views.decorators.cache import never_cache
|
||||||
from django.views.decorators.debug import (
|
from django.views.decorators.debug import (
|
||||||
@@ -15,8 +23,37 @@ from coulobre.mail_diagnostics import (
|
|||||||
|
|
||||||
from .access import PanelRole
|
from .access import PanelRole
|
||||||
from .account_administration import OperatorAuthorization
|
from .account_administration import OperatorAuthorization
|
||||||
|
from .domain_policies import policy_for
|
||||||
from .installation_features import panel_feature_allowed
|
from .installation_features import panel_feature_allowed
|
||||||
from .models import HostingMailDomain
|
from .models import HostingMailDomain, MailFilterCheck
|
||||||
|
|
||||||
|
|
||||||
|
def diagnostic_domains():
|
||||||
|
return (
|
||||||
|
HostingMailDomain.objects.filter(account__retired_at__isnull=True)
|
||||||
|
.select_related("account")
|
||||||
|
.order_by("domain")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class MailFilterCheckForm(forms.Form):
|
||||||
|
domain = forms.ModelChoiceField(
|
||||||
|
queryset=HostingMailDomain.objects.none(),
|
||||||
|
label="Managed mail domain",
|
||||||
|
help_text="The check runs on the mail node configured for this panel.",
|
||||||
|
)
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
super().__init__(*args, **kwargs)
|
||||||
|
self.fields["domain"].queryset = diagnostic_domains()
|
||||||
|
|
||||||
|
def clean_domain(self):
|
||||||
|
domain = self.cleaned_data["domain"]
|
||||||
|
if not policy_for(domain.account, domain.domain).mail_managed:
|
||||||
|
raise forms.ValidationError(
|
||||||
|
"This domain uses an external provider."
|
||||||
|
)
|
||||||
|
return domain
|
||||||
|
|
||||||
|
|
||||||
class MailDiagnosticsForm(forms.Form):
|
class MailDiagnosticsForm(forms.Form):
|
||||||
@@ -62,13 +99,70 @@ class MailDiagnosticsView(OperatorAuthorization, FormView):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def get_context_data(self, **kwargs):
|
def get_context_data(self, **kwargs):
|
||||||
|
available = panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING")
|
||||||
|
if available and "filter_form" not in kwargs:
|
||||||
|
kwargs["filter_form"] = MailFilterCheckForm()
|
||||||
|
check_id = self.request.GET.get("check")
|
||||||
|
if check_id is not None and "filter_check" not in kwargs:
|
||||||
|
if (
|
||||||
|
not available
|
||||||
|
or not check_id.isascii()
|
||||||
|
or not check_id.isdecimal()
|
||||||
|
or len(check_id) > 18
|
||||||
|
):
|
||||||
|
raise Http404
|
||||||
|
check = get_object_or_404(
|
||||||
|
MailFilterCheck,
|
||||||
|
pk=check_id,
|
||||||
|
actor=self.request.user,
|
||||||
|
domain__in=diagnostic_domains(),
|
||||||
|
expires_at__gt=timezone.now(),
|
||||||
|
)
|
||||||
|
if not policy_for(
|
||||||
|
check.domain.account, check.domain.domain
|
||||||
|
).mail_managed:
|
||||||
|
raise Http404
|
||||||
|
kwargs["filter_check"] = check
|
||||||
return super().get_context_data(
|
return super().get_context_data(
|
||||||
mail_delivery_available=panel_feature_allowed(
|
mail_delivery_available=available,
|
||||||
"LOCAL_MAILBOX_PROVISIONING"
|
|
||||||
),
|
|
||||||
**kwargs,
|
**kwargs,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def post(self, request, *args, **kwargs):
|
||||||
|
if request.POST.get("action") == "check-filter":
|
||||||
|
if not panel_feature_allowed("LOCAL_MAILBOX_PROVISIONING"):
|
||||||
|
raise Http404
|
||||||
|
return self.queue_filter_check()
|
||||||
|
return super().post(request, *args, **kwargs)
|
||||||
|
|
||||||
|
@transaction.atomic
|
||||||
|
def queue_filter_check(self):
|
||||||
|
form = MailFilterCheckForm(self.request.POST)
|
||||||
|
if form.is_valid():
|
||||||
|
get_user_model().objects.select_for_update().get(
|
||||||
|
pk=self.request.user.pk
|
||||||
|
)
|
||||||
|
now = timezone.now()
|
||||||
|
recent = MailFilterCheck.objects.filter(
|
||||||
|
actor=self.request.user,
|
||||||
|
requested_at__gte=now - timedelta(minutes=1),
|
||||||
|
)
|
||||||
|
if recent.exists():
|
||||||
|
form.add_error(None, "Wait a minute between filter checks.")
|
||||||
|
else:
|
||||||
|
check = MailFilterCheck.objects.create(
|
||||||
|
actor=self.request.user,
|
||||||
|
domain=form.cleaned_data["domain"],
|
||||||
|
expires_at=now + timedelta(hours=1),
|
||||||
|
)
|
||||||
|
url = reverse("panel:mail_diagnostics")
|
||||||
|
return redirect(f"{url}?check={check.pk}")
|
||||||
|
return self.render_to_response(
|
||||||
|
self.get_context_data(
|
||||||
|
form=self.form_class(), filter_form=form, filter_check=None
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
def form_invalid(self, form):
|
def form_invalid(self, form):
|
||||||
return self.render_to_response(
|
return self.render_to_response(
|
||||||
self.get_context_data(
|
self.get_context_data(
|
||||||
|
|||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Generated by Django 5.2.19 on 2026-12-01 23:42
|
||||||
|
|
||||||
|
import django.db.models.deletion
|
||||||
|
import django.utils.timezone
|
||||||
|
from django.conf import settings
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
dependencies = [
|
||||||
|
("hosting", "0086_smtp_applications"),
|
||||||
|
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.CreateModel(
|
||||||
|
name="MailFilterCheck",
|
||||||
|
fields=[
|
||||||
|
(
|
||||||
|
"id",
|
||||||
|
models.BigAutoField(
|
||||||
|
auto_created=True,
|
||||||
|
primary_key=True,
|
||||||
|
serialize=False,
|
||||||
|
verbose_name="ID",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"requested_at",
|
||||||
|
models.DateTimeField(default=django.utils.timezone.now),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"last_dispatched_at",
|
||||||
|
models.DateTimeField(blank=True, null=True),
|
||||||
|
),
|
||||||
|
("started_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("finished_at", models.DateTimeField(blank=True, null=True)),
|
||||||
|
("problem", models.TextField(blank=True)),
|
||||||
|
("report", models.JSONField(default=dict)),
|
||||||
|
("expires_at", models.DateTimeField(db_index=True)),
|
||||||
|
(
|
||||||
|
"actor",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
to=settings.AUTH_USER_MODEL,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"domain",
|
||||||
|
models.ForeignKey(
|
||||||
|
on_delete=django.db.models.deletion.CASCADE,
|
||||||
|
to="hosting.hostingmaildomain",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
options={
|
||||||
|
"abstract": False,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1040,6 +1040,15 @@ class MailDeliverySearch(ProvisioningJob):
|
|||||||
expires_at = models.DateTimeField(db_index=True)
|
expires_at = models.DateTimeField(db_index=True)
|
||||||
|
|
||||||
|
|
||||||
|
class MailFilterCheck(ProvisioningJob):
|
||||||
|
actor = models.ForeignKey(
|
||||||
|
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
||||||
|
)
|
||||||
|
domain = models.ForeignKey(HostingMailDomain, on_delete=models.CASCADE)
|
||||||
|
report = models.JSONField(default=dict)
|
||||||
|
expires_at = models.DateTimeField(db_index=True)
|
||||||
|
|
||||||
|
|
||||||
class AccountRetirement(models.Model):
|
class AccountRetirement(models.Model):
|
||||||
class Policy(models.TextChoices):
|
class Policy(models.TextChoices):
|
||||||
HOLD = "hold", "Keep names reserved"
|
HOLD = "hold", "Keep names reserved"
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ from .models import (
|
|||||||
MailboxProvisioning,
|
MailboxProvisioning,
|
||||||
MailboxRemoval,
|
MailboxRemoval,
|
||||||
MailDeliverySearch,
|
MailDeliverySearch,
|
||||||
|
MailFilterCheck,
|
||||||
MailRoutingPublication,
|
MailRoutingPublication,
|
||||||
MailVacationPublication,
|
MailVacationPublication,
|
||||||
OffsiteBackupTransfer,
|
OffsiteBackupTransfer,
|
||||||
@@ -311,6 +312,7 @@ def dispatch_dns_publications():
|
|||||||
@shared_task
|
@shared_task
|
||||||
def dispatch_mailbox_provisioning():
|
def dispatch_mailbox_provisioning():
|
||||||
MailDeliverySearch.objects.filter(expires_at__lte=timezone.now()).delete()
|
MailDeliverySearch.objects.filter(expires_at__lte=timezone.now()).delete()
|
||||||
|
MailFilterCheck.objects.filter(expires_at__lte=timezone.now()).delete()
|
||||||
if settings.LOCAL_MAILBOX_PROVISIONING:
|
if settings.LOCAL_MAILBOX_PROVISIONING:
|
||||||
dispatch_provisioning_jobs(
|
dispatch_provisioning_jobs(
|
||||||
MailDeliverySearch,
|
MailDeliverySearch,
|
||||||
@@ -318,6 +320,12 @@ def dispatch_mailbox_provisioning():
|
|||||||
MAILBOX_PROVISIONING_QUEUE,
|
MAILBOX_PROVISIONING_QUEUE,
|
||||||
expires_at__gt=timezone.now(),
|
expires_at__gt=timezone.now(),
|
||||||
)
|
)
|
||||||
|
dispatch_provisioning_jobs(
|
||||||
|
MailFilterCheck,
|
||||||
|
run_mail_filter_check,
|
||||||
|
MAILBOX_PROVISIONING_QUEUE,
|
||||||
|
expires_at__gt=timezone.now(),
|
||||||
|
)
|
||||||
dispatch_provisioning_jobs(
|
dispatch_provisioning_jobs(
|
||||||
MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE
|
MailboxProvisioning, provision_mailbox, MAILBOX_PROVISIONING_QUEUE
|
||||||
)
|
)
|
||||||
@@ -1528,6 +1536,45 @@ def search_mail_delivery(job_id):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@shared_task(queue=MAILBOX_PROVISIONING_QUEUE)
|
||||||
|
def run_mail_filter_check(job_id):
|
||||||
|
from coulobre.mail_filter_check import (
|
||||||
|
SCAN_TIMEOUT,
|
||||||
|
MailFilterCheckRequest,
|
||||||
|
validated_report,
|
||||||
|
)
|
||||||
|
|
||||||
|
from .domain_policies import policy_for
|
||||||
|
from .node_client import apply_on_local_node
|
||||||
|
|
||||||
|
def apply(job):
|
||||||
|
domain = job.domain
|
||||||
|
if (
|
||||||
|
not job.actor.is_active
|
||||||
|
or not job.actor.is_superuser
|
||||||
|
or domain.account.retired_at is not None
|
||||||
|
or job.expires_at <= timezone.now()
|
||||||
|
or not policy_for(domain.account, domain.domain).mail_managed
|
||||||
|
):
|
||||||
|
raise ValueError("This mail filter check is no longer available.")
|
||||||
|
reply = apply_on_local_node(
|
||||||
|
MailFilterCheckRequest(domain.domain),
|
||||||
|
"/run/coulobre-mail-apply.sock",
|
||||||
|
"mail node",
|
||||||
|
"filter check",
|
||||||
|
timeout=2 * SCAN_TIMEOUT + 10,
|
||||||
|
)
|
||||||
|
return {"report": validated_report(reply)}
|
||||||
|
|
||||||
|
if settings.LOCAL_MAILBOX_PROVISIONING:
|
||||||
|
run_provisioning_job(
|
||||||
|
MailFilterCheck.objects.select_related("domain__account", "actor"),
|
||||||
|
job_id,
|
||||||
|
apply,
|
||||||
|
"The mail node did not return a filter report.",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
@shared_task(acks_late=True, reject_on_worker_lost=True)
|
||||||
def apply_certificate_job(job_id):
|
def apply_certificate_job(job_id):
|
||||||
from django.views.decorators.debug import sensitive_variables
|
from django.views.decorators.debug import sensitive_variables
|
||||||
|
|||||||
@@ -2,7 +2,47 @@
|
|||||||
{% block title %}Mail diagnostics · Coulobre Panel{% endblock %}
|
{% block title %}Mail diagnostics · Coulobre Panel{% endblock %}
|
||||||
{% block page_title %}Mail diagnostics{% endblock %}
|
{% block page_title %}Mail diagnostics{% endblock %}
|
||||||
{% block page_content %}
|
{% block page_content %}
|
||||||
|
{% if filter_form %}
|
||||||
|
<section class="surface editor-surface">
|
||||||
|
<header class="section-heading"><h2>Check the spam filter</h2></header>
|
||||||
|
<p class="section-text">Run an isolated SpamAssassin scan with an ordinary sample and GTUBE. This checks local filtering rules. It does not send mail or test SMTP delivery.</p>
|
||||||
|
<form class="editor" method="post" action="{% url 'panel:mail_diagnostics' %}">
|
||||||
|
{% csrf_token %}
|
||||||
|
{{ filter_form.as_div }}
|
||||||
|
<button class="button secondary" type="submit" name="action" value="check-filter">Run filter check</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
|
{% if filter_check %}
|
||||||
|
<section class="surface" id="filter-check" aria-label="Filter check results" data-live-status="mail-filter-check">
|
||||||
|
<header class="section-heading">
|
||||||
|
<h2>Filter check for {{ filter_check.domain.domain }}</h2>
|
||||||
|
{% if not filter_check.finished_at %}<a class="button secondary" href="?check={{ filter_check.pk }}#filter-check">Refresh status</a>{% endif %}
|
||||||
|
</header>
|
||||||
|
{% if filter_check.problem %}
|
||||||
|
<p class="section-text">{{ filter_check.problem }}</p>
|
||||||
|
{% elif not filter_check.finished_at %}
|
||||||
|
<p class="section-text" data-live-pending>{{ filter_check.state|capfirst }}</p>
|
||||||
|
{% else %}
|
||||||
|
<p class="section-text">SpamAssassin on <strong>{{ filter_check.report.node }}</strong></p>
|
||||||
|
<div class="table-scroll"><table>
|
||||||
|
<thead><tr><th scope="col">Sample</th><th scope="col">Expected</th><th scope="col">Observed</th><th scope="col">Score / threshold</th><th scope="col">Matching rules</th><th scope="col">Check</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
{% for sample in filter_check.report.samples %}
|
||||||
|
<tr>
|
||||||
|
<th scope="row">{% if sample.sample == "gtube" %}GTUBE{% else %}Ordinary message{% endif %}</th>
|
||||||
|
<td>{{ sample.expected|capfirst }}</td><td>{{ sample.observed|capfirst }}</td>
|
||||||
|
<td>{{ sample.score }} / {{ sample.threshold }}</td><td>{{ sample.rules|join:", "|default:"—" }}</td>
|
||||||
|
<td>{% if sample.passed %}Passed{% else %}Unexpected result{% endif %}</td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
{% endif %}
|
||||||
|
</section>
|
||||||
|
{% endif %}
|
||||||
<section class="surface editor-surface">
|
<section class="surface editor-surface">
|
||||||
|
<header class="section-heading"><h2>Analyze a message</h2></header>
|
||||||
<form class="editor" method="post">
|
<form class="editor" method="post">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
{% if errors %}<ul class="errorlist" role="alert">{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul>{% endif %}
|
{% if errors %}<ul class="errorlist" role="alert">{% for error in errors %}<li>{{ error }}</li>{% endfor %}</ul>{% endif %}
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
from subprocess import TimeoutExpired
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from django.contrib.auth import get_user_model
|
||||||
|
from django.test import SimpleTestCase, TestCase, override_settings
|
||||||
|
from django.urls import reverse
|
||||||
|
from django_otp import DEVICE_ID_SESSION_KEY
|
||||||
|
from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||||
|
|
||||||
|
from coulobre.mail_filter_check import (
|
||||||
|
GTUBE,
|
||||||
|
SCAN_TIMEOUT,
|
||||||
|
MailFilterCheckRequest,
|
||||||
|
scan_result,
|
||||||
|
scan_sample,
|
||||||
|
validated_report,
|
||||||
|
)
|
||||||
|
from coulobre.mail_node import parse_mailbox_request
|
||||||
|
|
||||||
|
from .models import (
|
||||||
|
DomainServicePolicy,
|
||||||
|
HostingAccount,
|
||||||
|
HostingMailDomain,
|
||||||
|
MailFilterCheck,
|
||||||
|
)
|
||||||
|
from .tasks import run_mail_filter_check
|
||||||
|
|
||||||
|
ORDINARY = b"X-Spam-Status: No, score=-0.1 required=5.0 tests=none\n\n"
|
||||||
|
SPAM = b"X-Spam-Status: Yes, score=1000.0 required=5.0 tests=GTUBE\n\n"
|
||||||
|
|
||||||
|
|
||||||
|
def observed_results():
|
||||||
|
return {
|
||||||
|
"node": "mail.example.test",
|
||||||
|
"samples": [
|
||||||
|
scan_result("ordinary", ORDINARY),
|
||||||
|
scan_result("gtube", SPAM),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class FilterReceiverTests(SimpleTestCase):
|
||||||
|
def test_request_contains_only_a_domain_and_fixed_operation(self):
|
||||||
|
manifest = MailFilterCheckRequest("mail.example.test").manifest()
|
||||||
|
self.assertEqual(
|
||||||
|
parse_mailbox_request(manifest).domain, "mail.example.test"
|
||||||
|
)
|
||||||
|
with self.assertRaisesRegex(ValueError, "synthetic mail filter"):
|
||||||
|
parse_mailbox_request(manifest | {"message": "arbitrary input"})
|
||||||
|
|
||||||
|
@patch("coulobre.mail_filter_check.subprocess.run")
|
||||||
|
def test_scans_use_private_storage_and_avoid_network_and_learning(
|
||||||
|
self, run
|
||||||
|
):
|
||||||
|
run.return_value.stdout = SPAM
|
||||||
|
scan = scan_sample("gtube")
|
||||||
|
command = run.call_args.args[0]
|
||||||
|
self.assertIn("--property=DynamicUser=yes", command)
|
||||||
|
self.assertIn("--property=ProtectSystem=strict", command)
|
||||||
|
self.assertIn("--property=PrivateTmp=yes", command)
|
||||||
|
self.assertIn("--property=PrivateNetwork=yes", command)
|
||||||
|
self.assertIn("--property=SystemCallFilter=~@network-io", command)
|
||||||
|
self.assertIn("--property=SystemCallErrorNumber=EPERM", command)
|
||||||
|
self.assertIn("--local", command)
|
||||||
|
self.assertIn("--cf=bayes_auto_learn 0", command)
|
||||||
|
self.assertIn(GTUBE.encode("ascii"), run.call_args.kwargs["input"])
|
||||||
|
self.assertEqual(scan["rules"], ["GTUBE"])
|
||||||
|
self.assertEqual(run.call_args.kwargs["timeout"], SCAN_TIMEOUT)
|
||||||
|
|
||||||
|
run.side_effect = TimeoutExpired(command, SCAN_TIMEOUT)
|
||||||
|
with self.assertRaisesRegex(
|
||||||
|
ValueError, "isolated SpamAssassin scan failed"
|
||||||
|
):
|
||||||
|
scan_sample("ordinary")
|
||||||
|
|
||||||
|
def test_gtube_must_trigger_the_rule_and_the_spam_verdict(self):
|
||||||
|
report = observed_results()
|
||||||
|
self.assertTrue(
|
||||||
|
all(
|
||||||
|
result["passed"]
|
||||||
|
for result in validated_report(report)["samples"]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
report["samples"][1]["rules"] = ["OTHER"]
|
||||||
|
self.assertFalse(validated_report(report)["samples"][1]["passed"])
|
||||||
|
report["samples"][1]["observed"] = {"unknown": "checker output"}
|
||||||
|
with self.assertRaisesRegex(ValueError, "invalid filter result"):
|
||||||
|
validated_report(report)
|
||||||
|
with self.assertRaisesRegex(ValueError, "readable verdict"):
|
||||||
|
scan_result("ordinary", b"From: mail@example.test\n\n")
|
||||||
|
|
||||||
|
|
||||||
|
@override_settings(LOCAL_MAILBOX_PROVISIONING=True)
|
||||||
|
class FilterCheckTests(TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.url = reverse("panel:mail_diagnostics")
|
||||||
|
self.operator = get_user_model().objects.create_superuser(
|
||||||
|
"filter-operator"
|
||||||
|
)
|
||||||
|
self.login_verified(self.operator)
|
||||||
|
account = HostingAccount.objects.create(
|
||||||
|
name="Mail test account", primary_domain="sender.test"
|
||||||
|
)
|
||||||
|
self.domain = HostingMailDomain.objects.create(
|
||||||
|
account=account, domain=account.primary_domain
|
||||||
|
)
|
||||||
|
self.data = {"action": "check-filter", "domain": self.domain.pk}
|
||||||
|
|
||||||
|
def login_verified(self, user):
|
||||||
|
self.client.force_login(user)
|
||||||
|
device = TOTPDevice.objects.create(user=user, name="test")
|
||||||
|
session = self.client.session
|
||||||
|
session[DEVICE_ID_SESSION_KEY] = device.persistent_id
|
||||||
|
session.save()
|
||||||
|
|
||||||
|
@patch("coulobre.hosting.node_client.apply_on_local_node")
|
||||||
|
def test_queue_and_render_an_operator_owned_filter_check(self, apply):
|
||||||
|
response = self.client.post(self.url, self.data)
|
||||||
|
check = MailFilterCheck.objects.get()
|
||||||
|
result_url = f"{self.url}?check={check.pk}"
|
||||||
|
self.assertRedirects(response, result_url)
|
||||||
|
self.assertContains(self.client.get(result_url), "Queued")
|
||||||
|
self.assertContains(
|
||||||
|
self.client.post(self.url, self.data),
|
||||||
|
"Wait a minute between filter checks.",
|
||||||
|
)
|
||||||
|
apply.return_value = observed_results()
|
||||||
|
run_mail_filter_check.run(check.pk)
|
||||||
|
check.refresh_from_db()
|
||||||
|
self.assertEqual(check.problem, "")
|
||||||
|
request = apply.call_args.args[0]
|
||||||
|
self.assertEqual(request.domain, self.domain.domain)
|
||||||
|
response = self.client.get(result_url)
|
||||||
|
self.assertContains(response, "mail.example.test")
|
||||||
|
self.assertContains(response, "GTUBE")
|
||||||
|
self.assertContains(response, "Passed", count=2)
|
||||||
|
|
||||||
|
other = get_user_model().objects.create_superuser("other")
|
||||||
|
self.login_verified(other)
|
||||||
|
self.assertEqual(self.client.get(result_url).status_code, 404)
|
||||||
|
|
||||||
|
@patch("coulobre.hosting.node_client.apply_on_local_node")
|
||||||
|
def test_does_not_run_after_domain_moves_to_an_external_provider(
|
||||||
|
self, apply
|
||||||
|
):
|
||||||
|
self.client.post(self.url, self.data)
|
||||||
|
check = MailFilterCheck.objects.get()
|
||||||
|
DomainServicePolicy.objects.create(
|
||||||
|
account=self.domain.account,
|
||||||
|
domain=self.domain.domain,
|
||||||
|
mail_managed=False,
|
||||||
|
)
|
||||||
|
run_mail_filter_check.run(check.pk)
|
||||||
|
apply.assert_not_called()
|
||||||
|
check.refresh_from_db()
|
||||||
|
self.assertIn("no longer available", check.problem)
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.get(f"{self.url}?check={check.pk}").status_code, 404
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_verified_customer_cannot_queue_a_check(self):
|
||||||
|
self.login_verified(get_user_model().objects.create_user("customer"))
|
||||||
|
self.assertEqual(
|
||||||
|
self.client.post(self.url, self.data).status_code, 403
|
||||||
|
)
|
||||||
|
self.assertFalse(MailFilterCheck.objects.exists())
|
||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from email.utils import formatdate
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .domain_names import canonical_domain
|
||||||
|
from .mail_diagnostics import MAX_RULES, RULE, SPAM_STATUS
|
||||||
|
|
||||||
|
OPERATION = "check_spam_filter"
|
||||||
|
SCAN_TIMEOUT = 30
|
||||||
|
SPAMASSASSIN = Path("/usr/bin/spamassassin")
|
||||||
|
# Public-domain sample from https://spamassassin.apache.org/gtube/.
|
||||||
|
GTUBE = "XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X"
|
||||||
|
SAMPLES = ("ordinary", "gtube")
|
||||||
|
NUMBER = re.compile(r"-?\d{1,8}(?:\.\d{1,8})?", re.ASCII)
|
||||||
|
NODE = re.compile(r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}", re.ASCII)
|
||||||
|
SCAN_PROPERTIES = (
|
||||||
|
"Type=exec",
|
||||||
|
"DynamicUser=yes",
|
||||||
|
"NoNewPrivileges=yes",
|
||||||
|
"ProtectSystem=strict",
|
||||||
|
"ProtectHome=yes",
|
||||||
|
"PrivateTmp=yes",
|
||||||
|
"PrivateDevices=yes",
|
||||||
|
"PrivateNetwork=yes",
|
||||||
|
"SystemCallFilter=~@network-io",
|
||||||
|
"SystemCallErrorNumber=EPERM",
|
||||||
|
"RuntimeMaxSec=25s",
|
||||||
|
"TimeoutStopSec=3s",
|
||||||
|
"MemoryMax=256M",
|
||||||
|
"TasksMax=16",
|
||||||
|
)
|
||||||
|
SCAN_OPTIONS = (
|
||||||
|
"--local",
|
||||||
|
"--nocreate-prefs",
|
||||||
|
"--prefs-file=/dev/null",
|
||||||
|
"--cf=use_bayes 0",
|
||||||
|
"--cf=bayes_auto_learn 0",
|
||||||
|
"--cf=report_safe 0",
|
||||||
|
"--cf=add_header all Status _YESNO_, score=_SCORE_ required=_REQD_ "
|
||||||
|
"tests=_TESTS_ diagnostic=1",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class MailFilterCheckRequest:
|
||||||
|
domain: str
|
||||||
|
|
||||||
|
def __post_init__(self):
|
||||||
|
if not isinstance(self.domain, str):
|
||||||
|
raise ValueError("Expected a managed mail domain.")
|
||||||
|
object.__setattr__(self, "domain", canonical_domain(self.domain))
|
||||||
|
|
||||||
|
def manifest(self):
|
||||||
|
return {"operation": OPERATION, "domain": self.domain}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_manifest(cls, data):
|
||||||
|
if (
|
||||||
|
not isinstance(data, dict)
|
||||||
|
or data.keys() != {"operation", "domain"}
|
||||||
|
or data["operation"] != OPERATION
|
||||||
|
):
|
||||||
|
raise ValueError("Expected a synthetic mail filter request.")
|
||||||
|
return cls(data["domain"])
|
||||||
|
|
||||||
|
|
||||||
|
def synthetic_message(sample):
|
||||||
|
body = (
|
||||||
|
"Hello, this is a routine mail filter diagnostic.\n"
|
||||||
|
if sample == "ordinary"
|
||||||
|
else f"{GTUBE}\n"
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
"From: Filter sender <sender@example.org>\n"
|
||||||
|
"To: Filter recipient <recipient@example.net>\n"
|
||||||
|
"Subject: Mail filter diagnostic\n"
|
||||||
|
f"Date: {formatdate(usegmt=True)}\n"
|
||||||
|
f"Message-ID: <coulobre-filter-{sample}@example.org>\n"
|
||||||
|
"MIME-Version: 1.0\n"
|
||||||
|
"Content-Type: text/plain; charset=us-ascii\n"
|
||||||
|
"\n"
|
||||||
|
f"{body}"
|
||||||
|
).encode("ascii")
|
||||||
|
|
||||||
|
|
||||||
|
def scan_sample(sample):
|
||||||
|
command = [
|
||||||
|
"/usr/bin/systemd-run",
|
||||||
|
f"--unit=coulobre-spam-filter-check-{sample}",
|
||||||
|
"--quiet",
|
||||||
|
"--wait",
|
||||||
|
"--pipe",
|
||||||
|
"--collect",
|
||||||
|
"--setenv=HOME=/tmp",
|
||||||
|
"--setenv=LC_ALL=C",
|
||||||
|
*(f"--property={option}" for option in SCAN_PROPERTIES),
|
||||||
|
str(SPAMASSASSIN),
|
||||||
|
*SCAN_OPTIONS,
|
||||||
|
]
|
||||||
|
try:
|
||||||
|
# The scanner sees a pipe containing only the synthetic message.
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
input=synthetic_message(sample),
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
check=True,
|
||||||
|
timeout=SCAN_TIMEOUT,
|
||||||
|
)
|
||||||
|
except (OSError, subprocess.SubprocessError):
|
||||||
|
raise ValueError(
|
||||||
|
"The isolated SpamAssassin scan failed. Check this mail node's "
|
||||||
|
"service journal and SpamAssassin configuration."
|
||||||
|
) from None
|
||||||
|
return scan_result(sample, result.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
def scan_result(sample, scanned):
|
||||||
|
from email.parser import BytesHeaderParser
|
||||||
|
|
||||||
|
if len(scanned) > 65536:
|
||||||
|
raise ValueError("SpamAssassin returned an oversized scan result.")
|
||||||
|
message = BytesHeaderParser().parsebytes(scanned)
|
||||||
|
match = SPAM_STATUS.match(message.get("X-Spam-Status", ""))
|
||||||
|
if not match:
|
||||||
|
raise ValueError("SpamAssassin did not return a readable verdict.")
|
||||||
|
verdict, score, threshold, rules = match.groups()
|
||||||
|
return {
|
||||||
|
"sample": sample,
|
||||||
|
"observed": "spam" if verdict.lower() == "yes" else "clean",
|
||||||
|
"score": score,
|
||||||
|
"threshold": threshold,
|
||||||
|
"rules": [
|
||||||
|
rule
|
||||||
|
for rule in re.split(r"[,\s]+", rules or "")
|
||||||
|
if RULE.fullmatch(rule) and rule != "none"
|
||||||
|
][:MAX_RULES],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def check_spam_filter():
|
||||||
|
if not SPAMASSASSIN.is_file():
|
||||||
|
raise ValueError(
|
||||||
|
"SpamAssassin is unavailable on this mail node. "
|
||||||
|
"This check covers the SpamAssassin inbound filter."
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"node": socket.gethostname(),
|
||||||
|
"samples": [scan_sample(sample) for sample in SAMPLES],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def validated_report(reply):
|
||||||
|
node = reply.get("node")
|
||||||
|
scans = reply.get("samples")
|
||||||
|
if (
|
||||||
|
not isinstance(node, str)
|
||||||
|
or not NODE.fullmatch(node)
|
||||||
|
or not isinstance(scans, list)
|
||||||
|
or len(scans) != len(SAMPLES)
|
||||||
|
):
|
||||||
|
raise ValueError("The mail node returned an invalid filter report.")
|
||||||
|
|
||||||
|
results = []
|
||||||
|
for sample, result in zip(SAMPLES, scans, strict=True):
|
||||||
|
if (
|
||||||
|
not isinstance(result, dict)
|
||||||
|
or result.keys()
|
||||||
|
!= {"sample", "observed", "score", "threshold", "rules"}
|
||||||
|
or result["sample"] != sample
|
||||||
|
or result["observed"] not in ("clean", "spam")
|
||||||
|
or any(
|
||||||
|
not isinstance(result[key], str)
|
||||||
|
or not NUMBER.fullmatch(result[key])
|
||||||
|
for key in ("score", "threshold")
|
||||||
|
)
|
||||||
|
or not isinstance(result["rules"], list)
|
||||||
|
or len(result["rules"]) > MAX_RULES
|
||||||
|
or any(
|
||||||
|
not isinstance(rule, str) or not RULE.fullmatch(rule)
|
||||||
|
for rule in result["rules"]
|
||||||
|
)
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
"The mail node returned an invalid filter result."
|
||||||
|
)
|
||||||
|
expected = "spam" if sample == "gtube" else "clean"
|
||||||
|
results.append(
|
||||||
|
result
|
||||||
|
| {
|
||||||
|
"expected": expected,
|
||||||
|
"passed": result["observed"] == expected
|
||||||
|
and (sample != "gtube" or "GTUBE" in result["rules"]),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return {"node": node, "samples": results}
|
||||||
@@ -171,6 +171,8 @@ class MailboxRemovalRequest(RetirementRequest):
|
|||||||
|
|
||||||
def parse_mailbox_request(data):
|
def parse_mailbox_request(data):
|
||||||
from .mail_delivery import OPERATION, MailDeliveryRequest
|
from .mail_delivery import OPERATION, MailDeliveryRequest
|
||||||
|
from .mail_filter_check import OPERATION as FILTER_OPERATION
|
||||||
|
from .mail_filter_check import MailFilterCheckRequest
|
||||||
from .mail_policy import OPERATIONS, parse_mail_policy
|
from .mail_policy import OPERATIONS, parse_mail_policy
|
||||||
from .mail_queue import MailQueueAction, MailQueueRequest
|
from .mail_queue import MailQueueAction, MailQueueRequest
|
||||||
from .smtp_application import (
|
from .smtp_application import (
|
||||||
@@ -190,6 +192,8 @@ def parse_mailbox_request(data):
|
|||||||
return parse_mailbox_password_request(data)
|
return parse_mailbox_password_request(data)
|
||||||
if isinstance(data, dict) and data.get("operation") == OPERATION:
|
if isinstance(data, dict) and data.get("operation") == OPERATION:
|
||||||
return MailDeliveryRequest.from_manifest(data)
|
return MailDeliveryRequest.from_manifest(data)
|
||||||
|
if isinstance(data, dict) and data.get("operation") == FILTER_OPERATION:
|
||||||
|
return MailFilterCheckRequest.from_manifest(data)
|
||||||
if isinstance(data, dict) and data.get("operation") in {
|
if isinstance(data, dict) and data.get("operation") in {
|
||||||
"inspect_queue",
|
"inspect_queue",
|
||||||
"inspect_queue_entries",
|
"inspect_queue_entries",
|
||||||
@@ -247,6 +251,7 @@ def mailbox_request_identity(spec):
|
|||||||
|
|
||||||
def apply_mailbox_request(request):
|
def apply_mailbox_request(request):
|
||||||
from .mail_delivery import MailDeliveryRequest, inspect_delivery
|
from .mail_delivery import MailDeliveryRequest, inspect_delivery
|
||||||
|
from .mail_filter_check import MailFilterCheckRequest, check_spam_filter
|
||||||
from .mail_policy import MailRouting, MailVacation
|
from .mail_policy import MailRouting, MailVacation
|
||||||
from .mail_queue import (
|
from .mail_queue import (
|
||||||
MailQueueAction,
|
MailQueueAction,
|
||||||
@@ -269,6 +274,8 @@ def apply_mailbox_request(request):
|
|||||||
return apply_mailbox_password_request(request)
|
return apply_mailbox_password_request(request)
|
||||||
if isinstance(request, MailDeliveryRequest):
|
if isinstance(request, MailDeliveryRequest):
|
||||||
return inspect_delivery(request)
|
return inspect_delivery(request)
|
||||||
|
if isinstance(request, MailFilterCheckRequest):
|
||||||
|
return check_spam_filter()
|
||||||
if isinstance(request, MailQueueRequest):
|
if isinstance(request, MailQueueRequest):
|
||||||
return inspect_queue(request)
|
return inspect_queue(request)
|
||||||
if isinstance(request, MailQueueAction):
|
if isinstance(request, MailQueueAction):
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from uuid import uuid4
|
|||||||
|
|
||||||
from . import node_maintenance, node_setup, receiver_scope
|
from . import node_maintenance, node_setup, receiver_scope
|
||||||
from .dns_node import DnsZone
|
from .dns_node import DnsZone
|
||||||
|
from .mail_filter_check import MailFilterCheckRequest
|
||||||
from .mail_node import MailboxQuotaUpdate, MailboxSpec, parse_mailbox_request
|
from .mail_node import MailboxQuotaUpdate, MailboxSpec, parse_mailbox_request
|
||||||
from .mail_policy import MailRouting
|
from .mail_policy import MailRouting
|
||||||
from .mail_queue import MailQueueRequest
|
from .mail_queue import MailQueueRequest
|
||||||
@@ -59,6 +60,7 @@ class ReceiverScopeTests(TestCase):
|
|||||||
mailbox,
|
mailbox,
|
||||||
MailboxQuotaUpdate(mailbox),
|
MailboxQuotaUpdate(mailbox),
|
||||||
MailQueueRequest(mailbox.domain),
|
MailQueueRequest(mailbox.domain),
|
||||||
|
MailFilterCheckRequest(mailbox.domain),
|
||||||
MailRouting(mailbox.domain, {}),
|
MailRouting(mailbox.domain, {}),
|
||||||
ServiceAccessRequest(mailbox, True),
|
ServiceAccessRequest(mailbox, True),
|
||||||
RetirementRequest(mailbox, str(uuid4())),
|
RetirementRequest(mailbox, str(uuid4())),
|
||||||
@@ -76,8 +78,9 @@ class ReceiverScopeTests(TestCase):
|
|||||||
for request in requests:
|
for request in requests:
|
||||||
check_request("mail", request)
|
check_request("mail", request)
|
||||||
for domain in ("beta.example.test", "sub.alpha.example.test"):
|
for domain in ("beta.example.test", "sub.alpha.example.test"):
|
||||||
with self.assertRaisesRegex(ValueError, "not assigned"):
|
for request_type in (MailQueueRequest, MailFilterCheckRequest):
|
||||||
check_request("mail", MailQueueRequest(domain))
|
with self.assertRaisesRegex(ValueError, "not assigned"):
|
||||||
|
check_request("mail", request_type(domain))
|
||||||
|
|
||||||
def test_empty_scope_allows_probes_and_denies_managed_domains(self):
|
def test_empty_scope_allows_probes_and_denies_managed_domains(self):
|
||||||
with (
|
with (
|
||||||
|
|||||||
Reference in new issue
Block a user