Add scoped password-free mailbox import receiver
This commit is contained in:
1 parent
465c209447
commit
23cddcaac8
10 files changed
+534
-7
No files matched your search
@@ -13,10 +13,10 @@ if [ ! -e /etc/coulobre/panel.env ]; then
|
|||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
systemctl daemon-reload
|
||||||
systemd-run --quiet --wait --pipe --collect \
|
systemd-run --quiet --wait --pipe --collect \
|
||||||
--property=EnvironmentFile=/etc/coulobre/panel.env \
|
--property=EnvironmentFile=/etc/coulobre/panel.env \
|
||||||
--setenv=PYTHONPATH=/usr/share/coulobre-panel/source/src \
|
--setenv=PYTHONPATH=/usr/share/coulobre-panel/source/src \
|
||||||
/opt/coulobre/bin/python -P -m coulobre.package_upgrade
|
/opt/coulobre/bin/python -P -m coulobre.package_upgrade
|
||||||
|
|
||||||
systemctl daemon-reload
|
|
||||||
systemctl enable --now coulobre-remote-deploy.socket
|
systemctl enable --now coulobre-remote-deploy.socket
|
||||||
@@ -7,6 +7,7 @@ After=network-online.target mariadb.service rabbitmq-server.service
|
|||||||
Type=exec
|
Type=exec
|
||||||
User=coulobre-panel
|
User=coulobre-panel
|
||||||
Group=coulobre-panel
|
Group=coulobre-panel
|
||||||
|
SupplementaryGroups=coulobre-mail-provisioning
|
||||||
EnvironmentFile=/etc/coulobre/panel.env
|
EnvironmentFile=/etc/coulobre/panel.env
|
||||||
WorkingDirectory=/opt/coulobre
|
WorkingDirectory=/opt/coulobre
|
||||||
UMask=0077
|
UMask=0077
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[Service]
|
||||||
|
SupplementaryGroups=coulobre-mail-provisioning
|
||||||
@@ -2,7 +2,7 @@ import json
|
|||||||
import os
|
import os
|
||||||
import stat
|
import stat
|
||||||
from contextlib import redirect_stdout
|
from contextlib import redirect_stdout
|
||||||
from io import BytesIO, StringIO
|
from io import BufferedReader, BytesIO, StringIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from subprocess import CompletedProcess
|
from subprocess import CompletedProcess
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
@@ -48,7 +48,11 @@ class MailboxApplyRequestTests(SimpleTestCase):
|
|||||||
with (
|
with (
|
||||||
patch(
|
patch(
|
||||||
"sys.stdin",
|
"sys.stdin",
|
||||||
SimpleNamespace(buffer=BytesIO(json.dumps(manifest).encode())),
|
SimpleNamespace(
|
||||||
|
buffer=BufferedReader(
|
||||||
|
BytesIO(json.dumps(manifest).encode())
|
||||||
|
)
|
||||||
|
),
|
||||||
),
|
),
|
||||||
redirect_stdout(output),
|
redirect_stdout(output),
|
||||||
):
|
):
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import json
|
import json
|
||||||
from base64 import b64encode
|
from base64 import b64encode
|
||||||
from contextlib import nullcontext, redirect_stdout
|
from contextlib import nullcontext, redirect_stdout
|
||||||
from io import BytesIO, StringIO
|
from io import BufferedReader, BytesIO, StringIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
@@ -31,7 +31,9 @@ class NodeProbeTests(SimpleTestCase):
|
|||||||
patch(
|
patch(
|
||||||
"sys.stdin",
|
"sys.stdin",
|
||||||
SimpleNamespace(
|
SimpleNamespace(
|
||||||
buffer=BytesIO(json.dumps(PROBE).encode())
|
buffer=BufferedReader(
|
||||||
|
BytesIO(json.dumps(PROBE).encode())
|
||||||
|
)
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
patch(apply_path) as apply,
|
patch(apply_path) as apply,
|
||||||
|
|||||||
@@ -0,0 +1,365 @@
|
|||||||
|
"""Append-only destination sessions on the managed mail receiver."""
|
||||||
|
|
||||||
|
import imaplib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from contextlib import contextmanager, suppress
|
||||||
|
from select import select
|
||||||
|
from time import monotonic
|
||||||
|
|
||||||
|
from . import imap_import as imap
|
||||||
|
from .mail_node import MailboxSpec
|
||||||
|
from .mail_node_apply import (
|
||||||
|
check_registered_manifest,
|
||||||
|
credential_path,
|
||||||
|
home_is_prepared,
|
||||||
|
load_credentials,
|
||||||
|
locked_state,
|
||||||
|
retirement_guard,
|
||||||
|
)
|
||||||
|
from .node_maintenance import rollout_target
|
||||||
|
from .receiver_scope import authorized_request, socket_peer
|
||||||
|
|
||||||
|
SOCKET = "/run/coulobre-mail-apply.sock"
|
||||||
|
MARKER = b"!coulobre-mail-import-v1\n"
|
||||||
|
FRAME_LIMIT = 1024 * 1024
|
||||||
|
CONTROL_LIMIT = 8192
|
||||||
|
INVALID = "The destination import request or reply was invalid."
|
||||||
|
UNAVAILABLE = "The mail receiver could not open or continue the import."
|
||||||
|
|
||||||
|
|
||||||
|
def read_frame(stream, limit):
|
||||||
|
line = stream.readline(limit + 1)
|
||||||
|
if len(line) > limit or not line.endswith(b"\n"):
|
||||||
|
raise OSError(INVALID)
|
||||||
|
try:
|
||||||
|
data = json.loads(line)
|
||||||
|
except (ValueError, RecursionError):
|
||||||
|
raise imap.MailboxImportError(INVALID) from None
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def write_frame(stream, data):
|
||||||
|
stream.write(json.dumps(data, ensure_ascii=True).encode("ascii") + b"\n")
|
||||||
|
stream.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def read_reply(stream):
|
||||||
|
reply = read_frame(stream, FRAME_LIMIT)
|
||||||
|
if set(reply) == {"result"}:
|
||||||
|
return reply["result"]
|
||||||
|
if reply == {"retry": True}:
|
||||||
|
raise OSError(UNAVAILABLE)
|
||||||
|
if set(reply) == {"problem"} and isinstance(reply["problem"], str):
|
||||||
|
raise imap.MailboxImportError(reply["problem"][:300])
|
||||||
|
raise OSError(INVALID)
|
||||||
|
|
||||||
|
|
||||||
|
class Destination:
|
||||||
|
def __init__(self, stream):
|
||||||
|
self.stream = stream
|
||||||
|
self.flags = frozenset()
|
||||||
|
|
||||||
|
def request(self, operation, *, body=None, **fields):
|
||||||
|
write_frame(self.stream, {"operation": operation, **fields})
|
||||||
|
if body is not None:
|
||||||
|
self.stream.write(body)
|
||||||
|
self.stream.flush()
|
||||||
|
return read_reply(self.stream)
|
||||||
|
|
||||||
|
def list_folders(self, *, root=False):
|
||||||
|
return [
|
||||||
|
imap.Folder(
|
||||||
|
name.encode("ascii"), sep.encode("ascii") if sep else None
|
||||||
|
)
|
||||||
|
for name, sep in self.request("list", root=root)
|
||||||
|
]
|
||||||
|
|
||||||
|
def select(self, folder, *, readonly=False):
|
||||||
|
validity, next_uid, flags = self.request(
|
||||||
|
"select", folder=folder.decode("ascii")
|
||||||
|
)
|
||||||
|
self.flags = frozenset(flag.encode("ascii") for flag in flags)
|
||||||
|
return validity, next_uid
|
||||||
|
|
||||||
|
def create(self, folder):
|
||||||
|
self.request("create", folder=folder.decode("ascii"))
|
||||||
|
|
||||||
|
def append(self, folder, message, flags):
|
||||||
|
self.request(
|
||||||
|
"append",
|
||||||
|
folder=folder.decode("ascii"),
|
||||||
|
date=message.date.decode("ascii"),
|
||||||
|
flags=[flag.decode("ascii") for flag in flags],
|
||||||
|
size=len(message.body),
|
||||||
|
body=message.body,
|
||||||
|
)
|
||||||
|
|
||||||
|
def reconcile(self, first, digest, timestamp):
|
||||||
|
return self.request(
|
||||||
|
"reconcile", first=first, digest=digest, timestamp=timestamp
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def open_destination(mailbox):
|
||||||
|
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as peer:
|
||||||
|
peer.settimeout(imap.IO_TIMEOUT)
|
||||||
|
try:
|
||||||
|
peer.connect(SOCKET)
|
||||||
|
except (FileNotFoundError, PermissionError):
|
||||||
|
raise imap.MailboxImportError(
|
||||||
|
"The import worker cannot access the mail receiver. "
|
||||||
|
"Ask the operator to check the worker and socket setup."
|
||||||
|
) from None
|
||||||
|
with peer.makefile("rwb") as stream:
|
||||||
|
stream.write(MARKER)
|
||||||
|
write_frame(stream, mailbox.manifest())
|
||||||
|
if read_reply(stream) is not True:
|
||||||
|
raise OSError(INVALID)
|
||||||
|
yield Destination(stream)
|
||||||
|
|
||||||
|
|
||||||
|
class TimedPipeReader(io.RawIOBase):
|
||||||
|
def __init__(self, descriptor):
|
||||||
|
self.descriptor = descriptor
|
||||||
|
|
||||||
|
def readable(self):
|
||||||
|
return True
|
||||||
|
|
||||||
|
def readinto(self, buffer):
|
||||||
|
if not select([self.descriptor], [], [], imap.IO_TIMEOUT)[0]:
|
||||||
|
raise TimeoutError(UNAVAILABLE)
|
||||||
|
return os.readv(self.descriptor, [buffer])
|
||||||
|
|
||||||
|
|
||||||
|
class PreauthenticatedIMAP(imaplib.IMAP4):
|
||||||
|
def __init__(self, process):
|
||||||
|
self.process = process
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
def open(self, host="", port=0, timeout=None):
|
||||||
|
self.host, self.port = host, port
|
||||||
|
self.reader = io.BufferedReader(
|
||||||
|
TimedPipeReader(self.process.stdout.fileno())
|
||||||
|
)
|
||||||
|
self.writer = self.process.stdin.fileno()
|
||||||
|
os.set_blocking(self.writer, False)
|
||||||
|
|
||||||
|
def send(self, data):
|
||||||
|
deadline = monotonic() + imap.IO_TIMEOUT
|
||||||
|
remaining = memoryview(data)
|
||||||
|
while remaining:
|
||||||
|
wait = deadline - monotonic()
|
||||||
|
if wait <= 0 or not select([], [self.writer], [], wait)[1]:
|
||||||
|
raise TimeoutError(UNAVAILABLE)
|
||||||
|
try:
|
||||||
|
written = os.write(self.writer, remaining)
|
||||||
|
except BlockingIOError:
|
||||||
|
continue
|
||||||
|
remaining = remaining[written:]
|
||||||
|
|
||||||
|
def readline(self):
|
||||||
|
line = self.reader.readline(FRAME_LIMIT + 1)
|
||||||
|
if len(line) > FRAME_LIMIT:
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
return line
|
||||||
|
|
||||||
|
def read(self, size):
|
||||||
|
if not 0 <= size <= imap.MAX_PACKET_BYTES:
|
||||||
|
raise imap.MailboxImportError(
|
||||||
|
"The destination literal exceeds the import limit."
|
||||||
|
)
|
||||||
|
return self.reader.read(size)
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
self.reader.close()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def preauthenticated_mailbox(mailbox):
|
||||||
|
# Dovecot rejects standalone root IMAP with a socket on stdout.
|
||||||
|
with subprocess.Popen(
|
||||||
|
["/usr/bin/doveadm", "exec", "imap", "-u", mailbox.address],
|
||||||
|
stdin=subprocess.PIPE,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.DEVNULL,
|
||||||
|
) as process:
|
||||||
|
try:
|
||||||
|
client = PreauthenticatedIMAP(process)
|
||||||
|
try:
|
||||||
|
if client.state != "AUTH":
|
||||||
|
raise imap.MailboxImportError(UNAVAILABLE)
|
||||||
|
yield client
|
||||||
|
finally:
|
||||||
|
client.shutdown()
|
||||||
|
finally:
|
||||||
|
process.kill()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def active_mailbox(mailbox):
|
||||||
|
with locked_state(create=False) as directory:
|
||||||
|
if directory is None or retirement_guard(mailbox).exists():
|
||||||
|
raise imap.MailboxImportError(
|
||||||
|
"The destination mailbox is no longer ready."
|
||||||
|
)
|
||||||
|
record = load_credentials(credential_path(mailbox))
|
||||||
|
check_registered_manifest(record, mailbox)
|
||||||
|
if record.suspended or not home_is_prepared(record):
|
||||||
|
raise imap.MailboxImportError(
|
||||||
|
"The destination mailbox is no longer ready."
|
||||||
|
)
|
||||||
|
if rollout_target("mail"):
|
||||||
|
raise imap.MailboxImportError(
|
||||||
|
"The mail receiver is in upgrade maintenance."
|
||||||
|
)
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
class ImportSession:
|
||||||
|
def __init__(self, mailbox, client):
|
||||||
|
self.mailbox = mailbox
|
||||||
|
self.client = client
|
||||||
|
self.folder = None
|
||||||
|
self.flags = frozenset()
|
||||||
|
|
||||||
|
def apply(self, request, stream):
|
||||||
|
operation = request.get("operation")
|
||||||
|
client = self.client
|
||||||
|
fields = request.keys() - {"operation"}
|
||||||
|
if (
|
||||||
|
operation == "list"
|
||||||
|
and fields == {"root"}
|
||||||
|
and type(request["root"]) is bool
|
||||||
|
):
|
||||||
|
return [
|
||||||
|
(
|
||||||
|
folder.name.decode(),
|
||||||
|
folder.separator.decode() if folder.separator else None,
|
||||||
|
)
|
||||||
|
for folder in imap.list_folders(client, root=request["root"])
|
||||||
|
]
|
||||||
|
if operation == "reconcile" and fields == {
|
||||||
|
"first",
|
||||||
|
"digest",
|
||||||
|
"timestamp",
|
||||||
|
}:
|
||||||
|
first, digest, timestamp = (
|
||||||
|
request[key] for key in ("first", "digest", "timestamp")
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
self.folder is None
|
||||||
|
or type(first) is not int
|
||||||
|
or not 1 <= first <= 2**32 - 1
|
||||||
|
or not isinstance(digest, str)
|
||||||
|
or not re.fullmatch(r"[a-f0-9]{64}", digest)
|
||||||
|
or not isinstance(timestamp, str)
|
||||||
|
or len(timestamp) > 40
|
||||||
|
):
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
with active_mailbox(self.mailbox):
|
||||||
|
return imap.reconcile(client, first, digest, timestamp)
|
||||||
|
if operation not in ("select", "create", "append"):
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
required = {"folder"}
|
||||||
|
if operation == "append":
|
||||||
|
required |= {"date", "flags", "size"}
|
||||||
|
if fields != required or not isinstance(request["folder"], str):
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
folder = request["folder"].encode("ascii")
|
||||||
|
quoted = imap.quote(folder)
|
||||||
|
if operation == "select":
|
||||||
|
validity, next_uid = imap.select(client, folder, readonly=False)
|
||||||
|
self.folder = folder
|
||||||
|
self.flags = imap.permanent_flags(client)
|
||||||
|
return (
|
||||||
|
validity,
|
||||||
|
next_uid,
|
||||||
|
sorted(flag.decode("ascii") for flag in self.flags),
|
||||||
|
)
|
||||||
|
if operation == "create":
|
||||||
|
with active_mailbox(self.mailbox):
|
||||||
|
if client.create(quoted)[0] != "OK":
|
||||||
|
raise imap.MailboxImportError(
|
||||||
|
"A destination folder could not be created."
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
size, date, flags = (request[key] for key in ("size", "date", "flags"))
|
||||||
|
if (
|
||||||
|
folder != self.folder
|
||||||
|
or type(size) is not int
|
||||||
|
or not 0 <= size <= imap.MAX_MESSAGE_BYTES
|
||||||
|
or not isinstance(date, str)
|
||||||
|
or not isinstance(flags, list)
|
||||||
|
or len(flags) > 64
|
||||||
|
or any(not isinstance(flag, str) for flag in flags)
|
||||||
|
):
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
date = date.encode("ascii")
|
||||||
|
if not imap.INTERNALDATE.fullmatch(b"INTERNALDATE " + date):
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
flags = tuple(flag.encode("ascii") for flag in flags)
|
||||||
|
if imap.usable_flags(self.flags, flags)[0] != flags:
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
body = stream.read(size)
|
||||||
|
if len(body) != size:
|
||||||
|
raise OSError(INVALID)
|
||||||
|
message = imap.Message(body, date, flags)
|
||||||
|
with active_mailbox(self.mailbox):
|
||||||
|
imap.append(client, folder, message, flags)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def serve_import(source=None, output=None):
|
||||||
|
if source is None:
|
||||||
|
source = sys.stdin.buffer
|
||||||
|
if output is None:
|
||||||
|
output = sys.stdout.buffer
|
||||||
|
try:
|
||||||
|
if source.readline(len(MARKER) + 1) != MARKER:
|
||||||
|
raise imap.MailboxImportError(INVALID)
|
||||||
|
mailbox = MailboxSpec.from_manifest(read_frame(source, CONTROL_LIMIT))
|
||||||
|
peer = socket_peer()
|
||||||
|
if peer not in ("root", "coulobre-panel") and not (
|
||||||
|
peer and peer.startswith("coulobre-mail-p-")
|
||||||
|
):
|
||||||
|
raise imap.MailboxImportError(
|
||||||
|
"Use a domain-scoped mail receiver connection for imports."
|
||||||
|
)
|
||||||
|
with (
|
||||||
|
authorized_request("mail", mailbox, local_peer="coulobre-panel"),
|
||||||
|
active_mailbox(mailbox),
|
||||||
|
):
|
||||||
|
pass
|
||||||
|
with preauthenticated_mailbox(mailbox) as client:
|
||||||
|
session = ImportSession(mailbox, client)
|
||||||
|
write_frame(output, {"result": True})
|
||||||
|
while source.peek(1):
|
||||||
|
request = read_frame(source, CONTROL_LIMIT)
|
||||||
|
with authorized_request(
|
||||||
|
"mail", mailbox, local_peer="coulobre-panel"
|
||||||
|
):
|
||||||
|
result = session.apply(request, source)
|
||||||
|
write_frame(output, {"result": result})
|
||||||
|
except (OSError, imaplib.IMAP4.abort):
|
||||||
|
with suppress(OSError):
|
||||||
|
write_frame(output, {"retry": True})
|
||||||
|
return 1
|
||||||
|
except (ValueError, imaplib.IMAP4.error) as error:
|
||||||
|
with suppress(OSError):
|
||||||
|
problem = (
|
||||||
|
str(error)
|
||||||
|
if isinstance(error, imap.MailboxImportError)
|
||||||
|
else UNAVAILABLE
|
||||||
|
)
|
||||||
|
write_frame(output, {"problem": problem})
|
||||||
|
return 1
|
||||||
|
return 0
|
||||||
@@ -2,6 +2,7 @@ import argparse
|
|||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import sys
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -395,6 +396,11 @@ def main(argv=None):
|
|||||||
if args.command == "apply-request":
|
if args.command == "apply-request":
|
||||||
from .mail_policy import MAIL_POLICY_LIMIT
|
from .mail_policy import MAIL_POLICY_LIMIT
|
||||||
|
|
||||||
|
if sys.stdin.buffer.peek(1)[:1] == b"!":
|
||||||
|
from .mail_import_receiver import serve_import
|
||||||
|
|
||||||
|
return serve_import()
|
||||||
|
|
||||||
return serve_apply_request(
|
return serve_apply_request(
|
||||||
MANIFEST_VERSION,
|
MANIFEST_VERSION,
|
||||||
parse_mailbox_request,
|
parse_mailbox_request,
|
||||||
|
|||||||
@@ -94,9 +94,11 @@ def manifest_domain(spec):
|
|||||||
|
|
||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def authorized_request(role, spec=None):
|
def authorized_request(role, spec=None, *, local_peer=None):
|
||||||
peer = socket_peer()
|
peer = socket_peer()
|
||||||
if peer in (None, "root", LOCAL_WORKERS[role]):
|
if peer in (None, "root", LOCAL_WORKERS[role]) or (
|
||||||
|
local_peer is not None and peer == local_peer
|
||||||
|
):
|
||||||
yield
|
yield
|
||||||
return
|
return
|
||||||
assignment = role == "mail" and isinstance(spec, MailDomainAssignment)
|
assignment = role == "mail" and isinstance(spec, MailDomainAssignment)
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
"""Verify the import receiver cannot act as a general IMAP relay."""
|
||||||
|
|
||||||
|
import io
|
||||||
|
import unittest
|
||||||
|
from contextlib import nullcontext
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
from coulobre import imap_import as imap
|
||||||
|
from coulobre import mail_import_receiver as receiver
|
||||||
|
from coulobre.mail_node import MailboxSpec
|
||||||
|
|
||||||
|
MAILBOX = MailboxSpec("fixture.example", "customer")
|
||||||
|
DATE = '"01-Mar-2024 10:45:00 +0000"'
|
||||||
|
|
||||||
|
|
||||||
|
def stream_for(*requests):
|
||||||
|
source = io.BytesIO()
|
||||||
|
source.write(receiver.MARKER)
|
||||||
|
receiver.write_frame(source, MAILBOX.manifest())
|
||||||
|
for request in requests:
|
||||||
|
receiver.write_frame(source, request)
|
||||||
|
source.seek(0)
|
||||||
|
return io.BufferedReader(source)
|
||||||
|
|
||||||
|
|
||||||
|
class ReceiverTests(unittest.TestCase):
|
||||||
|
def test_denies_legacy_or_unidentified_peers_before_opening_mailbox(self):
|
||||||
|
for peer in (None, "nobody", "coulobre-mail-request"):
|
||||||
|
with (
|
||||||
|
self.subTest(peer=peer),
|
||||||
|
patch.object(receiver, "socket_peer", return_value=peer),
|
||||||
|
patch.object(
|
||||||
|
receiver, "preauthenticated_mailbox"
|
||||||
|
) as open_mail,
|
||||||
|
):
|
||||||
|
output = io.BytesIO()
|
||||||
|
self.assertEqual(
|
||||||
|
receiver.serve_import(stream_for(), output), 1
|
||||||
|
)
|
||||||
|
open_mail.assert_not_called()
|
||||||
|
self.assertIn(b"domain-scoped", output.getvalue())
|
||||||
|
|
||||||
|
def test_checks_domain_scope_before_opening_mailbox(self):
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
receiver, "socket_peer", return_value="coulobre-mail-p-web1"
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
receiver, "authorized_request", side_effect=ValueError
|
||||||
|
) as guard,
|
||||||
|
patch.object(receiver, "preauthenticated_mailbox") as open_mail,
|
||||||
|
):
|
||||||
|
self.assertEqual(
|
||||||
|
receiver.serve_import(stream_for(), io.BytesIO()), 1
|
||||||
|
)
|
||||||
|
guard.assert_called_once_with(
|
||||||
|
"mail", MAILBOX, local_peer="coulobre-panel"
|
||||||
|
)
|
||||||
|
open_mail.assert_not_called()
|
||||||
|
|
||||||
|
def test_does_not_accept_raw_imap_or_other_mailboxes(self):
|
||||||
|
with (
|
||||||
|
patch.object(receiver, "socket_peer", return_value="root"),
|
||||||
|
patch.object(
|
||||||
|
receiver, "authorized_request", return_value=nullcontext()
|
||||||
|
),
|
||||||
|
patch.object(
|
||||||
|
receiver, "active_mailbox", return_value=nullcontext()
|
||||||
|
),
|
||||||
|
):
|
||||||
|
for request in (
|
||||||
|
{"operation": "fetch", "uid": 1},
|
||||||
|
{"operation": "delete", "folder": "INBOX"},
|
||||||
|
{"operation": "select", "folder": "INBOX", "mailbox": "other"},
|
||||||
|
):
|
||||||
|
client = Mock()
|
||||||
|
with (
|
||||||
|
self.subTest(request=request),
|
||||||
|
patch.object(
|
||||||
|
receiver,
|
||||||
|
"preauthenticated_mailbox",
|
||||||
|
return_value=nullcontext(client),
|
||||||
|
),
|
||||||
|
):
|
||||||
|
self.assertEqual(
|
||||||
|
receiver.serve_import(
|
||||||
|
stream_for(request), io.BytesIO()
|
||||||
|
),
|
||||||
|
1,
|
||||||
|
)
|
||||||
|
self.assertEqual(client.mock_calls, [])
|
||||||
|
|
||||||
|
def test_append_is_bound_to_selected_folder_and_preserves_flags_and_date(
|
||||||
|
self,
|
||||||
|
):
|
||||||
|
client = Mock()
|
||||||
|
session = receiver.ImportSession(MAILBOX, client)
|
||||||
|
body = b"Subject: QA\r\n\r\nMessage\r\n"
|
||||||
|
append = {
|
||||||
|
"operation": "append",
|
||||||
|
"folder": "INBOX",
|
||||||
|
"size": len(body),
|
||||||
|
"date": DATE,
|
||||||
|
"flags": [r"\Seen"],
|
||||||
|
}
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
receiver, "active_mailbox", return_value=nullcontext()
|
||||||
|
) as active,
|
||||||
|
patch.object(imap, "select", return_value=(17, 8)),
|
||||||
|
patch.object(imap, "permanent_flags", return_value={b"\\SEEN"}),
|
||||||
|
patch.object(imap, "append") as write,
|
||||||
|
):
|
||||||
|
for overrides in (
|
||||||
|
{},
|
||||||
|
{"folder": "Sent"},
|
||||||
|
{"flags": [r"\Deleted"]},
|
||||||
|
{"size": imap.MAX_MESSAGE_BYTES + 1},
|
||||||
|
{"date": "invalid"},
|
||||||
|
):
|
||||||
|
if overrides:
|
||||||
|
session.apply(
|
||||||
|
{"operation": "select", "folder": "INBOX"},
|
||||||
|
io.BytesIO(),
|
||||||
|
)
|
||||||
|
with self.assertRaises(imap.MailboxImportError):
|
||||||
|
session.apply(append | overrides, io.BytesIO(body))
|
||||||
|
with self.assertRaises(OSError):
|
||||||
|
session.apply(append, io.BytesIO(body[:-1]))
|
||||||
|
write.assert_not_called()
|
||||||
|
session.apply(append, io.BytesIO(body))
|
||||||
|
message = imap.Message(body, DATE.encode(), (b"\\Seen",))
|
||||||
|
write.assert_called_once_with(
|
||||||
|
client, b"INBOX", message, message.flags
|
||||||
|
)
|
||||||
|
active.assert_called_once_with(MAILBOX)
|
||||||
@@ -87,6 +87,15 @@ def build_package(source, wheel, ref, output):
|
|||||||
path = units / name
|
path = units / name
|
||||||
shutil.copyfile(source_dir / "deploy/systemd" / name, path)
|
shutil.copyfile(source_dir / "deploy/systemd" / name, path)
|
||||||
path.chmod(0o644)
|
path.chmod(0o644)
|
||||||
|
import_access = (
|
||||||
|
"coulobre-mailbox-import-worker.service.d/receiver.conf"
|
||||||
|
)
|
||||||
|
import_unit = units / import_access
|
||||||
|
import_unit.parent.mkdir()
|
||||||
|
shutil.copyfile(
|
||||||
|
source_dir / "deploy/systemd" / import_access, import_unit
|
||||||
|
)
|
||||||
|
import_unit.chmod(0o644)
|
||||||
doc = root / "usr/share/doc/coulobre-panel"
|
doc = root / "usr/share/doc/coulobre-panel"
|
||||||
doc.mkdir(parents=True)
|
doc.mkdir(parents=True)
|
||||||
shutil.copyfile(source_dir / "LICENSE", doc / "copyright")
|
shutil.copyfile(source_dir / "LICENSE", doc / "copyright")
|
||||||
|
|||||||
Reference in new issue
Block a user