Give the test account a mailbox, read with coreapp inbox
Mail an app sends to coreapp.test@<domain> (resets, invitations, notifications) is now delivered: the account gets mailEnabled and a homeDirectory (from extensibleObject, so it takes no uidNumber Superpanel would give a person), older accounts on their next use. coreapp inbox shows the newest 10 messages with their text (HTML as text, with links' addresses); --clear empties it; removing the account removes its mail. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+128
-3
@@ -32,7 +32,9 @@ coreapps core what this Core offers apps: its services
|
||||
and their versions, and the machine
|
||||
coreapps test-account [--remove] make (or refresh, with the password on
|
||||
stdin) the person coreapp signin signs
|
||||
in with, or remove it
|
||||
in with, or remove it (with its mailbox)
|
||||
coreapps test-inbox [--clear] the newest mail in the test account's
|
||||
mailbox (or empty it)
|
||||
|
||||
<source> is a folder with coreapp.toml (and icon.png), or a git
|
||||
repository: https://host/owner/repo[@tag]. A private repository, and a
|
||||
@@ -47,7 +49,10 @@ tier would record the app as a billable add-on and --addon-ok isn't given.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import email.parser
|
||||
import email.policy
|
||||
import glob
|
||||
import html.parser
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -1565,6 +1570,15 @@ def app_mail(name, since="24h"):
|
||||
# never an app's mail account (coreapp-<name>).
|
||||
TEST_UID = "coreapp.test"
|
||||
TEST_DESCRIPTION = "coreapps: test account for coreapp signin"
|
||||
# Its mailbox, so mail apps send it is delivered (coreapp inbox reads it).
|
||||
# The Core's mail server delivers to entries with mailEnabled TRUE, and its
|
||||
# Dovecot needs a homeDirectory. People get that from posixAccount, which
|
||||
# also needs a uidNumber; extensibleObject gives it without one, so the
|
||||
# test account never takes a number Superpanel would give a person.
|
||||
TEST_MAILBOX = {"objectClass": ["PostfixBookMailAccount", "extensibleObject"],
|
||||
"mailEnabled": ["TRUE"], "homeDirectory": [f"/home/{TEST_UID}"]}
|
||||
INBOX_SHOWN = 10
|
||||
INBOX_TEXT = 4000
|
||||
|
||||
|
||||
def ldap_base():
|
||||
@@ -1589,6 +1603,7 @@ def test_account(remove=False):
|
||||
raise Refused("Can't find the Core's LDAP settings.")
|
||||
found = ldap(["ldapsearch", "-LLL", "-o", "ldif-wrap=no", "-b", base,
|
||||
f"(|(uid={TEST_UID})(mail={mail}))", "description"])
|
||||
maildir = test_maildir(domain)
|
||||
if found.returncode != 0:
|
||||
raise Refused(f"Can't search the Core's LDAP: {found.stderr.strip()}")
|
||||
dn = f"uid={TEST_UID},ou=people,{base}"
|
||||
@@ -1602,7 +1617,8 @@ def test_account(remove=False):
|
||||
out = ldap(["ldapdelete", dn])
|
||||
if out.returncode != 0:
|
||||
raise Refused(f"Can't remove {dn}: {out.stderr.strip()}")
|
||||
say(f"Removed the test account {mail}.")
|
||||
shutil.rmtree(maildir, ignore_errors=True)
|
||||
say(f"Removed the test account {mail}, with its mailbox.")
|
||||
else:
|
||||
say("There's no test account.")
|
||||
return 0
|
||||
@@ -1619,9 +1635,11 @@ sn: Test
|
||||
mail: {mail}
|
||||
description: {TEST_DESCRIPTION}
|
||||
userPassword: {{CRYPT}}!
|
||||
""")
|
||||
""" + "".join(f"{key}: {v}\n" for key, values in TEST_MAILBOX.items() for v in values))
|
||||
if out.returncode != 0:
|
||||
raise Refused(f"Can't add the test account: {out.stderr.strip()}")
|
||||
else:
|
||||
add_test_mailbox(dn)
|
||||
# The server hashes it
|
||||
out = ldap(["ldappasswd", "-T", "/dev/stdin", dn], password)
|
||||
if out.returncode != 0:
|
||||
@@ -1630,6 +1648,111 @@ userPassword: {{CRYPT}}!
|
||||
return 0
|
||||
|
||||
|
||||
def add_test_mailbox(dn):
|
||||
"""Give a test account made before it had one its mailbox."""
|
||||
found = ldap(["ldapsearch", "-LLL", "-o", "ldif-wrap=no", "-b", dn, "-s", "base",
|
||||
"(objectClass=*)", *TEST_MAILBOX]).stdout.lower()
|
||||
# Only the values it lacks: adding one that's there is an error
|
||||
changes = []
|
||||
for key, values in TEST_MAILBOX.items():
|
||||
missing = [v for v in values if f"{key.lower()}: {v.lower()}" not in found]
|
||||
if missing:
|
||||
changes.append(f"add: {key}\n" + "".join(f"{key}: {v}\n" for v in missing))
|
||||
if not changes:
|
||||
return
|
||||
out = ldap(["ldapmodify"], f"dn: {dn}\nchangetype: modify\n" + "-\n".join(changes))
|
||||
if out.returncode != 0:
|
||||
raise Refused(f"Can't give the test account its mailbox: {out.stderr.strip()}")
|
||||
|
||||
|
||||
def test_maildir(domain):
|
||||
"""Where the Core's mail server keeps the test account's mail."""
|
||||
return os.path.join(APPS, "mail", "data", "var", "mail", domain.lower(), TEST_UID)
|
||||
|
||||
|
||||
class TextOfHTML(html.parser.HTMLParser):
|
||||
"""An HTML mail's text, with each link's address after it."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.parts, self.href, self.skip = [], None, 0
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
if tag in ("style", "script", "head"):
|
||||
self.skip += 1
|
||||
elif tag == "a":
|
||||
self.href = dict(attrs).get("href")
|
||||
elif tag in ("br", "p", "div", "tr", "li", "h1", "h2", "h3", "table"):
|
||||
self.parts.append("\n")
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag in ("style", "script", "head"):
|
||||
self.skip = max(0, self.skip - 1)
|
||||
elif tag == "a" and self.href:
|
||||
self.parts.append(f" <{self.href}>")
|
||||
self.href = None
|
||||
|
||||
def handle_data(self, data):
|
||||
if not self.skip:
|
||||
self.parts.append(data)
|
||||
|
||||
def text(self):
|
||||
lines = (" ".join(line.split()) for line in "".join(self.parts).splitlines())
|
||||
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
|
||||
|
||||
|
||||
def mail_text(message):
|
||||
"""A message's text: its plain-text part, or its HTML part as text."""
|
||||
part = message.get_body(preferencelist=("plain", "html"))
|
||||
if part is None:
|
||||
return "(no text in it)"
|
||||
try:
|
||||
content = part.get_content()
|
||||
except (LookupError, UnicodeError):
|
||||
content = part.get_payload(decode=True).decode("utf-8", "replace")
|
||||
if part.get_content_subtype() == "html":
|
||||
parser = TextOfHTML()
|
||||
parser.feed(content)
|
||||
content = parser.text()
|
||||
content = content.strip()
|
||||
if len(content) > INBOX_TEXT:
|
||||
content = content[:INBOX_TEXT] + f"\n... ({len(content) - INBOX_TEXT} more characters)"
|
||||
return content
|
||||
|
||||
|
||||
def test_inbox(clear=False):
|
||||
"""The newest mail in the test account's mailbox, or empty it."""
|
||||
domain, _ = federated_settings()
|
||||
address = f"{TEST_UID}@{domain}"
|
||||
folder = test_maildir(domain)
|
||||
paths = [os.path.join(folder, sub, f) for sub in ("new", "cur")
|
||||
if os.path.isdir(os.path.join(folder, sub))
|
||||
for f in os.listdir(os.path.join(folder, sub)) if not f.startswith(".")]
|
||||
if clear:
|
||||
for path in paths:
|
||||
os.remove(path)
|
||||
say(f"Emptied {address}'s inbox ({len(paths)} message(s)).")
|
||||
return 0
|
||||
if not paths:
|
||||
say(f"{address}'s inbox is empty. (coreapp mail shows whether the app's mail "
|
||||
"was delivered.)")
|
||||
return 0
|
||||
paths.sort(key=os.path.getmtime)
|
||||
shown = paths[-INBOX_SHOWN:]
|
||||
say(f"{address}'s inbox: {len(paths)} message(s)"
|
||||
+ (f", the newest {len(shown)}" if len(shown) < len(paths) else "") + ", oldest first.")
|
||||
for path in shown:
|
||||
with open(path, "rb") as f:
|
||||
message = email.parser.BytesParser(policy=email.policy.default).parse(f)
|
||||
when = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(os.path.getmtime(path)))
|
||||
say(f"\n=== {when} UTC")
|
||||
for header in ("From", "To", "Subject"):
|
||||
say(f"{header}: {message.get(header, '')}")
|
||||
say("")
|
||||
say(mail_text(message))
|
||||
return 0
|
||||
|
||||
|
||||
# --- Command line -----------------------------------------------------------------
|
||||
|
||||
def main(args):
|
||||
@@ -1693,6 +1816,8 @@ def main(args):
|
||||
return core_info()
|
||||
if cmd == "test-account" and rest in ([], ["--remove"]):
|
||||
return test_account(remove=bool(rest))
|
||||
if cmd == "test-inbox" and rest in ([], ["--clear"]):
|
||||
return test_inbox(clear=bool(rest))
|
||||
sys.stderr.write(__doc__.split("\n\n", 2)[2].strip() + "\n")
|
||||
return 2
|
||||
|
||||
|
||||
Reference in New Issue
Block a user