Compare commits

..
Author SHA1 Message Date
link2xt 02c7d3da58 feat: setup websockify
This change makes it possible
to connect the client over WebSocket.
Running `websocat wss://example.org/imap`
connects to the IMAP
and running `websocat wss://example.org/smtp`
connects to SMTP (submission service, not port 25).

Connecting from a web client will still need a CORS policy
for clients not running on the same domain,
but for non-web clients this is already usable.
2026-07-29 22:10:14 +00:00
85 changed files with 930 additions and 1472 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
Please refer to Please refer to
[Delta Chat community standards and practices](https://delta.chat/community-standards) [Delta Chat community standards and practices](https://delta.chat/en/community-standards)
which also apply for all chatmail developments. which also apply for all chatmail developments.
+2
View File
@@ -20,6 +20,8 @@ concurrency:
jobs: jobs:
no-dns: no-dns:
name: LXC deploy and test name: LXC deploy and test
permissions:
contents: read
uses: chatmail/cmlxc/.github/workflows/lxc-test.yml@main uses: chatmail/cmlxc/.github/workflows/lxc-test.yml@main
with: with:
cmlxc_version: main cmlxc_version: main
+3 -1
View File
@@ -29,7 +29,7 @@ jobs:
ref: ${{ github.event.pull_request.head.sha }} ref: ${{ github.event.pull_request.head.sha }}
persist-credentials: false persist-credentials: false
- name: download filtermail - name: download filtermail
run: curl -L https://github.com/chatmail/filtermail/releases/download/v0.7.10/filtermail-x86_64 -o /usr/local/bin/filtermail && chmod +x /usr/local/bin/filtermail run: curl -L https://github.com/chatmail/filtermail/releases/download/v0.7.4/filtermail-x86_64 -o /usr/local/bin/filtermail && chmod +x /usr/local/bin/filtermail
- name: run chatmaild tests - name: run chatmaild tests
working-directory: chatmaild working-directory: chatmaild
run: pipx run tox run: pipx run tox
@@ -57,6 +57,8 @@ jobs:
lxc-test: lxc-test:
name: LXC deploy and test name: LXC deploy and test
permissions:
contents: read
uses: chatmail/cmlxc/.github/workflows/lxc-test.yml@main uses: chatmail/cmlxc/.github/workflows/lxc-test.yml@main
with: with:
cmlxc_version: main cmlxc_version: main
-5
View File
@@ -13,11 +13,6 @@ jobs:
scripts: scripts:
name: build name: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
env:
# Pin the repository links in the docs to this pull request's head commit
# so that linkcheck resolves files which only exist on the branch so far.
# see doc/conf.py
DOC_GITHUB_REF: ${{ github.event.pull_request.head.sha }}
environment: environment:
name: 'staging.chatmail.at/doc/relay/' name: 'staging.chatmail.at/doc/relay/'
url: https://staging.chatmail.at/doc/relay/${{ steps.prepare.outputs.prid }} url: https://staging.chatmail.at/doc/relay/${{ steps.prepare.outputs.prid }}
+1 -1
View File
@@ -47,5 +47,5 @@ jobs:
mkdir -p "$HOME/.ssh" mkdir -p "$HOME/.ssh"
echo "${{ secrets.CHATMAIL_STAGING_SSHKEY }}" > "$HOME/.ssh/key" echo "${{ secrets.CHATMAIL_STAGING_SSHKEY }}" > "$HOME/.ssh/key"
chmod 600 "$HOME/.ssh/key" chmod 600 "$HOME/.ssh/key"
rsync -rILvh -e "ssh -i $HOME/.ssh/key -o StrictHostKeyChecking=no" $GITHUB_WORKSPACE/doc/build/ "${{ secrets.USERNAME }}@chatmail.at:" rsync -rILvh -e "ssh -i $HOME/.ssh/key -o StrictHostKeyChecking=no" $GITHUB_WORKSPACE/doc/build/ "${{ secrets.USERNAME }}@chatmail.at:/var/www/html/chatmail.at/doc/relay/"
-88
View File
@@ -1,93 +1,5 @@
# Changelog for chatmail deployment # Changelog for chatmail deployment
## [1.13.0] - 2026-09-22
### Bug Fixes
- Actually use UTC time instead of just seemingly using it
### Documentation
- Describe Madmail v2 as a Rust chatmail relay
### Features
- Serve an APPVERSIONS.json index file to clients via IMAP metadata
- *(mtail)* Deploy filtermail.mtail and gate mtail rule copy on mtail_address
- *(mtail)* Validate programs during deploy
- Move doveauth from dictproxy to lua/http
- Distinguish AUTHENTICATION_FAILED/UNAVAILABLE login failures
### Miscellaneous Tasks
- Try to fix lack of RFC822 item support in madmail and make CI pass
- Un-hardcode executable paths in some systemd service files
- Follow the new mtail release source, upgrade 3.0.8 to 3.4.9
- *(cmdeploy)* Refactor all pins into pins.py
- *(doc)* Use sphinx roles for referencing repository files and dirs
- update deltachat-android link to 2.59.1
### Testing
- Integrate lua testing into regular pytest run for push notifications
- Cleanup and allow a repo-root level "pytest -n6" to succeed.
- [**breaking**] Remove global registration of pytest plugins
## [1.12.0] - 2026-07-31
### Breaking Changes
- [**breaking**] Introduce configurable system limits to reject new address creation and limit imap/smtp connections.
Dovecot default connection limit lowered from 50k to 10k,
Postfix default connection limit lowered from 5k to 1k,
larger relays need to adjust their settings.
### Features
- Reduce maximal_queue_lifetime from 5d to 2d
- Disable negative cache in unbound (#992)
- *(mtail)* Add incoming_mailer_daemon_mail_count
- *(postfix)* Disable processing of MIME headers
- *(dovecot)* Advertise privacy_mail as admin contact, drop server comment
### Bug Fixes
- Set relay restrictions per smtpd service with default reject
- Reduce maxproc for filtermail-transport LMTP client to 500
- Core 2.50.0 does not have delete_server_after config anymore.
- Check if all required ports are available for filtermail (#983)
- Always deploy unbound.conf.d/chatmail.conf (#993)
- Expire empty directories (#994)
- Crypt-r dependency was declared for wrong Python version
- Always overwrite /etc/resolv.conf, even if it is a symbolic link
- Pass kwargs to files.put()
- List Iroh proxy endpoints used by 0.35 and 1.0, drop stale /relay/probe from earlier versions
- Fix port discovery when ss -tulpn shows dovecot before stats
### Documentation
- Add scripts/initenv.sh to upgrade instructions
- Update overview diagrams (#995)
- *(overview)* Remove mermaid styles from 'Accepting and delivering mail' (#1009)
- *(README.md)* Clarify security enforcement (#1011)
### Miscellaneous Tasks
- *(ci)* Auto-trigger docker build on release tag push
- *(acmetool)* Update let's encrypt ToS link to 1.8
- *(ci)* Update doc staging upload path
- *(ci)* Fix docs upload path
### Refactor
- *(postfix)* Remove unused "filter" lmtp service
- Install dns-root-data instead of using unbound-anchor
- *(deps)* Remove domain-validator dependency
### Testing
- Set socket security for IMAP and SMTP to "TLS" in "dclogin"
## [1.11.0] - 2026-05-15 ## [1.11.0] - 2026-05-15
### Breaking Changes ### Breaking Changes
-3
View File
@@ -5,6 +5,3 @@ We use [git-cliff] to generate the changelog from commit messages before the rel
[Conventional Commits]: https://www.conventionalcommits.org/ [Conventional Commits]: https://www.conventionalcommits.org/
[git-cliff]: https://git-cliff.org/ [git-cliff]: https://git-cliff.org/
To update client app version information,
edit [chatmaild/src/chatmaild/defaults/appversions.json](chatmaild/src/chatmaild/defaults/appversions.json).
+7 -5
View File
@@ -1,13 +1,15 @@
# Releasing a new version of chatmail relay # Releasing a new version of chatmail relay
For example, to release version 1.14.0 of chatmail relay, do the following steps. For example, to release version 1.9.0 of chatmail relay, do the following steps.
1. Update the changelog: `git cliff --unreleased --tag 1.14.0 --prepend CHANGELOG.md` or `git cliff -u -t 1.14.0 -p CHANGELOG.md`. 1. Update the changelog: `git cliff --unreleased --tag 1.9.0 --prepend CHANGELOG.md` or `git cliff -u -t 1.9.0 -p CHANGELOG.md`.
2. Open the changelog in the editor, edit it if required. 2. Open the changelog in the editor, edit it if required.
3. Commit the changes to the changelog with a commit message `chore(release): prepare for 1.14.0`. 3. Commit the changes to the changelog with a commit message `chore(release): prepare for 1.9.0`.
4. Open a PR with the new commit, merge it to main after review. 3. Tag the release: `git tag --annotate 1.9.0`.
5. In the web interface, create a GitHub release, tell it to create a new tag. 4. Push the release tag: `git push origin 1.9.0`.
5. Create a GitHub release: `gh release create 1.9.0`.
-1
View File
@@ -1,4 +1,3 @@
include src/chatmaild/defaults/*.json
include src/chatmaild/ini/*.ini.f include src/chatmaild/ini/*.ini.f
include src/chatmaild/ini/*.ini include src/chatmaild/ini/*.ini
include src/chatmaild/tests/mail-data/* include src/chatmaild/tests/mail-data/*
+4
View File
@@ -24,8 +24,12 @@ doveauth = "chatmaild.doveauth:main"
chatmail-metadata = "chatmaild.metadata:main" chatmail-metadata = "chatmaild.metadata:main"
chatmail-expire = "chatmaild.expire:daily_expire_main" chatmail-expire = "chatmaild.expire:daily_expire_main"
chatmail-quota-expire = "chatmaild.expire:quota_expire_main" chatmail-quota-expire = "chatmaild.expire:quota_expire_main"
chatmail-fsreport = "chatmaild.fsreport:main"
lastlogin = "chatmaild.lastlogin:main" lastlogin = "chatmaild.lastlogin:main"
[project.entry-points.pytest11]
"chatmaild.testplugin" = "chatmaild.tests.plugin"
[tool.pytest.ini_options] [tool.pytest.ini_options]
addopts = "-v -ra --strict-markers" addopts = "-v -ra --strict-markers"
log_format = "%(asctime)s %(levelname)s %(message)s" log_format = "%(asctime)s %(levelname)s %(message)s"
+1 -2
View File
@@ -31,7 +31,7 @@ class Config:
self.max_user_send_per_minute = int(params.pop("max_user_send_per_minute", 60)) self.max_user_send_per_minute = int(params.pop("max_user_send_per_minute", 60))
self.max_user_send_burst_size = int(params.pop("max_user_send_burst_size", 10)) self.max_user_send_burst_size = int(params.pop("max_user_send_burst_size", 10))
self.max_mailbox_size = params.pop("max_mailbox_size", "500M") self.max_mailbox_size = params.pop("max_mailbox_size", "500M")
self.max_message_size = int(params.pop("max_message_size", 52428800)) self.max_message_size = int(params.pop("max_message_size", 31457280))
self.delete_mails_after = params.pop("delete_mails_after", "20") self.delete_mails_after = params.pop("delete_mails_after", "20")
self.delete_large_after = params.pop("delete_large_after", "7") self.delete_large_after = params.pop("delete_large_after", "7")
self.delete_inactive_users_after = int( self.delete_inactive_users_after = int(
@@ -55,7 +55,6 @@ class Config:
self.postfix_reinject_port_incoming = int( self.postfix_reinject_port_incoming = int(
params.pop("postfix_reinject_port_incoming", "10026") params.pop("postfix_reinject_port_incoming", "10026")
) )
self.doveauth_http_port = int(params.pop("doveauth_http_port", "10084"))
self.mtail_address = params.pop("mtail_address", None) self.mtail_address = params.pop("mtail_address", None)
self.disable_ipv6 = params.pop("disable_ipv6", "false").lower() == "true" self.disable_ipv6 = params.pop("disable_ipv6", "false").lower() == "true"
self.acme_email = params.pop("acme_email", "") self.acme_email = params.pop("acme_email", "")
@@ -1,15 +0,0 @@
{
"clients": [
{
"clientId": "deltachat",
"sources": [
{
"sourceId": "gplay",
"versionInteger": 761,
"versionString": "2.69.0",
"downloadUrl": "https://github.com/deltachat/deltachat-android/releases/download/v2.69.0/deltachat-gplay-release-2.69.0.apk"
}
]
}
]
}
+96 -110
View File
@@ -1,17 +1,10 @@
"""Create chatmail addresses on first login. import json
Dovecot only asks us about addresses it does not already find in the mailbox:
the auth.lua we deploy with dovecot (cmdeploy/src/cmdeploy/dovecot/auth.lua.j2)
verifies existing users itself against a mailbox password file,
and HTTP-POSTs everything else to the /create endpoint implemented in this module.
"""
import logging import logging
import os import os
import re import re
import sys import sys
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import filelock
try: try:
import crypt_r import crypt_r
@@ -19,6 +12,7 @@ except ImportError:
import crypt as crypt_r import crypt as crypt_r
from .config import Config, read_config from .config import Config, read_config
from .dictproxy import DictProxy
from .migrate_db import migrate_from_db_to_maildir from .migrate_db import migrate_from_db_to_maildir
from .syslimits import has_sufficient_resources from .syslimits import has_sufficient_resources
@@ -70,117 +64,109 @@ def is_allowed_to_create(config: Config, user, cleartext_password) -> bool:
return True return True
def verify_password(stored, cleartext_password) -> bool: def split_and_unescape(s):
if stored.startswith("{"): """Split strings using double quote as a separator and backslash as escape character
stored = stored.split("}", 1)[1] into parts."""
return crypt_r.crypt(cleartext_password, stored) == stored
out = ""
i = 0
while i < len(s):
c = s[i]
if c == "\\":
# Skip escape character.
i += 1
# This will raise IndexError if there is no character
# after escape character. This is expected
# as this is an invalid input.
out += s[i]
elif c == '"':
# Separator
yield out
out = ""
else:
out += c
i += 1
yield out
class DoveAuth: class AuthDictProxy(DictProxy):
def __init__(self, config): def __init__(self, config):
super().__init__()
self.config = config self.config = config
self.creation_lock = threading.Lock()
def create_user(self, addr, cleartext_password) -> bool: def handle_lookup(self, parts):
"""Create the address, or verify the password if it exists already.""" # Dovecot <2.3.17 has only one part,
# do not attempt to read any other parts for compatibility.
keyname = parts[0]
namespace, type, args = keyname.split("/", 2)
args = list(split_and_unescape(args))
config = self.config config = self.config
if not addr.endswith(f"@{config.mail_domain}"): reply_command = "F"
logging.warning("address not in mail domain: %r", addr) res = ""
return False if namespace == "shared":
try: if type == "userdb":
user = config.get_user(addr) user = args[0]
except ValueError: if user.endswith(f"@{config.mail_domain}"):
logging.warning("invalid address: %r", addr) res = self.lookup_userdb(user)
return False if res:
with self.creation_lock: reply_command = "O"
passhash = user.get_password_hash() else:
if passhash is not None: reply_command = "N"
# a concurrent first login may have just created the address elif type == "passdb":
return verify_password(passhash, cleartext_password) user = args[1]
if not is_allowed_to_create(config, addr, cleartext_password): if user.endswith(f"@{config.mail_domain}"):
return False res = self.lookup_passdb(user, cleartext_password=args[0])
if not has_sufficient_resources(config): if res:
return False reply_command = "O"
else:
reply_command = "N"
json_res = json.dumps(res) if res else ""
return f"{reply_command}{json_res}\n"
def handle_iterate(self, parts):
# example: I0\t0\tshared/userdb/
if parts[2] == "shared/userdb/":
result = "".join(
f"Oshared/userdb/{user}\t\n" for user in self.iter_userdb()
)
return f"{result}\n"
def iter_userdb(self) -> list:
"""Get a list of all user addresses."""
return [x for x in os.listdir(self.config.mailboxes_dir) if "@" in x]
def lookup_userdb(self, addr):
return self.config.get_user(addr).get_userdb_dict()
def lookup_passdb(self, addr, cleartext_password):
user = self.config.get_user(addr)
userdata = user.get_userdb_dict()
if userdata:
return userdata
if not is_allowed_to_create(self.config, addr, cleartext_password):
return
if not has_sufficient_resources(self.config):
return
lock = filelock.FileLock(str(user.password_path) + ".lock", timeout=5)
with lock:
userdata = user.get_userdb_dict()
if userdata:
return userdata
user.set_password(encrypt_password(cleartext_password)) user.set_password(encrypt_password(cleartext_password))
# mtail counts created_accounts off this exact line print(f"Created address: {addr}", file=sys.stderr)
print(f"Created address: {addr}", file=sys.stderr) return user.get_userdb_dict()
return True
class CreateHandler(BaseHTTPRequestHandler):
"""Answer POST /create requests from dovecot's auth.lua, body `addr\\tpassword`.
The body must be UTF-8 and only the first tab separates the fields,
so a password may itself contain tabs.
Any non-UTF8 or \\0 bytes in the body fail the request.
Addresses are ASCII: dovecot refuses any login name outside its
auth_username_chars before auth.lua ever sees it.
Dovecot hands auth.lua the exact password bytes the client sent;
decoding and re-encoding UTF-8 is byte-identical,
so dovecot's password_verify later recomputes the same hash crypt() stores here.
"""
protocol_version = "HTTP/1.1" # dovecot's HTTP client reuses connections
max_body_len = 512 # an address and a password
def do_POST(self):
if self.path != "/create":
self.reply(404)
return
length = self.body_length()
if length is None:
self.reply(400)
return
body = self.rfile.read(length)
try:
addr, _, password = body.decode("utf-8").partition("\t")
except UnicodeDecodeError:
self.reply(400)
return
if "\0" in addr or "\0" in password:
self.reply(400)
return
self.reply(200 if self.server.doveauth.create_user(addr, password) else 403)
def body_length(self):
try:
length = int(self.headers["Content-Length"])
except (TypeError, ValueError):
return None
return length if 0 <= length <= self.max_body_len else None
def reply(self, status):
self.send_response(status)
self.send_header("Content-Length", "0")
if status != 200:
# Just close on any failure, as body might not be fully read.
# It's anyway cheap to re-establish http localhost without TLS.
self.send_header("Connection", "close")
self.end_headers()
def log_message(self, format, *args):
# the per-request access log would only duplicate our own stderr lines
pass
class DoveAuthServer(ThreadingHTTPServer):
# a burst of first-time logins (e.g. from CI) must not overflow
# the accept queue, see https://github.com/chatmail/relay/issues/436
request_queue_size = 1000
def __init__(self, config, port):
super().__init__(("127.0.0.1", port), CreateHandler)
self.doveauth = DoveAuth(config)
def main(): def main():
(cfgpath,) = sys.argv[1:] socket, cfgpath = sys.argv[1:]
config = read_config(cfgpath) config = read_config(cfgpath)
migrate_from_db_to_maildir(config) migrate_from_db_to_maildir(config)
server = DoveAuthServer(config, config.doveauth_http_port) dictproxy = AuthDictProxy(config=config)
server.serve_forever()
dictproxy.serve_forever_from_socket(socket)
+9 -91
View File
@@ -99,24 +99,22 @@ def scan_mailbox_messages(mbox):
return messages return messages
def expire_to_target(mbox, target_bytes, dry=False, skip=()): def expire_to_target(mbox, target_bytes):
messages = scan_mailbox_messages(mbox) messages = scan_mailbox_messages(mbox)
messages = [m for m in messages if str(mbox / m.path) not in skip]
total_size = sum(m.quota_size for m in messages) total_size = sum(m.quota_size for m in messages)
# Keep recent 24 hours of messages protected from expiry because # Keep recent 24 hours of messages protected from expiry because
# likely something is wrong with interactions on that address # likely something is wrong with interactions on that address
# and quota-full signal can help the address owner's device to notice it # and quota-full signal can help the address owner's device to notice it
undeletable_messages_cutoff = time.time() - (3600 * 24) undeletable_messages_cutoff = time.time() - (3600 * 24)
removed = [] removed = 0
for entry in sorted(messages): for entry in sorted(messages):
if total_size <= target_bytes: if total_size <= target_bytes:
break break
if entry.mtime > undeletable_messages_cutoff: if entry.mtime > undeletable_messages_cutoff:
break break
if not dry: (mbox / entry.path).unlink(missing_ok=True)
(mbox / entry.path).unlink(missing_ok=True)
total_size -= entry.quota_size total_size -= entry.quota_size
removed.append(entry) removed += 1
return removed return removed
@@ -125,24 +123,7 @@ def print_info(msg):
print(msg, file=sys.stderr) print(msg, file=sys.stderr)
PROM_HELP = {
"storage_bytes": "Mailbox storage in bytes.",
"messages_bytes": "Sum of msg bytes >= threshold.",
"messages_count": "Number of msgs >= size threshold.",
"messages_age_bytes": "Sum of msg bytes older than N days.",
"accounts": "Number of accounts.",
"accounts_active": "Non-CI accounts active within N days.",
"expire_removed_mailboxes": "Mailboxes removed by the last run.",
"expire_removed_files": "Files removed by the last run.",
"expire_duration_seconds": "Duration of the last run.",
"expire_last_run_timestamp_seconds": "End of the last run.",
}
class Expiry: class Expiry:
login_days = (1, 10, 30, 40, 80, 100, 150)
size_thresholds = (0, 100 * 1024, 512 * 1024, 1 << 20, 2 << 20, 5 << 20, 10 << 20)
def __init__(self, config, dry, now, verbose): def __init__(self, config, dry, now, verbose):
self.config = config self.config = config
self.dry = dry self.dry = dry
@@ -153,12 +134,6 @@ class Expiry:
self.del_files = 0 self.del_files = 0
self.all_files = 0 self.all_files = 0
self.start = time.time() self.start = time.time()
self.size_messages = self.size_extra = 0
self.num_ci_logins = self.num_all_logins = 0
self.login_buckets = dict.fromkeys(self.login_days, 0)
self.msg_bytes = dict.fromkeys(self.size_thresholds, 0)
self.msg_counts = dict.fromkeys(self.size_thresholds, 0)
self.msg_age_bytes = dict.fromkeys((1, 3, 7, 14), 0)
def remove_mailbox(self, mboxdir): def remove_mailbox(self, mboxdir):
if self.verbose: if self.verbose:
@@ -212,17 +187,14 @@ class Expiry:
else: else:
print_info(f"checking mailbox (no last_login) {mboxname}") print_info(f"checking mailbox (no last_login) {mboxname}")
self.all_files += len(mbox.messages) self.all_files += len(mbox.messages)
removed_paths = set()
for message in mbox.messages: for message in mbox.messages:
if message.mtime < cutoff_mails: if message.mtime < cutoff_mails:
self.remove_file(message.path, mtime=message.mtime) self.remove_file(message.path, mtime=message.mtime)
removed_paths.add(message.path)
elif message.size > 200000 and message.mtime < cutoff_large_mails: elif message.size > 200000 and message.mtime < cutoff_large_mails:
# we only remove noticed large files (not unnoticed ones in new/) # we only remove noticed large files (not unnoticed ones in new/)
parts = message.path.split("/") parts = message.path.split("/")
if len(parts) >= 2 and parts[-2] == "cur": if len(parts) >= 2 and parts[-2] == "cur":
self.remove_file(message.path, mtime=message.mtime) self.remove_file(message.path, mtime=message.mtime)
removed_paths.add(message.path)
else: else:
continue continue
changed = True changed = True
@@ -230,40 +202,18 @@ class Expiry:
target_bytes = ( target_bytes = (
self.config.max_mailbox_size_mb * 1024 * 1024 * QUOTA_CLEANUP_FACTOR self.config.max_mailbox_size_mb * 1024 * 1024 * QUOTA_CLEANUP_FACTOR
) )
removed = expire_to_target( removed = expire_to_target(Path(mbox.basedir), target_bytes)
Path(mbox.basedir), target_bytes, dry=self.dry, skip=removed_paths
)
if removed: if removed:
changed = True changed = True
self.del_files += len(removed) self.del_files += removed
removed_paths.update(f"{mbox.basedir}/{e.path}" for e in removed)
if self.verbose: if self.verbose:
print_info( print_info(
f"quota-expire: removed {len(removed)} message(s) from {mboxname}" f"quota-expire: removed {removed} message(s) from {mboxname}"
) )
if changed: if changed:
self.remove_file(f"{mbox.basedir}/maildirsize") self.remove_file(f"{mbox.basedir}/maildirsize")
self.num_all_logins += 1
if mboxname.startswith("ci-"):
self.num_ci_logins += 1
else:
for days in self.login_buckets:
if mbox.last_login >= self.now - days * 86400:
self.login_buckets[days] += 1
kept = [m for m in mbox.messages if m.path not in removed_paths]
for size in self.msg_bytes:
for msg in kept:
if msg.size >= size:
self.msg_bytes[size] += msg.size
self.msg_counts[size] += 1
for days in self.msg_age_bytes:
cutoff = self.now - days * 86400
self.msg_age_bytes[days] += sum(m.size for m in kept if m.mtime < cutoff)
self.size_messages += sum(m.size for m in kept)
self.size_extra += sum(entry.size for entry in mbox.extrafiles)
def get_summary(self): def get_summary(self):
return ( return (
f"Removed {self.del_mboxes} out of {self.all_mboxes} mailboxes " f"Removed {self.del_mboxes} out of {self.all_mboxes} mailboxes "
@@ -271,36 +221,6 @@ class Expiry:
f"in {time.time() - self.start:2.2f} seconds" f"in {time.time() - self.start:2.2f} seconds"
) )
def write_prom(self, path):
end = time.time()
storage = dict(messages=self.size_messages, extra=self.size_extra)
storage["total"] = self.size_messages + self.size_extra
accounts = dict(all=self.num_all_logins, ci=self.num_ci_logins)
accounts["user"] = accounts["all"] - accounts["ci"]
help = dict(PROM_HELP)
tmp = f"{path}.tmp"
with open(tmp, "w") as f:
def gauge(name, values, label=None):
print(f"# HELP chatmail_{name} {help.pop(name)}", file=f)
print(f"# TYPE chatmail_{name} gauge", file=f)
for key, value in values.items() if label else [(None, values)]:
labels = f'{{{label}="{key}"}}' if label else ""
print(f"chatmail_{name}{labels} {value}", file=f)
gauge("storage_bytes", storage, "kind")
gauge("messages_bytes", self.msg_bytes, "min_size")
gauge("messages_count", self.msg_counts, "min_size")
gauge("messages_age_bytes", self.msg_age_bytes, "min_days")
gauge("accounts", accounts, "kind")
gauge("accounts_active", self.login_buckets, "days")
gauge("expire_removed_mailboxes", self.del_mboxes)
gauge("expire_removed_files", self.del_files)
gauge("expire_duration_seconds", f"{end - self.start:.2f}")
gauge("expire_last_run_timestamp_seconds", f"{end:.0f}")
assert not help, f"unused PROM_HELP entries: {list(help)}"
os.replace(tmp, path)
def daily_expire_main(args=None): def daily_expire_main(args=None):
"""Expire mailboxes and messages according to chatmail config""" """Expire mailboxes and messages according to chatmail config"""
@@ -339,7 +259,7 @@ def daily_expire_main(args=None):
args = parser.parse_args(args) args = parser.parse_args(args)
config = read_config(args.chatmail_ini) config = read_config(args.chatmail_ini)
now = time.time() now = datetime.utcnow().timestamp()
if args.days: if args.days:
now = now - 86400 * int(args.days) now = now - 86400 * int(args.days)
@@ -348,8 +268,6 @@ def daily_expire_main(args=None):
for mailbox in iter_mailboxes(str(config.mailboxes_dir), maxnum=maxnum): for mailbox in iter_mailboxes(str(config.mailboxes_dir), maxnum=maxnum):
exp.process_mailbox_stat(mailbox) exp.process_mailbox_stat(mailbox)
print(exp.get_summary()) print(exp.get_summary())
if prompath := os.environ.get("CHATMAIL_EXPIRE_PROMPATH"):
exp.write_prom(prompath)
def quota_expire_main(args=None): def quota_expire_main(args=None):
@@ -373,7 +291,7 @@ def quota_expire_main(args=None):
target_bytes = args.target_mb * 1024 * 1024 target_bytes = args.target_mb * 1024 * 1024
removed_count = len(expire_to_target(args.mailbox_path, target_bytes)) removed_count = expire_to_target(args.mailbox_path, target_bytes)
if removed_count: if removed_count:
(args.mailbox_path / "maildirsize").unlink(missing_ok=True) (args.mailbox_path / "maildirsize").unlink(missing_ok=True)
print( print(
+287
View File
@@ -0,0 +1,287 @@
"""
command line tool to analyze mailbox message storage
example invocation:
python -m chatmaild.fsreport /path/to/chatmail.ini
to show storage summaries for all "cur" folders
python -m chatmaild.fsreport /path/to/chatmail.ini --mdir cur
to show storage summaries only for first 1000 mailboxes
python -m chatmaild.fsreport /path/to/chatmail.ini --maxnum 1000
to write Prometheus textfile for node_exporter
python -m chatmaild.fsreport --textfile /var/lib/prometheus/node-exporter/
writes to /var/lib/prometheus/node-exporter/fsreport.prom
to also write legacy metrics.py style output (default: /var/www/html/metrics):
python -m chatmaild.fsreport --textfile /var/lib/prometheus/node-exporter/ --legacy-metrics
"""
import os
import tempfile
from argparse import ArgumentParser
from datetime import datetime
from chatmaild.config import read_config
from chatmaild.expire import iter_mailboxes
DAYSECONDS = 24 * 60 * 60
MONTHSECONDS = DAYSECONDS * 30
def HSize(size: int):
"""Format a size integer as a Human-readable string Kilobyte, Megabyte or Gigabyte"""
if size < 10000:
return f"{size / 1000:5.2f}K"
if size < 1000 * 1000:
return f"{size / 1000:5.0f}K"
if size < 1000 * 1000 * 1000:
return f"{int(size / 1000000):5.0f}M"
return f"{size / 1000000000:5.2f}G"
class Report:
def __init__(self, now, min_login_age, mdir):
self.size_extra = 0
self.size_messages = 0
self.now = now
self.min_login_age = min_login_age
self.mdir = mdir
self.num_ci_logins = self.num_all_logins = 0
self.login_buckets = {x: 0 for x in (1, 10, 30, 40, 80, 100, 150)}
KiB = 1024
MiB = 1024 * KiB
self.message_size_thresholds = (
0,
100 * KiB,
MiB // 2,
1 * MiB,
2 * MiB,
5 * MiB,
10 * MiB,
)
self.message_buckets = {x: 0 for x in self.message_size_thresholds}
self.message_count_buckets = {x: 0 for x in self.message_size_thresholds}
def process_mailbox_stat(self, mailbox):
# categorize login times
last_login = mailbox.last_login
if last_login:
self.num_all_logins += 1
if os.path.basename(mailbox.basedir)[:3] == "ci-":
self.num_ci_logins += 1
else:
for days in self.login_buckets:
if last_login >= self.now - days * DAYSECONDS:
self.login_buckets[days] += 1
cutoff_login_date = self.now - self.min_login_age * DAYSECONDS
if last_login and last_login <= cutoff_login_date:
# categorize message sizes
for size in self.message_buckets:
for msg in mailbox.messages:
if msg.size >= size:
if self.mdir and f"/{self.mdir}/" not in msg.path:
continue
self.message_buckets[size] += msg.size
self.message_count_buckets[size] += 1
self.size_messages += sum(entry.size for entry in mailbox.messages)
self.size_extra += sum(entry.size for entry in mailbox.extrafiles)
def dump_summary(self):
all_messages = self.size_messages
print()
print("## Mailbox storage use analysis")
print(f"Mailbox data total size: {HSize(self.size_extra + all_messages)}")
print(f"Messages total size : {HSize(all_messages)}")
try:
percent = self.size_extra / (self.size_extra + all_messages) * 100
except ZeroDivisionError:
percent = 100
print(f"Extra files : {HSize(self.size_extra)} ({percent:.2f}%)")
print()
if self.min_login_age:
print(f"### Message storage for {self.min_login_age} days old logins")
pref = f"[{self.mdir}] " if self.mdir else ""
for minsize, sumsize in self.message_buckets.items():
count = self.message_count_buckets[minsize]
percent = (sumsize / all_messages * 100) if all_messages else 0
print(
f"{pref}larger than {HSize(minsize)}: {HSize(sumsize)} ({percent:.2f}%), {count} msgs"
)
user_logins = self.num_all_logins - self.num_ci_logins
def p(num):
return f"({num / user_logins * 100:2.2f}%)" if user_logins else "100%"
print()
print(f"## Login stats, from date reference {datetime.fromtimestamp(self.now)}")
print(f"all: {HSize(self.num_all_logins)}")
print(f"non-ci: {HSize(user_logins)}")
print(f"ci: {HSize(self.num_ci_logins)}")
for days, active in self.login_buckets.items():
print(f"last {days:3} days: {HSize(active)} {p(active)}")
def _write_atomic(self, filepath, content):
"""Atomically write content to filepath via tmp+rename."""
dirpath = os.path.dirname(os.path.abspath(filepath))
fd, tmppath = tempfile.mkstemp(dir=dirpath, suffix=".tmp")
try:
with os.fdopen(fd, "w") as f:
f.write(content)
os.chmod(tmppath, 0o644)
os.rename(tmppath, filepath)
except BaseException:
try:
os.unlink(tmppath)
except OSError:
pass
raise
def dump_textfile(self, filepath):
"""Dump metrics in Prometheus exposition format."""
lines = []
lines.append("# HELP chatmail_storage_bytes Mailbox storage in bytes.")
lines.append("# TYPE chatmail_storage_bytes gauge")
lines.append(f'chatmail_storage_bytes{{kind="messages"}} {self.size_messages}')
lines.append(f'chatmail_storage_bytes{{kind="extra"}} {self.size_extra}')
total = self.size_extra + self.size_messages
lines.append(f'chatmail_storage_bytes{{kind="total"}} {total}')
lines.append("# HELP chatmail_messages_bytes Sum of msg bytes >= threshold.")
lines.append("# TYPE chatmail_messages_bytes gauge")
for minsize, sumsize in self.message_buckets.items():
lines.append(f'chatmail_messages_bytes{{min_size="{minsize}"}} {sumsize}')
lines.append("# HELP chatmail_messages_count Number of msgs >= size threshold.")
lines.append("# TYPE chatmail_messages_count gauge")
for minsize, count in self.message_count_buckets.items():
lines.append(f'chatmail_messages_count{{min_size="{minsize}"}} {count}')
lines.append("# HELP chatmail_accounts Number of accounts.")
lines.append("# TYPE chatmail_accounts gauge")
user_logins = self.num_all_logins - self.num_ci_logins
lines.append(f'chatmail_accounts{{kind="all"}} {self.num_all_logins}')
lines.append(f'chatmail_accounts{{kind="ci"}} {self.num_ci_logins}')
lines.append(f'chatmail_accounts{{kind="user"}} {user_logins}')
lines.append(
"# HELP chatmail_accounts_active Non-CI accounts active within N days."
)
lines.append("# TYPE chatmail_accounts_active gauge")
for days, active in self.login_buckets.items():
lines.append(f'chatmail_accounts_active{{days="{days}"}} {active}')
self._write_atomic(filepath, "\n".join(lines) + "\n")
def dump_compat_textfile(self, filepath):
"""Dump legacy metrics.py style metrics."""
user_logins = self.num_all_logins - self.num_ci_logins
lines = [
"# HELP total number of accounts",
"# TYPE accounts gauge",
f"accounts {self.num_all_logins}",
"# HELP number of CI accounts",
"# TYPE ci_accounts gauge",
f"ci_accounts {self.num_ci_logins}",
"# HELP number of non-CI accounts",
"# TYPE nonci_accounts gauge",
f"nonci_accounts {user_logins}",
]
self._write_atomic(filepath, "\n".join(lines) + "\n")
def main(args=None):
"""Report about filesystem storage usage of all mailboxes and messages"""
parser = ArgumentParser(description=main.__doc__)
ini = "/usr/local/lib/chatmaild/chatmail.ini"
parser.add_argument(
"chatmail_ini",
action="store",
nargs="?",
help=f"path pointing to chatmail.ini file, default: {ini}",
default=ini,
)
parser.add_argument(
"--days",
default=0,
action="store",
help="assume date to be DAYS older than now",
)
parser.add_argument(
"--min-login-age",
default=0,
metavar="DAYS",
dest="min_login_age",
action="store",
help="only sum up message size if last login is at least DAYS days old",
)
parser.add_argument(
"--mdir",
metavar="{cur,new,tmp}",
action="store",
help="only consider messages in specified Maildir subdirectory for summary",
)
parser.add_argument(
"--maxnum",
default=None,
action="store",
help="maximum number of mailboxes to iterate on",
)
parser.add_argument(
"--textfile",
metavar="PATH",
default=None,
help="write Prometheus textfile to PATH (directory or file); "
"if PATH is a directory, writes 'fsreport.prom' inside it",
)
parser.add_argument(
"--legacy-metrics",
metavar="FILENAME",
nargs="?",
const="/var/www/html/metrics",
default=None,
help="write legacy metrics.py textfile (default: /var/www/html/metrics)",
)
args = parser.parse_args(args)
config = read_config(args.chatmail_ini)
now = datetime.utcnow().timestamp()
if args.days:
now = now - 86400 * int(args.days)
maxnum = int(args.maxnum) if args.maxnum else None
rep = Report(now=now, min_login_age=int(args.min_login_age), mdir=args.mdir)
for mbox in iter_mailboxes(str(config.mailboxes_dir), maxnum=maxnum):
rep.process_mailbox_stat(mbox)
if args.textfile:
path = args.textfile
if os.path.isdir(path):
path = os.path.join(path, "fsreport.prom")
rep.dump_textfile(path)
if args.legacy_metrics:
rep.dump_compat_textfile(args.legacy_metrics)
if not args.textfile and not args.legacy_metrics:
rep.dump_summary()
if __name__ == "__main__":
main()
+1 -1
View File
@@ -22,7 +22,7 @@ mail_domain = {mail_domain}
#max_mailbox_size = 500M #max_mailbox_size = 500M
# maximum message size for an e-mail in bytes # maximum message size for an e-mail in bytes
#max_message_size = 52428800 #max_message_size = 31457280
# days after which mails are unconditionally deleted # days after which mails are unconditionally deleted
#delete_mails_after = 20 #delete_mails_after = 20
-18
View File
@@ -1,10 +1,8 @@
import json
import logging import logging
import socket import socket
import sys import sys
import time import time
from contextlib import contextmanager from contextlib import contextmanager
from importlib.resources import files
from .config import read_config from .config import read_config
from .dictproxy import DictProxy from .dictproxy import DictProxy
@@ -20,18 +18,6 @@ def turn_credentials(turn_socket_path):
return file.readline().decode("utf-8").strip() return file.readline().decode("utf-8").strip()
def read_appversions(path):
try:
data = json.loads(path.read_bytes())
except FileNotFoundError:
return None
except (OSError, ValueError):
logging.exception(f"failed to read {path}")
return None
# the dict protocol is line-based, keep the value single-line
return json.dumps(data, separators=(",", ":"))
def _is_valid_token_timestamp(timestamp, now): def _is_valid_token_timestamp(timestamp, now):
# Token if invalid after 90 days # Token if invalid after 90 days
# or if the timestamp is in the future. # or if the timestamp is in the future.
@@ -115,7 +101,6 @@ class MetadataDictProxy(DictProxy):
self.iroh_relay = iroh_relay self.iroh_relay = iroh_relay
self.turn_hostname = turn_hostname self.turn_hostname = turn_hostname
self.turn_socket_path = turn_socket_path self.turn_socket_path = turn_socket_path
self.appversions_path = files(__package__).joinpath("defaults/appversions.json")
def handle_lookup(self, parts): def handle_lookup(self, parts):
# Lpriv/43f5f508a7ea0366dff30200c15250e3/devicetoken\tlkj123poi@c2.testrun.org # Lpriv/43f5f508a7ea0366dff30200c15250e3/devicetoken\tlkj123poi@c2.testrun.org
@@ -140,9 +125,6 @@ class MetadataDictProxy(DictProxy):
case "maxsmtprecipients": case "maxsmtprecipients":
# postfix default (see "postconf smtpd_recipient_limit") # postfix default (see "postconf smtpd_recipient_limit")
return "O1000\n" return "O1000\n"
case "appversions":
value = read_appversions(self.appversions_path)
return f"O{value}\n" if value else "N\n"
logging.warning(f"lookup ignored: {parts!r}") logging.warning(f"lookup ignored: {parts!r}")
return "N\n" return "N\n"
@@ -1,3 +0,0 @@
"""Opt in to the chatmaild fixtures, which are not registered globally."""
from chatmaild.tests.plugin import * # noqa: F403
+5 -5
View File
@@ -41,22 +41,22 @@ def ipv4_config(make_config):
@pytest.fixture @pytest.fixture
def example_maildomain(example_config): def maildomain(example_config):
return example_config.mail_domain return example_config.mail_domain
@pytest.fixture @pytest.fixture
def testaddr(example_maildomain): def testaddr(maildomain):
return f"user.name@{example_maildomain}" return f"user.name@{maildomain}"
@pytest.fixture @pytest.fixture
def example_gencreds(example_maildomain): def gencreds(maildomain):
count = itertools.count() count = itertools.count()
next(count) next(count)
def gen(domain=None): def gen(domain=None):
domain = domain if domain else example_maildomain domain = domain if domain else maildomain
while 1: while 1:
num = next(count) num = next(count)
alphanumeric = "abcdefghijklmnopqrstuvwxyz1234567890" alphanumeric = "abcdefghijklmnopqrstuvwxyz1234567890"
@@ -1,96 +0,0 @@
import json
import pytest
from chatmaild.metadata import MetadataDictProxy
ALLOWED_URL_PREFIXES = (
"https://github.com/deltachat/",
"https://download.delta.chat/",
)
def check_string(value):
assert isinstance(value, str), value
assert value
def check_version_integer(value):
# core parses this as u32, see https://github.com/chatmail/core/pull/8557
assert isinstance(value, int) and not isinstance(value, bool), value
assert 0 <= value < 2**32, value
def check_appversions(data):
"""Verifies the file the way core parses it.
core deserializes into typed structs and drops the whole payload
of a relay if a single value has an unexpected type,
while missing or misspelled keys silently turn into defaults.
"""
assert set(data) == {"clients"}, data
assert isinstance(data["clients"], list)
assert data["clients"]
client_ids = []
for client in data["clients"]:
assert set(client) == {"clientId", "sources"}, client
check_string(client["clientId"])
client_ids.append(client["clientId"])
assert isinstance(client["sources"], list)
assert client["sources"]
source_ids = []
for source in client["sources"]:
assert set(source) == {
"sourceId",
"versionInteger",
"versionString",
"downloadUrl",
}, source
check_string(source["sourceId"])
source_ids.append(source["sourceId"])
check_version_integer(source["versionInteger"])
check_string(source["versionString"])
check_string(source["downloadUrl"])
assert source["downloadUrl"].startswith(ALLOWED_URL_PREFIXES)
# core takes the first matching source, later duplicates never surface
assert len(set(source_ids)) == len(source_ids), source_ids
assert len(set(client_ids)) == len(client_ids), client_ids
@pytest.fixture
def appversions():
# check the file which chatmail-metadata actually serves
path = MetadataDictProxy(notifier=None, metadata=None).appversions_path
return json.loads(path.read_text())
def test_appversions_schema(appversions):
check_appversions(appversions)
@pytest.mark.parametrize("value", [True, -1, 2**32, "754", 754.0, None])
def test_version_integer_rejected(appversions, value):
appversions["clients"][0]["sources"][0]["versionInteger"] = value
with pytest.raises(AssertionError):
check_appversions(appversions)
@pytest.mark.parametrize("key", ["clientId", "sources"])
def test_misspelled_client_key_rejected(appversions, key):
client = appversions["clients"][0]
client[key + "s"] = client.pop(key)
with pytest.raises(AssertionError):
check_appversions(appversions)
def test_duplicate_source_id_rejected(appversions):
sources = appversions["clients"][0]["sources"]
sources.append(dict(sources[0]))
with pytest.raises(AssertionError):
check_appversions(appversions)
def test_foreign_download_url_rejected(appversions):
appversions["clients"][0]["sources"][0]["downloadUrl"] = "https://example.org/x.apk"
with pytest.raises(AssertionError):
check_appversions(appversions)
+2 -2
View File
@@ -30,9 +30,9 @@ def test_read_config_ipv4(ipv4_config):
assert ipv4_config.mail_domain == "[1.3.3.7]" assert ipv4_config.mail_domain == "[1.3.3.7]"
def test_read_config_basic_using_defaults(tmp_path, example_maildomain): def test_read_config_basic_using_defaults(tmp_path, maildomain):
inipath = tmp_path.joinpath("chatmail.ini") inipath = tmp_path.joinpath("chatmail.ini")
inipath.write_text(f"[params]\nmail_domain = {example_maildomain}") inipath.write_text(f"[params]\nmail_domain = {maildomain}")
example_config = read_config(inipath) example_config = read_config(inipath)
assert example_config.max_user_send_per_minute == 60 assert example_config.max_user_send_per_minute == 60
assert example_config.filtermail_smtp_port_incoming == 10081 assert example_config.filtermail_smtp_port_incoming == 10081
@@ -1,6 +1,6 @@
import time import time
from chatmaild.doveauth import DoveAuth from chatmaild.doveauth import AuthDictProxy
from chatmaild.expire import daily_expire_main as main_expire from chatmaild.expire import daily_expire_main as main_expire
@@ -18,10 +18,10 @@ def test_login_timestamps(example_config):
def test_delete_inactive_users(example_config): def test_delete_inactive_users(example_config):
new = time.time() new = time.time()
old = new - (example_config.delete_inactive_users_after * 86400) - 1 old = new - (example_config.delete_inactive_users_after * 86400) - 1
doveauth = DoveAuth(example_config) dictproxy = AuthDictProxy(example_config)
def create_user(addr, last_login): def create_user(addr, last_login):
doveauth.create_user(addr, "q9mr3faue") dictproxy.lookup_passdb(addr, "q9mr3faue")
user = example_config.get_user(addr) user = example_config.get_user(addr)
user.maildir.joinpath("cur").mkdir() user.maildir.joinpath("cur").mkdir()
user.maildir.joinpath("cur", "something").mkdir() user.maildir.joinpath("cur", "something").mkdir()
+143 -167
View File
@@ -1,37 +1,42 @@
import http.client import io
import json
import queue
import threading import threading
from concurrent.futures import ThreadPoolExecutor import traceback
import pytest import pytest
import chatmaild.doveauth import chatmaild.doveauth
from chatmaild.doveauth import ( from chatmaild.doveauth import (
CreateHandler, AuthDictProxy,
DoveAuth,
DoveAuthServer,
is_allowed_to_create, is_allowed_to_create,
) )
from chatmaild.newemail import create_newemail_dict from chatmaild.newemail import create_newemail_dict
@pytest.fixture @pytest.fixture
def doveauth(example_config): def dictproxy(example_config):
return DoveAuth(example_config) return AuthDictProxy(config=example_config)
def stored_hash(config, addr): def test_basic(dictproxy, gencreds):
return config.get_user(addr).get_password_hash() addr, password = gencreds()
dictproxy.lookup_passdb(addr, password)
data = dictproxy.lookup_userdb(addr)
assert data
data2 = dictproxy.lookup_passdb(addr, password)
assert data == data2
def test_basic(doveauth, example_config, example_gencreds): def test_iterate_addresses(dictproxy):
addr, password = example_gencreds() addresses = []
assert doveauth.create_user(addr, password)
passhash = stored_hash(example_config, addr)
assert passhash.startswith("{SHA512-CRYPT}")
# a second login verifies against the stored hash and rewrites nothing for i in range(10):
assert doveauth.create_user(addr, password) addresses.append(f"asdf1234{i}@chat.example.org")
assert stored_hash(example_config, addr) == passhash dictproxy.lookup_passdb(addresses[-1], "q9mr3faue")
res = dictproxy.iter_userdb()
assert set(res) == set(addresses)
def test_invalid_username_length(example_config): def test_invalid_username_length(example_config):
@@ -48,32 +53,75 @@ def test_invalid_username_length(example_config):
) )
def test_dont_overwrite_password_on_wrong_login(doveauth, example_config): def test_dont_overwrite_password_on_wrong_login(dictproxy):
addr = "newuser12@chat.example.org" """Test that logging in with a different password doesn't create a new user"""
assert doveauth.create_user(addr, "kajdlkajsldk12l3kj1983") res = dictproxy.lookup_passdb(
passhash = stored_hash(example_config, addr) "newuser12@chat.example.org", "kajdlkajsldk12l3kj1983"
)
assert not doveauth.create_user(addr, "kajdslqwe") assert res["password"]
assert stored_hash(example_config, addr) == passhash res2 = dictproxy.lookup_passdb("newuser12@chat.example.org", "kajdslqwe")
# this function always returns a password hash, which is actually compared by dovecot.
assert doveauth.create_user(addr, "kajdlkajsldk12l3kj1983") assert res["password"] == res2["password"]
assert stored_hash(example_config, addr) == passhash
def test_foreign_domain_is_refused(doveauth): def test_nocreate_file(monkeypatch, tmpdir, dictproxy):
assert not doveauth.create_user("newuser12@evil.example.org", "qlwkejqlwe12")
def test_nocreate_file(monkeypatch, tmpdir, doveauth, example_config):
p = tmpdir.join("nocreate") p = tmpdir.join("nocreate")
p.write("") p.write("")
monkeypatch.setattr(chatmaild.doveauth, "NOCREATE_FILE", str(p)) monkeypatch.setattr(chatmaild.doveauth, "NOCREATE_FILE", str(p))
addr = "newuser12@chat.example.org" dictproxy.lookup_passdb("newuser12@chat.example.org", "zequ0Aimuchoodaechik")
assert not doveauth.create_user(addr, "zequ0Aimuchoodaechik") assert not dictproxy.lookup_userdb("newuser12@chat.example.org")
assert stored_hash(example_config, addr) is None
def test_handle_dovecot_request(dictproxy):
transactions = {}
# Test that password can contain ", ', \ and /
msg = (
'Lshared/passdb/laksjdlaksjdlak\\\\sjdlk\\"12j\\\'3l1/k2j3123"'
"some42123@chat.example.org\tsome42123@chat.example.org"
)
res = dictproxy.handle_dovecot_request(msg, transactions)
assert res
assert res[0] == "O" and res.endswith("\n")
userdata = json.loads(res[1:].strip())
assert userdata["home"].endswith("chat.example.org/some42123@chat.example.org")
assert userdata["uid"] == userdata["gid"] == "vmail"
assert userdata["password"].startswith("{SHA512-CRYPT}")
def test_handle_dovecot_protocol_hello_is_skipped(example_config, caplog):
dictproxy = AuthDictProxy(config=example_config)
rfile = io.BytesIO(b"H3\t2\t0\t\tauth\n")
wfile = io.BytesIO()
dictproxy.loop_forever(rfile, wfile)
assert wfile.getvalue() == b""
assert not caplog.messages
def test_handle_dovecot_protocol_user_not_exists(example_config):
dictproxy = AuthDictProxy(config=example_config)
rfile = io.BytesIO(
b"H3\t2\t0\t\tauth\nLshared/userdb/foobar@chat.example.org\tfoobar@chat.example.org\n"
)
wfile = io.BytesIO()
dictproxy.loop_forever(rfile, wfile)
assert wfile.getvalue() == b"N\n"
def test_handle_dovecot_protocol_iterate(gencreds, example_config):
dictproxy = AuthDictProxy(config=example_config)
dictproxy.lookup_passdb("asdf00000@chat.example.org", "q9mr3faue")
dictproxy.lookup_passdb("asdf11111@chat.example.org", "q9mr3faue")
rfile = io.BytesIO(b"H3\t2\t0\t\tauth\nI0\t0\tshared/userdb/")
wfile = io.BytesIO()
dictproxy.loop_forever(rfile, wfile)
lines = wfile.getvalue().decode("ascii").split("\n")
assert "Oshared/userdb/asdf00000@chat.example.org\t" in lines
assert "Oshared/userdb/asdf11111@chat.example.org\t" in lines
assert not lines[2]
def test_invalid_localpart_characters(make_config): def test_invalid_localpart_characters(make_config):
"""Test that is_allowed_to_create rejects localparts with invalid characters."""
config = make_config("chat.example.org", {"username_min_length": "3"}) config = make_config("chat.example.org", {"username_min_length": "3"})
password = "zequ0Aimuchoodaechik" password = "zequ0Aimuchoodaechik"
domain = config.mail_domain domain = config.mail_domain
@@ -93,150 +141,78 @@ def test_invalid_localpart_characters(make_config):
assert not is_allowed_to_create(config, f"ab@cdef@{domain}", password) assert not is_allowed_to_create(config, f"ab@cdef@{domain}", password)
assert not is_allowed_to_create(config, f"abc/def@{domain}", password) assert not is_allowed_to_create(config, f"abc/def@{domain}", password)
assert not is_allowed_to_create(config, f"abc\\def@{domain}", password) assert not is_allowed_to_create(config, f"abc\\def@{domain}", password)
assert not is_allowed_to_create(config, f"üser123@{domain}", password)
def test_concurrent_creation_same_account(doveauth, example_config, capsys): def test_concurrent_creation_same_account(dictproxy):
"""Test that concurrent creation of the same account doesn't corrupt password."""
addr = "racetest1@chat.example.org" addr = "racetest1@chat.example.org"
password = "zequ0Aimuchoodaechik" password = "zequ0Aimuchoodaechik"
num_threads = 10
results = queue.Queue()
def create(_): def create():
ok = doveauth.create_user(addr, password) try:
return ok, stored_hash(example_config, addr) res = dictproxy.lookup_passdb(addr, password)
results.put(("ok", res))
except Exception:
results.put(("err", traceback.format_exc()))
threads = [threading.Thread(target=create, daemon=True) for _ in range(num_threads)]
for t in threads:
t.start()
for t in threads:
t.join(timeout=10)
passwords_seen = set()
for _ in range(num_threads):
status, res = results.get()
if status == "err":
pytest.fail(f"concurrent creation failed\n{res}")
passwords_seen.add(res["password"])
with ThreadPoolExecutor(10) as pool:
results = list(pool.map(create, range(10)))
assert all(ok for ok, _ in results)
# all threads must see the same password hash # all threads must see the same password hash
assert len({passhash for _, passhash in results}) == 1 assert len(passwords_seen) == 1
assert capsys.readouterr().err.count("Created address:") == 1
def test_50_concurrent_lookups_different_accounts(gencreds, dictproxy):
num_threads = 50
req_per_thread = 5
results = queue.Queue()
def lookup():
for i in range(req_per_thread):
addr, password = gencreds()
try:
dictproxy.lookup_passdb(addr, password)
except Exception:
results.put(traceback.format_exc())
else:
results.put(None)
threads = []
for i in range(num_threads):
thread = threading.Thread(target=lookup, daemon=True)
threads.append(thread)
print(f"created {num_threads} threads, starting them and waiting for results")
for thread in threads:
thread.start()
for i in range(num_threads * req_per_thread):
res = results.get()
if res is not None:
pytest.fail(f"concurrent lookup failed\n{res}")
def test_insufficient_resources_block_creation_not_existing_logins( def test_insufficient_resources_block_creation_not_existing_logins(
doveauth, example_gencreds, monkeypatch dictproxy, gencreds, monkeypatch
): ):
addr, password = example_gencreds() addr, password = gencreds()
assert doveauth.create_user(addr, password) assert dictproxy.lookup_passdb(addr, password)
monkeypatch.setattr( monkeypatch.setattr(
chatmaild.doveauth, "has_sufficient_resources", lambda config: False chatmaild.doveauth, "has_sufficient_resources", lambda config: False
) )
newaddr, newpassword = example_gencreds() newaddr, newpassword = gencreds()
assert not doveauth.create_user(newaddr, newpassword) assert not dictproxy.lookup_passdb(newaddr, newpassword)
assert doveauth.create_user(addr, password) assert dictproxy.lookup_passdb(addr, password)
class TestHttpPost:
@pytest.fixture
def doveauth_server(self, example_config):
server = DoveAuthServer(example_config, port=0)
threading.Thread(target=server.serve_forever, daemon=True).start()
yield f"127.0.0.1:{server.server_address[1]}"
server.shutdown()
server.server_close()
@pytest.fixture
def post(self, doveauth_server):
def post(path, data):
conn = http.client.HTTPConnection(doveauth_server, timeout=10)
try:
return self.post_on(conn, path, data).status
finally:
conn.close()
return post
@pytest.fixture
def connection(self, doveauth_server):
"""One kept-alive connection, which is all dovecot's HTTP client opens."""
conn = http.client.HTTPConnection(doveauth_server, timeout=10)
yield conn
conn.close()
@staticmethod
def post_on(conn, path, data):
conn.request("POST", path, body=data)
resp = conn.getresponse()
resp.read()
return resp
def test_create_and_verify(self, post, example_config, example_gencreds):
addr, password = example_gencreds()
assert post("/create", f"{addr}\t{password}".encode()) == 200
assert stored_hash(example_config, addr).startswith("{SHA512-CRYPT}")
# second login with the same password verifies, a wrong one is refused
assert post("/create", f"{addr}\t{password}".encode()) == 200
assert post("/create", f"{addr}\twrong{password}".encode()) == 403
def test_password_special_chars_survive_transport(self, post, example_gencreds):
addr, _ = example_gencreds()
password = "laksjdlaksjdlak\\sjdlk\"12j'3l1/k2\tj3123"
body = f"{addr}\t{password}".encode()
assert post("/create", body) == 200
assert post("/create", body) == 200
assert post("/create", f"{addr}\totherpassword1".encode()) == 403
def test_password_must_be_utf8(self, post, example_gencreds):
addr, _ = example_gencreds()
assert post("/create", f"{addr}\tpässwort12".encode()) == 200
assert post("/create", addr.encode() + b"\tp\xe4sswort12") == 400
def test_nul_is_refused_before_crypt_sees_it(self, post, example_gencreds):
addr, _ = example_gencreds()
assert post("/create", f"{addr}\tpass\0word12".encode()) == 400
assert (
post("/create", "us\0er12345@chat.example.org\tlongenough1".encode()) == 400
)
def test_refused_creation(self, post, example_gencreds):
addr, _ = example_gencreds()
assert post("/create", f"{addr}\tshort".encode()) == 403
assert post("/create", b"not-an-address\tlongenoughpassword") == 403
body = "bürger123@chat.example.org\tlongenoughpw".encode()
assert post("/create", body) == 403
assert post("/create", b"") == 403
def test_body_length_limit(self, post, example_gencreds):
addr, _ = example_gencreds()
fill = CreateHandler.max_body_len - len(addr) - len("\t")
body = f"{addr}\t{'x' * fill}".encode()
assert len(body) == CreateHandler.max_body_len
assert post("/create", body) == 200
body = f"{addr}\t{'x' * (fill + 1)}".encode()
assert len(body) == CreateHandler.max_body_len + 1
assert post("/create", body) == 400
def test_connection_is_reused_across_200_replies(
self, connection, example_gencreds
):
addr, password = example_gencreds()
body = f"{addr}\t{password}".encode()
# create, then verify the same password, on one connection
for _ in range(2):
resp = self.post_on(connection, "/create", body)
assert (resp.status, resp.will_close) == (200, False)
@pytest.mark.parametrize(
"path,data,status",
[
("/other", b"not read", 404),
("/create", b"x" * (CreateHandler.max_body_len + 1), 400),
("/create", b"not-an-address\tlongenoughpassword", 403),
],
)
def test_error_replies_close_the_connection(self, connection, path, data, status):
resp = self.post_on(connection, path, data)
assert (resp.status, resp.will_close) == (status, True)
@pytest.mark.parametrize("content_length", [None, "-1", "notanumber", "999999"])
def test_bad_content_length(self, connection, content_length):
# the fixture timeout turns a server that waits for the body into a failure
connection.putrequest("POST", "/create", skip_accept_encoding=True)
if content_length is not None:
connection.putheader("Content-Length", content_length)
connection.endheaders()
resp = connection.getresponse()
assert resp.status == 400
assert resp.will_close
+56 -36
View File
@@ -3,6 +3,7 @@ import os
import random import random
import shutil import shutil
import time import time
from datetime import datetime
from fnmatch import fnmatch from fnmatch import fnmatch
from pathlib import Path from pathlib import Path
@@ -21,6 +22,7 @@ from chatmaild.expire import (
scan_mailbox_messages, scan_mailbox_messages,
) )
from chatmaild.expire import daily_expire_main as expiry_main from chatmaild.expire import daily_expire_main as expiry_main
from chatmaild.fsreport import main as report_main
MB = 1024 * 1024 MB = 1024 * 1024
@@ -39,7 +41,7 @@ def fill_mbox(folderdir):
def create_new_messages(basedir, relpaths, size=1000, days=0): def create_new_messages(basedir, relpaths, size=1000, days=0):
now = time.time() now = datetime.utcnow().timestamp()
for relpath in relpaths: for relpath in relpaths:
msg_path = Path(basedir).joinpath(relpath) msg_path = Path(basedir).joinpath(relpath)
@@ -110,7 +112,9 @@ def test_mbox_without_password(mbox1, example_config, capsys):
mbox_rescan = MailboxStat(mbox1.basedir) mbox_rescan = MailboxStat(mbox1.basedir)
assert mbox_rescan.last_login is None assert mbox_rescan.last_login is None
exp = Expiry(example_config, dry=False, now=time.time(), verbose=False) exp = Expiry(
example_config, dry=False, now=datetime.now().timestamp(), verbose=False
)
exp.process_mailbox_stat(mbox_rescan) exp.process_mailbox_stat(mbox_rescan)
out, err = capsys.readouterr() out, err = capsys.readouterr()
assert "doesn't have last_login but isn't empty" in err assert "doesn't have last_login but isn't empty" in err
@@ -128,46 +132,62 @@ def test_mbox_without_password(mbox1, example_config, capsys):
assert not os.path.isdir(mbox_rescan.basedir) assert not os.path.isdir(mbox_rescan.basedir)
def test_expiry_cli_prom(example_config, mbox1, tmp_path, monkeypatch): def test_report_no_mailboxes(example_config):
days = int(example_config.delete_mails_after) + 1 args = (str(example_config._inipath),)
create_new_messages(mbox1.basedir, ["cur/msg_old"], size=1000, days=days) report_main(args)
create_new_messages(mbox1.basedir, ["cur/msg_4days"], size=100, days=4)
path = tmp_path / "chatmail-expire.prom"
monkeypatch.setenv("CHATMAIL_EXPIRE_PROMPATH", str(path))
expiry_main([str(example_config._inipath), "--remove"])
text = path.read_text()
# fill_mbox 500 + 600 bytes and msg_4days remain after msg_old expired
assert 'chatmail_storage_bytes{kind="messages"} 1200\n' in text
assert 'chatmail_messages_count{min_size="0"} 3\n' in text
assert 'chatmail_messages_age_bytes{min_days="3"} 100\n' in text
assert 'chatmail_messages_age_bytes{min_days="7"} 0\n' in text
assert 'chatmail_accounts{kind="all"} 1\n' in text
# msg_old and maildirsize
assert "chatmail_expire_removed_files 2\n" in text
assert "chatmail_expire_last_run_timestamp_seconds " in text
@pytest.mark.parametrize("dry", [True, False]) def test_report(mbox1, example_config):
def test_expiry_dry_counts_like_real_run(example_config, mbox1, dry): args = (str(example_config._inipath),)
mboxdir = Path(mbox1.basedir) report_main(args)
days = int(example_config.delete_mails_after) + 1 args = list(args) + "--days 1".split()
_create_message(mboxdir, "cur", 400 * MB, days_old=days, disk_size=10) report_main(args)
_create_message(mboxdir, "cur", 400 * MB, days_old=2, disk_size=10) args = list(args) + "--min-login-age 1".split()
exp = Expiry(example_config, dry=dry, now=time.time(), verbose=False) report_main(args)
exp.process_mailbox_stat(MailboxStat(mboxdir)) args = list(args) + "--mdir cur".split()
# age pass removes the old one, quota pass the other, plus maildirsize report_main(args)
assert exp.del_files == 3
assert exp.size_messages == 1100
def test_report_mdir_filters_by_path(mbox1, example_config):
"""Test that Report with mdir='cur' only counts messages in cur/ subdirectory."""
from chatmaild.fsreport import Report
now = datetime.utcnow().timestamp()
# Set password mtime to old enough so min_login_age check passes
password = Path(mbox1.basedir).joinpath("password")
old_time = now - 86400 * 10 # 10 days ago
os.utime(password, (old_time, old_time))
# Reload mailbox with updated mtime
from chatmaild.expire import MailboxStat
mbox = MailboxStat(mbox1.basedir)
# Report without mdir — should count all messages
rep_all = Report(now=now, min_login_age=1, mdir=None)
rep_all.process_mailbox_stat(mbox)
total_all = rep_all.message_buckets[0]
# Report with mdir='cur' — should only count cur/ messages
rep_cur = Report(now=now, min_login_age=1, mdir="cur")
rep_cur.process_mailbox_stat(mbox)
total_cur = rep_cur.message_buckets[0]
# Report with mdir='new' — should only count new/ messages
rep_new = Report(now=now, min_login_age=1, mdir="new")
rep_new.process_mailbox_stat(mbox)
total_new = rep_new.message_buckets[0]
# cur has 500-byte msg, new has 600-byte msg (from fill_mbox)
assert total_cur == 500
assert total_new == 600
assert total_all == 500 + 600
def test_expiry_cli_basic(example_config, mbox1): def test_expiry_cli_basic(example_config, mbox1):
mboxdir = Path(mbox1.basedir)
p1 = _create_message(mboxdir, "cur", 400 * MB, days_old=2, disk_size=10)
p2 = _create_message(mboxdir, "cur", 400 * MB, days_old=2, disk_size=10)
args = (str(example_config._inipath),) args = (str(example_config._inipath),)
expiry_main(args) expiry_main(args)
assert p1.exists() and p2.exists()
assert mboxdir.joinpath("maildirsize").exists()
def test_expiry_cli_old_files(capsys, example_config, mbox1): def test_expiry_cli_old_files(capsys, example_config, mbox1):
@@ -245,7 +265,7 @@ def test_expire_to_target(tmp_path):
assert len(scan_mailbox_messages(tmp_path)) == 3 assert len(scan_mailbox_messages(tmp_path)) == 3
# removes oldest first, uses S= size not disk size # removes oldest first, uses S= size not disk size
removed = expire_to_target(tmp_path, MB) removed = expire_to_target(tmp_path, MB)
assert len(removed) == 2 assert removed == 2
msgs = scan_mailbox_messages(tmp_path) msgs = scan_mailbox_messages(tmp_path)
assert len(msgs) == 1 assert len(msgs) == 1
# the surviving message is the fresh undeletable one # the surviving message is the fresh undeletable one
@@ -1,6 +1,6 @@
import time import time
from chatmaild.doveauth import DoveAuth from chatmaild.doveauth import AuthDictProxy
from chatmaild.lastlogin import ( from chatmaild.lastlogin import (
LastLoginDictProxy, LastLoginDictProxy,
) )
@@ -9,8 +9,8 @@ from chatmaild.lastlogin import (
def test_handle_dovecot_request_last_login(testaddr, example_config): def test_handle_dovecot_request_last_login(testaddr, example_config):
dictproxy = LastLoginDictProxy(config=example_config) dictproxy = LastLoginDictProxy(config=example_config)
doveauth = DoveAuth(example_config) authproxy = AuthDictProxy(config=example_config)
doveauth.create_user(testaddr, "1l2k3j1l2k3jl123") authproxy.lookup_passdb(testaddr, "1l2k3j1l2k3jl123")
dictproxy_transactions = {} dictproxy_transactions = {}
@@ -1,5 +1,4 @@
import io import io
import json
import time import time
import pytest import pytest
@@ -8,7 +7,6 @@ import requests
from chatmaild.metadata import ( from chatmaild.metadata import (
Metadata, Metadata,
MetadataDictProxy, MetadataDictProxy,
read_appversions,
) )
from chatmaild.notifier import ( from chatmaild.notifier import (
Notifier, Notifier,
@@ -371,32 +369,6 @@ def test_iroh_relay(dictproxy):
assert wfile.getvalue() == b"Ohttps://example.org/\n" assert wfile.getvalue() == b"Ohttps://example.org/\n"
def test_read_appversions(tmp_path):
path = tmp_path.joinpath("appversions.json")
assert read_appversions(path) is None
path.write_text('{\n "clients": []\n}')
assert read_appversions(path) == '{"clients":[]}'
# the value travels as a single dict protocol line
path.write_text('{"clients": [{"clientId": "one\\ntwo"}]}')
assert read_appversions(path) == '{"clients":[{"clientId":"one\\ntwo"}]}'
path.write_text("bad json")
assert read_appversions(path) is None
def test_appversions_lookup(dictproxy):
# the version information shipped with chatmaild is served as a single line
key = b"Lshared/0123/vendor/vendor.dovecot/pvt/server/vendor/deltachat/appversions"
key += b"\tuser@example.org"
rfile, wfile = io.BytesIO(b"H\n" + key), io.BytesIO()
dictproxy.loop_forever(rfile, wfile)
value = wfile.getvalue()
assert value.startswith(b"O") and value.endswith(b"\n")
assert json.loads(value[1:])["clients"]
def test_legacy_token_migration(metadata, testaddr): def test_legacy_token_migration(metadata, testaddr):
with metadata.get_metadata_dict(testaddr).modify() as data: with metadata.get_metadata_dict(testaddr).modify() as data:
data[metadata.DEVICETOKEN_KEY] = ["oldtoken1", "oldtoken2"] data[metadata.DEVICETOKEN_KEY] = ["oldtoken1", "oldtoken2"]
@@ -63,7 +63,7 @@ def test_migration(tmp_path, example_config, caplog):
user = example_config.get_user(path.name) user = example_config.get_user(path.name)
if last_login: if last_login:
assert user.get_last_login_timestamp() == last_login assert user.get_last_login_timestamp() == last_login
assert password == user.get_password_hash() assert password == user.get_userdb_dict()["password"]
assert not all assert not all
assert not example_config.passdb_path.exists() assert not example_config.passdb_path.exists()
@@ -48,7 +48,7 @@ def test_create_dclogin_url_ipv4(ipv4_config):
assert addr in url assert addr in url
def test_print_new_account(capsys, monkeypatch, tmpdir, example_config): def test_print_new_account(capsys, monkeypatch, maildomain, tmpdir, example_config):
monkeypatch.setattr(chatmaild.newemail, "CONFIG_PATH", str(example_config._inipath)) monkeypatch.setattr(chatmaild.newemail, "CONFIG_PATH", str(example_config._inipath))
print_new_account() print_new_account()
out, err = capsys.readouterr() out, err = capsys.readouterr()
+11 -6
View File
@@ -8,23 +8,28 @@ def test_login_timestamp(testaddr, example_config):
assert user.get_last_login_timestamp() == 86400 * 2 assert user.get_last_login_timestamp() == 86400 * 2
def test_get_password_hash_not_set(testaddr, example_config, caplog): def test_get_user_dict_not_set(testaddr, example_config, caplog):
user = example_config.get_user(testaddr) user = example_config.get_user(testaddr)
assert not caplog.records assert not caplog.records
assert user.get_password_hash() is None assert user.get_userdb_dict() == {}
assert len(caplog.records) == 0 assert len(caplog.records) == 0
user.set_password("") user.set_password("")
assert user.get_password_hash() is None assert user.get_userdb_dict() == {}
assert len(caplog.records) == 1 assert len(caplog.records) == 1
def test_get_password_hash(make_config, tmp_path): def test_get_user_dict(make_config, tmp_path):
config = make_config("something.testrun.org") config = make_config("something.testrun.org")
user = config.get_user("user1@something.org") addr = "user1@something.org"
user = config.get_user(addr)
enc_password = "l1k2j31lk2j3l1k23j123" enc_password = "l1k2j31lk2j3l1k23j123"
user.set_password(enc_password) user.set_password(enc_password)
assert user.get_password_hash() == enc_password data = user.get_userdb_dict()
assert addr in str(data["home"])
assert data["uid"] == "vmail"
assert data["gid"] == "vmail"
assert data["password"] == enc_password
def test_no_mailboxes_dir(testaddr, example_config, tmp_path): def test_no_mailboxes_dir(testaddr, example_config, tmp_path):
+9 -6
View File
@@ -21,17 +21,20 @@ class User:
def can_track(self): def can_track(self):
return "@" in self.addr return "@" in self.addr
def get_password_hash(self): def get_userdb_dict(self):
"""Return a non-empty dovecot 'userdb' style dict
if the user has an existing non-empty password"""
try: try:
passhash = self.password_path.read_text() pw = self.password_path.read_text()
except FileNotFoundError: except FileNotFoundError:
return None return {}
if not passhash: if not pw:
logging.error(f"password is empty for: {self.addr}") logging.error(f"password is empty for: {self.addr}")
return None return {}
return passhash home = str(self.maildir)
return dict(addr=self.addr, home=home, uid=self.uid, gid=self.gid, password=pw)
def is_incoming_cleartext_ok(self): def is_incoming_cleartext_ok(self):
return not self.enforce_E2EE_path.exists() return not self.enforce_E2EE_path.exists()
+4 -2
View File
@@ -19,8 +19,6 @@ dependencies = [
"pytest-xdist", "pytest-xdist",
"execnet", "execnet",
"imap_tools", "imap_tools",
"jinja2",
"lupa",
"deltachat-rpc-client", "deltachat-rpc-client",
"deltachat-rpc-server", "deltachat-rpc-server",
] ]
@@ -28,6 +26,10 @@ dependencies = [
[project.scripts] [project.scripts]
cmdeploy = "cmdeploy.cmdeploy:main" cmdeploy = "cmdeploy.cmdeploy:main"
[project.entry-points.pytest11]
"chatmaild.testplugin" = "chatmaild.tests.plugin"
"cmdeploy.testplugin" = "cmdeploy.tests.plugin"
[tool.pytest.ini_options] [tool.pytest.ini_options]
addopts = "-v -ra --strict-markers" addopts = "-v -ra --strict-markers"
-1
View File
@@ -1 +0,0 @@
+3 -9
View File
@@ -4,8 +4,6 @@ from ..basedeploy import Deployer
class AcmetoolDeployer(Deployer): class AcmetoolDeployer(Deployer):
bin_path = "/usr/bin/acmetool"
def __init__(self, email, domains): def __init__(self, email, domains):
self.domains = domains self.domains = domains
self.email = email self.email = email
@@ -43,12 +41,8 @@ class AcmetoolDeployer(Deployer):
domains=self.domains, domains=self.domains,
) )
self.ensure_systemd_unit( self.ensure_systemd_unit("acmetool/acmetool-redirector.service")
"acmetool/acmetool-redirector.service.j2", bin_path=self.bin_path self.ensure_systemd_unit("acmetool/acmetool-reconcile.service")
)
self.ensure_systemd_unit(
"acmetool/acmetool-reconcile.service.j2", bin_path=self.bin_path
)
self.ensure_systemd_unit("acmetool/acmetool-reconcile.timer") self.ensure_systemd_unit("acmetool/acmetool-reconcile.timer")
def activate(self): def activate(self):
@@ -58,5 +52,5 @@ class AcmetoolDeployer(Deployer):
server.shell( server.shell(
name=f"Reconcile certificates for: {', '.join(self.domains)}", name=f"Reconcile certificates for: {', '.join(self.domains)}",
commands=[f"{self.bin_path} --batch --xlog.severity=debug reconcile"], commands=["acmetool --batch --xlog.severity=debug reconcile"],
) )
@@ -4,5 +4,5 @@ After=network.target
[Service] [Service]
Type=oneshot Type=oneshot
ExecStart={{ bin_path }} --batch reconcile ExecStart=/usr/bin/acmetool --batch reconcile
@@ -3,7 +3,7 @@ Description=acmetool HTTP redirector
[Service] [Service]
Type=notify Type=notify
ExecStart={{ bin_path }} redirector --service.uid=daemon --bind=127.0.0.1:402 ExecStart=/usr/bin/acmetool redirector --service.uid=daemon --bind=127.0.0.1:402
Restart=always Restart=always
RestartSec=30 RestartSec=30
+4 -5
View File
@@ -51,7 +51,7 @@ def get_resource(arg, pkg=__package__):
return importlib.resources.files(pkg).joinpath(arg) return importlib.resources.files(pkg).joinpath(arg)
def configure_remote_units(deployer, mail_domain, units, **kwargs) -> None: def configure_remote_units(deployer, mail_domain, units) -> None:
remote_base_dir = "/usr/local/lib/chatmaild" remote_base_dir = "/usr/local/lib/chatmaild"
remote_venv_dir = f"{remote_base_dir}/venv" remote_venv_dir = f"{remote_base_dir}/venv"
remote_chatmail_inipath = f"{remote_base_dir}/chatmail.ini" remote_chatmail_inipath = f"{remote_base_dir}/chatmail.ini"
@@ -63,7 +63,6 @@ def configure_remote_units(deployer, mail_domain, units, **kwargs) -> None:
config_path=remote_chatmail_inipath, config_path=remote_chatmail_inipath,
remote_venv_dir=remote_venv_dir, remote_venv_dir=remote_venv_dir,
mail_domain=mail_domain, mail_domain=mail_domain,
**kwargs,
) )
basename = fn if "." in fn else f"{fn}.service" basename = fn if "." in fn else f"{fn}.service"
@@ -82,7 +81,7 @@ def activate_remote_units(deployer, units) -> None:
for fn in units: for fn in units:
basename = fn if "." in fn else f"{fn}.service" basename = fn if "." in fn else f"{fn}.service"
if fn == "chatmail-expire": if fn == "chatmail-expire" or fn == "chatmail-fsreport":
# don't auto-start but let the corresponding timer trigger execution # don't auto-start but let the corresponding timer trigger execution
enabled = False enabled = False
else: else:
@@ -227,7 +226,7 @@ class Deployer:
res = files.directory(name=name, path=path, present=False, **kwargs) res = files.directory(name=name, path=path, present=False, **kwargs)
return self._update_restart_signals(path, res) return self._update_restart_signals(path, res)
def download_executable(self, url, dest, sha256sum, extract=None, mode="755"): def download_executable(self, url, dest, sha256sum, extract=None):
existing = host.get_fact(Sha256File, dest) existing = host.get_fact(Sha256File, dest)
if existing == sha256sum: if existing == sha256sum:
return return
@@ -244,7 +243,7 @@ class Deployer:
f"({dl_cmd}" f"({dl_cmd}"
f" && echo '{sha256sum} {tmp}' | sha256sum -c" f" && echo '{sha256sum} {tmp}' | sha256sum -c"
f" && mv {tmp} {dest})", f" && mv {tmp} {dest})",
f"chmod {mode} {dest}", f"chmod 755 {dest}",
], ],
) )
self.need_restart = True self.need_restart = True
+32 -45
View File
@@ -12,7 +12,6 @@ from chatmaild.config import read_config
from pyinfra import facts, host, logger from pyinfra import facts, host, logger
from pyinfra.api import FactBase from pyinfra.api import FactBase
from pyinfra.facts import hardware from pyinfra.facts import hardware
from pyinfra.facts.files import Sha256File
from pyinfra.facts.systemd import SystemdEnabled from pyinfra.facts.systemd import SystemdEnabled
from pyinfra.operations import apt, files, pip, server, systemd from pyinfra.operations import apt, files, pip, server, systemd
@@ -33,14 +32,12 @@ from .external.deployer import ExternalTlsDeployer
from .filtermail.deployer import FiltermailDeployer from .filtermail.deployer import FiltermailDeployer
from .mtail.deployer import MtailDeployer from .mtail.deployer import MtailDeployer
from .nginx.deployer import NginxDeployer from .nginx.deployer import NginxDeployer
from .websockify.deployer import WebsockifyDeployer
from .opendkim.deployer import OpendkimDeployer from .opendkim.deployer import OpendkimDeployer
from .pins import IROH_ARTIFACTS, TURN_ARTIFACTS
from .postfix.deployer import PostfixDeployer from .postfix.deployer import PostfixDeployer
from .selfsigned.deployer import SelfSignedTlsDeployer from .selfsigned.deployer import SelfSignedTlsDeployer
from .www import build_webpages, find_merge_conflict, get_paths from .www import build_webpages, find_merge_conflict, get_paths
OLD_JOURNALD_SHA256 = "107c678516c972d5293a67386458fd4785d467cfa2f2b7174185e9a74e034be5"
class Port(FactBase): class Port(FactBase):
""" """
@@ -288,18 +285,6 @@ class LegacyRemoveDeployer(Deployer):
enabled=False, enabled=False,
) )
# chatmail-fsreport was folded into chatmail-expiry
timer = "chatmail-fsreport.timer"
if has_systemd() and host.get_fact(SystemdEnabled).get(timer):
systemd.service(
name=f"Disable {timer}",
service=timer,
running=False,
enabled=False,
)
self.remove_file(f"/etc/systemd/system/{timer}")
self.remove_file("/etc/systemd/system/chatmail-fsreport.service")
def check_config(config): def check_config(config):
mail_domain = config.mail_domain mail_domain = config.mail_domain
@@ -317,48 +302,55 @@ def check_config(config):
class TurnDeployer(Deployer): class TurnDeployer(Deployer):
bin_path = "/usr/local/bin/chatmail-turn"
def __init__(self, mail_domain): def __init__(self, mail_domain):
self.mail_domain = mail_domain self.mail_domain = mail_domain
self.units = ["turnserver"] self.units = ["turnserver"]
def install(self): def install(self):
(url, sha256sum) = TURN_ARTIFACTS[host.get_fact(facts.server.Arch)] (url, sha256sum) = {
self.download_executable(url, self.bin_path, sha256sum) "x86_64": (
"https://github.com/chatmail/chatmail-turn/releases/download/v0.4/chatmail-turn-x86_64-linux",
"1ec1f5c50122165e858a5a91bcba9037a28aa8cb8b64b8db570aa457c6141a8a",
),
"aarch64": (
"https://github.com/chatmail/chatmail-turn/releases/download/v0.4/chatmail-turn-aarch64-linux",
"0fb3e792419494e21ecad536464929dba706bb2c88884ed8f1788141d26fc756",
),
}[host.get_fact(facts.server.Arch)]
self.download_executable(url, "/usr/local/bin/chatmail-turn", sha256sum)
def configure(self): def configure(self):
configure_remote_units( configure_remote_units(self, self.mail_domain, self.units)
self, self.mail_domain, self.units, bin_path=self.bin_path
)
def activate(self): def activate(self):
activate_remote_units(self, self.units) activate_remote_units(self, self.units)
class IrohDeployer(Deployer): class IrohDeployer(Deployer):
bin_path = "/usr/local/bin/iroh-relay"
config_path = "/etc/iroh-relay.toml"
def __init__(self, enable_iroh_relay): def __init__(self, enable_iroh_relay):
self.enable_iroh_relay = enable_iroh_relay self.enable_iroh_relay = enable_iroh_relay
def install(self): def install(self):
(url, sha256sum) = IROH_ARTIFACTS[host.get_fact(facts.server.Arch)] (url, sha256sum) = {
"x86_64": (
"https://github.com/n0-computer/iroh/releases/download/v0.35.0/iroh-relay-v0.35.0-x86_64-unknown-linux-musl.tar.gz",
"45c81199dbd70f8c4c30fef7f3b9727ca6e3cea8f2831333eeaf8aa71bf0fac1",
),
"aarch64": (
"https://github.com/n0-computer/iroh/releases/download/v0.35.0/iroh-relay-v0.35.0-aarch64-unknown-linux-musl.tar.gz",
"f8ef27631fac213b3ef668d02acd5b3e215292746a3fc71d90c63115446008b1",
),
}[host.get_fact(facts.server.Arch)]
self.download_executable( self.download_executable(
url, url,
self.bin_path, "/usr/local/bin/iroh-relay",
sha256sum, sha256sum,
extract="gunzip | tar -xf - ./iroh-relay -O", extract="gunzip | tar -xf - ./iroh-relay -O",
) )
def configure(self): def configure(self):
self.ensure_systemd_unit( self.ensure_systemd_unit("iroh-relay.service")
"iroh-relay.service.j2", self.put_file("iroh-relay.toml", "/etc/iroh-relay.toml")
bin_path=self.bin_path,
config_path=self.config_path,
)
self.put_file("iroh-relay.toml", self.config_path)
def activate(self): def activate(self):
self.ensure_service( self.ensure_service(
@@ -369,15 +361,7 @@ class IrohDeployer(Deployer):
class JournaldDeployer(Deployer): class JournaldDeployer(Deployer):
def configure(self): def configure(self):
self.put_file("90-volatile-logging.conf", "/etc/systemd/journald.conf.d/90-volatile-logging.conf") self.put_file("journald.conf", "/etc/systemd/journald.conf")
if host.get_fact(Sha256File, "/etc/systemd/journald.conf") == OLD_JOURNALD_SHA256:
server.shell(
name="Restore Debian's journald.conf",
commands=[
"rm /etc/systemd/journald.conf",
"DEBIAN_FRONTEND=noninteractive apt-get install -y --reinstall -o Dpkg::Options::=--force-confmiss systemd",
],
)
def activate(self): def activate(self):
self.ensure_service("systemd-journald.service") self.ensure_service("systemd-journald.service")
@@ -393,6 +377,8 @@ class ChatmailVenvDeployer(Deployer):
"lastlogin", "lastlogin",
"chatmail-expire", "chatmail-expire",
"chatmail-expire.timer", "chatmail-expire.timer",
"chatmail-fsreport",
"chatmail-fsreport.timer",
) )
def install(self): def install(self):
@@ -535,10 +521,10 @@ def deploy_chatmail(config_path: Path, disable_mail: bool, website_only: bool) -
("nginx", 443), ("nginx", 443),
(["master", "smtpd"], 465), (["master", "smtpd"], 465),
(["master", "smtpd"], 587), (["master", "smtpd"], 587),
(["dovecot", "imap-login"], 993), (["imap-login", "dovecot"], 993),
("iroh-relay", 3340), ("iroh-relay", 3340),
("mtail", 3903), ("mtail", 3903),
(["dovecot", "stats"], 3904), ("stats", 3904),
("nginx", 8443), ("nginx", 8443),
(["master", "smtpd"], config.postfix_reinject_port), (["master", "smtpd"], config.postfix_reinject_port),
(["master", "smtpd"], config.postfix_reinject_port_incoming), (["master", "smtpd"], config.postfix_reinject_port_incoming),
@@ -580,6 +566,7 @@ def deploy_chatmail(config_path: Path, disable_mail: bool, website_only: bool) -
PostfixDeployer(config, disable_mail), PostfixDeployer(config, disable_mail),
FcgiwrapDeployer(), FcgiwrapDeployer(),
NginxDeployer(config), NginxDeployer(config),
WebsockifyDeployer(config),
MtailDeployer(config.mtail_address), MtailDeployer(config.mtail_address),
GithashDeployer(), GithashDeployer(),
] ]
+2 -4
View File
@@ -68,6 +68,7 @@ def get_filled_zone_file(remote_data):
"CAA", "CAA",
f'0 issue "letsencrypt.org;accounturi={remote_data["acme_account_url"]}"', f'0 issue "letsencrypt.org;accounturi={remote_data["acme_account_url"]}"',
) )
append_record(f"_adsp._domainkey.{d}.", "TXT", '"dkim=discardable"')
append_record(f"_submission._tcp.{d}.", "SRV", f"0 1 587 {d}.") append_record(f"_submission._tcp.{d}.", "SRV", f"0 1 587 {d}.")
append_record(f"_submissions._tcp.{d}.", "SRV", f"0 1 465 {d}.") append_record(f"_submissions._tcp.{d}.", "SRV", f"0 1 465 {d}.")
append_record(f"_imap._tcp.{d}.", "SRV", f"0 1 143 {d}.") append_record(f"_imap._tcp.{d}.", "SRV", f"0 1 143 {d}.")
@@ -102,10 +103,7 @@ def check_full_zone(sshexec, remote_data, out, zonefile) -> int:
out("WARNING: these recommended DNS entries are not set:\n") out("WARNING: these recommended DNS entries are not set:\n")
for line in recommended_diff: for line in recommended_diff:
out(line) out(line)
if adsp := remote_data.get("ADSP"):
out("WARNING: this obsolete DNS entry can be deleted:\n")
out(f"_adsp._domainkey.{remote_data['mail_domain']}. TXT {adsp}")
if not (recommended_diff or required_diff or adsp): if not (recommended_diff or required_diff):
out.green("Great! All your DNS entries are verified and correct.") out.green("Great! All your DNS entries are verified and correct.")
return returncode return returncode
+12
View File
@@ -0,0 +1,12 @@
uri = proxy:/run/doveauth/doveauth.socket:auth
iterate_disable = no
iterate_prefix = userdb/
default_pass_scheme = plain
# %E escapes characters " (double quote), ' (single quote) and \ (backslash) with \ (backslash).
# See <https://doc.dovecot.org/2.3/configuration_manual/config_file/config_variables/#modifiers>
# for documentation.
#
# We escape user-provided input and use double quote as a separator.
password_key = passdb/%Ew"%Eu
user_key = userdb/%Eu
-68
View File
@@ -1,68 +0,0 @@
-- Existing addresses are served from the maildir directly.
-- Unknown ones are offered to doveauth, which owns the creation policy.
local mailboxes_dir = "{{ config.mailboxes_dir }}"
local domain_suffix = "@{{ config.mail_domain }}"
local create_url = "http://127.0.0.1:{{ config.doveauth_http_port }}/create"
local http_client
local function is_ours(user)
return user:sub(-#domain_suffix) == domain_suffix
and not user:find("/", 1, true)
end
local function password_hash(user)
local fh = io.open(mailboxes_dir .. "/" .. user .. "/password", "r")
if not fh then
return nil
end
local hash, rest = fh:read("l", "a")
fh:close()
if hash == nil or hash == "" or rest ~= "" then
return nil
end
return hash
end
local function userdb_fields(user)
return {home = mailboxes_dir .. "/" .. user, uid = "vmail", gid = "vmail"}
end
local function create(user, password)
local request = http_client:request({url = create_url, method = "POST"})
request:set_payload(user .. "\t" .. password)
return request:submit():status()
end
-- Entry points called by dovecot
function script_init()
http_client = dovecot.http.client({request_timeout_msecs = 5000, max_attempts = 1})
return 0
end
function auth_userdb_lookup(req)
if not is_ours(req.user) or password_hash(req.user) == nil then
return dovecot.auth.USERDB_RESULT_USER_UNKNOWN, {}
end
return dovecot.auth.USERDB_RESULT_OK, userdb_fields(req.user)
end
function auth_password_verify(req, password)
if not is_ours(req.user) then
return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, {}
end
local hash = password_hash(req.user)
if hash == nil then
-- doveauth refuses with 4xx; dovecot reports its own failures as 9000 and up
local status = create(req.user, password)
if status >= 500 then
return dovecot.auth.PASSDB_RESULT_INTERNAL_FAILURE, {}
elseif status ~= 200 then
return dovecot.auth.PASSDB_RESULT_USER_UNKNOWN, {}
end
elseif req:password_verify(hash, password) ~= 1 then
return dovecot.auth.PASSDB_RESULT_PASSWORD_MISMATCH, {}
end
return dovecot.auth.PASSDB_RESULT_OK, userdb_fields(req.user)
end
+14 -9
View File
@@ -14,9 +14,18 @@ from cmdeploy.basedeploy import (
configure_remote_units, configure_remote_units,
is_in_container, is_in_container,
) )
from cmdeploy.pins import DOVECOT_SHA256, DOVECOT_VERSION
DOVECOT_PACKAGE_VERSION = f"1:{DOVECOT_VERSION}" DOVECOT_ARCHIVE_VERSION = "2.3.21+dfsg1-3"
DOVECOT_PACKAGE_VERSION = f"1:{DOVECOT_ARCHIVE_VERSION}"
DOVECOT_SHA256 = {
("core", "amd64"): "dd060706f52a306fa863d874717210b9fe10536c824afe1790eec247ded5b27d",
("core", "arm64"): "e7548e8a82929722e973629ecc40fcfa886894cef3db88f23535149e7f730dc9",
("imapd", "amd64"): "8d8dc6fc00bbb6cdb25d345844f41ce2f1c53f764b79a838eb2a03103eebfa86",
("imapd", "arm64"): "178fa877ddd5df9930e8308b518f4b07df10e759050725f8217a0c1fb3fd707f",
("lmtpd", "amd64"): "2f69ba5e35363de50962d42cccbfe4ed8495265044e244007d7ccddad77513ab",
("lmtpd", "arm64"): "89f52fb36524f5877a177dff4a713ba771fd3f91f22ed0af7238d495e143b38f",
}
class DovecotDeployer(Deployer): class DovecotDeployer(Deployer):
@@ -31,7 +40,7 @@ class DovecotDeployer(Deployer):
arch = host.get_fact(Arch) arch = host.get_fact(Arch)
with blocked_service_startup(): with blocked_service_startup():
debs = [] debs = []
for pkg in ("core", "imapd", "lmtpd", "auth-lua"): for pkg in ("core", "imapd", "lmtpd"):
deb, changed = _download_dovecot_package(pkg, arch) deb, changed = _download_dovecot_package(pkg, arch)
self.need_restart |= changed self.need_restart |= changed
if deb: if deb:
@@ -108,7 +117,7 @@ def _download_dovecot_package(package: str, arch: str) -> tuple[str | None, bool
if DOVECOT_PACKAGE_VERSION in installed_versions: if DOVECOT_PACKAGE_VERSION in installed_versions:
return None, False return None, False
url_version = DOVECOT_VERSION.replace("+", "%2B") url_version = DOVECOT_ARCHIVE_VERSION.replace("+", "%2B")
deb_base = f"{pkg_name}_{url_version}_{arch}.deb" deb_base = f"{pkg_name}_{url_version}_{arch}.deb"
primary_url = f"https://download.delta.chat/dovecot/{deb_base}" primary_url = f"https://download.delta.chat/dovecot/{deb_base}"
fallback_url = f"https://github.com/chatmail/dovecot/releases/download/upstream%2F{url_version}/{deb_base}" fallback_url = f"https://github.com/chatmail/dovecot/releases/download/upstream%2F{url_version}/{deb_base}"
@@ -133,12 +142,8 @@ def _configure_dovecot(deployer, config: Config, debug: bool = False):
config=config, config=config,
debug=debug, debug=debug,
disable_ipv6=config.disable_ipv6, disable_ipv6=config.disable_ipv6,
config_dir="/etc/dovecot",
dh_path="/usr/share/dovecot/dh.pem",
quota_expire_bin="/usr/local/lib/chatmaild/venv/bin/chatmail-quota-expire",
) )
deployer.put_template("dovecot/auth.lua.j2", "/etc/dovecot/auth.lua", config=config) deployer.put_file("dovecot/auth.conf", "/etc/dovecot/auth.conf")
deployer.remove_file("/etc/dovecot/auth.conf")
deployer.put_file( deployer.put_file(
"dovecot/push_notification.lua", "/etc/dovecot/push_notification.lua" "dovecot/push_notification.lua", "/etc/dovecot/push_notification.lua"
) )
@@ -56,15 +56,17 @@ mail_server_admin = mailto:{{ config.privacy_mail }}
# <https://doc.dovecot.org/2.3/configuration_manual/quota_plugin/> # <https://doc.dovecot.org/2.3/configuration_manual/quota_plugin/>
mail_plugins = zlib quota mail_plugins = zlib quota
imap_capability = +XDELTAPUSH XCHATMAIL
# Authentication for system users. # Authentication for system users.
passdb { passdb {
driver = lua driver = dict
args = file={{ config_dir }}/auth.lua blocking=yes args = /etc/dovecot/auth.conf
} }
userdb { userdb {
driver = lua driver = dict
args = file={{ config_dir }}/auth.lua blocking=yes args = /etc/dovecot/auth.conf
} }
## ##
## Mailbox locations and namespaces ## Mailbox locations and namespaces
@@ -166,7 +168,7 @@ plugin {
} }
service quota-warning { service quota-warning {
executable = script {{ quota_expire_bin }} executable = script /usr/local/lib/chatmaild/venv/bin/chatmail-quota-expire
user = vmail user = vmail
unix_listener quota-warning { unix_listener quota-warning {
user = vmail user = vmail
@@ -177,7 +179,7 @@ service quota-warning {
# push_notification configuration # push_notification configuration
plugin { plugin {
# <https://doc.dovecot.org/2.3/configuration_manual/push_notification/#lua-lua> # <https://doc.dovecot.org/2.3/configuration_manual/push_notification/#lua-lua>
push_notification_driver = lua:file={{ config_dir }}/push_notification.lua push_notification_driver = lua:file=/etc/dovecot/push_notification.lua
} }
service lmtp { service lmtp {
@@ -252,7 +254,7 @@ service anvil {
ssl = required ssl = required
ssl_cert = <{{ config.tls_cert_path }} ssl_cert = <{{ config.tls_cert_path }}
ssl_key = <{{ config.tls_key_path }} ssl_key = <{{ config.tls_key_path }}
ssl_dh = <{{ dh_path }} ssl_dh = </usr/share/dovecot/dh.pem
ssl_min_protocol = TLSv1.3 ssl_min_protocol = TLSv1.3
ssl_prefer_server_ciphers = yes ssl_prefer_server_ciphers = yes
+5 -2
View File
@@ -3,7 +3,6 @@ import os
from pyinfra import facts, host from pyinfra import facts, host
from cmdeploy.basedeploy import Deployer from cmdeploy.basedeploy import Deployer
from cmdeploy.pins import FILTERMAIL_ARTIFACTS
class FiltermailDeployer(Deployer): class FiltermailDeployer(Deployer):
@@ -21,7 +20,11 @@ class FiltermailDeployer(Deployer):
return return
arch = host.get_fact(facts.server.Arch) arch = host.get_fact(facts.server.Arch)
url, sha256sum = FILTERMAIL_ARTIFACTS[arch] url = f"https://github.com/chatmail/filtermail/releases/download/v0.7.4/filtermail-{arch}"
sha256sum = {
"x86_64": "484cb8dff083134aefba9fce4a6b7ef4784a0f0e28e5108ecf8bb9e58a44fd2c",
"aarch64": "66aa0ca2ca9add7a12d92883d76f8786384092adfde24a3d3a1d0b1f30d23a9e",
}[arch]
self.download_executable(url, self.bin_path, sha256sum) self.download_executable(url, self.bin_path, sha256sum)
def configure(self): def configure(self):
@@ -2,7 +2,7 @@
Description=Iroh relay Description=Iroh relay
[Service] [Service]
ExecStart={{ bin_path }} --config-path {{ config_path }} ExecStart=/usr/local/bin/iroh-relay --config-path /etc/iroh-relay.toml
Restart=on-failure Restart=on-failure
RestartSec=5s RestartSec=5s
User=iroh User=iroh
+13 -31
View File
@@ -1,14 +1,10 @@
from pyinfra import facts, host from pyinfra import facts, host
from pyinfra.operations import apt, server from pyinfra.operations import apt
from cmdeploy.basedeploy import Deployer from cmdeploy.basedeploy import Deployer
from cmdeploy.pins import FILTERMAIL_ARTIFACTS, MTAIL_ARTIFACTS
class MtailDeployer(Deployer): class MtailDeployer(Deployer):
bin_path = "/usr/local/bin/mtail"
progs_dir = "/etc/mtail"
def __init__(self, mtail_address): def __init__(self, mtail_address):
self.mtail_address = mtail_address self.mtail_address = mtail_address
@@ -16,10 +12,19 @@ class MtailDeployer(Deployer):
# Uninstall mtail package to install a static binary. # Uninstall mtail package to install a static binary.
apt.packages(name="Uninstall mtail", packages=["mtail"], present=False) apt.packages(name="Uninstall mtail", packages=["mtail"], present=False)
(url, sha256sum) = MTAIL_ARTIFACTS[host.get_fact(facts.server.Arch)] (url, sha256sum) = {
"x86_64": (
"https://github.com/google/mtail/releases/download/v3.0.8/mtail_3.0.8_linux_amd64.tar.gz",
"d55cb601049c5e61eabab29998dbbcea95d480e5448544f9470337ba2eea882e",
),
"aarch64": (
"https://github.com/google/mtail/releases/download/v3.0.8/mtail_3.0.8_linux_arm64.tar.gz",
"f748db8ad2a1e0b63684d4c8868cf6a373a20f7e6922e5ece601fff0ee00eb1a",
),
}[host.get_fact(facts.server.Arch)]
self.download_executable( self.download_executable(
url, url,
self.bin_path, "/usr/local/bin/mtail",
sha256sum, sha256sum,
extract="gunzip | tar -xf - mtail -O", extract="gunzip | tar -xf - mtail -O",
) )
@@ -31,31 +36,8 @@ class MtailDeployer(Deployer):
"mtail/mtail.service.j2", "mtail/mtail.service.j2",
address=self.mtail_address or "127.0.0.1", address=self.mtail_address or "127.0.0.1",
port=3903, port=3903,
bin_path=self.bin_path,
progs_dir=self.progs_dir,
) )
if self.mtail_address: self.put_file("mtail/delivered_mail.mtail", "/etc/mtail/delivered_mail.mtail")
self.put_file(
"mtail/delivered_mail.mtail", f"{self.progs_dir}/delivered_mail.mtail"
)
url, sha256sum = FILTERMAIL_ARTIFACTS['mtail']
self.download_executable(
url,
f"{self.progs_dir}/filtermail.mtail",
sha256sum,
mode="644",
)
if self.need_restart:
# Check if all installed mtail rules compile or fail early
# --one_shot to exit, --port 0 to not clash with running mtail.
server.shell(
name="Validate mtail programs",
commands=[
f"timeout 30 {self.bin_path} --compile_only --one_shot"
f" --progs {self.progs_dir} --logs /dev/null"
" --address 127.0.0.1 --port 0"
],
)
def activate(self): def activate(self):
active = bool(self.mtail_address) active = bool(self.mtail_address)
+1 -1
View File
@@ -5,7 +5,7 @@ Wants=network-online.target
[Service] [Service]
Type=simple Type=simple
ExecStart=/bin/sh -c "journalctl -f -o short-iso -n 0 | {{ bin_path }} --address={{ address }} --port={{ port }} --progs {{ progs_dir }} --logtostderr --logs -" ExecStart=/bin/sh -c "journalctl -f -o short-iso -n 0 | /usr/local/bin/mtail --address={{ address }} --port={{ port }} --progs /etc/mtail --logtostderr --logs -"
Restart=on-failure Restart=on-failure
RestartSec=2s RestartSec=2s
-4
View File
@@ -55,10 +55,6 @@ def _configure_nginx(deployer, config: Config, debug: bool = False):
"/etc/nginx/nginx.conf", "/etc/nginx/nginx.conf",
config=config, config=config,
disable_ipv6=config.disable_ipv6, disable_ipv6=config.disable_ipv6,
config_dir="/etc/nginx",
stream_module="modules/ngx_stream_module.so",
www_root="/var/www/html",
cgi_dir="/usr/lib/cgi-bin",
) )
deployer.put_template( deployer.put_template(
+21 -13
View File
@@ -1,4 +1,4 @@
{% if stream_module %}load_module {{ stream_module }};{% endif %} load_module modules/ngx_stream_module.so;
user www-data; user www-data;
worker_processes auto; worker_processes auto;
@@ -54,7 +54,7 @@ http {
# Do not emit nginx version on error pages. # Do not emit nginx version on error pages.
server_tokens off; server_tokens off;
include {{ config_dir }}/mime.types; include /etc/nginx/mime.types;
default_type application/octet-stream; default_type application/octet-stream;
ssl_protocols TLSv1.2 TLSv1.3; ssl_protocols TLSv1.2 TLSv1.3;
@@ -68,19 +68,13 @@ http {
listen 127.0.0.1:8443 ssl default_server; listen 127.0.0.1:8443 ssl default_server;
# nginx is reached through the stream proxy on port 443, root /var/www/html;
# so redirects it generates itself (e.g. /dir -> /dir/)
# must not contain the internal port 8443.
absolute_redirect off;
root {{ www_root }};
index index.html index.htm; index index.html index.htm;
server_name {{ config.mail_domain }} mta-sts.{{ config.mail_domain }}; server_name {{ config.mail_domain }} mta-sts.{{ config.mail_domain }};
location /mxdeliv { location /mxdeliv {
client_max_body_size {{ config.max_message_size }};
proxy_pass http://127.0.0.1:{{ config.filtermail_http_port_incoming }}; proxy_pass http://127.0.0.1:{{ config.filtermail_http_port_incoming }};
} }
@@ -102,8 +96,8 @@ http {
{% endif %} {% endif %}
fastcgi_pass unix:/run/fcgiwrap.socket; fastcgi_pass unix:/run/fcgiwrap.socket;
include {{ config_dir }}/fastcgi_params; include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME {{ cgi_dir }}/newemail.py; fastcgi_param SCRIPT_FILENAME /usr/lib/cgi-bin/newemail.py;
} }
# Old URL for compatibility with e.g. printed QR codes. # Old URL for compatibility with e.g. printed QR codes.
@@ -120,8 +114,8 @@ http {
{% endif %} {% endif %}
fastcgi_pass unix:/run/fcgiwrap.socket; fastcgi_pass unix:/run/fcgiwrap.socket;
include {{ config_dir }}/fastcgi_params; include /etc/nginx/fastcgi_params;
fastcgi_param SCRIPT_FILENAME {{ cgi_dir }}/newemail.py; fastcgi_param SCRIPT_FILENAME /usr/lib/cgi-bin/newemail.py;
} }
# Proxy to iroh-relay service. # Proxy to iroh-relay service.
@@ -146,6 +140,20 @@ http {
proxy_pass http://127.0.0.1:3340; proxy_pass http://127.0.0.1:3340;
proxy_http_version 1.1; proxy_http_version 1.1;
} }
location /imap {
proxy_pass http://127.0.0.1:8143;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location /smtp {
proxy_pass http://127.0.0.1:8587;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
} }
# Redirect www. to non-www # Redirect www. to non-www
+1 -1
View File
@@ -1 +1 @@
{{ config.opendkim_selector }}._domainkey.{{ config.domain_name }} {{ config.domain_name }}:{{ config.opendkim_selector }}:{{ keys_dir }}/{{ config.opendkim_selector }}.private {{ config.opendkim_selector }}._domainkey.{{ config.domain_name }} {{ config.domain_name }}:{{ config.opendkim_selector }}:/etc/dkimkeys/{{ config.opendkim_selector }}.private
@@ -30,8 +30,6 @@ class OpendkimDeployer(Deployer):
"opendkim/opendkim.conf", "opendkim/opendkim.conf",
"/etc/opendkim.conf", "/etc/opendkim.conf",
config={"domain_name": domain, "opendkim_selector": dkim_selector}, config={"domain_name": domain, "opendkim_selector": dkim_selector},
keys_dir="/etc/dkimkeys",
trust_anchor="/usr/share/dns/root.key",
) )
self.remove_file("/etc/opendkim/screen.lua") self.remove_file("/etc/opendkim/screen.lua")
@@ -48,7 +46,6 @@ class OpendkimDeployer(Deployer):
"/etc/dkimkeys/KeyTable", "/etc/dkimkeys/KeyTable",
owner="opendkim", owner="opendkim",
config={"domain_name": domain, "opendkim_selector": dkim_selector}, config={"domain_name": domain, "opendkim_selector": dkim_selector},
keys_dir="/etc/dkimkeys",
) )
self.put_template( self.put_template(
+4 -4
View File
@@ -21,9 +21,9 @@ DNSTimeout 60
# setup options can be found in /usr/share/doc/opendkim/README.opendkim. # setup options can be found in /usr/share/doc/opendkim/README.opendkim.
Domain {{ config.domain_name }} Domain {{ config.domain_name }}
Selector {{ config.opendkim_selector }} Selector {{ config.opendkim_selector }}
KeyFile {{ keys_dir }}/{{ config.opendkim_selector }}.private KeyFile /etc/dkimkeys/{{ config.opendkim_selector }}.private
KeyTable {{ keys_dir }}/KeyTable KeyTable /etc/dkimkeys/KeyTable
SigningTable refile:{{ keys_dir }}/SigningTable SigningTable refile:/etc/dkimkeys/SigningTable
# Sign Autocrypt header in addition to the default specified in RFC 6376. # Sign Autocrypt header in addition to the default specified in RFC 6376.
# #
@@ -58,7 +58,7 @@ PidFile /run/opendkim/opendkim.pid
# The trust anchor enables DNSSEC. In Debian, the trust anchor file is provided # The trust anchor enables DNSSEC. In Debian, the trust anchor file is provided
# by the package dns-root-data. # by the package dns-root-data.
TrustAnchorFile {{ trust_anchor }} TrustAnchorFile /usr/share/dns/root.key
# Sign messages when `-o milter_macro_daemon_name=ORIGINATING` is set. # Sign messages when `-o milter_macro_daemon_name=ORIGINATING` is set.
MTA ORIGINATING MTA ORIGINATING
-64
View File
@@ -1,64 +0,0 @@
"""Versions, hashes, and download URLs for pre-built artifacts fetched during deploy."""
FILTERMAIL_VERSION = "v0.7.10"
FILTERMAIL_ARTIFACTS = {
"x86_64": (
f"https://github.com/chatmail/filtermail/releases/download/{FILTERMAIL_VERSION}/filtermail-x86_64",
"c800e39e37d81c504f48dee2e61c10fcdd679c23e7ab958d6f0e6413c19d2be3",
),
"aarch64": (
f"https://github.com/chatmail/filtermail/releases/download/{FILTERMAIL_VERSION}/filtermail-aarch64",
"eaf2a46c7c39e898bb37b82716a0a866cea5bbbc642675c78c259e0f98517ceb",
),
"mtail": (
f"https://raw.githubusercontent.com/chatmail/filtermail/{FILTERMAIL_VERSION}/contrib/filtermail.mtail",
"948f688bb89ad47e6eb0fc8fa107e201a689f5adc264ff926be487a2a8562b51",
),
}
MTAIL_VERSION = "3.4.9"
MTAIL_ARTIFACTS = {
"x86_64": (
f"https://github.com/jaqx0r/mtail/releases/download/v{MTAIL_VERSION}/mtail_{MTAIL_VERSION}_linux_amd64.tar.gz",
"55f64a87f71955bb871c724b4aadf19fe9d854e6327196919c7fe44943427eab",
),
"aarch64": (
f"https://github.com/jaqx0r/mtail/releases/download/v{MTAIL_VERSION}/mtail_{MTAIL_VERSION}_linux_arm64.tar.gz",
"e0a2b66b372ca257d7daeb7ba10f9233a2192a1f9057618fccc6be5c854a2a3c",
),
}
DOVECOT_VERSION = "2.3.21+dfsg1-3"
DOVECOT_SHA256 = {
("core", "amd64"): "dd060706f52a306fa863d874717210b9fe10536c824afe1790eec247ded5b27d",
("core", "arm64"): "e7548e8a82929722e973629ecc40fcfa886894cef3db88f23535149e7f730dc9",
("imapd", "amd64"): "8d8dc6fc00bbb6cdb25d345844f41ce2f1c53f764b79a838eb2a03103eebfa86",
("imapd", "arm64"): "178fa877ddd5df9930e8308b518f4b07df10e759050725f8217a0c1fb3fd707f",
("lmtpd", "amd64"): "2f69ba5e35363de50962d42cccbfe4ed8495265044e244007d7ccddad77513ab",
("lmtpd", "arm64"): "89f52fb36524f5877a177dff4a713ba771fd3f91f22ed0af7238d495e143b38f",
("auth-lua", "amd64"): "d724f37712faba52e177153114af1831e54da555c57c6474c05f96f176176ce4",
("auth-lua", "arm64"): "7272768e20de148c35891d99cd60205acbe7e732b056caf0a83e8194d49136e6",
}
TURN_VERSION = "v0.4"
TURN_ARTIFACTS = {
"x86_64": (
f"https://github.com/chatmail/chatmail-turn/releases/download/{TURN_VERSION}/chatmail-turn-x86_64-linux",
"1ec1f5c50122165e858a5a91bcba9037a28aa8cb8b64b8db570aa457c6141a8a",
),
"aarch64": (
f"https://github.com/chatmail/chatmail-turn/releases/download/{TURN_VERSION}/chatmail-turn-aarch64-linux",
"0fb3e792419494e21ecad536464929dba706bb2c88884ed8f1788141d26fc756",
),
}
IROH_VERSION = "v0.35.0"
IROH_ARTIFACTS = {
"x86_64": (
f"https://github.com/n0-computer/iroh/releases/download/{IROH_VERSION}/iroh-relay-{IROH_VERSION}-x86_64-unknown-linux-musl.tar.gz",
"45c81199dbd70f8c4c30fef7f3b9727ca6e3cea8f2831333eeaf8aa71bf0fac1",
),
"aarch64": (
f"https://github.com/n0-computer/iroh/releases/download/{IROH_VERSION}/iroh-relay-{IROH_VERSION}-aarch64-unknown-linux-musl.tar.gz",
"f8ef27631fac213b3ef668d02acd5b3e215292746a3fc71d90c63115446008b1",
),
}
@@ -24,8 +24,6 @@ class PostfixDeployer(Deployer):
"/etc/postfix/main.cf", "/etc/postfix/main.cf",
config=config, config=config,
disable_ipv6=config.disable_ipv6, disable_ipv6=config.disable_ipv6,
config_dir="/etc/postfix",
ca_path="/etc/ssl/certs",
) )
self.put_template( self.put_template(
@@ -33,7 +31,6 @@ class PostfixDeployer(Deployer):
"/etc/postfix/master.cf", "/etc/postfix/master.cf",
debug=False, debug=False,
config=config, config=config,
config_dir="/etc/postfix",
) )
self.put_file( self.put_file(
+4 -5
View File
@@ -19,13 +19,13 @@ smtpd_tls_cert_file={{ config.tls_cert_path }}
smtpd_tls_key_file={{ config.tls_key_path }} smtpd_tls_key_file={{ config.tls_key_path }}
smtpd_tls_security_level=may smtpd_tls_security_level=may
smtp_tls_CApath={{ ca_path }} smtp_tls_CApath=/etc/ssl/certs
smtp_tls_security_level=verify smtp_tls_security_level=verify
# Send SNI extension when connecting to other servers. # Send SNI extension when connecting to other servers.
# <https://www.postfix.org/postconf.5.html#smtp_tls_servername> # <https://www.postfix.org/postconf.5.html#smtp_tls_servername>
smtp_tls_servername = hostname smtp_tls_servername = hostname
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache
smtp_tls_policy_maps = regexp:{{ config_dir }}/smtp_tls_policy_map smtp_tls_policy_maps = regexp:/etc/postfix/smtp_tls_policy_map
smtp_tls_protocols = >=TLSv1.2 smtp_tls_protocols = >=TLSv1.2
smtp_tls_mandatory_protocols = >=TLSv1.2 smtp_tls_mandatory_protocols = >=TLSv1.2
@@ -83,7 +83,7 @@ inet_protocols = ipv4
inet_protocols = all inet_protocols = all
{% endif %} {% endif %}
lmtp_header_checks = regexp:{{ config_dir }}/lmtp_header_cleanup lmtp_header_checks = regexp:/etc/postfix/lmtp_header_cleanup
# Do not apply header checks to MIME headers # Do not apply header checks to MIME headers
# and other headers that are actually part of the message body. # and other headers that are actually part of the message body.
@@ -98,7 +98,7 @@ mua_sender_restrictions = reject_sender_login_mismatch, permit_sasl_authenticate
mua_helo_restrictions = permit_mynetworks, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, permit mua_helo_restrictions = permit_mynetworks, reject_invalid_helo_hostname, reject_non_fqdn_helo_hostname, permit
# 1:1 map MAIL FROM to SASL login name. # 1:1 map MAIL FROM to SASL login name.
smtpd_sender_login_maps = regexp:{{ config_dir }}/login_map smtpd_sender_login_maps = regexp:/etc/postfix/login_map
# Do not lookup SMTP client hostnames to reduce delays # Do not lookup SMTP client hostnames to reduce delays
# and avoid unnecessary DNS requests. # and avoid unnecessary DNS requests.
@@ -127,7 +127,6 @@ lmtp-filtermail_destination_concurrency_limit=10000
# Do not try to deliver messages for more than 2 days. # Do not try to deliver messages for more than 2 days.
maximal_queue_lifetime = 2d maximal_queue_lifetime = 2d
bounce_queue_lifetime = 2d
{% if not config.ipv4_relay %} {% if not config.ipv4_relay %}
# DKIM-sign locally generated mail (bounces, DSNs). # DKIM-sign locally generated mail (bounces, DSNs).
+1 -1
View File
@@ -102,7 +102,7 @@ postlog unix-dgram n - n - 1 postlogd
# to make sure the users # to make sure the users
# cannot send unprotected Subject. # cannot send unprotected Subject.
authclean unix n - - - 0 cleanup authclean unix n - - - 0 cleanup
-o header_checks=regexp:{{ config_dir }}/submission_header_cleanup -o header_checks=regexp:/etc/postfix/submission_header_cleanup
# Reducing `maxproc` here may result in a head of line blocking # Reducing `maxproc` here may result in a head of line blocking
# when there are many messages sent to unreachable destinations # when there are many messages sent to unreachable destinations
-1
View File
@@ -26,7 +26,6 @@ def perform_initial_checks(mail_domain, pre_command=""):
WWW = query_dns("CNAME", f"www.{mail_domain}") WWW = query_dns("CNAME", f"www.{mail_domain}")
res = dict(mail_domain=mail_domain, A=A, AAAA=AAAA, MTA_STS=MTA_STS, WWW=WWW) res = dict(mail_domain=mail_domain, A=A, AAAA=AAAA, MTA_STS=MTA_STS, WWW=WWW)
res["ADSP"] = query_dns("TXT", f"_adsp._domainkey.{mail_domain}")
res["acme_account_url"] = shell( res["acme_account_url"] = shell(
pre_command + "acmetool account-url", fail_ok=True, print=log_progress pre_command + "acmetool account-url", fail_ok=True, print=log_progress
) )
@@ -5,5 +5,5 @@ After=network.target
[Service] [Service]
Type=oneshot Type=oneshot
User=vmail User=vmail
ExecStart={execpath} {config_path} -v --remove ExecStart=/usr/local/lib/chatmaild/venv/bin/chatmail-expire /usr/local/lib/chatmaild/chatmail.ini -v --remove
@@ -0,0 +1,9 @@
[Unit]
Description=chatmail file system storage reporting job
After=network.target
[Service]
Type=oneshot
User=vmail
ExecStart=/usr/local/lib/chatmaild/venv/bin/chatmail-fsreport /usr/local/lib/chatmaild/chatmail.ini
@@ -0,0 +1,9 @@
[Unit]
Description=Run Daily Chatmail fsreport Job
[Timer]
OnCalendar=*-*-* 08:02:00
Persistent=true
[Install]
WantedBy=timers.target
@@ -1,11 +1,12 @@
[Unit] [Unit]
Description=Chatmail HTTP authentication service for dovecot Description=Chatmail dict authentication proxy for dovecot
[Service] [Service]
ExecStart={execpath} {config_path} ExecStart={execpath} /run/doveauth/doveauth.socket {config_path}
Restart=always Restart=always
RestartSec=5 RestartSec=30
User=vmail User=vmail
RuntimeDirectory=doveauth
UMask=0077 UMask=0077
[Install] [Install]
@@ -5,7 +5,7 @@ After=network.target
[Service] [Service]
Type=simple Type=simple
Restart=always Restart=always
ExecStart={bin_path} --realm {mail_domain} --socket /run/chatmail-turn/turn.socket ExecStart=/usr/local/bin/chatmail-turn --realm {mail_domain} --socket /run/chatmail-turn/turn.socket
# Create /run/chatmail-turn # Create /run/chatmail-turn
RuntimeDirectory=chatmail-turn RuntimeDirectory=chatmail-turn
-27
View File
@@ -1,27 +0,0 @@
"""Run the lua scripts we ship under lupa, which bundles Lua 5.4 like dovecot."""
import pytest
from chatmaild.tests.plugin import * # noqa: F403
from lupa import lua54
from cmdeploy.basedeploy import get_resource
from cmdeploy.tests.plugin import * # noqa: F403
class Lua:
"""A Lua runtime to load shipped scripts and mocks into."""
def __init__(self):
self.rt = lua54.LuaRuntime(unpack_returned_tuples=True)
self.g = self.rt.globals()
def load(self, path):
self.rt.execute(get_resource(path).read_text())
def table(self, **kwargs):
return self.rt.table(**kwargs)
@pytest.fixture
def lua():
return Lua()
@@ -11,6 +11,7 @@ opendkim._domainkey.zftest.testrun.org. 3600 IN TXT "v=DKIM1;k=rsa;p=MIIB
zftest.testrun.org. 3600 IN TXT "v=spf1 a ~all" zftest.testrun.org. 3600 IN TXT "v=spf1 a ~all"
_dmarc.zftest.testrun.org. 3600 IN TXT "v=DMARC1;p=reject;adkim=s;aspf=s" _dmarc.zftest.testrun.org. 3600 IN TXT "v=DMARC1;p=reject;adkim=s;aspf=s"
zftest.testrun.org. 3600 IN CAA 0 issue "letsencrypt.org;accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/1371472956" zftest.testrun.org. 3600 IN CAA 0 issue "letsencrypt.org;accounturi=https://acme-v02.api.letsencrypt.org/acme/acct/1371472956"
_adsp._domainkey.zftest.testrun.org. 3600 IN TXT "dkim=discardable"
_submission._tcp.zftest.testrun.org. 3600 IN SRV 0 1 587 zftest.testrun.org. _submission._tcp.zftest.testrun.org. 3600 IN SRV 0 1 587 zftest.testrun.org.
_submissions._tcp.zftest.testrun.org. 3600 IN SRV 0 1 465 zftest.testrun.org. _submissions._tcp.zftest.testrun.org. 3600 IN SRV 0 1 465 zftest.testrun.org.
_imap._tcp.zftest.testrun.org. 3600 IN SRV 0 1 143 zftest.testrun.org. _imap._tcp.zftest.testrun.org. 3600 IN SRV 0 1 143 zftest.testrun.org.
@@ -15,6 +15,13 @@ def test_init(tmp_path, maildomain):
assert config.mail_domain_bare == maildomain assert config.mail_domain_bare == maildomain
def test_capabilities(imap):
imap.connect()
capas = imap.conn.capabilities
assert "XCHATMAIL" in capas
assert "XDELTAPUSH" in capas
def test_login_basic_functioning(imap_or_smtp, gencreds, lp): def test_login_basic_functioning(imap_or_smtp, gencreds, lp):
"""Test a) that an initial login creates a user automatically """Test a) that an initial login creates a user automatically
and b) verify we can also login a second time with the same password and b) verify we can also login a second time with the same password
@@ -84,7 +91,7 @@ def test_concurrent_logins_same_account(
def test_no_vrfy(cmfactory, chatmail_config, maildomain): def test_no_vrfy(cmfactory, chatmail_config, maildomain):
ac = cmfactory.get_online_account() ac = cmfactory.get_online_account()
addr = ac.list_transports()[0]["addr"] addr = ac.get_config("addr")
s = smtplib.SMTP(maildomain) s = smtplib.SMTP(maildomain)
s.starttls() s.starttls()
@@ -20,17 +20,17 @@ def test_fastcgi_working(maildomain, chatmail_config):
@pytest.mark.filterwarnings("ignore::urllib3.exceptions.InsecureRequestWarning") @pytest.mark.filterwarnings("ignore::urllib3.exceptions.InsecureRequestWarning")
def test_newemail_configure(maildomain, cmrpc, chatmail_config): def test_newemail_configure(maildomain, rpc, chatmail_config):
"""Test configuring accounts by scanning a QR code works.""" """Test configuring accounts by scanning a QR code works."""
url = f"DCACCOUNT:https://{maildomain}/new" url = f"DCACCOUNT:https://{maildomain}/new"
for i in range(3): for i in range(3):
account_id = cmrpc.add_account() account_id = rpc.add_account()
if chatmail_config.tls_cert_mode == "self": if chatmail_config.tls_cert_mode == "self":
# deltachat core's rustls rejects self-signed HTTPS certs during # deltachat core's rustls rejects self-signed HTTPS certs during
# set_config_from_qr, so fetch credentials via requests instead # set_config_from_qr, so fetch credentials via requests instead
res = requests.post(f"https://{maildomain}/new", verify=False) res = requests.post(f"https://{maildomain}/new", verify=False)
data = res.json() data = res.json()
cmrpc.add_or_update_transport(account_id, { rpc.add_or_update_transport(account_id, {
"addr": data["email"], "addr": data["email"],
"password": data["password"], "password": data["password"],
"imapServer": maildomain, "imapServer": maildomain,
@@ -38,4 +38,4 @@ def test_newemail_configure(maildomain, cmrpc, chatmail_config):
"certificateChecks": "acceptInvalidCertificates", "certificateChecks": "acceptInvalidCertificates",
}) })
else: else:
cmrpc.add_transport_from_qr(account_id, url) rpc.add_transport_from_qr(account_id, url)
@@ -5,7 +5,6 @@ import subprocess
import time import time
import pytest import pytest
import requests
from chatmaild.config import is_valid_ipv4 from chatmaild.config import is_valid_ipv4
from cmdeploy import remote from cmdeploy import remote
@@ -133,8 +132,8 @@ def test_use_two_chatmailservers(cmfactory, maildomain2):
ac1 = cmfactory.get_online_account() ac1 = cmfactory.get_online_account()
ac2 = cmfactory.get_online_account(domain=maildomain2) ac2 = cmfactory.get_online_account(domain=maildomain2)
cmfactory.get_accepted_chat(ac1, ac2) cmfactory.get_accepted_chat(ac1, ac2)
domain1 = ac1.list_transports()[0]["addr"].split("@")[1] domain1 = ac1.get_config("addr").split("@")[1]
domain2 = ac2.list_transports()[0]["addr"].split("@")[1] domain2 = ac2.get_config("addr").split("@")[1]
assert domain1 != domain2 assert domain1 != domain2
@@ -327,14 +326,3 @@ def test_nginx_access_log_only_defined_once(sshdomain):
assert len(access_logs) == 1, ( assert len(access_logs) == 1, (
f"expected 1 access_log, found {len(access_logs)}: {access_logs}" f"expected 1 access_log, found {len(access_logs)}: {access_logs}"
) )
@pytest.mark.filterwarnings("ignore::urllib3.exceptions.InsecureRequestWarning")
def test_mxdeliv_respects_max_message_size(maildomain, chatmail_config):
url = f"https://{maildomain}/mxdeliv"
verify = chatmail_config.tls_cert_mode == "acme"
size = chatmail_config.max_message_size
res = requests.post(url, data=b"x" * size, verify=verify)
assert res.text == "500 Invalid DATA"
res = requests.post(url, data=b"x" * (size + 1), verify=verify)
assert res.status_code == 413
@@ -1,12 +1,10 @@
import ipaddress import ipaddress
import json
import re import re
import time import time
import imap_tools import imap_tools
import pytest import pytest
import requests import requests
from chatmaild.tests.test_appversions import check_appversions
from cmdeploy.cmdeploy import get_sshexec from cmdeploy.cmdeploy import get_sshexec
from cmdeploy.remote import rshell from cmdeploy.remote import rshell
@@ -15,10 +13,8 @@ from cmdeploy.remote import rshell
@pytest.fixture @pytest.fixture
def imap_mailbox(cmfactory, ssl_context): def imap_mailbox(cmfactory, ssl_context):
(ac1,) = cmfactory.get_online_accounts(1) (ac1,) = cmfactory.get_online_accounts(1)
# Delta Chat 2.63 stopped writing the legacy addr and mail_pw config keys. user = ac1.get_config("addr")
transport = ac1.list_transports()[0] password = ac1.get_config("mail_pw")
user = transport["addr"]
password = transport["password"]
host = user.split("@")[1].strip("[").strip("]") host = user.split("@")[1].strip("[").strip("]")
mailbox = imap_tools.MailBox(host, ssl_context=ssl_context) mailbox = imap_tools.MailBox(host, ssl_context=ssl_context)
mailbox.login(user, password) mailbox.login(user, password)
@@ -55,17 +51,6 @@ class TestMetadataTokens:
assert res == b"1111 2222" assert res == b"1111 2222"
assert b"Getmetadata completed" in client.readline() assert b"Getmetadata completed" in client.readline()
def test_get_appversions(self, imap_mailbox):
"get app version information shipped with the relay"
client = imap_mailbox.client
client.send(b'a01 GETMETADATA "" /shared/vendor/deltachat/appversions\n')
res = client.readline()
assert res[:1] == b"*"
res = client.readline().strip().rstrip(b")")
# the served value is a single line and passes the shipped file's schema
check_appversions(json.loads(res))
assert b"Getmetadata completed" in client.readline()
class TestEndToEndDeltaChat: class TestEndToEndDeltaChat:
"Tests that use Delta Chat accounts on the chat mail instance." "Tests that use Delta Chat accounts on the chat mail instance."
@@ -90,7 +75,7 @@ class TestEndToEndDeltaChat:
ac1, ac2 = cmfactory.get_online_accounts(2) ac1, ac2 = cmfactory.get_online_accounts(2)
chat = cmfactory.get_accepted_chat(ac1, ac2) chat = cmfactory.get_accepted_chat(ac1, ac2)
user = ac2.list_transports()[0]["addr"] user = ac2.get_config("configured_addr")
def parse_size_limit(limit: str) -> int: def parse_size_limit(limit: str) -> int:
"""Parse a size limit and return the number of bytes as integer. """Parse a size limit and return the number of bytes as integer.
@@ -192,10 +177,9 @@ def test_hide_senders_ip_address(cmfactory, ssl_context):
chat.send_text("testing submission header cleanup") chat.send_text("testing submission header cleanup")
user2.wait_for_incoming_msg() user2.wait_for_incoming_msg()
transport = user2.list_transports()[0] addr = user2.get_config("addr")
addr = transport["addr"]
host = addr.split("@")[1].strip("[").strip("]") host = addr.split("@")[1].strip("[").strip("]")
pw = transport["password"] pw = user2.get_config("mail_pw")
mailbox = imap_tools.MailBox(host, ssl_context=ssl_context) mailbox = imap_tools.MailBox(host, ssl_context=ssl_context)
mailbox.login(addr, pw) mailbox.login(addr, pw)
msgs = list(mailbox.fetch(mark_seen=False)) msgs = list(mailbox.fetch(mark_seen=False))
+11 -9
View File
@@ -18,8 +18,14 @@ def format_mail_domain(raw_domain: str) -> str:
return raw_domain return raw_domain
conftestdir = Path(__file__).parent
def pytest_configure(config): def pytest_configure(config):
config._benchresults = {} config._benchresults = {}
config.addinivalue_line(
"markers", "slow: mark test to require --slow option to run"
)
def _get_chatmail_config(): def _get_chatmail_config():
@@ -205,7 +211,7 @@ class ImapConn:
status, res = self.conn.select() status, res = self.conn.select()
if int(res[0]) == 0: if int(res[0]) == 0:
raise ValueError("no messages in imap folder") raise ValueError("no messages in imap folder")
status, results = self.conn.fetch("1:*", "(BODY.PEEK[])") status, results = self.conn.fetch("1:*", "(RFC822)")
assert status == "OK" assert status == "OK"
return results return results
@@ -371,12 +377,8 @@ class ChatmailACFactory:
@pytest.fixture(scope="session") @pytest.fixture(scope="session")
def cmrpc(tmp_path_factory): def rpc(tmp_path_factory):
"""Start a deltachat-rpc-server process for the test session. """Start a deltachat-rpc-server process for the test session."""
Not named "rpc": the deltachat-rpc-client pytest plugin registers a
function-scoped fixture under that name and would shadow this one.
"""
# NB: accounts_dir must NOT already exist as directory -- # NB: accounts_dir must NOT already exist as directory --
# core-rust only creates accounts.toml if the dir doesn't exist yet. # core-rust only creates accounts.toml if the dir doesn't exist yet.
@@ -388,10 +390,10 @@ def cmrpc(tmp_path_factory):
@pytest.fixture @pytest.fixture
def cmfactory(cmrpc, gencreds, maildomain, chatmail_config): def cmfactory(rpc, gencreds, maildomain, chatmail_config):
"""Return a ChatmailACFactory for creating online Delta Chat accounts.""" """Return a ChatmailACFactory for creating online Delta Chat accounts."""
return ChatmailACFactory( return ChatmailACFactory(
rpc=cmrpc, rpc=rpc,
maildomain=maildomain, maildomain=maildomain,
gencreds=gencreds, gencreds=gencreds,
chatmail_config=chatmail_config, chatmail_config=chatmail_config,
+2
View File
@@ -0,0 +1,2 @@
[pytest]
addopts = -vrsx --strict-markers
-216
View File
@@ -1,216 +0,0 @@
"""Test auth.lua script against mocked dovecot auth API."""
import jinja2
import pytest
from chatmaild.doveauth import encrypt_password, verify_password
from cmdeploy.basedeploy import get_resource
USER1 = "user12345@chat.example.org"
USER2 = "newuser12@chat.example.org"
OK, UNKNOWN, MISMATCH, INTERNAL = 1, -2, -3, -4
DOVECOT_MOCKS = """
create_status = 200
dovecot = {
auth = {
PASSDB_RESULT_OK = OK,
PASSDB_RESULT_USER_UNKNOWN = UNKNOWN,
PASSDB_RESULT_PASSWORD_MISMATCH = MISMATCH,
PASSDB_RESULT_INTERNAL_FAILURE = INTERNAL,
USERDB_RESULT_OK = OK,
USERDB_RESULT_USER_UNKNOWN = UNKNOWN,
},
http = {
client = function(options)
client_options = options
return {request = function(_, options)
create_request = options
return {
set_payload = function(_, payload) create_payload = payload end,
submit = function()
return {status = function() return create_status end}
end,
}
end}
end,
},
}
"""
def load_authlua(lua, config):
lua.g.OK, lua.g.UNKNOWN = OK, UNKNOWN
lua.g.MISMATCH, lua.g.INTERNAL = MISMATCH, INTERNAL
lua.rt.execute(DOVECOT_MOCKS)
template = jinja2.Template(get_resource("dovecot/auth.lua.j2").read_text())
lua.rt.execute(template.render(config=config))
assert lua.g.script_init() == 0
return lua
@pytest.fixture
def authlua(lua, example_config):
return load_authlua(lua, example_config)
@pytest.fixture
def request_for(lua):
def request_for(addr):
def password_verify(_self, hashed, plain):
return 1 if verify_password(hashed, plain) else 0
return lua.table(user=addr, password_verify=password_verify)
return request_for
@pytest.fixture
def create_user(example_config):
def create_user(addr, password):
example_config.get_user(addr).set_password(encrypt_password(password))
return create_user
@pytest.fixture
def write_password_file(example_config):
def write_password_file(addr, content):
maildir = example_config.mailboxes_dir / addr
maildir.mkdir(parents=True, exist_ok=True)
maildir.joinpath("password").write_text(content)
return write_password_file
def test_http_client_uses_dovecot_setting_names(authlua):
"""dovecot's lua http binding silently ignores keys it does not know."""
assert dict(authlua.g.client_options) == {
"request_timeout_msecs": 5000,
"max_attempts": 1,
}
def test_existing_address_correct_password(authlua, request_for, create_user):
create_user(USER1, "correctgoose")
res, fields = authlua.g.auth_password_verify(request_for(USER1), "correctgoose")
assert res == OK
assert fields["uid"] == fields["gid"] == "vmail"
assert fields["home"].endswith(USER1)
assert authlua.g.create_payload is None
def test_existing_address_wrong_password(authlua, request_for, create_user):
create_user(USER1, "correctgoose")
res, _ = authlua.g.auth_password_verify(request_for(USER1), "wronghorse")
assert res == MISMATCH
def test_foreign_domain_is_refused_without_calling_out(
authlua, request_for, create_user
):
create_user("user12345@evil.example.org", "correctgoose")
request = request_for("user12345@evil.example.org")
res, _ = authlua.g.auth_password_verify(request, "correctgoose")
assert res == UNKNOWN
assert authlua.g.auth_userdb_lookup(request)[0] == UNKNOWN
assert authlua.g.create_payload is None
def test_name_shorter_than_the_domain_is_refused(authlua, request_for):
for name in ("x", "", "chat.example.org"):
res, _ = authlua.g.auth_password_verify(request_for(name), "correctgoose")
assert res == UNKNOWN
assert authlua.g.auth_userdb_lookup(request_for(name))[0] == UNKNOWN
assert authlua.g.create_payload is None
def test_slash_in_username_is_refused(authlua, request_for):
request = request_for("../../etc/shadow@chat.example.org")
res, _ = authlua.g.auth_password_verify(request, "somepassword")
assert res == UNKNOWN
assert authlua.g.auth_userdb_lookup(request)[0] == UNKNOWN
assert authlua.g.create_payload is None
def test_localpart_policy_is_left_to_doveauth(authlua, request_for):
authlua.g.create_status = 403
res, _ = authlua.g.auth_password_verify(request_for("@chat.example.org"), "somepw")
assert res == UNKNOWN
assert authlua.g.create_payload == "@chat.example.org\tsomepw"
def test_unknown_address_is_created_via_endpoint(authlua, request_for):
res, fields = authlua.g.auth_password_verify(request_for(USER2), "brandnewpass")
assert res == OK
assert fields["home"].endswith(USER2)
assert authlua.g.create_payload == f"{USER2}\tbrandnewpass"
assert authlua.g.create_request["url"] == "http://127.0.0.1:10084/create"
# doveauth refusing is the user's problem, doveauth failing is ours
@pytest.mark.parametrize("status", [400, 403, 404])
def test_creation_refused_by_doveauth_is_user_unknown(authlua, request_for, status):
authlua.g.create_status = status
res, _ = authlua.g.auth_password_verify(request_for(USER2), "brandnewpass")
assert res == UNKNOWN
# 9003 is dovecot's own CONNECT_FAILED, what a stopped doveauth actually yields
@pytest.mark.parametrize("status", [500, 502, 9003, 9005])
def test_creation_that_doveauth_could_not_answer_is_internal_failure(
authlua, request_for, status
):
authlua.g.create_status = status
res, _ = authlua.g.auth_password_verify(request_for(USER2), "brandnewpass")
assert res == INTERNAL
def test_userdb_unknown_before_creation_ok_after(authlua, request_for, create_user):
request = request_for(USER1)
res, _ = authlua.g.auth_userdb_lookup(request)
assert res == UNKNOWN
# a userdb lookup must never create anything
assert authlua.g.create_payload is None
create_user(USER1, "correctgoose")
res, fields = authlua.g.auth_userdb_lookup(request)
assert res == OK
assert fields["home"].endswith(USER1)
assert fields["uid"] == fields["gid"] == "vmail"
def test_empty_password_file_is_unknown(authlua, request_for, write_password_file):
write_password_file(USER1, "")
assert authlua.g.auth_userdb_lookup(request_for(USER1))[0] == UNKNOWN
write_password_file(USER1, "\n")
assert authlua.g.auth_userdb_lookup(request_for(USER1))[0] == UNKNOWN
def test_password_file_format_checks(authlua, request_for, write_password_file):
write_password_file(USER1, encrypt_password("correctgoose") + "\n")
res, _ = authlua.g.auth_password_verify(request_for(USER1), "correctgoose")
assert res == OK
assert authlua.g.auth_userdb_lookup(request_for(USER1))[0] == OK
passhash = encrypt_password("correctgoose")
write_password_file(USER1, passhash + "\ntrailing junk")
authlua.g.create_status = 403
res, _ = authlua.g.auth_password_verify(request_for(USER1), "correctgoose")
assert res == UNKNOWN
assert authlua.g.auth_userdb_lookup(request_for(USER1))[0] == UNKNOWN
def test_ipv4_relay_uses_bracketed_domain(lua, ipv4_config, request_for):
# mail_domain is "[1.3.3.7]" here, and is_ours must not read it as a pattern
authlua = load_authlua(lua, ipv4_config)
addr = f"user12345@{ipv4_config.mail_domain}"
ipv4_config.get_user(addr).set_password(encrypt_password("correctgoose"))
res, fields = authlua.g.auth_password_verify(request_for(addr), "correctgoose")
assert res == OK
assert fields["home"].endswith(addr)
assert authlua.g.auth_userdb_lookup(request_for(addr))[0] == OK
assert authlua.g.auth_userdb_lookup(request_for(USER1))[0] == UNKNOWN
+2 -2
View File
@@ -207,7 +207,7 @@ class TestZonefileChecks:
parse_zonefile_into_dict(zonefile_mocked, mockdns_base) parse_zonefile_into_dict(zonefile_mocked, mockdns_base)
required_diff, recommended_diff = remote.rdns.check_zonefile(zonefile) required_diff, recommended_diff = remote.rdns.check_zonefile(zonefile)
assert not required_diff assert not required_diff
assert len(recommended_diff) == 7 assert len(recommended_diff) == 8
def test_check_zonefile_output_required_fine(self, cm_data, mockdns_base, mockout): def test_check_zonefile_output_required_fine(self, cm_data, mockdns_base, mockout):
zonefile = cm_data.get("zftest.zone") zonefile = cm_data.get("zftest.zone")
@@ -218,7 +218,7 @@ class TestZonefileChecks:
res = check_full_zone(mssh, mockdns_base, out=mockout, zonefile=zonefile) res = check_full_zone(mssh, mockdns_base, out=mockout, zonefile=zonefile)
assert res == 0 assert res == 0
assert "WARNING" in mockout.captured_plain[0] assert "WARNING" in mockout.captured_plain[0]
assert len(mockout.captured_plain) == 8 assert len(mockout.captured_plain) == 9
def test_check_zonefile_output_full(self, cm_data, mockdns_base, mockout): def test_check_zonefile_output_full(self, cm_data, mockdns_base, mockout):
zonefile = cm_data.get("zftest.zone") zonefile = cm_data.get("zftest.zone")
@@ -111,7 +111,7 @@ def test_download_dovecot_package_uses_archive_version_for_url_and_filename(
deb, changed = dovecot_deployer._download_dovecot_package("core", "amd64") deb, changed = dovecot_deployer._download_dovecot_package("core", "amd64")
archive_version = dovecot_deployer.DOVECOT_VERSION.replace("+", "%2B") archive_version = dovecot_deployer.DOVECOT_ARCHIVE_VERSION.replace("+", "%2B")
expected_deb = f"/root/dovecot-core_{archive_version}_amd64.deb" expected_deb = f"/root/dovecot-core_{archive_version}_amd64.deb"
# Verify the returned path uses archive version, not package version (with epoch) # Verify the returned path uses archive version, not package version (with epoch)
@@ -136,7 +136,6 @@ def test_install_skips_dpkg_path_when_epoch_matched_packages_present(
"dovecot-core": [dovecot_deployer.DOVECOT_PACKAGE_VERSION], "dovecot-core": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
"dovecot-imapd": [dovecot_deployer.DOVECOT_PACKAGE_VERSION], "dovecot-imapd": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
"dovecot-lmtpd": [dovecot_deployer.DOVECOT_PACKAGE_VERSION], "dovecot-lmtpd": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
"dovecot-auth-lua": [dovecot_deployer.DOVECOT_PACKAGE_VERSION],
}, },
), ),
(dovecot_deployer.Arch, "x86_64"), (dovecot_deployer.Arch, "x86_64"),
@@ -181,12 +180,9 @@ def test_install_unsupported_arch_falls_back_to_apt(
deployer.install() deployer.install()
actual_pkgs = [c["packages"] for c in apt_calls] actual_pkgs = [c["packages"] for c in apt_calls]
assert actual_pkgs == [ assert actual_pkgs == [["dovecot-core"], ["dovecot-imapd"], ["dovecot-lmtpd"]], (
["dovecot-core"], f"expected apt install of core/imapd/lmtpd, got {actual_pkgs}"
["dovecot-imapd"], )
["dovecot-lmtpd"],
["dovecot-auth-lua"],
], f"expected apt install of core/imapd/lmtpd/auth-lua, got {actual_pkgs}"
assert track_shell == [], "should not run dpkg for unsupported arch" assert track_shell == [], "should not run dpkg for unsupported arch"
assert deployer.need_restart is True, ( assert deployer.need_restart is True, (
"need_restart should be True when apt installed a package" "need_restart should be True when apt installed a package"
@@ -1,85 +0,0 @@
"""Test the push_notification.lua we ship, against a mocked dovecot mail API."""
import textwrap
import pytest
USER1 = "user12345@chat.example.org"
USER2 = "user67890@chat.example.org"
DOVECOT_MOCKS = textwrap.dedent("""
function make_user(username)
local function mailbox(_, name)
record("mailbox " .. name)
return {
sync = function() record("sync") end,
metadata_set = function(_, k, v)
record("metadata_set " .. k .. "=" .. v)
end,
free = function() record("free") end,
}
end
return {username = username, mailbox = mailbox}
end
""")
@pytest.fixture
def script(lua):
lua.rt.execute(DOVECOT_MOCKS)
lua.load("dovecot/push_notification.lua")
return lua
@pytest.fixture
def deliver(script):
def deliver(recipient, sender):
calls = []
script.g.record = calls.append
user = script.g.make_user(recipient)
ctx = script.g.dovecot_lua_notify_begin_txn(user)
event = script.table(mailbox="INBOX", from_address=sender)
script.g.dovecot_lua_notify_event_message_new(ctx, event)
script.g.dovecot_lua_notify_end_txn(ctx, True)
return calls
return deliver
def test_entry_points_have_the_names_dovecot_calls(script):
assert script.g.dovecot_lua_notify_begin_txn is not None
assert script.g.dovecot_lua_notify_event_message_new is not None
assert script.g.dovecot_lua_notify_end_txn is not None
def test_begin_txn_returns_the_user_as_event_context(script):
user = script.g.make_user(USER1)
ctx = script.g.dovecot_lua_notify_begin_txn(user)
ctx.marker = "seen"
assert user.marker == "seen"
def test_incoming_message_notifies_metadata_server(deliver):
assert deliver(USER1, sender=USER2) == [
"mailbox INBOX",
"sync",
"metadata_set /private/messagenew=",
"free",
]
def test_own_message_does_not_wake_the_sending_device(deliver):
assert deliver(USER1, sender=USER1) == [
"mailbox INBOX",
"sync",
"free",
]
def test_message_without_from_address_is_notified(deliver):
assert deliver(USER1, sender=None) == [
"mailbox INBOX",
"sync",
"metadata_set /private/messagenew=",
"free",
]
@@ -0,0 +1,19 @@
from pyinfra.operations import apt, server
from cmdeploy.basedeploy import Deployer
class WebsockifyDeployer(Deployer):
def __init__(self, config):
self.config = config
def install(self):
apt.packages(name="Install websockify", packages=["websockify"])
def configure(self):
self.ensure_systemd_unit("websockify/websockify-imap.service")
self.ensure_systemd_unit("websockify/websockify-submission.service")
def activate(self):
self.ensure_service("websockify-imap.service")
self.ensure_service("websockify-submission.service")
@@ -0,0 +1,12 @@
[Unit]
Description=WebSocket proxy for IMAP
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/websockify 127.0.0.1:8143 localhost:143
DynamicUser=true
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,12 @@
[Unit]
Description=WebSocket proxy for SMTP
After=network.target
[Service]
Type=simple
Restart=always
ExecStart=/usr/bin/websockify 127.0.0.1:8587 localhost:587
DynamicUser=true
[Install]
WantedBy=multi-user.target
-17
View File
@@ -3,8 +3,6 @@
# For the full list of built-in configuration values, see the documentation: # For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html # https://www.sphinx-doc.org/en/master/usage/configuration.html
import os
# -- Project information ----------------------------------------------------- # -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
@@ -18,27 +16,12 @@ author = 'chatmail collective'
extensions = [ extensions = [
#'sphinx.ext.autodoc', #'sphinx.ext.autodoc',
#'sphinx.ext.viewdoc', #'sphinx.ext.viewdoc',
'sphinx.ext.extlinks',
'sphinxcontrib.mermaid', 'sphinxcontrib.mermaid',
] ]
templates_path = ['_templates'] templates_path = ['_templates']
exclude_patterns = [] exclude_patterns = []
# Repository links go through the roles below.
# CI sets DOC_GITHUB_REF to the head commit of a pull request,
gh_ref = os.environ.get("DOC_GITHUB_REF", "main")
extlinks = {
"repofile": (f"https://github.com/chatmail/relay/blob/{gh_ref}/%s", "%s"),
"repodir": (f"https://github.com/chatmail/relay/tree/{gh_ref}/%s", "%s"),
}
# Warn about repository links spelled out in full instead of using the roles.
extlinks_detect_hardcoded_links = True
# delta.chat/help picks the reader's language in JavaScript and keeps the anchor.
linkcheck_anchors_ignore_for_url = [r"https://delta\.chat/help"]
# -- Options for HTML output ------------------------------------------------- # -- Options for HTML output -------------------------------------------------
+5 -13
View File
@@ -54,7 +54,7 @@ How can I upgrade my chatmail relay?
------------------------------------ ------------------------------------
To upgrade to the latest ``main`` branch, To upgrade to the latest ``main`` branch,
``cd`` into your local checkout of https://github.com/chatmail/relay/ ``cd`` into your local checkout of `https://github.com/chatmail/relay/`_
and run the following commands: and run the following commands:
:: ::
@@ -63,17 +63,9 @@ and run the following commands:
scripts/initenv.sh scripts/initenv.sh
scripts/cmdeploy run scripts/cmdeploy run
To upgrade to the latest tag, If you don't want the latest development version,
``cd`` into your local checkout of https://github.com/chatmail/relay/ but a specific tagged release like `1.10.0 <https://github.com/chatmail/relay/releases/tag/1.10.0>`_,
and run the following commands: run ``git pull origin 1.10.0`` instead.
::
git fetch --tags
latestTag=$(git describe --tags "$(git rev-list --tags --max-count=1)")
git checkout $latestTag
scripts/initenv.sh
scripts/cmdeploy run
If you made local changes for your setup, If you made local changes for your setup,
they will be reapplied as long as they don't conflict with the upgrade. they will be reapplied as long as they don't conflict with the upgrade.
@@ -90,4 +82,4 @@ enforce end-to-end encryption on their own.
The end-to-end encryption protection includes attached media, user The end-to-end encryption protection includes attached media, user
display names, avatars and group names. What is visible to operators is: display names, avatars and group names. What is visible to operators is:
message date, sender and receiver addresses. message date, sender and receiver addresses.
Please see the `Delta Chat FAQ on encryption and security <https://delta.chat/help#e2ee>`_ for further info. Please see the `Delta Chat FAQ on encryption and security <https://delta.chat/en/help#e2ee>`_ for further info.
+32 -52
View File
@@ -6,13 +6,13 @@ Technical overview
Directories of the relay repository Directories of the relay repository
----------------------------------- -----------------------------------
The `chatmail relay repository <https://github.com/chatmail/relay>`_ The `chatmail relay repository <https://github.com/chatmail/relay/tree/main/>`_
has four main directories. has four main directories.
``scripts/`` ``scripts/``
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
:repodir:`scripts` `scripts <https://github.com/chatmail/relay/tree/main/scripts>`_
offers two convenience tools for beginners: offers two convenience tools for beginners:
- ``initenv.sh`` installs a local virtualenv Python environment and - ``initenv.sh`` installs a local virtualenv Python environment and
@@ -52,7 +52,8 @@ The deployed system components of a chatmail relay are:
- `acmetool <https://hlandau.github.io/acmetool/>`_ manages TLS - `acmetool <https://hlandau.github.io/acmetool/>`_ manages TLS
certificates for Dovecot, Postfix, and Nginx certificates for Dovecot, Postfix, and Nginx
- `OpenDKIM <http://www.opendkim.org/>`_ for signing outgoing messages with DKIM - `OpenDKIM <http://www.opendkim.org/>`_ for signing messages with
DKIM and rejecting inbound messages without DKIM
- `mtail <https://google.github.io/mtail/>`_ for collecting anonymized - `mtail <https://google.github.io/mtail/>`_ for collecting anonymized
metrics in case you have monitoring metrics in case you have monitoring
@@ -70,7 +71,7 @@ The deployed system components of a chatmail relay are:
``chatmaild/`` ``chatmaild/``
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
:repodir:`chatmaild` `chatmaild <https://github.com/chatmail/relay/tree/main/chatmaild>`_
is a Python package containing several small services which handle is a Python package containing several small services which handle
authentication, trigger push notifications on new messages, ensure authentication, trigger push notifications on new messages, ensure
that outbound mails are encrypted, delete inactive users, and some that outbound mails are encrypted, delete inactive users, and some
@@ -82,25 +83,25 @@ that integrate with Dovecot and Postfix to achieve instant-onboarding
and only relaying OpenPGP end-to-end messages encrypted messages. A and only relaying OpenPGP end-to-end messages encrypted messages. A
short overview of ``chatmaild`` services: short overview of ``chatmaild`` services:
- :repofile:`doveauth <chatmaild/src/chatmaild/doveauth.py>` - `doveauth <https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/doveauth.py>`_
implements create-on-login address semantics. implements create-on-login address semantics and is used by Dovecot
Dovecot authenticates IMAP logins, and Postfix SMTP/SUBMISSION logins through `Dovecot SASL during IMAP login and by Postfix during SMTP/SUBMISSION login which
<https://doc.dovecot.org/2.3/configuration_manual/authentication/authentication_mechanisms/>`_, in turn uses `Dovecot SASL
from an :repofile:`auth.lua <cmdeploy/src/cmdeploy/dovecot/auth.lua.j2>` script <https://doc.dovecot.org/2.3/configuration_manual/authentication/dict/#complete-example-for-authenticating-via-a-unix-socket>`_
that reads the maildir directly. Only addresses which do not exist yet to authenticate logins.
are passed on to doveauth, which owns the creation policy.
- :repofile:`chatmail-metadata <chatmaild/src/chatmaild/metadata.py>` - `chatmail-metadata <https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/metadata.py>`_
is contacted by a is contacted by a `Dovecot lua
:repofile:`Dovecot lua script <cmdeploy/src/cmdeploy/dovecot/push_notification.lua>` script <https://github.com/chatmail/relay/blob/main/cmdeploy/src/cmdeploy/dovecot/push_notification.lua>`_
to store user-specific relay-side config. On new messages, it to store user-specific relay-side config. On new messages, it `passes
:repofile:`passes the user’s push notification token <chatmaild/src/chatmaild/notifier.py>` the user’s push notification
token <https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/notifier.py>`_
to to
`notifications.delta.chat <https://delta.chat/help#instant-delivery>`_ `notifications.delta.chat <https://delta.chat/en/help#instant-delivery>`_
so the push notifications on the user’s phone can be triggered by so the push notifications on the user’s phone can be triggered by
Apple/Google/Huawei. Apple/Google/Huawei.
- :repofile:`chatmail-expire <chatmaild/src/chatmaild/expire.py>` - `chatmail-expire <https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/expire.py>`_
deletes old messages, large messages, and entire mailboxes deletes old messages, large messages, and entire mailboxes
of users who have not logged in for longer than of users who have not logged in for longer than
``delete_inactive_users_after`` days. ``delete_inactive_users_after`` days.
@@ -108,14 +109,15 @@ short overview of ``chatmaild`` services:
- ``chatmail-quota-expire`` is called by Dovecot's ``quota_warning`` mechanism - ``chatmail-quota-expire`` is called by Dovecot's ``quota_warning`` mechanism
and will automatically remove oldest messages to keep mailboxes well under ``max_mailbox_size``. and will automatically remove oldest messages to keep mailboxes well under ``max_mailbox_size``.
- :repofile:`lastlogin <chatmaild/src/chatmaild/lastlogin.py>` - `lastlogin <https://github.com/chatmail/relay/blob/main/chatmaild/src/chatmaild/lastlogin.py>`_
is contacted by Dovecot when a user logs in and stores the date of is contacted by Dovecot when a user logs in and stores the date of
the login. the login.
``www/`` ``www/``
~~~~~~~~~ ~~~~~~~~~
:repodir:`www` contains the html, css, and markdown files which make up a chatmail relay’s `www <https://github.com/chatmail/relay/tree/main/www>`_ contains
the html, css, and markdown files which make up a chatmail relay’s
web page. Edit them before deploying to make your chatmail relay web page. Edit them before deploying to make your chatmail relay
stand out. stand out.
@@ -142,6 +144,7 @@ Chatmail relay dependency diagram
/var/lib/acme`")] --> nginx-internal; /var/lib/acme`")] --> nginx-internal;
systemd-timer --- acmetool; systemd-timer --- acmetool;
systemd-timer --- chatmail-expire-daily; systemd-timer --- chatmail-expire-daily;
systemd-timer --- chatmail-fsreport-daily;
acmetool --> certs[("`TLS certs acmetool --> certs[("`TLS certs
/var/lib/acme`")]; /var/lib/acme`")];
nginx-external --- |993|dovecot; nginx-external --- |993|dovecot;
@@ -154,7 +157,7 @@ Chatmail relay dependency diagram
filtermail-outgoing --- |10025 reinject|postfix; filtermail-outgoing --- |10025 reinject|postfix;
filtermail-incoming --- |10026 reinject|postfix; filtermail-incoming --- |10026 reinject|postfix;
postfix --- |milter opendkim.sock|OpenDKIM postfix --- |milter opendkim.sock|OpenDKIM
dovecot --- |10084 create|doveauth; dovecot --- |doveauth.socket|doveauth;
dovecot --- |message delivery|maildir["maildir dovecot --- |message delivery|maildir["maildir
/home/vmail/.../user"]; /home/vmail/.../user"];
dovecot --- |lastlogin.socket|lastlogin; dovecot --- |lastlogin.socket|lastlogin;
@@ -164,6 +167,7 @@ Chatmail relay dependency diagram
lastlogin --- maildir; lastlogin --- maildir;
doveauth --- maildir; doveauth --- maildir;
chatmail-expire-daily --- maildir; chatmail-expire-daily --- maildir;
chatmail-fsreport-daily --- maildir;
chatmail-metadata --- iroh-relay; chatmail-metadata --- iroh-relay;
chatmail-metadata --- |encrypted device token| notifications.delta.chat; chatmail-metadata --- |encrypted device token| notifications.delta.chat;
certs-nginx --> postfix; certs-nginx --> postfix;
@@ -245,33 +249,6 @@ Fresh chatmail addresses have a mailbox directory that contains:
directories will typically be empty unless the user of that address directories will typically be empty unless the user of that address
hasn’t been online for a while. hasn’t been online for a while.
App version information (experimental)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A chatmail relay ships the
:repofile:`appversions.json <chatmaild/src/chatmaild/defaults/appversions.json>`
file of the ``chatmaild`` package
and serves its content under the IMAP METADATA key
``/shared/vendor/deltachat/appversions``.
Chat apps installed outside of app stores read this key
to learn about updates and where to download them.
The mechanism is experimental and may change.
The file travels with the normal deploy:
update the repository checkout and run ``cmdeploy run``.
Local modifications of ``appversions.json`` are deployed as-is,
so you can serve your own app version information,
including links to app downloads.
There is no automatic refresh:
version information changes only when you deploy again.
.. note::
Note that as of August 2026, only Delta Chat Android Google Play version
is beginning to support discovering app versions from relays.
Generally, consumers of relay-provided app version information
need to verify themselves that downloaded app files are valid.
Active ports Active ports
~~~~~~~~~~~~ ~~~~~~~~~~~~
@@ -291,14 +268,15 @@ Dovecot_ listens on ports
Nginx_ listens on port Nginx_ listens on port
- 80 (HTTP), which passes certificate challenges on to
`acmetool <https://hlandau.github.io/acmetool/>`_ and redirects everything else to HTTPS,
- 8443 (HTTPS-ALT) and - 8443 (HTTPS-ALT) and
- 443 (HTTPS) which multiplexes HTTPS, IMAP and SMTP using ALPN - 443 (HTTPS) which multiplexes HTTPS, IMAP and SMTP using ALPN
to redirect connections to ports 8443, 465 or 993. to redirect connections to ports 8443, 465 or 993.
`acmetool <https://hlandau.github.io/acmetool/>`_ listens on port:
- 80 (HTTP).
`chatmail-turn <https://github.com/chatmail/chatmail-turn>`_ listens on port `chatmail-turn <https://github.com/chatmail/chatmail-turn>`_ listens on port
- 3478 UDP (STUN/TURN), and temporarily opens further UDP ports - 3478 UDP (STUN/TURN), and temporarily opens further UDP ports
@@ -318,10 +296,12 @@ Chatmail relays enforce :rfc:`DKIM <6376>` to authenticate incoming emails
Incoming emails must have a valid DKIM signature with Incoming emails must have a valid DKIM signature with
Signing Domain Identifier (SDID, ``d=`` parameter in the DKIM-Signature Signing Domain Identifier (SDID, ``d=`` parameter in the DKIM-Signature
header) equal to the ``From:`` header domain. This property is checked header) equal to the ``From:`` header domain. This property is checked
by filtermail when it verifies the signatures. This by OpenDKIM screen policy script before validating the signatures. This
corresponds to strict :rfc:`DMARC <7489>` alignment (``adkim=s``). corresponds to strict :rfc:`DMARC <7489>` alignment (``adkim=s``).
If there is no valid DKIM signature on the incoming email, the If there is no valid DKIM signature on the incoming email, the
sender receives a “5.7.1 No valid DKIM signature found” error. sender receives a “5.7.1 No valid DKIM signature found” error.
After validating the DKIM signature,
the `final.lua` script strips all ``OpenDKIM:`` headers to reduce message size on disc.
Note that chatmail relays Note that chatmail relays
+4 -5
View File
@@ -14,11 +14,10 @@ We know of three work-in-progress alternative implementation efforts:
it to support all of the features and configuration settings required it to support all of the features and configuration settings required
to operate as a chatmail relay. to operate as a chatmail relay.
- `Madmail <https://github.com/themadorg/madmail>`_: a Rust-based - `Madmail <https://github.com/themadorg/madmail>`_: an
single-binary chatmail relay. Madmail v2 is a rewrite of an earlier experimental fork of `Maddy Mail Server <https://maddy.email/>`_, modified
experimental fork of `Maddy Mail Server <https://maddy.email/>`_. for chatmail deployments. It provides a single binary solution
It includes SMTP, IMAP, encryption enforcement, and real-time for running a chatmail relay.
services (TURN/Iroh), and runs on Linux and Windows.
- `Chatmail Cookbook <https://github.com/feld/chatmail-cookbook>`_: - `Chatmail Cookbook <https://github.com/feld/chatmail-cookbook>`_:
A Chef Cookbook implementing a relay server. The project follows the A Chef Cookbook implementing a relay server. The project follows the
-4
View File
@@ -20,10 +20,6 @@ fi
python3 -m venv --upgrade-deps venv python3 -m venv --upgrade-deps venv
# an editable install puts src/ on sys.path, so a leftover egg-info there is
# found as a second distribution and keeps removed entry points registered
rm -rf chatmaild/src/*.egg-info cmdeploy/src/*.egg-info
venv/bin/pip install -e chatmaild venv/bin/pip install -e chatmaild
venv/bin/pip install -e cmdeploy venv/bin/pip install -e cmdeploy
venv/bin/pip install sphinx sphinxcontrib-mermaid sphinx-autobuild furo # for building the docs venv/bin/pip install sphinx sphinxcontrib-mermaid sphinx-autobuild furo # for building the docs
+1 -1
View File
@@ -35,4 +35,4 @@ you can also **scan this QR code** with Delta Chat:
🐣 **Choose** your Avatar and Name 🐣 **Choose** your Avatar and Name
💬 **Start** chatting with any Delta Chat contacts using [QR invite codes](https://delta.chat/help#howtoe2ee) 💬 **Start** chatting with any Delta Chat contacts using [QR invite codes](https://delta.chat/en/help#howtoe2ee)
+2 -2
View File
@@ -10,12 +10,12 @@ for the usage in chats, especially DeltaChat.
### Rate and storage limits ### Rate and storage limits
- Un-encrypted messages are blocked to recipients outside - Un-encrypted messages are blocked to recipients outside
{{config.mail_domain}} but setting up contact via [QR invite codes](https://delta.chat/help#howtoe2ee) {{config.mail_domain}} but setting up contact via [QR invite codes](https://delta.chat/en/help#howtoe2ee)
allows your messages to pass freely to any outside recipients. allows your messages to pass freely to any outside recipients.
- You may send up to {{ config.max_user_send_per_minute }} messages per minute. - You may send up to {{ config.max_user_send_per_minute }} messages per minute.
- You can store up to [{{ config.max_mailbox_size }} messages on the server](https://delta.chat/help#what-happens-if-i-turn-on-delete-old-messages-from-server). - You can store up to [{{ config.max_mailbox_size }} messages on the server](https://delta.chat/en/help#what-happens-if-i-turn-on-delete-old-messages-from-server).
- Messages are unconditionally removed latest {{ config.delete_mails_after }} days after arriving on the server. - Messages are unconditionally removed latest {{ config.delete_mails_after }} days after arriving on the server.
Earlier, if storage may exceed otherwise. Earlier, if storage may exceed otherwise.
+1 -1
View File
@@ -5,7 +5,7 @@
Welcome to `{{config.mail_domain}}`, the default chatmail onboarding server for Delta Chat users. Welcome to `{{config.mail_domain}}`, the default chatmail onboarding server for Delta Chat users.
It is operated on the side by a small sysops team It is operated on the side by a small sysops team
on a voluntary basis. on a voluntary basis.
See [other chatmail servers](https://chatmail.at/relays) for alternative server operators. See [other chatmail servers](https://delta.chat/en/chatmail) for alternative server operators.
{% endif %} {% endif %}