#!/usr/bin/env python3
"""Wombat-Email: the nightly mail test (installed by installer/93-mailtest.sh as
/usr/local/sbin/wombat-email-mailtest). Run as root; prints one line per check, exits 1 on a failure.

A throwaway mailbox on the server's own domain, gone again at the end whatever happens. Through the
server's public address, the way others reach it: mail arrives on 25 and lands in the inbox; sending on
587 and 465 needs a login, signs with DKIM and delivers; a wrong password, another sender's address,
the spam test, a test virus and relaying to another domain are all refused. Nothing leaves the server.
The result goes to /var/lib/wombat-email/mailtest-status.json for the daily report and the Status page.
"""
import imaplib, secrets, shutil, smtplib, ssl, subprocess, sys, time
from email.message import EmailMessage
from email.utils import formatdate, make_msgid

sys.path.insert(0, "/usr/local/lib/wombat-email")
import wombat_email as we   # what the server's scripts share

settings = we.settings()
host = settings["HOSTNAME"]
ip = we.server_ip()
tag = "mailtest-" + secrets.token_hex(6)
failed = []


sql = we.psql   # values as :'p0', :'p1'...


def check(label, f):
    try:
        why = f()
    except Exception as e:
        why = f"{type(e).__name__}: {e}"
    print(("ok   " if not why else "FAIL ") + label + (f": {why}" if why else ""), flush=True)
    if why:
        failed.append(label)


def letter(frm, to, subject, body="Wombat-Email nightly test"):
    m = EmailMessage()
    m["From"], m["To"], m["Subject"] = frm, to, f"{subject} {tag}"
    m["Date"], m["Message-ID"] = formatdate(localtime=True), make_msgid(domain=host)   # as real mail has
    m.set_content(body)
    return m


def s25():
    s = smtplib.SMTP(ip, 25, host, timeout=30); s.starttls(context=ctx_any); return s
def s587():
    s = smtplib.SMTP(ip, 587, host, timeout=30); s.starttls(context=ctx_any); return s
def s465():
    return smtplib.SMTP_SSL(ip, 465, host, timeout=30, context=ctx_any)
ctx_any = ssl.create_default_context(); ctx_any.check_hostname = False   # by address: the name isn't what's tested


def refused(send, code):
    """None when sending is refused with this code (first digit enough)."""
    try:
        send()
    except (smtplib.SMTPRecipientsRefused, smtplib.SMTPSenderRefused, smtplib.SMTPDataError, smtplib.SMTPAuthenticationError) as e:
        got = str(e)
        return None if f"({code}" in got or f"'{code}" in got or f" {code}" in got or code in got else f"refused differently: {got[:120]}"
    return "it was accepted"


def wait(box_user, password, subject, seconds=45):
    """The message with this subject, from the inbox ('INBOX', raw) or Spam, or (None, None)."""
    end = time.time() + seconds
    while time.time() < end:
        with imaplib.IMAP4_SSL(ip, 993, ssl_context=ctx_any) as m:
            m.login(box_user, password)
            for folder in ("INBOX", "Spam"):
                if m.select(folder, readonly=True)[0] != "OK":
                    continue
                _, found = m.search(None, "SUBJECT", f'"{subject} {tag}"')
                if found[0]:
                    _, data = m.fetch(found[0].split()[-1], "(BODY.PEEK[])")
                    return folder, data[0][1].decode(errors="replace")
        time.sleep(2)
    return None, None


own = sql("SELECT d.name FROM aliases a JOIN domains d ON d.id = a.domain_id WHERE a.system AND a.source LIKE 'hostmaster@%' LIMIT 1")
box = f"{tag}@{own}"
password = secrets.token_urlsafe(24)
hashed = subprocess.run(["doveadm", "pw", "-s", "ARGON2ID", "-p", password], capture_output=True, text=True, check=True).stdout.strip()
sql("INSERT INTO mailboxes (domain_id, email, password) SELECT id, :'p0', :'p1' FROM domains WHERE name = :'p2'", box, hashed, own)


def maps():
    # Rspamd's list of this server's mailboxes (aliases.map): without the throwaway box in it, the spam
    # check takes it for an address that forwards out and refuses its Spam-bound port-25 message (554
    # "not forwarded"). Rspamd rereads the file within a second.
    subprocess.run(["/usr/local/sbin/wombat-email-senders"], capture_output=True)
    time.sleep(2)


try:
    maps()
    def inbound():
        with s25() as s:
            s.send_message(letter(f"mailtest@{host}", box, "in"))   # the hostname's SPF allows this address
        # The inbox or Spam: from this server's own address the local /etc/hosts makes SPF fail, which
        # no outside sender ever sees. tests/outside-test.py checks the inbox from another server.
        return None if wait(box, password, "in")[0] else "it didn't arrive"
    # Said in the output too, so nobody reading the logs takes the Spam verdict for a fault.
    check("mail arrives on port 25 (in Spam, as expected: sent from this server itself, its own SPF check fails)", inbound)

    def outbound(connect, subject):
        def f():
            with connect() as s:
                s.login(box, password)
                s.send_message(letter(box, box, subject))
            where, raw = wait(box, password, subject)
            if where != "INBOX":
                return f"landed in {where}"
            return None if "DKIM-Signature:" in raw else "not signed with DKIM"
        return f
    check("sending on 587 works, signed with DKIM", outbound(s587, "out587"))
    check("sending on 465 works, signed with DKIM", outbound(s465, "out465"))

    def wrong_password():
        with s587() as s:
            s.login(box, password + "x")
    check("a wrong password is refused", lambda: refused(wrong_password, "535"))

    def spoof():
        with s587() as s:
            s.login(box, password)
            s.send_message(letter(f"postmaster@{own}", box, "spoof"))
    check("sending as someone else is refused", lambda: refused(spoof, "553"))

    def relay():
        with s25() as s:
            s.send_message(letter(f"postmaster@{own}", "relay-check@example.com", "relay"))
    check("relaying to another domain is refused", lambda: refused(relay, "554"))
    check("sending without a login is refused on 587", lambda: refused(lambda: s587().send_message(letter(box, f"relay-check@example.com", "nologin")), "5"))

    gtube = "XJS*C4JDBQADN1.NSBN3*2IDNEN*GTUBE-STANDARD-ANTI-UBE-TEST-EMAIL*C.34X"
    eicar = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
    def bad(body, attach=False):
        def f():
            m = letter(f"mailtest@{host}", box, "bad", body)
            if attach:
                m.add_attachment(body.encode(), maintype="application", subtype="octet-stream", filename="eicar.com")
            with s25() as s:
                s.send_message(m)
        return f
    check("the spam test is refused", lambda: refused(bad(gtube), "5"))
    check("a test virus is refused", lambda: refused(bad(eicar, attach=True), "5"))
finally:
    sql("DELETE FROM mailboxes WHERE email = :'p0'", box)
    shutil.rmtree(f"/var/mail/vmail/{own}/{tag}", ignore_errors=True)
    subprocess.run(["doveadm", "auth", "cache", "flush"], capture_output=True)
    maps()

we.write_json("/var/lib/wombat-email/mailtest-status.json", {"finished": int(time.time()), "failed": failed})
print("FAIL: " + ", ".join(failed) if failed else "PASS")
sys.exit(1 if failed else 0)
