diff --git a/deploy/systemd/coulobre-mailbox-import-worker.service b/deploy/systemd/coulobre-mailbox-import-worker.service new file mode 100644 index 0000000..441d19b --- /dev/null +++ b/deploy/systemd/coulobre-mailbox-import-worker.service @@ -0,0 +1,24 @@ +[Unit] +Description=Coulobre mailbox import worker +Wants=network-online.target +After=network-online.target mariadb.service rabbitmq-server.service + +[Service] +Type=exec +User=coulobre-panel +Group=coulobre-panel +EnvironmentFile=/etc/coulobre/panel.env +WorkingDirectory=/opt/coulobre +UMask=0077 +ExecStart=/opt/coulobre/bin/celery -A coulobre worker --loglevel=INFO --concurrency=1 --prefetch-multiplier=1 -Q coulobre-mailbox-import -n mailbox-import@%H +KillMode=mixed +Restart=on-failure +RestartSec=5s +NoNewPrivileges=true +PrivateTmp=true +ProtectHome=true +ProtectSystem=strict +MemoryMax=512M + +[Install] +WantedBy=multi-user.target diff --git a/src/coulobre/hosting/access.py b/src/coulobre/hosting/access.py index 157e1e7..ae3509b 100644 --- a/src/coulobre/hosting/access.py +++ b/src/coulobre/hosting/access.py @@ -60,6 +60,8 @@ def owns_customer_operations(user, account): def panel_access(request): customer = customer_for_user(request.user) is not None reseller = not customer and reseller_for_user(request.user) is not None + from .mailbox_imports import PERMISSIONS as IMPORT_PERMISSIONS + from .mailbox_imports import available as mailbox_import_available from .workspaces import ( CUSTOMER_ACCOUNT, active_navigation, @@ -98,6 +100,11 @@ def panel_access(request): "active_navigation_link": active_link, "workspace_accounts": available if len(available) > 1 else [], "workspace_selected": selected, + "mailbox_import_enabled": ( + mailbox_import_available() + and not getattr(request, "impersonation", None) + and can_manage_hosting(request.user, IMPORT_PERMISSIONS) + ), } diff --git a/src/coulobre/hosting/mailbox_import_tasks.py b/src/coulobre/hosting/mailbox_import_tasks.py new file mode 100644 index 0000000..d4c43b4 --- /dev/null +++ b/src/coulobre/hosting/mailbox_import_tasks.py @@ -0,0 +1,106 @@ +"""Dispatch credential-bounded IMAP work to an independent queue.""" + +import imaplib +from datetime import timedelta + +from billiard.exceptions import SoftTimeLimitExceeded +from celery import shared_task +from django.core.exceptions import ObjectDoesNotExist +from django.db.models import Q +from django.utils import timezone +from django.views.decorators.debug import sensitive_variables + +from coulobre.imap_import import MailboxImportError + +from . import mailbox_imports as imports +from .models import MailboxImport + + +def finish(jobs, now, problem=""): + jobs.update( + phase="failed" if problem else "complete", + finished_at=now, + problem=problem, + sealed_credentials="", + ) + + +@shared_task( + name="coulobre.hosting.tasks.dispatch_mailbox_imports", ignore_result=True +) +def dispatch_mailbox_imports(): + now = timezone.now() + waiting = MailboxImport.objects.filter( + finished_at__isnull=True, started_at__isnull=True + ) + finish( + waiting.filter( + requested_at__lte=now + - timedelta(seconds=imports.CREDENTIAL_SECONDS) + ), + now, + "The passwords expired. Enter them again to resume.", + ) + finish( + MailboxImport.objects.filter( + finished_at__isnull=True, + started_at__lt=now - timedelta(seconds=imports.STALE_SECONDS), + ), + now, + imports.INTERRUPTED, + ) + if not imports.available(): + finish( + waiting, now, "Mailbox imports are not configured on this panel." + ) + return + ready = waiting.filter( + Q(last_dispatched_at__isnull=True) + | Q(last_dispatched_at__lt=now - timedelta(seconds=90)), + ).order_by("requested_at") + # Claim work before opening any sockets. + for pk in list(ready.values_list("pk", flat=True)[:5]): + if ready.filter(pk=pk).update(last_dispatched_at=now): + run_mailbox_import.apply_async( + args=[pk], queue=imports.QUEUE, expires=60, retry=False + ) + + +@shared_task( + name="coulobre.hosting.tasks.run_mailbox_import", + ignore_result=True, + soft_time_limit=imports.TASK_SECONDS - 15, + time_limit=imports.TASK_SECONDS, +) +@sensitive_variables() +def run_mailbox_import(pk): + started = timezone.now() + active = MailboxImport.objects.filter( + pk=pk, + finished_at__isnull=True, + started_at__isnull=True, + requested_at__gt=started + - timedelta(seconds=imports.CREDENTIAL_SECONDS), + ).exclude(sealed_credentials="") + if not active.update(started_at=started, phase="checking"): + return + owned = MailboxImport.objects.filter( + pk=pk, started_at=started, finished_at__isnull=True + ) + job = owned.first() + if job is None: + return + try: + imports.run_import(job) + except MailboxImportError as exc: + problem = str(exc) + except SoftTimeLimitExceeded: + problem = imports.INTERRUPTED + except (imaplib.IMAP4.error, OSError, ObjectDoesNotExist): + problem = ( + "The IMAP connection stopped or the mailbox changed. " + "Retry to resume." + ) + else: + problem = "" + finish(owned, timezone.now(), problem) diff --git a/src/coulobre/hosting/mailbox_import_views.py b/src/coulobre/hosting/mailbox_import_views.py new file mode 100644 index 0000000..a24e282 --- /dev/null +++ b/src/coulobre/hosting/mailbox_import_views.py @@ -0,0 +1,136 @@ +from django import forms +from django.contrib import messages +from django.contrib.auth.mixins import PermissionRequiredMixin +from django.core.exceptions import ObjectDoesNotExist, ValidationError +from django.shortcuts import get_object_or_404, redirect +from django.urls import reverse +from django.utils.decorators import method_decorator +from django.utils.functional import cached_property +from django.views.decorators.cache import never_cache +from django.views.decorators.debug import ( + sensitive_post_parameters, + sensitive_variables, +) +from django.views.generic import FormView + +from coulobre.imap_import import MailboxImportError, source_hostname + +from .access import can_manage_hosting, customer_for_user +from .mailbox_imports import PERMISSIONS, available, display_name, queue_import +from .models import HostingMailbox, MailboxImport + + +class MailboxImportForm(forms.Form): + source_host = forms.CharField(label="Source IMAP hostname", max_length=253) + source_user = forms.CharField(label="Source username", max_length=254) + source_password = forms.CharField( + label="Source password", + max_length=1024, + strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "off"}), + ) + target_password = forms.CharField( + label="Destination mailbox password", + max_length=1024, + strip=False, + widget=forms.PasswordInput(attrs={"autocomplete": "off"}), + ) + + def clean_source_host(self): + try: + return source_hostname(self.cleaned_data["source_host"]) + except MailboxImportError as exc: + raise forms.ValidationError(str(exc)) from None + + @sensitive_variables() + def clean(self): + data = super().clean() + for field in ("source_user", "source_password", "target_password"): + if any( + ord(char) < 32 or ord(char) == 127 + for char in data.get(field, "") + ): + self.add_error( + field, "Remove control characters from this field." + ) + return data + + +@method_decorator(never_cache, name="dispatch") +@method_decorator(sensitive_post_parameters(), name="dispatch") +class MailboxImportView(PermissionRequiredMixin, FormView): + form_class = MailboxImportForm + template_name = "hosting/mailbox_import.html" + permission_required = PERMISSIONS + + def has_permission(self): + return ( + available() + and not getattr(self.request, "impersonation", None) + and can_manage_hosting(self.request.user, PERMISSIONS) + ) + + @cached_property + def mailbox(self): + query = HostingMailbox.objects.filter( + mail_domain__account__retired_at__isnull=True, + removal__isnull=True, + ).select_related("mail_domain__account", "provisioning") + customer = customer_for_user(self.request.user) + if customer is not None: + query = query.filter(mail_domain__account__customer=customer) + return get_object_or_404(query, pk=self.kwargs["pk"]) + + @cached_property + def job(self): + return MailboxImport.objects.filter(mailbox=self.mailbox).first() + + def get_initial(self): + if not self.job: + return {} + return { + "source_host": self.job.source_host, + "source_user": self.job.source_user, + } + + def get_context_data(self, **kwargs): + account = self.mailbox.mail_domain.account + items = [] + if self.job: + items = [ + (display_name(folder.source_name.encode("ascii")), folder) + for folder in self.job.folders.order_by("source_name") + ] + return super().get_context_data( + mailbox=self.mailbox, + job=self.job, + folders=items, + return_url=reverse( + "panel:domain_workspace", + args=[account.pk, "email"], + query={"domain": self.mailbox.mail_domain.domain}, + ) + if customer_for_user(self.request.user) is not None + else account.get_absolute_url() + "#email", + **kwargs, + ) + + @sensitive_variables() + def form_valid(self, form): + try: + queue_import(self.mailbox, self.request.user, form.cleaned_data) + except ValidationError as exc: + form.add_error(None, exc) + except MailboxImportError as exc: + form.add_error(None, str(exc)) + except ObjectDoesNotExist: + form.add_error( + None, "This mailbox is no longer available for import." + ) + else: + messages.success( + self.request, + "Mailbox import queued. No DNS records will be changed.", + ) + return redirect("panel:mailbox_import", pk=self.mailbox.pk) + return self.form_invalid(form) diff --git a/src/coulobre/hosting/mailbox_imports.py b/src/coulobre/hosting/mailbox_imports.py new file mode 100644 index 0000000..f0acb94 --- /dev/null +++ b/src/coulobre/hosting/mailbox_imports.py @@ -0,0 +1,471 @@ +"""Orchestrate authorized, resumable external mailbox imports.""" + +import imaplib +import json +import re +import ssl +from base64 import b64decode, urlsafe_b64encode +from contextlib import ExitStack, suppress +from hashlib import sha256 +from time import monotonic + +from cryptography.fernet import Fernet, InvalidToken, MultiFernet +from django.conf import settings +from django.core.exceptions import ValidationError +from django.db import transaction +from django.utils import timezone +from django.views.decorators.debug import sensitive_variables + +from coulobre import imap_import as imap + +from .access import can_manage_hosting, customer_for_user +from .domain_policies import require_managed +from .models import HostingMailbox, MailboxImport, MailboxImportFolder +from .panel_roles import assigned_roles, scoped_user +from .resource_requests import lock_hosting_account, require_active_services + +QUEUE = "coulobre-mailbox-import" +CREDENTIAL_SECONDS = 30 * 60 +RUN_SECONDS = 12 * 60 +TASK_SECONDS = 13 * 60 +STALE_SECONDS = TASK_SECONDS + 120 +PERMISSIONS = ("hosting.view_hostingmailbox", "hosting.change_hostingmailbox") +INTERRUPTED = ( + "The import stopped before finishing. Enter the passwords to resume." +) + + +def available(): + return ( + settings.MAILBOX_IMAP_IMPORT + and bool(settings.MAIL_IMAP_HOST) + and settings.LOCAL_MAILBOX_PROVISIONING + ) + + +def can_import(user, mailbox): + if not user.is_authenticated or not user.is_active: + return False + account = mailbox.mail_domain.account + customer = customer_for_user(user) + return can_manage_hosting(user, PERMISSIONS) and ( + customer is None or account.customer_id == customer.pk + ) + + +def ready(mailbox): + account = mailbox.mail_domain.account + require_active_services(account) + require_managed(account, mailbox.mail_domain.domain, "mail_managed") + if ( + getattr(mailbox, "removal", None) is not None + or getattr(mailbox, "provisioning", None) is None + or mailbox.provisioning.state != "configured" + ): + raise ValidationError( + "Choose a provisioned mailbox that is not being removed." + ) + + +def encryption(): + return MultiFernet( + [ + Fernet( + urlsafe_b64encode( + sha256( + b"coulobre-imap-import-v1\0" + secret.encode("utf-8") + ).digest() + ) + ) + for secret in (settings.SECRET_KEY, *settings.SECRET_KEY_FALLBACKS) + ] + ) + + +def job_identity(job): + return [ + job.mailbox_id, + job.actor_id, + job.actor_role, + job.source_host, + job.source_user, + job.target_host, + job.target_user, + ] + + +@sensitive_variables() +@transaction.atomic +def queue_import(mailbox, actor, data): + if not available(): + raise ValidationError( + "Mailbox imports are not configured on this panel." + ) + customer = customer_for_user(actor) + account = lock_hosting_account( + mailbox.mail_domain.account_id, customer.pk if customer else None + ) + current = HostingMailbox.objects.select_related( + "mail_domain__account", "provisioning", "removal" + ).get(pk=mailbox.pk, mail_domain__account=account) + if not can_import(actor, current): + raise ValidationError("This mailbox is not available for import.") + ready(current) + source_host = imap.source_hostname(data["source_host"]) + target_host = imap.source_hostname(settings.MAIL_IMAP_HOST) + if source_host == target_host: + raise ValidationError( + "Choose a different source server from this mailbox's server." + ) + target_user = str(current) + job = ( + MailboxImport.objects.select_for_update() + .filter(mailbox=current) + .first() + ) + if job is None: + job = MailboxImport(mailbox=current) + else: + if job.finished_at is None: + raise ValidationError("An import is already queued or running.") + if ( + job.source_host, + job.source_user, + job.target_host, + job.target_user, + ) != (source_host, data["source_user"], target_host, target_user): + if job.folders.exclude(copied=0, pending={}).exists(): + raise ValidationError( + "Resume with the original servers and login names." + ) + job.folders.all().delete() + job.source_host = source_host + job.source_user = data["source_user"] + job.target_host = target_host + job.target_user = target_user + job.actor = actor + job.actor_role = getattr(actor, "panel_role", "") or "" + job.sealed_credentials = ( + encryption() + .encrypt( + json.dumps( + [ + job_identity(job), + data["source_password"], + data["target_password"], + ] + ).encode() + ) + .decode("ascii") + ) + job.requested_at = timezone.now() + job.last_dispatched_at = job.started_at = job.finished_at = None + job.problem = "" + job.phase = "checking" + job.save() + return job + + +@sensitive_variables() +def open_credentials(job): + try: + identity, source_password, target_password = json.loads( + encryption().decrypt( + job.sealed_credentials.encode("ascii"), ttl=CREDENTIAL_SECONDS + ) + ) + if identity == job_identity(job): + return source_password, target_password + except (ValueError, InvalidToken, UnicodeError): + pass + raise imap.MailboxImportError( + "The passwords expired. Enter them again to resume." + ) + + +def check_access(job): + current = ( + MailboxImport.objects.select_related( + "mailbox__mail_domain__account", + "mailbox__provisioning", + "mailbox__removal", + "actor", + ) + .filter(pk=job.pk, finished_at__isnull=True) + .first() + ) + if not available() or current is None or current.actor is None: + raise imap.MailboxImportError( + "This import no longer has access to the mailbox." + ) + actor = current.actor + if current.actor_role: + if current.actor_role not in assigned_roles(actor): + raise imap.MailboxImportError( + "This import no longer has access to the mailbox." + ) + actor = scoped_user(actor, current.actor_role) + if ( + not can_import(actor, current.mailbox) + or str(current.mailbox) != job.target_user + or imap.source_hostname(settings.MAIL_IMAP_HOST) != job.target_host + ): + raise imap.MailboxImportError( + "This import no longer has access to the mailbox." + ) + try: + ready(current.mailbox) + except ValidationError: + raise imap.MailboxImportError( + "The destination mailbox is no longer ready." + ) from None + + +def disconnect(client): + with suppress(imaplib.IMAP4.error, OSError): + client.shutdown() + + +def connect(host, addresses, side, stack): + for address in addresses[:4]: + try: + client = imap.PinnedIMAPS(host, address) + except ssl.SSLCertVerificationError: + raise imap.MailboxImportError( + f"The {side} IMAP TLS certificate could not be verified." + ) from None + except (imaplib.IMAP4.error, OSError): + continue + stack.callback(disconnect, client) + return client + raise imap.MailboxImportError( + f"The {side} IMAP server did not respond over TLS." + ) + + +def display_name(name): + # IMAP4 uses modified UTF-7 unless UTF-8 is enabled. + try: + decoded = [] + text = name.decode("ascii") + for atom in re.split(r"(&[A-Za-z0-9+,]*-)", text): + if atom == "&-": + decoded.append("&") + elif re.fullmatch(r"&[A-Za-z0-9+,]+-", atom): + value = atom[1:-1].replace(",", "/") + decoded.append( + b64decode( + value + "=" * (-len(value) % 4), validate=True + ).decode("utf-16-be") + ) + else: + decoded.append(atom) + return "".join(decoded) + except (UnicodeError, ValueError): + return name.decode("ascii", "replace") + + +def check_cutoff(job, deadline): + if monotonic() >= deadline: + raise imap.MailboxImportError( + "This pass reached its time limit. Resume to copy the remaining " + "messages." + ) + check_access(job) + + +def finish_message(checkpoint, uid, omitted): + checkpoint.last_uid = uid + checkpoint.copied += 1 + checkpoint.omitted_flags += omitted + checkpoint.pending = {} + checkpoint.save( + update_fields=["last_uid", "copied", "omitted_flags", "pending"] + ) + + +def folder_key(name): + return sha256(b"INBOX" if name.upper() == b"INBOX" else name).hexdigest() + + +def prepare_checkpoint( + job, source_name, target_name, source_validity, target_validity +): + source_key = folder_key(source_name) + checkpoint, _ = MailboxImportFolder.objects.get_or_create( + job=job, + source_key=source_key, + defaults={ + "source_name": source_name.decode("ascii"), + "target_name": target_name.decode("ascii"), + "source_validity": source_validity, + "target_validity": target_validity, + }, + ) + if not checkpoint.source_validity and not checkpoint.target_validity: + checkpoint.source_validity = source_validity + checkpoint.target_validity = target_validity + checkpoint.save(update_fields=["source_validity", "target_validity"]) + if ( + checkpoint.source_validity != source_validity + or checkpoint.target_validity != target_validity + or checkpoint.target_name != target_name.decode("ascii") + ): + raise imap.MailboxImportError( + "A folder changed its UID identity or mapping. Review that " + "folder before resuming." + ) + return checkpoint + + +def copy_folder( + job, source, target, source_name, target_name, existing, deadline +): + check_cutoff(job, deadline) + source_validity, _ = imap.select(source, source_name, readonly=True) + if target_name not in existing: + if job.folders.filter( + source_key=folder_key(source_name), target_validity__gt=0 + ).exists(): + raise imap.MailboxImportError( + "A previously copied destination folder is missing. " + "Review that folder before resuming." + ) + if target.create(imap.quote(target_name))[0] != "OK": + raise imap.MailboxImportError( + "A destination folder could not be created." + ) + existing.add(target_name) + target_validity, _ = imap.select(target, target_name, readonly=False) + allowed_flags = imap.permanent_flags(target) + checkpoint = prepare_checkpoint( + job, source_name, target_name, source_validity, target_validity + ) + checkpoint.complete = False + checkpoint.problem = "" + checkpoint.save(update_fields=["complete", "problem"]) + if pending := checkpoint.pending: + if imap.reconcile( + target, pending["target_next"], pending["digest"], pending["date"] + ): + finish_message(checkpoint, pending["uid"], pending["omitted"]) + else: + message = imap.fetch_message(source, pending["uid"]) + if ( + message.digest != pending["digest"] + or message.timestamp != pending["date"] + ): + raise imap.MailboxImportError( + "The source changed after an interrupted copy. Review " + "the folder before retrying." + ) + flags, omitted = imap.usable_flags(allowed_flags, message.flags) + imap.append(target, target_name, message, flags) + finish_message(checkpoint, pending["uid"], omitted) + + for uid in imap.search_uids(source, checkpoint.last_uid + 1): + check_cutoff(job, deadline) + message = imap.fetch_message(source, uid) + verified_validity, target_next = imap.select( + target, target_name, readonly=False + ) + if verified_validity != target_validity: + raise imap.MailboxImportError( + "The destination folder changed during the copy." + ) + flags, omitted = imap.usable_flags( + imap.permanent_flags(target), message.flags + ) + checkpoint.pending = { + "uid": uid, + "target_next": target_next, + "digest": message.digest, + "date": message.timestamp, + "omitted": omitted, + } + checkpoint.save(update_fields=["pending"]) + imap.append(target, target_name, message, flags) + finish_message(checkpoint, uid, omitted) + checkpoint.complete = True + checkpoint.save(update_fields=["complete"]) + + +@sensitive_variables() +def run_import(job): + check_access(job) + source_password, target_password = open_credentials(job) + source_ips = imap.resolve(job.source_host, public_only=True) + target_ips = imap.resolve(job.target_host, public_only=False) + if set(source_ips).intersection(target_ips): + raise imap.MailboxImportError( + "The source and destination resolve to the same server." + ) + deadline = monotonic() + RUN_SECONDS + with ExitStack() as stack: + source = connect(job.source_host, source_ips, "source", stack) + target = connect(job.target_host, target_ips, "destination", stack) + imap.login(source, job.source_user, source_password, "source") + imap.login(target, job.target_user, target_password, "destination") + imap.select(target, b"INBOX", readonly=True) + roots = imap.list_folders(target, root=True) + if len(roots) != 1: + raise imap.MailboxImportError( + "The destination did not identify its folder separator." + ) + mapping = imap.map_folders( + imap.list_folders(source), roots[0].separator + ) + existing = { + b"INBOX" if folder.name.upper() == b"INBOX" else folder.name + for folder in imap.list_folders(target) + } + if not mapping: + raise imap.MailboxImportError( + "The source has no selectable folders to copy." + ) + keys = [folder_key(name) for name, _ in mapping] + if ( + job.folders.exclude(source_key__in=keys) + .exclude(pending={}) + .exists() + ): + raise imap.MailboxImportError( + "A source folder disappeared during an interrupted copy. " + "Restore the source folder before resuming." + ) + MailboxImport.objects.filter(pk=job.pk).update(phase="copying") + for source_name, target_name in mapping: + try: + copy_folder( + job, + source, + target, + source_name, + target_name, + existing, + deadline, + ) + except ( + imap.MailboxImportError, + imaplib.IMAP4.error, + OSError, + ) as exc: + message = ( + str(exc) + if isinstance(exc, imap.MailboxImportError) + else ( + "The IMAP connection stopped while copying the folder." + ) + ) + folder, _ = MailboxImportFolder.objects.get_or_create( + job=job, + source_key=folder_key(source_name), + defaults={ + "source_name": source_name.decode("ascii"), + "target_name": target_name.decode("ascii"), + }, + ) + folder.problem = message + folder.complete = False + folder.save(update_fields=["problem", "complete"]) + raise imap.MailboxImportError(message) from None diff --git a/src/coulobre/hosting/migrations/0094_mailbox_import.py b/src/coulobre/hosting/migrations/0094_mailbox_import.py new file mode 100644 index 0000000..ffa6181 --- /dev/null +++ b/src/coulobre/hosting/migrations/0094_mailbox_import.py @@ -0,0 +1,111 @@ +# Generated by Django 5.2.19 on 2026-12-03 21:34 + +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", "0093_offsite_backup_recovery"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name="MailboxImport", + 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)), + ("actor_role", models.CharField(blank=True, max_length=16)), + ("source_host", models.CharField(max_length=253)), + ("source_user", models.CharField(max_length=254)), + ("target_host", models.CharField(max_length=253)), + ("target_user", models.CharField(max_length=254)), + ( + "sealed_credentials", + models.TextField(blank=True, editable=False), + ), + ("phase", models.CharField(default="checking", max_length=16)), + ( + "actor", + models.ForeignKey( + null=True, + on_delete=django.db.models.deletion.SET_NULL, + to=settings.AUTH_USER_MODEL, + ), + ), + ( + "mailbox", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, + related_name="imap_import", + to="hosting.hostingmailbox", + ), + ), + ], + options={ + "abstract": False, + }, + ), + migrations.CreateModel( + name="MailboxImportFolder", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("source_key", models.CharField(max_length=64)), + ("source_name", models.TextField()), + ("target_name", models.TextField()), + ("source_validity", models.PositiveBigIntegerField(default=0)), + ("target_validity", models.PositiveBigIntegerField(default=0)), + ("last_uid", models.PositiveBigIntegerField(default=0)), + ("copied", models.PositiveBigIntegerField(default=0)), + ("omitted_flags", models.PositiveBigIntegerField(default=0)), + ("pending", models.JSONField(blank=True, default=dict)), + ("problem", models.TextField(blank=True)), + ("complete", models.BooleanField(default=False)), + ( + "job", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="folders", + to="hosting.mailboximport", + ), + ), + ], + options={ + "constraints": [ + models.UniqueConstraint( + fields=("job", "source_key"), + name="hosting_mail_import_folder_key", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index ff8c53b..be26112 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1638,6 +1638,47 @@ class MailboxProvisioning(ProvisioningJob): quota_update = models.BooleanField(default=False) +class MailboxImport(ProvisioningJob): + mailbox = models.OneToOneField( + HostingMailbox, on_delete=models.CASCADE, related_name="imap_import" + ) + actor = models.ForeignKey( + settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True + ) + actor_role = models.CharField(max_length=16, blank=True) + source_host = models.CharField(max_length=253) + source_user = models.CharField(max_length=254) + target_host = models.CharField(max_length=253) + target_user = models.CharField(max_length=254) + sealed_credentials = models.TextField(blank=True, editable=False) + phase = models.CharField(max_length=16, default="checking") + + +class MailboxImportFolder(models.Model): + job = models.ForeignKey( + MailboxImport, on_delete=models.CASCADE, related_name="folders" + ) + source_key = models.CharField(max_length=64) + source_name = models.TextField() + target_name = models.TextField() + source_validity = models.PositiveBigIntegerField(default=0) + target_validity = models.PositiveBigIntegerField(default=0) + last_uid = models.PositiveBigIntegerField(default=0) + copied = models.PositiveBigIntegerField(default=0) + omitted_flags = models.PositiveBigIntegerField(default=0) + pending = models.JSONField(default=dict, blank=True) + problem = models.TextField(blank=True) + complete = models.BooleanField(default=False) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=("job", "source_key"), + name="hosting_mail_import_folder_key", + ) + ] + + class MailboxRemoval(ProvisioningJob): archive_id = models.UUIDField( default=uuid.uuid4, unique=True, editable=False diff --git a/src/coulobre/hosting/tasks.py b/src/coulobre/hosting/tasks.py index 10c9d38..07ad0c4 100644 --- a/src/coulobre/hosting/tasks.py +++ b/src/coulobre/hosting/tasks.py @@ -38,6 +38,9 @@ from .independent_websites import active_websites, apply_website_operation from .mail_dns_setup import sync_mail_dns from .mail_domain_aliases import aliases_available, apply_domain_alias from .mail_policies import apply_policy, mail_policy_available +from .mailbox_import_tasks import ( + dispatch_mailbox_imports as dispatch_mailbox_imports, +) from .mailbox_removal import apply_removal from .models import ( AccountBackupExpiration, diff --git a/src/coulobre/hosting/templates/hosting/mailbox_import.html b/src/coulobre/hosting/templates/hosting/mailbox_import.html new file mode 100644 index 0000000..c2d99db --- /dev/null +++ b/src/coulobre/hosting/templates/hosting/mailbox_import.html @@ -0,0 +1,68 @@ +{% extends "hosting/workspace_page.html" %} + +{% block title %}Import mailbox ยท Coulobre Panel{% endblock %} + +{% block page_header %} +
+
+

Import mailbox

+

{{ mailbox }}

+
+ Back to email +
+{% endblock %} + +{% block page_content %} +
+{% if job %} +
+
+

Import progress

+ Reload page +
+

+ {% if job.finished_at %} + {% if job.problem %}{{ job.problem }}{% else %}The copy is complete.{% endif %} + {% elif job.phase == "copying" %} + Copying messages. + {% elif job.started_at %} + Checking the source and destination. + {% else %} + Waiting for the import worker. + {% endif %} +

+ {% if folders %} +
+ + + + + + {% for name, folder in folders %} + + + + + + + {% endfor %} + +
Source folderCopiedFlags skippedStatus
{{ name }}{{ folder.copied }}{{ folder.omitted_flags }}{% if folder.problem %}{{ folder.problem }}{% elif folder.complete %}Complete{% else %}In progress{% endif %}
+
+ {% endif %} +
+{% endif %} + +{% if not job or job.finished_at %} +
+
+ {% csrf_token %} +

Coulobre copies mail over TLS on port 993. It does not delete mail or change DNS. Use an app password if your provider requires one.

+ {% if job %}

Enter the passwords again to retry or copy messages that arrived since the last run.

{% endif %} + {{ form.as_div }} +
+
+
+{% endif %} +
+{% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/mailbox_management_links.html b/src/coulobre/hosting/templates/hosting/mailbox_management_links.html index b7b4c6c..6cee312 100644 --- a/src/coulobre/hosting/templates/hosting/mailbox_management_links.html +++ b/src/coulobre/hosting/templates/hosting/mailbox_management_links.html @@ -3,6 +3,9 @@ Retry removal {% endif %} {% else %} + {% if mailbox_import_enabled and mailbox.provisioning.state == "configured" %} + Import mail + {% endif %} {% if show_mailbox_rotation and mailbox.provisioning.state == "configured" %} Change password {% endif %} diff --git a/src/coulobre/hosting/test_mailbox_imports.py b/src/coulobre/hosting/test_mailbox_imports.py new file mode 100644 index 0000000..8a4984a --- /dev/null +++ b/src/coulobre/hosting/test_mailbox_imports.py @@ -0,0 +1,280 @@ +from datetime import timedelta +from time import monotonic +from unittest.mock import Mock, patch + +from django.contrib.auth import get_user_model +from django.core.exceptions import ValidationError +from django.test import TestCase, override_settings +from django.urls import reverse +from django.utils import timezone +from django_otp.plugins.otp_totp.models import TOTPDevice + +from coulobre import imap_import as imap + +from . import mailbox_imports as imports +from .mailbox_import_tasks import dispatch_mailbox_imports, run_mailbox_import +from .models import ( + Customer, + HostingAccount, + HostingMailbox, + HostingMailDomain, + MailboxImport, + MailboxProvisioning, +) +from .panel_roles import scoped_user + + +@override_settings( + MAILBOX_IMAP_IMPORT=True, + LOCAL_MAILBOX_PROVISIONING=True, + MAIL_IMAP_HOST="receiver.example.com", +) +class MailboxImportTests(TestCase): + @classmethod + def setUpTestData(cls): + users = get_user_model().objects + cls.customer = users.create_user("customer") + cls.operator = users.create_superuser("operator") + cls.stranger = users.create_user("stranger") + for user in (cls.customer, cls.operator, cls.stranger): + TOTPDevice.objects.create(user=user, name="Panel") + cls.profile = Customer.objects.create(user=cls.customer) + Customer.objects.create(user=cls.stranger) + account = HostingAccount.objects.create( + name="Hosted", primary_domain="example.com", customer=cls.profile + ) + domain = HostingMailDomain.objects.create( + account=account, domain=account.primary_domain + ) + cls.mailbox = HostingMailbox.objects.create( + mail_domain=domain, local_part="contact" + ) + MailboxProvisioning.objects.create( + mailbox=cls.mailbox, finished_at=timezone.now() + ) + + def sign_in(self, user): + self.client.force_login(user) + session = self.client.session + session["otp_device_id"] = TOTPDevice.objects.get( + user=user + ).persistent_id + session.save() + + def data(self, **overrides): + return { + "source_host": "imap.provider.example", + "source_user": "contact@provider.example", + "source_password": "synthetic-source-password", + "target_password": "synthetic-destination-password", + **overrides, + } + + def url(self): + return reverse("panel:mailbox_import", args=[self.mailbox.pk]) + + def queue(self): + return imports.queue_import(self.mailbox, self.customer, self.data()) + + def test_only_the_owner_and_authorized_operator_can_start_import(self): + self.sign_in(self.stranger) + self.assertEqual(self.client.get(self.url()).status_code, 404) + self.assertEqual( + self.client.post(self.url(), self.data()).status_code, 404 + ) + self.assertFalse(MailboxImport.objects.exists()) + self.sign_in(self.customer) + response = self.client.get(self.url()) + self.assertContains(response, "Check and import") + self.assertIn("no-store", response.headers["Cache-Control"]) + self.assertRedirects( + self.client.post(self.url(), self.data()), self.url() + ) + self.assertEqual(MailboxImport.objects.get().actor, self.customer) + self.client.logout() + self.sign_in(self.operator) + response = self.client.get(self.url()) + self.assertContains(response, "Waiting for the import worker") + self.assertNotContains(response, self.data()["source_password"]) + self.assertNotContains(response, self.data()["target_password"]) + + def test_disabled_feature_does_not_accept_credentials(self): + self.sign_in(self.customer) + with override_settings(MAILBOX_IMAP_IMPORT=False): + self.assertEqual( + self.client.post(self.url(), self.data()).status_code, 403 + ) + self.assertFalse(MailboxImport.objects.exists()) + + def test_rejects_unprovisioned_mailbox_without_storing_credentials(self): + self.mailbox.provisioning.delete() + self.sign_in(self.customer) + response = self.client.post(self.url(), self.data()) + self.assertContains(response, "Choose a provisioned mailbox") + self.assertFalse(MailboxImport.objects.exists()) + + def test_dispatch_deduplicates_and_only_passes_job_id(self): + job = self.queue() + self.assertEqual(job.target_host, "receiver.example.com") + self.assertEqual(job.target_user, "contact@example.com") + for field in ("source_password", "target_password"): + self.assertNotIn(self.data()[field], job.sealed_credentials) + with patch.object(run_mailbox_import, "apply_async") as publish: + dispatch_mailbox_imports() + dispatch_mailbox_imports() + publish.assert_called_once_with( + args=[job.pk], queue=imports.QUEUE, expires=60, retry=False + ) + with patch.object(imports, "run_import") as run: + run_mailbox_import(job.pk) + run_mailbox_import(job.pk) + run.assert_called_once() + job.refresh_from_db() + self.assertEqual(job.phase, "complete") + self.assertFalse(job.sealed_credentials) + + def test_expired_jobs_and_interrupted_workers_discard_credentials(self): + job = self.queue() + MailboxImport.objects.filter(pk=job.pk).update( + requested_at=timezone.now() + - timedelta(seconds=imports.CREDENTIAL_SECONDS + 1) + ) + dispatch_mailbox_imports() + job.refresh_from_db() + self.assertIn("expired", job.problem) + self.assertFalse(job.sealed_credentials) + job = self.queue() + MailboxImport.objects.filter(pk=job.pk).update( + started_at=timezone.now() + - timedelta(seconds=imports.STALE_SECONDS + 1) + ) + dispatch_mailbox_imports() + job.refresh_from_db() + self.assertEqual(job.problem, imports.INTERRUPTED) + self.assertFalse(job.sealed_credentials) + + def test_worker_does_not_regain_operator_rights_in_customer_workspace( + self, + ): + Customer.objects.create(user=self.operator) + self.mailbox.mail_domain.account.customer = ( + self.operator.hosting_customer + ) + self.mailbox.mail_domain.account.save(update_fields=["customer"]) + job = imports.queue_import( + self.mailbox, scoped_user(self.operator, "customer"), self.data() + ) + self.mailbox.mail_domain.account.customer = self.profile + self.mailbox.mail_domain.account.save(update_fields=["customer"]) + with patch.object(imap, "resolve") as resolve: + run_mailbox_import(job.pk) + resolve.assert_not_called() + job.refresh_from_db() + self.assertIn("no longer has access", job.problem) + self.assertFalse(job.sealed_credentials) + + def test_retries_require_same_source_and_target_identity(self): + job = self.queue() + checkpoint = imports.prepare_checkpoint( + job, b"INBOX", b"INBOX", 17, 18 + ) + imports.finish_message(checkpoint, 1, 0) + MailboxImport.objects.filter(pk=job.pk).update( + finished_at=timezone.now(), sealed_credentials="" + ) + with self.assertRaisesRegex(ValidationError, "original servers"): + imports.queue_import( + self.mailbox, + self.customer, + self.data(source_host="different.example.com"), + ) + + def test_can_correct_the_source_after_a_failed_preflight(self): + job = self.queue() + MailboxImport.objects.filter(pk=job.pk).update( + phase="failed", finished_at=timezone.now(), sealed_credentials="" + ) + job = imports.queue_import( + self.mailbox, + self.customer, + self.data(source_host="correct.example.com"), + ) + self.assertEqual(job.source_host, "correct.example.com") + self.assertIsNone(job.finished_at) + + def test_auth_failure_does_not_modify_destination(self): + job = self.queue() + source, target = Mock(), Mock() + source.capabilities = target.capabilities = () + target.login.side_effect = imap.imaplib.IMAP4.error("credential") + with ( + patch.object( + imap, "resolve", side_effect=[("8.8.8.8",), ("10.0.0.1",)] + ), + patch.object(imports, "connect", side_effect=[source, target]), + ): + run_mailbox_import(job.pk) + target.create.assert_not_called() + target.append.assert_not_called() + job.refresh_from_db() + self.assertEqual( + job.problem, "The destination IMAP server rejected the login." + ) + self.assertFalse(job.sealed_credentials) + + def test_lost_append_ack_is_reconciled_without_duplicating_messages(self): + job = self.queue() + source, target = Mock(), Mock() + message = imap.Message( + b"Subject: Imported\r\n\r\nFixture\r\n", + b'"01-Mar-2024 10:45:00 +0000"', + (b"\\Seen",), + ) + source_uids, target_uids = [1], [] + + def search(client, start): + values = source_uids if client is source else target_uids + return [uid for uid in values if uid >= start] + + def append(*args): + target_uids.append(len(target_uids) + 10) + if len(target_uids) == 1: + raise OSError("Connection lost after APPEND") + + def do_copy(): + imports.copy_folder( + job, + source, + target, + b"INBOX", + b"INBOX", + {b"INBOX"}, + monotonic() + 10, + ) + + with ( + patch.object(imap, "select", return_value=(17, 10)), + patch.object(imap, "permanent_flags", return_value={b"\\SEEN"}), + patch.object(imap, "fetch_message", return_value=message), + patch.object(imap, "search_uids", side_effect=search), + patch.object(imap, "append", side_effect=append) as write, + ): + with self.assertRaises(OSError): + do_copy() + self.assertEqual(job.folders.get().pending["uid"], 1) + do_copy() + self.assertEqual(write.call_count, 1) + source_uids.append(2) + do_copy() + self.assertEqual(write.call_count, 2) + progress = job.folders.get() + self.assertEqual(progress.last_uid, 2) + self.assertEqual(progress.copied, 2) + self.assertEqual(progress.pending, {}) + self.assertTrue(progress.complete) + + def test_resume_rejects_a_changed_destination_uid_validity(self): + job = self.queue() + imports.prepare_checkpoint(job, b"INBOX", b"INBOX", 17, 18) + with self.assertRaisesRegex(imap.MailboxImportError, "UID identity"): + imports.prepare_checkpoint(job, b"inbox", b"INBOX", 17, 81) diff --git a/src/coulobre/hosting/urls.py b/src/coulobre/hosting/urls.py index 7b4e15e..d8bc810 100644 --- a/src/coulobre/hosting/urls.py +++ b/src/coulobre/hosting/urls.py @@ -60,6 +60,7 @@ from .mail_policy_views import ( MailVacationEditor, ) from .mail_queue_views import MailQueueIndex, MailQueueView, mail_queue_action +from .mailbox_import_views import MailboxImportView from .mailbox_removal import MailboxRemovalView from .notification_views import NotificationPreferencesView from .operator_backups import OperatorBackupsView @@ -777,6 +778,11 @@ urlpatterns = [ views.MailboxQuotaEdit.as_view(), name="mailbox_quota", ), + path( + "mailboxes//import/", + MailboxImportView.as_view(), + name="mailbox_import", + ), path( "mailboxes//remove/", MailboxRemovalView.as_view(), diff --git a/src/coulobre/imap_import.py b/src/coulobre/imap_import.py new file mode 100644 index 0000000..d6b6a6a --- /dev/null +++ b/src/coulobre/imap_import.py @@ -0,0 +1,389 @@ +"""Bounded IMAPS connections and an append-only mailbox protocol.""" + +import hashlib +import imaplib +import re +import socket +import ssl +from dataclasses import dataclass +from datetime import UTC, datetime +from ipaddress import ip_address, ip_network + +from coulobre.domain_names import canonical_domain + +MAX_MESSAGE_BYTES = 50 * 1024**2 +MAX_PACKET_BYTES = MAX_MESSAGE_BYTES +MAX_FOLDERS = 500 +MAX_RECONCILE = 250 +IMAPS_PORT = 993 +IO_TIMEOUT = 15 +NATIVE_IPV6 = ip_network("2000::/3") +LIST_REPLY = re.compile(rb'^\(([^()]*)\) (NIL|"[^"\\]"|"\\[\\"]") (.+)$', re.I) +UID_NUMBER = re.compile(rb"^[1-9][0-9]{0,9}$") +FLAG = re.compile(rb"\\?[A-Za-z0-9._$+-]{1,64}\Z") +INTERNALDATE = re.compile( + rb'\bINTERNALDATE ("[ 0-9][0-9]-[A-Za-z]{3}-[0-9]{4} ' + rb'[0-9]{2}:[0-9]{2}:[0-9]{2} [+-][0-9]{4}")', + re.I, +) + + +class MailboxImportError(ValueError): + """An operator-readable error without raw remote responses.""" + + +@dataclass(frozen=True) +class Folder: + name: bytes + separator: bytes | None + + +@dataclass(frozen=True) +class Message: + body: bytes + date: bytes + flags: tuple[bytes, ...] + + @property + def digest(self): + return hashlib.sha256(self.body).hexdigest() + + @property + def timestamp(self): + try: + return ( + datetime.strptime( + self.date[1:-1].decode("ascii").strip(), + "%d-%b-%Y %H:%M:%S %z", + ) + .astimezone(UTC) + .isoformat() + ) + except ValueError: + raise MailboxImportError( + "The message has an invalid original date." + ) from None + + +def source_hostname(value): + try: + name = canonical_domain(value) + except ValueError: + raise MailboxImportError( + "Enter the source IMAP server hostname." + ) from None + if "." not in name: + raise MailboxImportError("Enter the source IMAP server hostname.") + try: + ip_address(name) + except ValueError: + return name + raise MailboxImportError("Use the source hostname, not an IP address.") + + +def resolve(host, *, public_only): + try: + answers = socket.getaddrinfo( + host, IMAPS_PORT, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP + ) + except OSError: + raise MailboxImportError( + "The IMAP hostname could not be resolved." + ) from None + addresses = [] + for _, _, _, _, record in answers: + ip = ip_address(record[0]) + if getattr(ip, "ipv4_mapped", None): + ip = ip.ipv4_mapped + if public_only and not public_address(ip): + raise MailboxImportError( + "The source IMAP hostname must resolve only to public " + "addresses." + ) + addresses.append(str(ip)) + if not addresses: + raise MailboxImportError("The IMAP hostname has no usable address.") + return tuple(dict.fromkeys(addresses)) + + +def public_address(ip): + if not ip.is_global or ip.is_multicast or ip.is_reserved: + return False + return ip.version == 4 or ( + ip in NATIVE_IPV6 and ip.sixtofour is None and ip.teredo is None + ) + + +class PinnedIMAPS(imaplib.IMAP4_SSL): + def __init__(self, host, address): + self.address = address + super().__init__( + host, + IMAPS_PORT, + ssl_context=ssl.create_default_context(), + timeout=IO_TIMEOUT, + ) + + def _create_socket(self, timeout): + raw = socket.create_connection((self.address, self.port), timeout) + try: + return self.ssl_context.wrap_socket(raw, server_hostname=self.host) + except BaseException: + raw.close() + raise + + def read(self, size): + if not 0 <= size <= MAX_PACKET_BYTES: + raise MailboxImportError( + "The IMAP server returned an oversized literal." + ) + return super().read(size) + + +def quote(value): + if ( + not isinstance(value, bytes) + or len(value) > 1024 + or any(char < 32 or char > 126 for char in value) + ): + raise MailboxImportError("An IMAP name uses an unsupported encoding.") + return b'"' + value.replace(b"\\", b"\\\\").replace(b'"', b'\\"') + b'"' + + +def unquote(value): + if value.startswith(b'"') and value.endswith(b'"'): + if not re.fullmatch(rb'"(?:[^"\\]|\\["\\])*"', value): + raise MailboxImportError( + "The server returned an invalid folder name." + ) + value = re.sub(rb'\\(["\\])', rb"\1", value[1:-1]) + elif not re.fullmatch(rb"[^\s(){}%*\"\\]+", value): + raise MailboxImportError( + "The server returned an unsupported folder name." + ) + quote(value) + return value + + +def login(client, user, password, side): + # Never place raw credentials on command lines or in logs. + try: + if "AUTH=PLAIN" in client.capabilities: + payload = ( + b"\0" + user.encode("utf-8") + b"\0" + password.encode("utf-8") + ) + client.authenticate("PLAIN", lambda _: payload) + else: + client.login(quote(user.encode("ascii")), password) + except (imaplib.IMAP4.error, UnicodeError): + raise MailboxImportError( + f"The {side} IMAP server rejected the login." + ) from None + + +def list_folders(client, *, root=False): + result, rows = client.list('""', '""' if root else '"*"') + if result != "OK" or len(rows) > MAX_FOLDERS: + raise MailboxImportError( + "The server could not list folders within the import limit." + ) + items = [] + for row in rows: + if row is None: + continue + if not isinstance(row, bytes) or not ( + parsed := LIST_REPLY.fullmatch(row) + ): + raise MailboxImportError( + "The server uses an unsupported IMAP folder listing." + ) + flags, separator, name = parsed.groups() + if not root and b"\\NOSELECT" in flags.upper().split(): + continue + items.append( + Folder( + unquote(name), + None if separator.upper() == b"NIL" else unquote(separator), + ) + ) + return items + + +def map_folders(folders, delimiter): + mapping = [] + keys = set() + for folder in folders: + pieces = ( + folder.name.split(folder.separator) + if folder.separator + else [folder.name] + ) + if ( + not all(pieces) + or len(pieces) > 32 + or (delimiter is None and len(pieces) > 1) + or ( + delimiter is not None + and any(delimiter in part for part in pieces) + ) + ): + raise MailboxImportError( + "A source folder cannot be mapped to the destination " + "hierarchy." + ) + if pieces[0].upper() == b"INBOX": + pieces[0] = b"INBOX" + destination = (delimiter or b"").join(pieces) + quote(destination) + if destination in keys: + raise MailboxImportError( + "Two source folders map to the same destination folder." + ) + keys.add(destination) + mapping.append((folder.name, destination)) + return mapping + + +def response_number(client, key): + _, fields = client.response(key) + if ( + not fields + or not isinstance(fields[-1], bytes) + or not UID_NUMBER.fullmatch(fields[-1]) + ): + raise MailboxImportError( + "The IMAP server did not report a valid folder UID state." + ) + return int(fields[-1]) + + +def select(client, folder, *, readonly): + result, _ = client.select(quote(folder), readonly=readonly) + if result != "OK": + raise MailboxImportError("An IMAP folder could not be opened.") + uidvalidity = response_number(client, "UIDVALIDITY") + uidnext = response_number(client, "UIDNEXT") + return uidvalidity, uidnext + + +def search_uids(client, first): + result, rows = client.uid("SEARCH", None, "UID", f"{first}:*") + if result != "OK" or len(rows) != 1 or not isinstance(rows[0], bytes): + raise MailboxImportError( + "The server could not enumerate messages in a folder." + ) + values = rows[0].split() + if any(not UID_NUMBER.fullmatch(value) for value in values): + raise MailboxImportError( + "The server returned invalid message identifiers." + ) + return sorted({int(value) for value in values if int(value) >= first}) + + +def fetch_message(client, uid): + result, metadata = client.uid("FETCH", str(uid), "(UID RFC822.SIZE)") + match = ( + re.search(rb"\bRFC822.SIZE (\d{1,12})\b", metadata[0] or b"", re.I) + if result == "OK" and metadata and isinstance(metadata[0], bytes) + else None + ) + if not match: + raise MailboxImportError("A message disappeared or could not be read.") + if int(match[1]) > MAX_MESSAGE_BYTES: + raise MailboxImportError("A message exceeds the 50 MiB import limit.") + result, rows = client.uid( + "FETCH", str(uid), "(UID FLAGS INTERNALDATE BODY.PEEK[])" + ) + if result != "OK": + raise MailboxImportError( + "The IMAP server could not return a message body." + ) + parts = [row for row in rows if isinstance(row, tuple)] + if len(parts) != 1: + raise MailboxImportError("The server returned an incomplete message.") + header, body = parts[0] + trailer = b" ".join(row for row in rows if isinstance(row, bytes)) + fields = header + b" " + trailer + date = INTERNALDATE.search(fields) + found_uid = re.search(rb"\bUID (\d+)\b", fields, re.I) + if ( + not date + or not found_uid + or found_uid[1] != str(uid).encode() + or not isinstance(body, bytes) + ): + raise MailboxImportError( + "The server did not return this message's UID and original date." + ) + flags = re.search(rb"\bFLAGS \(([^()]*)\)", fields, re.I) + if flags is None: + raise MailboxImportError("The IMAP server omitted the message flags.") + return Message( + imaplib.MapCRLF.sub(imaplib.CRLF, body), + date[1], + tuple(flags[1].split()), + ) + + +def permanent_flags(client): + _, values = client.response("PERMANENTFLAGS") + value = values[-1] if values else None + return frozenset((value or b"").upper().strip(b"()").split()) + + +def usable_flags(allowed, flags): + standard = (b"\\SEEN", b"\\ANSWERED", b"\\FLAGGED", b"\\DRAFT") + reportable = [flag for flag in flags if flag.upper() != b"\\RECENT"] + kept = tuple( + flag + for flag in reportable + if FLAG.fullmatch(flag) + and flag.upper() != b"\\DELETED" + and ( + flag.upper() in allowed + or (b"\\*" in allowed and not flag.startswith(b"\\")) + or (not allowed and flag.upper() in standard) + ) + ) + return kept, len(reportable) - len(kept) + + +def append(client, destination, message, flags): + result, response = client.append( + quote(destination), + "(" + b" ".join(flags).decode("ascii") + ")", + message.date.decode("ascii"), + message.body, + ) + if result != "OK": + if any( + isinstance(row, bytes) and b"OVERQUOTA" in row.upper() + for row in response + ): + raise MailboxImportError( + "The destination mailbox is over its storage quota." + ) + raise MailboxImportError( + "The destination rejected a message. Check quota and size limits." + ) + + +def reconcile(destination, first, digest, timestamp): + uids = search_uids(destination, first) + if len(uids) > MAX_RECONCILE: + raise MailboxImportError( + "Too many new destination messages followed an interrupted " + "copy. Review the folder before retrying." + ) + matches = [ + uid + for uid in uids + if (message := fetch_message(destination, uid)).digest == digest + and message.timestamp == timestamp + ] + if len(matches) > 1: + raise MailboxImportError( + "An interrupted copy has multiple matches. Review the " + "destination folder before retrying." + ) + return bool(matches) diff --git a/src/coulobre/local_update.py b/src/coulobre/local_update.py index 398613f..ab66b84 100644 --- a/src/coulobre/local_update.py +++ b/src/coulobre/local_update.py @@ -62,6 +62,7 @@ MANAGED_UNITS = frozenset( "coulobre-mail-archive-restore.socket", "coulobre-mail-credentials.socket", "coulobre-mail-passwords.socket", + "coulobre-mailbox-import-worker.service", "coulobre-mailbox-provisioner.service", "coulobre-offsite-worker.service", "coulobre-operator-apply.socket", diff --git a/src/coulobre/settings.py b/src/coulobre/settings.py index 12c4ee3..9335296 100644 --- a/src/coulobre/settings.py +++ b/src/coulobre/settings.py @@ -311,6 +311,7 @@ LOCAL_MAILBOX_CREDENTIALS = ( os.environ.get("COULOBRE_LOCAL_MAILBOX_CREDENTIALS") == "1" ) MAIL_IMAP_HOST = os.environ.get("COULOBRE_MAIL_IMAP_HOST", "").strip() +MAILBOX_IMAP_IMPORT = os.environ.get("COULOBRE_MAILBOX_IMAP_IMPORT") == "1" MAIL_SUBMISSION_HOST = os.environ.get( "COULOBRE_MAIL_SUBMISSION_HOST", "" ).strip() @@ -422,6 +423,11 @@ if (LOCAL_ACCOUNT_BACKUP_MAIL and REMOTE_ACCOUNT_BACKUP_MAIL) or ( "Choose one mailbox transport for backup and one for restore." ) CELERY_BEAT_SCHEDULE = { + "dispatch-mailbox-imports": { + "task": "coulobre.hosting.tasks.dispatch_mailbox_imports", + "schedule": 15.0, + "options": {"expires": 14.0}, + }, "expire-panel-sign-in-windows": { "task": "coulobre.hosting.tasks.expire_sign_in_windows", "schedule": 600.0, diff --git a/src/coulobre/test_imap_import.py b/src/coulobre/test_imap_import.py new file mode 100644 index 0000000..5983fde --- /dev/null +++ b/src/coulobre/test_imap_import.py @@ -0,0 +1,159 @@ +from datetime import UTC, datetime +from ipaddress import ip_address +from unittest.mock import Mock, patch + +from django.test import SimpleTestCase + +from . import imap_import as imap + + +class ImapProtocolTests(SimpleTestCase): + def test_source_dns_requires_every_address_to_be_public(self): + for address in ( + "127.0.0.1", + "::1", + "169.254.169.254", + "::ffff:192.168.10.1", + "64:ff9b::c0a8:101", + "100.64.0.1", + "224.1.1.1", + "fd01::1", + "2002:c0a8:0101::1", + ): + with ( + self.subTest(address=address), + patch.object( + imap.socket, + "getaddrinfo", + return_value=[ + (0, 0, 0, "", ("8.8.8.8", 993)), + (0, 0, 0, "", (address, 993)), + ], + ), + ): + with self.assertRaisesRegex(imap.MailboxImportError, "public"): + imap.resolve("imap.example.com", public_only=True) + self.assertEqual( + imap.resolve("mail.example.com", public_only=False)[0], + "8.8.8.8", + ) + self.assertTrue(imap.public_address(ip_address("2606:4700::1111"))) + + def test_tls_uses_the_pinned_address_and_original_hostname(self): + client = object.__new__(imap.PinnedIMAPS) + client.address = "8.8.8.8" + client.host = "imap.example.com" + client.port = 993 + client.ssl_context = Mock() + with patch.object(imap.socket, "create_connection") as dial: + self.assertIs( + client._create_socket(15), + client.ssl_context.wrap_socket.return_value, + ) + dial.assert_called_once_with(("8.8.8.8", 993), 15) + client.ssl_context.wrap_socket.assert_called_once_with( + dial.return_value, server_hostname="imap.example.com" + ) + + def test_list_and_map_encoded_folder_names(self): + server = Mock() + server.list.return_value = ( + "OK", + [ + b'(\\Noselect) "/" "Parent"', + b'() "/" "Parent/Bo&AO4-te"', + b'() "/" "inbox"', + b'() "/" "Say \\"hello\\""', + ], + ) + self.assertEqual( + imap.map_folders(imap.list_folders(server), b"."), + [ + (b"Parent/Bo&AO4-te", b"Parent.Bo&AO4-te"), + (b"inbox", b"INBOX"), + (b'Say "hello"', b'Say "hello"'), + ], + ) + with self.assertRaisesRegex(imap.MailboxImportError, "same"): + imap.map_folders( + [imap.Folder(b"INBOX", b"/"), imap.Folder(b"inbox", b"/")], + b".", + ) + with self.assertRaisesRegex(imap.MailboxImportError, "hierarchy"): + imap.map_folders([imap.Folder(b"Parent/A.B", b"/")], b".") + + def test_message_fetch_preserves_date_and_does_not_mark_as_seen(self): + server = Mock() + server.uid.side_effect = [ + ("OK", [b"2 (UID 42 RFC822.SIZE 26)"]), + ( + "OK", + [ + ( + b"2 (BODY[] {26}", + b"Subject: Test\r\n\r\nMessage\r\n", + ), + ( + b" UID 42 FLAGS (\\Answered SeenKeyword) " + b'INTERNALDATE " 4-Feb-2025 13:15:00 +0100")' + ), + ], + ), + ] + message = imap.fetch_message(server, 42) + self.assertEqual( + message.timestamp, + datetime(2025, 2, 4, 12, 15, tzinfo=UTC).isoformat(), + ) + self.assertEqual(message.flags, (b"\\Answered", b"SeenKeyword")) + server.uid.assert_called_with( + "FETCH", "42", "(UID FLAGS INTERNALDATE BODY.PEEK[])" + ) + + def test_oversized_message_is_rejected_before_fetching_body(self): + server = Mock() + size = imap.MAX_MESSAGE_BYTES + 1 + server.uid.return_value = ( + "OK", + [f"1 (UID 1 RFC822.SIZE {size})".encode()], + ) + with self.assertRaisesRegex(imap.MailboxImportError, "50 MiB"): + imap.fetch_message(server, 1) + server.uid.assert_called_once_with("FETCH", "1", "(UID RFC822.SIZE)") + + def test_retains_supported_flags_without_marking_anything_for_deletion( + self, + ): + self.assertEqual( + imap.usable_flags( + {b"\\SEEN", b"\\*"}, + (b"\\Seen", b"\\Deleted", b"\\Recent", b"$Forwarded"), + ), + ((b"\\Seen", b"$Forwarded"), 1), + ) + + def test_quota_problem_is_reported_without_raw_server_output(self): + server = Mock() + server.append.return_value = ("NO", [b"[OVERQUOTA] private detail"]) + message = imap.Message( + b"Subject: Test\r\n\r\nMessage", + b'"04-Feb-2025 13:15:00 +0100"', + (), + ) + with self.assertRaisesRegex( + imap.MailboxImportError, + "^The destination mailbox is over its storage quota.$", + ): + imap.append(server, b"INBOX", message, ()) + + def test_reconciliation_pauses_if_more_than_one_match_exists(self): + client = Mock() + message = imap.Message(b"message", b'"04-Feb-2025 13:15:00 +0100"', ()) + with ( + patch.object(imap, "search_uids", return_value=[7, 8]), + patch.object(imap, "fetch_message", return_value=message), + self.assertRaisesRegex( + imap.MailboxImportError, "multiple matches" + ), + ): + imap.reconcile(client, 7, message.digest, message.timestamp)