Compare commits
3
Commits
d0c308eb04
...
93194b48eb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93194b48eb | ||
|
|
898bb47877 | ||
|
|
f0665b2028 |
No files matched your search
@@ -2481,6 +2481,19 @@ password or app password. The source must resolve only to public addresses
|
||||
and support implicit TLS on port 993 with a trusted certificate. OAuth-only
|
||||
accounts are not supported.
|
||||
|
||||
Choose **Preview import** to check the source and destination and view a
|
||||
read-only count of source folders and messages before copying. The size
|
||||
is shown only when the source reports it for every folder. Partial
|
||||
inventories identify how many folders were counted. Counts describe the
|
||||
source at the time of the check and include mail already copied on prior
|
||||
passes. On a subsequent pass, the preview can count messages after a
|
||||
matching checkpoint in a bounded UID range. It leaves the estimate
|
||||
unavailable for folders where it cannot do so reliably. Confirmation
|
||||
starts a new copy pass with the same source
|
||||
credentials and uses the existing checkpoints. The preview expires after
|
||||
30 minutes. Use **Import without preview** if you do not need an
|
||||
inventory or your provider does not supply usable folder counts.
|
||||
|
||||
Start once and leave the page if needed. The worker continues from saved
|
||||
checkpoints in batches and retries interrupted connections. Progress updates
|
||||
without a page reload and shows copied messages, previously copied messages,
|
||||
|
||||
@@ -134,6 +134,14 @@ Show a blocked prerequisite beside the resource that needs it. Put the
|
||||
reason and retry action there for operators with the relevant permission.
|
||||
Give customers a short next step without showing internal service details.
|
||||
|
||||
### Import previews
|
||||
|
||||
Separate a read-only preview from the action that starts a copy. Identify
|
||||
the source and destination, show the snapshot totals first, and put the
|
||||
per-folder or per-item breakdown below. Label partial counts and missing
|
||||
estimates explicitly. Distinguish the full source inventory from work
|
||||
remaining after a checkpoint. Do not display credentials or source content.
|
||||
|
||||
## Review a UI change
|
||||
|
||||
Compare the result with a Core page that serves the same purpose. In light
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Inspect a source and destination without copying any mailbox data."""
|
||||
|
||||
import imaplib
|
||||
import json
|
||||
import re
|
||||
from contextlib import ExitStack
|
||||
from datetime import timedelta
|
||||
from time import monotonic
|
||||
|
||||
from cryptography.fernet import InvalidToken
|
||||
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 coulobre.mail_import_receiver import SOCKET, open_destination
|
||||
|
||||
from . import mailbox_imports as imports
|
||||
from .models import HostingMailbox, MailboxImport, MailboxImportPreview
|
||||
from .node_client import NodeReplyError, require_matching_receiver
|
||||
from .panel_roles import assigned_roles, scoped_user
|
||||
from .resource_requests import lock_hosting_account
|
||||
|
||||
LIFETIME = timedelta(minutes=30)
|
||||
INSPECT_SECONDS = 70
|
||||
MAX_FOLDERS = 1000
|
||||
STAT = re.compile(
|
||||
rb"\b(MESSAGES|SIZE|UIDNEXT|UIDVALIDITY) ([0-9]{1,18})(?=[ )])"
|
||||
)
|
||||
EXPIRED = "The preview expired. Enter the source password to check again."
|
||||
UNAVAILABLE = "This mailbox is no longer available for preview."
|
||||
|
||||
|
||||
def actor_role(actor):
|
||||
return getattr(actor, "panel_role", "") or ""
|
||||
|
||||
|
||||
def previews(mailbox, actor):
|
||||
return MailboxImportPreview.objects.filter(
|
||||
mailbox=mailbox, actor=actor, actor_role=actor_role(actor)
|
||||
)
|
||||
|
||||
|
||||
def identity(preview):
|
||||
return ["preview-v1", preview.pk, *imports.job_identity(preview)]
|
||||
|
||||
|
||||
@sensitive_variables()
|
||||
@transaction.atomic
|
||||
def queue_preview(mailbox, actor, data):
|
||||
account = lock_hosting_account(mailbox.mail_domain.account_id, None)
|
||||
current = HostingMailbox.objects.select_related(
|
||||
"mail_domain__account", "provisioning", "removal"
|
||||
).get(pk=mailbox.pk, mail_domain__account=account)
|
||||
if not imports.available() or not imports.can_import(actor, current):
|
||||
raise ValidationError(UNAVAILABLE)
|
||||
imports.ready(current)
|
||||
if MailboxImport.objects.filter(
|
||||
mailbox=current, finished_at__isnull=True
|
||||
).exists():
|
||||
raise ValidationError("An import is already queued or running.")
|
||||
source = imap.source_hostname(data["source_host"])
|
||||
target = imap.source_hostname(settings.MAIL_IMAP_HOST)
|
||||
if source == target:
|
||||
raise ValidationError(
|
||||
"Choose a different source server from this mailbox's server."
|
||||
)
|
||||
previous = MailboxImportPreview.objects.filter(
|
||||
mailbox=current, actor=actor
|
||||
)
|
||||
if previous.filter(finished_at__isnull=True).exists():
|
||||
raise ValidationError("A preview is already queued or running.")
|
||||
previous.delete()
|
||||
preview = MailboxImportPreview.objects.create(
|
||||
mailbox=current,
|
||||
actor=actor,
|
||||
actor_role=actor_role(actor),
|
||||
source_host=source,
|
||||
source_user=data["source_user"],
|
||||
target_host=target,
|
||||
target_user=str(current),
|
||||
)
|
||||
preview.sealed_credentials = (
|
||||
imports.encryption()
|
||||
.encrypt(
|
||||
json.dumps([identity(preview), data["source_password"]]).encode()
|
||||
)
|
||||
.decode("ascii")
|
||||
)
|
||||
preview.save(update_fields=["sealed_credentials"])
|
||||
return preview
|
||||
|
||||
|
||||
@sensitive_variables()
|
||||
def password_for(preview):
|
||||
try:
|
||||
stored, secret = json.loads(
|
||||
imports.encryption().decrypt(
|
||||
preview.sealed_credentials.encode("ascii"),
|
||||
ttl=int(LIFETIME.total_seconds()),
|
||||
)
|
||||
)
|
||||
if stored == identity(preview):
|
||||
return secret
|
||||
except (InvalidToken, ValueError, UnicodeError, TypeError):
|
||||
pass
|
||||
raise imap.MailboxImportError(EXPIRED)
|
||||
|
||||
|
||||
@sensitive_variables()
|
||||
@transaction.atomic
|
||||
def confirm_preview(mailbox, actor, pk):
|
||||
# Match the lock order of both queue functions.
|
||||
lock_hosting_account(mailbox.mail_domain.account_id, None)
|
||||
preview = (
|
||||
previews(mailbox, actor)
|
||||
.select_for_update()
|
||||
.filter(
|
||||
pk=pk,
|
||||
finished_at__isnull=False,
|
||||
problem="",
|
||||
requested_at__gt=timezone.now() - LIFETIME,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if preview is None or not preview.report.get("readable"):
|
||||
raise ValidationError("Run a new preview before importing.")
|
||||
if (
|
||||
str(mailbox) != preview.target_user
|
||||
or imap.source_hostname(settings.MAIL_IMAP_HOST) != preview.target_host
|
||||
):
|
||||
raise ValidationError("Run a new preview for the current destination.")
|
||||
job = imports.queue_import(
|
||||
mailbox,
|
||||
actor,
|
||||
{
|
||||
"source_host": preview.source_host,
|
||||
"source_user": preview.source_user,
|
||||
"source_password": password_for(preview),
|
||||
},
|
||||
)
|
||||
preview.delete()
|
||||
return job
|
||||
|
||||
|
||||
def authorized_mailbox(preview):
|
||||
actor = preview.actor
|
||||
if preview.actor_role:
|
||||
if preview.actor_role not in assigned_roles(actor):
|
||||
raise imap.MailboxImportError(UNAVAILABLE)
|
||||
actor = scoped_user(actor, preview.actor_role)
|
||||
mailbox = preview.mailbox
|
||||
if (
|
||||
not imports.available()
|
||||
or not imports.can_import(actor, mailbox)
|
||||
or str(mailbox) != preview.target_user
|
||||
or imap.source_hostname(settings.MAIL_IMAP_HOST) != preview.target_host
|
||||
):
|
||||
raise imap.MailboxImportError(UNAVAILABLE)
|
||||
imports.ready(mailbox)
|
||||
return mailbox
|
||||
|
||||
|
||||
def folder_status(client, name, include_size):
|
||||
attributes = "(MESSAGES UIDNEXT UIDVALIDITY"
|
||||
attributes += " SIZE)" if include_size else ")"
|
||||
try:
|
||||
result, rows = client.status(imap.quote(name), attributes)
|
||||
except imaplib.IMAP4.abort:
|
||||
raise
|
||||
except imaplib.IMAP4.error:
|
||||
result, rows = "NO", []
|
||||
if result != "OK" and include_size:
|
||||
return folder_status(client, name, False)
|
||||
if result != "OK" or not rows or not isinstance(rows[0], bytes):
|
||||
return {}
|
||||
# Match attributes after the folder name, which may contain spaces.
|
||||
fields = rows[0].rsplit(b"(", 1)[-1]
|
||||
return {key: int(count) for key, count in STAT.findall(fields)}
|
||||
|
||||
|
||||
def messages_after_checkpoint(client, name, status, checkpoint, deadline):
|
||||
count = status.get(b"MESSAGES")
|
||||
if checkpoint is None:
|
||||
return count
|
||||
validity = status.get(b"UIDVALIDITY")
|
||||
next_uid = status.get(b"UIDNEXT")
|
||||
if (
|
||||
count is None
|
||||
or next_uid is None
|
||||
or not validity
|
||||
or validity != checkpoint.source_validity
|
||||
or checkpoint.pending
|
||||
):
|
||||
return None
|
||||
if not checkpoint.last_uid:
|
||||
return count
|
||||
first = checkpoint.last_uid + 1
|
||||
if next_uid <= first:
|
||||
return 0
|
||||
if next_uid - first > imports.UID_WINDOW or monotonic() >= deadline:
|
||||
return None
|
||||
try:
|
||||
actual_validity, actual_next = imap.select(client, name, readonly=True)
|
||||
if actual_validity == validity and actual_next == next_uid:
|
||||
return len(imap.search_uids(client, first, last=next_uid - 1))
|
||||
except imaplib.IMAP4.abort:
|
||||
raise
|
||||
except (imap.MailboxImportError, imaplib.IMAP4.error):
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def inventory(client, mapping, checkpoints=None):
|
||||
deadline = monotonic() + INSPECT_SECONDS
|
||||
caps = {cap.upper() for cap in client.capabilities}
|
||||
include_size = bool({"STATUS=SIZE", "IMAP4REV2"} & caps)
|
||||
folders = []
|
||||
for source_name, _ in mapping[:MAX_FOLDERS]:
|
||||
if monotonic() >= deadline:
|
||||
break
|
||||
status = folder_status(client, source_name, include_size)
|
||||
folders.append(
|
||||
{
|
||||
"name": imports.display_name(source_name),
|
||||
"count": status.get(b"MESSAGES"),
|
||||
"bytes": status.get(b"SIZE"),
|
||||
"remaining": messages_after_checkpoint(
|
||||
client,
|
||||
source_name,
|
||||
status,
|
||||
(checkpoints or {}).get(imports.folder_key(source_name)),
|
||||
deadline,
|
||||
),
|
||||
}
|
||||
)
|
||||
readable = [folder for folder in folders if folder["count"] is not None]
|
||||
complete = len(readable) == len(mapping)
|
||||
return {
|
||||
"folders": folders,
|
||||
"total_folders": len(mapping),
|
||||
"readable": len(readable),
|
||||
"messages": sum(folder["count"] for folder in readable),
|
||||
"bytes": sum(folder["bytes"] for folder in readable)
|
||||
if complete and all(folder["bytes"] is not None for folder in readable)
|
||||
else None,
|
||||
"complete": complete,
|
||||
"incremental": bool(checkpoints),
|
||||
"remaining": sum(folder["remaining"] for folder in folders)
|
||||
if complete
|
||||
and all(folder["remaining"] is not None for folder in folders)
|
||||
else None,
|
||||
}
|
||||
|
||||
|
||||
def checkpoints_for(preview):
|
||||
job = MailboxImport.objects.filter(
|
||||
mailbox=preview.mailbox,
|
||||
finished_at__isnull=False,
|
||||
source_host=preview.source_host,
|
||||
source_user=preview.source_user,
|
||||
target_host=preview.target_host,
|
||||
target_user=preview.target_user,
|
||||
).first()
|
||||
if not job:
|
||||
return {}
|
||||
return {folder.source_key: folder for folder in job.folders.all()}
|
||||
|
||||
|
||||
@sensitive_variables()
|
||||
def run_preview(preview):
|
||||
mailbox = authorized_mailbox(preview)
|
||||
source_ips = imap.resolve(preview.source_host, public_only=True)
|
||||
target_ips = imap.resolve(preview.target_host, public_only=False)
|
||||
if set(source_ips).intersection(target_ips):
|
||||
raise imap.MailboxImportError(
|
||||
"The source and destination resolve to the same server."
|
||||
)
|
||||
try:
|
||||
require_matching_receiver(SOCKET)
|
||||
except NodeReplyError as exc:
|
||||
raise imap.MailboxImportError(str(exc)) from None
|
||||
with ExitStack() as stack:
|
||||
source = imports.connect(
|
||||
preview.source_host, source_ips, "source", stack
|
||||
)
|
||||
imap.login(
|
||||
source, preview.source_user, password_for(preview), "source"
|
||||
)
|
||||
target = stack.enter_context(open_destination(mailbox.spec))
|
||||
target.select(b"INBOX", readonly=True)
|
||||
roots = target.list_folders(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
|
||||
)
|
||||
if not mapping:
|
||||
raise imap.MailboxImportError(
|
||||
"The source has no selectable folders to copy."
|
||||
)
|
||||
return inventory(source, mapping, checkpoints_for(preview))
|
||||
@@ -5,7 +5,7 @@ from datetime import timedelta
|
||||
|
||||
from billiard.exceptions import SoftTimeLimitExceeded
|
||||
from celery import shared_task
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from django.core.exceptions import ObjectDoesNotExist, ValidationError
|
||||
from django.db.models import F, Q
|
||||
from django.db.models.functions import Coalesce
|
||||
from django.utils import timezone
|
||||
@@ -13,8 +13,9 @@ from django.views.decorators.debug import sensitive_variables
|
||||
|
||||
from coulobre.imap_import import MailboxImportError
|
||||
|
||||
from . import mailbox_import_preview as preview
|
||||
from . import mailbox_imports as imports
|
||||
from .models import MailboxImport
|
||||
from .models import MailboxImport, MailboxImportPreview
|
||||
|
||||
EXPIRED = "The source password expired. Enter it again to resume."
|
||||
CONNECTION_LOST = (
|
||||
@@ -50,6 +51,7 @@ def yield_batch(owned, now, *, retry=False):
|
||||
)
|
||||
def dispatch_mailbox_imports():
|
||||
now = timezone.now()
|
||||
dispatch_previews(now)
|
||||
unfinished = MailboxImport.objects.filter(finished_at__isnull=True)
|
||||
waiting = unfinished.filter(started_at__isnull=True)
|
||||
expired = Q(
|
||||
@@ -148,3 +150,87 @@ def run_mailbox_import(pk, requested_at=None):
|
||||
finish(owned, timezone.now(), imports.INTERRUPTED)
|
||||
else:
|
||||
finish(owned, timezone.now())
|
||||
|
||||
|
||||
def dispatch_previews(now):
|
||||
previews = MailboxImportPreview.objects.all()
|
||||
cutoff = now - preview.LIFETIME
|
||||
previews.filter(requested_at__lt=now - timedelta(days=1)).delete()
|
||||
previews.filter(requested_at__lte=cutoff).exclude(
|
||||
sealed_credentials=""
|
||||
).update(sealed_credentials="")
|
||||
unfinished = previews.filter(finished_at__isnull=True)
|
||||
unfinished.filter(requested_at__lte=cutoff).update(
|
||||
finished_at=now, problem=preview.EXPIRED
|
||||
)
|
||||
unfinished.filter(
|
||||
started_at__lt=now - timedelta(seconds=imports.STALE_SECONDS)
|
||||
).update(
|
||||
finished_at=now, problem=imports.INTERRUPTED, sealed_credentials=""
|
||||
)
|
||||
if not imports.available():
|
||||
return
|
||||
waiting = (
|
||||
unfinished.filter(started_at__isnull=True, requested_at__gt=cutoff)
|
||||
.filter(
|
||||
Q(last_dispatched_at__isnull=True)
|
||||
| Q(last_dispatched_at__lt=now - timedelta(seconds=90))
|
||||
)
|
||||
.order_by("requested_at")
|
||||
)
|
||||
for pk in list(waiting.values_list("pk", flat=True)[:3]):
|
||||
if waiting.filter(pk=pk).update(last_dispatched_at=now):
|
||||
run_mailbox_import_preview.apply_async(
|
||||
args=[pk], queue=imports.QUEUE, expires=60, retry=False
|
||||
)
|
||||
|
||||
|
||||
@shared_task(
|
||||
name="coulobre.hosting.tasks.run_mailbox_import_preview",
|
||||
ignore_result=True,
|
||||
soft_time_limit=100,
|
||||
time_limit=115,
|
||||
)
|
||||
@sensitive_variables()
|
||||
def run_mailbox_import_preview(pk):
|
||||
started = timezone.now()
|
||||
waiting = MailboxImportPreview.objects.filter(
|
||||
pk=pk,
|
||||
finished_at__isnull=True,
|
||||
started_at__isnull=True,
|
||||
requested_at__gt=started - preview.LIFETIME,
|
||||
)
|
||||
if not waiting.update(started_at=started):
|
||||
return
|
||||
owned = MailboxImportPreview.objects.filter(
|
||||
pk=pk, started_at=started, finished_at__isnull=True
|
||||
)
|
||||
item = owned.select_related(
|
||||
"actor",
|
||||
"mailbox__mail_domain__account",
|
||||
"mailbox__provisioning",
|
||||
"mailbox__removal",
|
||||
).first()
|
||||
if item is None:
|
||||
return
|
||||
problem = ""
|
||||
report = {}
|
||||
try:
|
||||
report = preview.run_preview(item)
|
||||
if not report["readable"]:
|
||||
problem = "No source folder could be counted."
|
||||
except MailboxImportError as exc:
|
||||
problem = str(exc)
|
||||
except (ValidationError, ObjectDoesNotExist):
|
||||
problem = preview.UNAVAILABLE
|
||||
except (SoftTimeLimitExceeded, imaplib.IMAP4.error, OSError):
|
||||
problem = (
|
||||
"The IMAP preview did not finish. Check the source settings "
|
||||
"or start the import without a preview."
|
||||
)
|
||||
owned.update(
|
||||
finished_at=timezone.now(),
|
||||
problem=problem,
|
||||
report=report,
|
||||
**({"sealed_credentials": ""} if problem else {}),
|
||||
)
|
||||
@@ -16,6 +16,7 @@ from django.views.generic import FormView
|
||||
|
||||
from coulobre.imap_import import MailboxImportError, source_hostname
|
||||
|
||||
from . import mailbox_import_preview as preview
|
||||
from .access import can_manage_hosting, customer_for_user
|
||||
from .mailbox_imports import PERMISSIONS, available, display_name, queue_import
|
||||
from .models import HostingMailbox, MailboxImport
|
||||
@@ -80,12 +81,45 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
|
||||
def job(self):
|
||||
return MailboxImport.objects.filter(mailbox=self.mailbox).first()
|
||||
|
||||
@cached_property
|
||||
def preview(self):
|
||||
return (
|
||||
preview.previews(self.mailbox, self.request.user)
|
||||
.filter(requested_at__gt=timezone.now() - preview.LIFETIME)
|
||||
.first()
|
||||
)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
if request.POST.get("action") != "confirm-preview":
|
||||
return super().post(request, *args, **kwargs)
|
||||
pk = request.POST.get("preview_id", "")
|
||||
try:
|
||||
if not pk.isascii() or not pk.isdecimal() or len(pk) > 18:
|
||||
raise ValidationError("Run a new preview before importing.")
|
||||
preview.confirm_preview(self.mailbox, request.user, int(pk))
|
||||
except (ValidationError, MailboxImportError) as exc:
|
||||
messages.error(
|
||||
request,
|
||||
exc.messages[0]
|
||||
if isinstance(exc, ValidationError)
|
||||
else str(exc),
|
||||
)
|
||||
except ObjectDoesNotExist:
|
||||
messages.error(request, preview.UNAVAILABLE)
|
||||
else:
|
||||
messages.success(
|
||||
request,
|
||||
"Mailbox import queued. No DNS records will be changed.",
|
||||
)
|
||||
return redirect("panel:mailbox_import", pk=self.mailbox.pk)
|
||||
|
||||
def get_initial(self):
|
||||
if not self.job:
|
||||
item = self.preview or self.job
|
||||
if not item:
|
||||
return {}
|
||||
return {
|
||||
"source_host": self.job.source_host,
|
||||
"source_user": self.job.source_user,
|
||||
"source_host": item.source_host,
|
||||
"source_user": item.source_user,
|
||||
}
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
@@ -122,6 +156,7 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
|
||||
return super().get_context_data(
|
||||
mailbox=self.mailbox,
|
||||
job=self.job,
|
||||
preview=self.preview,
|
||||
folders=items,
|
||||
report=report,
|
||||
return_url=reverse(
|
||||
@@ -137,6 +172,14 @@ class MailboxImportView(PermissionRequiredMixin, FormView):
|
||||
@sensitive_variables()
|
||||
def form_valid(self, form):
|
||||
try:
|
||||
if self.request.POST.get("action") == "preview":
|
||||
preview.queue_preview(
|
||||
self.mailbox, self.request.user, form.cleaned_data
|
||||
)
|
||||
messages.success(
|
||||
self.request, "Preview queued. No messages will be copied."
|
||||
)
|
||||
return redirect("panel:mailbox_import", pk=self.mailbox.pk)
|
||||
queue_import(self.mailbox, self.request.user, form.cleaned_data)
|
||||
except ValidationError as exc:
|
||||
form.add_error(None, exc)
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Generated by Django 5.2.19 on 2026-12-04 12:58
|
||||
|
||||
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", "0097_panel_mail_relay"),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name="MailboxImportPreview",
|
||||
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(editable=False)),
|
||||
("report", models.JSONField(blank=True, default=dict)),
|
||||
(
|
||||
"actor",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to=settings.AUTH_USER_MODEL,
|
||||
),
|
||||
),
|
||||
(
|
||||
"mailbox",
|
||||
models.ForeignKey(
|
||||
on_delete=django.db.models.deletion.CASCADE,
|
||||
to="hosting.hostingmailbox",
|
||||
),
|
||||
),
|
||||
],
|
||||
options={
|
||||
"constraints": [
|
||||
models.UniqueConstraint(
|
||||
fields=("mailbox", "actor"),
|
||||
name="one_imap_preview_per_mailbox_actor",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -1672,6 +1672,28 @@ class MailboxImport(ProvisioningJob):
|
||||
consecutive_retries = models.PositiveSmallIntegerField(default=0)
|
||||
|
||||
|
||||
class MailboxImportPreview(ProvisioningJob):
|
||||
mailbox = models.ForeignKey(HostingMailbox, on_delete=models.CASCADE)
|
||||
actor = models.ForeignKey(
|
||||
settings.AUTH_USER_MODEL, on_delete=models.CASCADE
|
||||
)
|
||||
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(editable=False)
|
||||
report = models.JSONField(default=dict, blank=True)
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
fields=("mailbox", "actor"),
|
||||
name="one_imap_preview_per_mailbox_actor",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class MailboxImportFolder(models.Model):
|
||||
job = models.ForeignKey(
|
||||
MailboxImport, on_delete=models.CASCADE, related_name="folders"
|
||||
|
||||
@@ -70,6 +70,53 @@
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if preview and not job or preview and job.finished_at %}
|
||||
<section class="surface" id="import-preview" aria-labelledby="preview-heading" data-live-status="mailbox-import-preview">
|
||||
<header class="section-heading"><h2 id="preview-heading">Import preview</h2></header>
|
||||
{% if not preview.finished_at %}
|
||||
<p class="section-text" role="status" data-live-pending>Checking the source and destination. Nothing is being copied.</p>
|
||||
<noscript><p class="section-text"><a href="{% url 'panel:mailbox_import' mailbox.pk %}">Refresh preview</a></p></noscript>
|
||||
{% elif preview.problem %}
|
||||
<p class="section-text" role="status">{{ preview.problem }}</p>
|
||||
{% else %}
|
||||
<dl class="details section-text">
|
||||
<div><dt>Source</dt><dd>{{ preview.source_user }} at {{ preview.source_host }}</dd></div>
|
||||
<div><dt>Destination</dt><dd>{{ preview.target_user }}</dd></div>
|
||||
</dl>
|
||||
<p class="section-text">Source snapshot. These counts include previously copied messages. The import skips messages recorded at its checkpoints.</p>
|
||||
<dl class="details section-text">
|
||||
<div><dt>Folders counted</dt><dd>{{ preview.report.readable }} of {{ preview.report.total_folders }}</dd></div>
|
||||
<div><dt>Messages in counted folders</dt><dd>{{ preview.report.messages }}</dd></div>
|
||||
{% if preview.report.incremental %}<div><dt>Messages after previous checkpoints</dt><dd>{{ preview.report.remaining|default_if_none:"Not available" }}</dd></div>{% endif %}
|
||||
<div><dt>Source size</dt><dd>{% if preview.report.bytes is not None %}{{ preview.report.bytes|filesizeformat }}{% else %}Not available{% endif %}</dd></div>
|
||||
</dl>
|
||||
{% if not preview.report.complete %}
|
||||
<p class="section-text">This preview is partial. Unchecked or unreadable folders are not included in the totals.</p>
|
||||
{% endif %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Source folder</th><th scope="col">Messages</th><th scope="col">Source size</th>{% if preview.report.incremental %}<th scope="col">After checkpoint</th>{% endif %}</tr></thead>
|
||||
<tbody>
|
||||
{% for folder in preview.report.folders %}
|
||||
<tr>
|
||||
<th scope="row">{{ folder.name }}</th>
|
||||
<td>{{ folder.count|default_if_none:"Not available" }}</td>
|
||||
<td>{% if folder.bytes is not None %}{{ folder.bytes|filesizeformat }}{% else %}Not available{% endif %}</td>
|
||||
{% if preview.report.incremental %}<td>{{ folder.remaining|default_if_none:"Not available" }}</td>{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<form class="editor" method="post">
|
||||
{% csrf_token %}
|
||||
<input type="hidden" name="preview_id" value="{{ preview.pk }}">
|
||||
<div class="form-actions"><button class="button primary" name="action" value="confirm-preview">Start import</button></div>
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% if not job or job.finished_at %}
|
||||
<section id="import-source" class="surface editor-surface">
|
||||
<form class="editor" method="post">
|
||||
@@ -77,7 +124,10 @@
|
||||
<p class="muted">Coulobre reads the source over TLS on port 993. It does not delete mail or change DNS. Use an app password if your provider requires one.</p>
|
||||
{% if job %}<p>Enter the source password to resume a stopped import or copy new messages. Previously copied messages are not copied again.</p>{% endif %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions"><button class="button primary" type="submit">{% if job %}Check and continue{% else %}Check and import{% endif %}</button></div>
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit" name="action" value="preview">Preview import</button>
|
||||
<button class="button secondary" type="submit" name="action" value="direct">{% if job %}Continue without preview{% else %}Import without preview{% endif %}</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
@@ -11,14 +11,20 @@ from django_otp.plugins.otp_totp.models import TOTPDevice
|
||||
|
||||
from coulobre import imap_import as imap
|
||||
|
||||
from . import mailbox_import_preview as preview
|
||||
from . import mailbox_imports as imports
|
||||
from .mailbox_import_tasks import dispatch_mailbox_imports, run_mailbox_import
|
||||
from .mailbox_import_tasks import (
|
||||
dispatch_mailbox_imports,
|
||||
run_mailbox_import,
|
||||
run_mailbox_import_preview,
|
||||
)
|
||||
from .models import (
|
||||
Customer,
|
||||
HostingAccount,
|
||||
HostingMailbox,
|
||||
HostingMailDomain,
|
||||
MailboxImport,
|
||||
MailboxImportPreview,
|
||||
MailboxProvisioning,
|
||||
)
|
||||
from .panel_roles import scoped_user
|
||||
@@ -150,7 +156,7 @@ class MailboxImportTests(TestCase):
|
||||
self.assertFalse(MailboxImport.objects.exists())
|
||||
self.sign_in(self.customer)
|
||||
response = self.client.get(self.url())
|
||||
self.assertContains(response, "Check and import")
|
||||
self.assertContains(response, "Preview import")
|
||||
self.assertIn("no-store", response.headers["Cache-Control"])
|
||||
self.assertRedirects(
|
||||
self.client.post(self.url(), self.data()), self.url()
|
||||
@@ -163,6 +169,120 @@ class MailboxImportTests(TestCase):
|
||||
self.assertNotContains(response, self.data()["source_password"])
|
||||
self.assertNotContains(response, "Destination mailbox password")
|
||||
|
||||
def test_preview_requires_separate_confirmation_and_discards_secret(self):
|
||||
self.sign_in(self.customer)
|
||||
self.assertRedirects(
|
||||
self.client.post(self.url(), self.data(action="preview")),
|
||||
self.url(),
|
||||
)
|
||||
item = MailboxImportPreview.objects.get()
|
||||
self.assertNotIn(
|
||||
self.data()["source_password"], item.sealed_credentials
|
||||
)
|
||||
self.assertContains(
|
||||
self.client.get(self.url()), "Nothing is being copied"
|
||||
)
|
||||
self.assertFalse(MailboxImport.objects.exists())
|
||||
report = {
|
||||
"folders": [{"name": "INBOX", "count": 35, "bytes": None}],
|
||||
"total_folders": 1,
|
||||
"readable": 1,
|
||||
"messages": 35,
|
||||
"bytes": None,
|
||||
"complete": True,
|
||||
}
|
||||
with patch.object(preview, "run_preview", return_value=report) as run:
|
||||
run_mailbox_import_preview(item.pk)
|
||||
run_mailbox_import_preview(item.pk)
|
||||
run.assert_called_once()
|
||||
page = self.client.get(self.url())
|
||||
self.assertContains(page, "Start import")
|
||||
self.assertContains(page, "Not available")
|
||||
events = {"action": "confirm-preview", "preview_id": item.pk}
|
||||
self.sign_in(self.operator)
|
||||
self.client.post(self.url(), events)
|
||||
self.assertFalse(MailboxImport.objects.exists())
|
||||
self.sign_in(self.customer)
|
||||
self.client.post(self.url(), events)
|
||||
self.client.post(self.url(), events)
|
||||
self.assertFalse(MailboxImportPreview.objects.exists())
|
||||
job = MailboxImport.objects.get()
|
||||
self.assertEqual(
|
||||
imports.open_credentials(job), self.data()["source_password"]
|
||||
)
|
||||
|
||||
def test_preview_reports_partial_counts_without_inventing_a_size(self):
|
||||
source = Mock(capabilities=("IMAP4REV1", "STATUS=SIZE"))
|
||||
source.status.side_effect = [
|
||||
("OK", [b'"INBOX" (MESSAGES 0 SIZE 0)']),
|
||||
("NO", []),
|
||||
("OK", [b'"Archive.2020" (MESSAGES 13)']),
|
||||
("NO", []),
|
||||
("NO", []),
|
||||
]
|
||||
report = preview.inventory(
|
||||
source,
|
||||
[(name, name) for name in (b"INBOX", b"Archive.2020", b"Lost")],
|
||||
)
|
||||
self.assertEqual(report["messages"], 13)
|
||||
self.assertEqual(report["readable"], 2)
|
||||
self.assertEqual(report["total_folders"], 3)
|
||||
self.assertIsNone(report["bytes"])
|
||||
self.assertFalse(report["complete"])
|
||||
self.assertEqual(report["folders"][0]["count"], 0)
|
||||
source.select.assert_not_called()
|
||||
source.fetch.assert_not_called()
|
||||
source.append.assert_not_called()
|
||||
|
||||
def test_preview_separates_incremental_work_from_source_count(self):
|
||||
names = [b"Archive.2020", b"Archive.2021", b"INBOX"]
|
||||
source = Mock(capabilities=("IMAP4REV1",))
|
||||
source.status.side_effect = [
|
||||
(
|
||||
"OK",
|
||||
[b'"Archive.2020" (MESSAGES 999 UIDNEXT 1001 UIDVALIDITY 1)'],
|
||||
),
|
||||
("OK", [b'"Archive.2021" (MESSAGES 12 UIDNEXT 21 UIDVALIDITY 5)']),
|
||||
("OK", [b'"INBOX" (MESSAGES 3 UIDNEXT 4 UIDVALIDITY 2)']),
|
||||
]
|
||||
first = Mock(last_uid=1000, source_validity=1, pending={})
|
||||
second = Mock(last_uid=12, source_validity=5, pending={})
|
||||
with (
|
||||
patch.object(imap, "select", return_value=(5, 21)) as select,
|
||||
patch.object(imap, "search_uids", return_value=[14, 17]) as search,
|
||||
):
|
||||
report = preview.inventory(
|
||||
source,
|
||||
[(name, name) for name in names],
|
||||
{
|
||||
imports.folder_key(names[0]): first,
|
||||
imports.folder_key(names[1]): second,
|
||||
},
|
||||
)
|
||||
select.assert_called_once_with(source, names[1], readonly=True)
|
||||
search.assert_called_once_with(source, 13, last=20)
|
||||
self.assertEqual(report["messages"], 1014)
|
||||
self.assertTrue(report["incremental"])
|
||||
self.assertEqual(report["remaining"], 5)
|
||||
|
||||
def test_preview_expires_without_queuing_an_import(self):
|
||||
self.sign_in(self.customer)
|
||||
self.client.post(self.url(), self.data(action="preview"))
|
||||
item = MailboxImportPreview.objects.get()
|
||||
MailboxImportPreview.objects.update(
|
||||
requested_at=timezone.now()
|
||||
- preview.LIFETIME
|
||||
- timedelta(seconds=1)
|
||||
)
|
||||
dispatch_mailbox_imports()
|
||||
item.refresh_from_db()
|
||||
self.assertIn("expired", item.problem)
|
||||
self.assertFalse(item.sealed_credentials)
|
||||
self.client.post(
|
||||
self.url(), {"action": "confirm-preview", "preview_id": item.pk}
|
||||
)
|
||||
self.assertFalse(MailboxImport.objects.exists())
|
||||
|
||||
def test_disabled_feature_does_not_accept_credentials(self):
|
||||
self.sign_in(self.customer)
|
||||
with override_settings(MAILBOX_IMAP_IMPORT=False):
|
||||
|
||||
Reference in new issue
Block a user