mirror of
https://github.com/chatmail/relay.git
synced 2026-05-11 16:34:39 +00:00
Compare commits
1 Commits
link2xt/do
...
link2xt/de
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9dad84746a |
56
.github/workflows/test-and-deploy.yaml
vendored
56
.github/workflows/test-and-deploy.yaml
vendored
@@ -4,17 +4,12 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
pull_request:
|
- staging-ci
|
||||||
paths-ignore:
|
|
||||||
- 'scripts/**'
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
deploy:
|
deploy:
|
||||||
name: deploy on staging.testrun.org, and run tests
|
name: deploy on staging.testrun.org, and run tests
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
concurrency:
|
|
||||||
group: staging-deploy
|
|
||||||
cancel-in-progress: true
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v3
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
@@ -24,57 +19,48 @@ jobs:
|
|||||||
echo "${{ secrets.STAGING_SSH_KEY }}" >> ~/.ssh/id_ed25519
|
echo "${{ secrets.STAGING_SSH_KEY }}" >> ~/.ssh/id_ed25519
|
||||||
chmod 600 ~/.ssh/id_ed25519
|
chmod 600 ~/.ssh/id_ed25519
|
||||||
ssh-keyscan staging.testrun.org > ~/.ssh/known_hosts
|
ssh-keyscan staging.testrun.org > ~/.ssh/known_hosts
|
||||||
# save previous acme & dkim state
|
# rsync -avz root@staging.testrun.org:/var/lib/acme . || true
|
||||||
rsync -avz root@staging.testrun.org:/var/lib/acme . || true
|
# rsync -avz root@staging.testrun.org:/var/lib/rspamd/dkim . || true
|
||||||
rsync -avz root@staging.testrun.org:/etc/dkimkeys . || true
|
|
||||||
# store previous acme & dkim state on ns.testrun.org, if it contains useful certs
|
|
||||||
if [ -f dkimkeys/opendkim.private ]; then rsync -avz -e "ssh -o StrictHostKeyChecking=accept-new" dkimkeys root@ns.testrun.org:/tmp/ || true; fi
|
|
||||||
if [ -z "$(ls -A acme/certs)" ]; then rsync -avz -e "ssh -o StrictHostKeyChecking=accept-new" acme root@ns.testrun.org:/tmp/ || true; fi
|
|
||||||
|
|
||||||
- name: rebuild staging.testrun.org to have a clean VPS
|
#- name: rebuild staging.testrun.org to have a clean VPS
|
||||||
run: |
|
# run: |
|
||||||
curl -X POST \
|
# curl -X POST \
|
||||||
-H "Authorization: Bearer ${{ secrets.HETZNER_API_TOKEN }}" \
|
# -H "Authorization: Bearer ${{ secrets.HETZNER_API_TOKEN }}" \
|
||||||
-H "Content-Type: application/json" \
|
# -H "Content-Type: application/json" \
|
||||||
-d '{"image":"debian-12"}' \
|
# -d '{"image":"debian-12"}' \
|
||||||
"https://api.hetzner.cloud/v1/servers/${{ secrets.STAGING_SERVER_ID }}/actions/rebuild"
|
# "https://api.hetzner.cloud/v1/servers/${{ secrets.STAGING_SERVER_ID }}/actions/rebuild"
|
||||||
|
|
||||||
- run: scripts/initenv.sh
|
- run: scripts/initenv.sh
|
||||||
|
|
||||||
- name: append venv/bin to PATH
|
- name: append venv/bin to PATH
|
||||||
run: echo venv/bin >>$GITHUB_PATH
|
run: echo venv/bin >>$GITHUB_PATH
|
||||||
|
|
||||||
- name: upload TLS cert after rebuilding
|
|
||||||
run: |
|
|
||||||
echo " --- wait until staging.testrun.org VPS is rebuilt --- "
|
|
||||||
rm ~/.ssh/known_hosts
|
|
||||||
while ! ssh -o ConnectTimeout=180 -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org id -u ; do sleep 1 ; done
|
|
||||||
ssh -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org id -u
|
|
||||||
# download acme & dkim state from ns.testrun.org
|
|
||||||
rsync -e "ssh -o StrictHostKeyChecking=accept-new" -avz root@ns.testrun.org:/tmp/acme acme-restore || true
|
|
||||||
rsync -avz root@ns.testrun.org:/tmp/dkimkeys dkimkeys-restore || true
|
|
||||||
# restore acme & dkim state to staging.testrun.org
|
|
||||||
rsync -avz acme-restore/acme/ root@staging.testrun.org:/var/lib/acme || true
|
|
||||||
rsync -avz dkimkeys-restore/dkimkeys/ root@staging.testrun.org:/etc/dkimkeys || true
|
|
||||||
ssh -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org chown root:root -R /var/lib/acme
|
|
||||||
|
|
||||||
- name: run formatting checks
|
- name: run formatting checks
|
||||||
run: cmdeploy fmt -v
|
run: cmdeploy fmt -v
|
||||||
|
|
||||||
- name: run deploy-chatmail offline tests
|
- name: run deploy-chatmail offline tests
|
||||||
run: pytest --pyargs cmdeploy
|
run: pytest --pyargs cmdeploy
|
||||||
|
|
||||||
|
#- name: upload TLS cert after rebuilding
|
||||||
|
# run: |
|
||||||
|
# echo " --- wait until staging.testrun.org VPS is rebuilt --- "
|
||||||
|
# rm ~/.ssh/known_hosts
|
||||||
|
# while ! ssh -o ConnectTimeout=180 -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org id -u ; do sleep 1 ; done
|
||||||
|
# ssh -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org id -u
|
||||||
|
# rsync -avz acme root@staging.testrun.org:/var/lib/ || true
|
||||||
|
# rsync -avz dkim root@staging.testrun.org:/var/lib/rspamd/ || true
|
||||||
|
|
||||||
- run: cmdeploy init staging.testrun.org
|
- run: cmdeploy init staging.testrun.org
|
||||||
|
|
||||||
- run: cmdeploy run
|
- run: cmdeploy run
|
||||||
|
|
||||||
- name: set DNS entries
|
- name: set DNS entries
|
||||||
run: |
|
run: |
|
||||||
ssh -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org chown opendkim:opendkim -R /etc/dkimkeys
|
#ssh -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org chown _rspamd:_rspamd -R /var/lib/rspamd/dkim
|
||||||
cmdeploy dns --zonefile staging-generated.zone
|
cmdeploy dns --zonefile staging-generated.zone
|
||||||
cat staging-generated.zone >> .github/workflows/staging.testrun.org-default.zone
|
cat staging-generated.zone >> .github/workflows/staging.testrun.org-default.zone
|
||||||
cat .github/workflows/staging.testrun.org-default.zone
|
cat .github/workflows/staging.testrun.org-default.zone
|
||||||
scp .github/workflows/staging.testrun.org-default.zone root@ns.testrun.org:/etc/nsd/staging.testrun.org.zone
|
scp -o StrictHostKeyChecking=accept-new .github/workflows/staging.testrun.org-default.zone root@ns.testrun.org:/etc/nsd/staging.testrun.org.zone
|
||||||
ssh root@ns.testrun.org nsd-checkzone staging.testrun.org /etc/nsd/staging.testrun.org.zone
|
ssh root@ns.testrun.org nsd-checkzone staging.testrun.org /etc/nsd/staging.testrun.org.zone
|
||||||
ssh root@ns.testrun.org systemctl reload nsd
|
ssh root@ns.testrun.org systemctl reload nsd
|
||||||
|
|
||||||
|
|||||||
52
CHANGELOG.md
52
CHANGELOG.md
@@ -1,52 +0,0 @@
|
|||||||
# Changelog for chatmail deployment
|
|
||||||
|
|
||||||
## untagged
|
|
||||||
|
|
||||||
## 1.2.0 - 2024-04-04
|
|
||||||
|
|
||||||
- Install dig on the server to resolve DNS records
|
|
||||||
([#267](https://github.com/deltachat/chatmail/pull/267))
|
|
||||||
|
|
||||||
- preserve notification order and exponentially backoff with
|
|
||||||
retries for tokens where we didn't get a successful return
|
|
||||||
([#265](https://github.com/deltachat/chatmail/pull/263))
|
|
||||||
|
|
||||||
- Run chatmail-metadata and doveauth as vmail
|
|
||||||
([#261](https://github.com/deltachat/chatmail/pull/261))
|
|
||||||
|
|
||||||
- Apply systemd restrictions to echobot
|
|
||||||
([#259](https://github.com/deltachat/chatmail/pull/259))
|
|
||||||
|
|
||||||
- re-enable running the CI in pull requests, but not concurrently
|
|
||||||
([#258](https://github.com/deltachat/chatmail/pull/258))
|
|
||||||
|
|
||||||
|
|
||||||
## 1.1.0 - 2024-03-28
|
|
||||||
|
|
||||||
### The changelog starts to record changes from March 15th, 2024
|
|
||||||
|
|
||||||
- Move systemd unit templates to cmdeploy package
|
|
||||||
([#255](https://github.com/deltachat/chatmail/pull/255))
|
|
||||||
|
|
||||||
- Persist push tokens and support multiple device per address
|
|
||||||
([#254](https://github.com/deltachat/chatmail/pull/254))
|
|
||||||
|
|
||||||
- Avoid warning for regular doveauth protocol's hello message.
|
|
||||||
([#250](https://github.com/deltachat/chatmail/pull/250))
|
|
||||||
|
|
||||||
- Fix various tests to pass again with "cmdeploy test".
|
|
||||||
([#245](https://github.com/deltachat/chatmail/pull/245),
|
|
||||||
[#242](https://github.com/deltachat/chatmail/pull/242)
|
|
||||||
|
|
||||||
- Ensure lets-encrypt certificates are reloaded after renewal
|
|
||||||
([#244]) https://github.com/deltachat/chatmail/pull/244
|
|
||||||
|
|
||||||
- Persist tokens to avoid iOS users loosing push-notifications when the
|
|
||||||
chatmail metadata service is restarted (happens regularly during deploys)
|
|
||||||
([#238](https://github.com/deltachat/chatmail/pull/239)
|
|
||||||
|
|
||||||
- Fix failing sieve-script compile errors on incoming messages
|
|
||||||
([#237](https://github.com/deltachat/chatmail/pull/239)
|
|
||||||
|
|
||||||
- Fix quota reporting after expunging of old mails
|
|
||||||
([#233](https://github.com/deltachat/chatmail/pull/239)
|
|
||||||
23
README.md
23
README.md
@@ -159,27 +159,4 @@ While this file is present, account creation will be blocked.
|
|||||||
Delta Chat apps will, however, discover all ports and configurations
|
Delta Chat apps will, however, discover all ports and configurations
|
||||||
automatically by reading the [autoconfig XML file](https://www.ietf.org/archive/id/draft-bucksch-autoconfig-00.html) from the chatmail service.
|
automatically by reading the [autoconfig XML file](https://www.ietf.org/archive/id/draft-bucksch-autoconfig-00.html) from the chatmail service.
|
||||||
|
|
||||||
## Email authentication
|
|
||||||
|
|
||||||
chatmail servers rely on [DKIM](https://www.rfc-editor.org/rfc/rfc6376)
|
|
||||||
to authenticate incoming emails.
|
|
||||||
Incoming emails must have a valid DKIM signature with
|
|
||||||
Signing Domain Identifier (SDID, `d=` parameter in the DKIM-Signature header)
|
|
||||||
equal to the `From:` header domain.
|
|
||||||
This property is checked by OpenDKIM screen policy script
|
|
||||||
before validating the signatures.
|
|
||||||
This correpsonds to strict [DMARC](https://www.rfc-editor.org/rfc/rfc7489) alignment (`adkim=s`),
|
|
||||||
but chatmail does not rely on DMARC and does not consult the sender policy published in DMARC records.
|
|
||||||
Other legacy authentication mechanisms such as [iprev](https://www.rfc-editor.org/rfc/rfc8601#section-2.7.3)
|
|
||||||
and [SPF](https://www.rfc-editor.org/rfc/rfc7208) are also not taken into account.
|
|
||||||
If there is no valid DKIM signature on the incoming email,
|
|
||||||
the sender receives a "5.7.1 No valid DKIM signature found" error.
|
|
||||||
|
|
||||||
Outgoing emails must be sent over authenticated connection
|
|
||||||
with envelope MAIL FROM (return path) corresponding to the login.
|
|
||||||
This is ensured by Postfix which maps login username
|
|
||||||
to MAIL FROM with
|
|
||||||
[`smtpd_sender_login_maps`](https://www.postfix.org/postconf.5.html#smtpd_sender_login_maps)
|
|
||||||
and rejects incorrectly authenticated emails with [`reject_sender_login_mismatch`](reject_sender_login_mismatch) policy.
|
|
||||||
`From:` header must correspond to envelope MAIL FROM,
|
|
||||||
this is ensured by `filtermail` proxy.
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
include src/chatmaild/*.f
|
||||||
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/*
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ dependencies = [
|
|||||||
"iniconfig",
|
"iniconfig",
|
||||||
"deltachat-rpc-server",
|
"deltachat-rpc-server",
|
||||||
"deltachat-rpc-client",
|
"deltachat-rpc-client",
|
||||||
"filelock",
|
|
||||||
"requests",
|
"requests",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
10
chatmaild/src/chatmaild/chatmail-metadata.service.f
Normal file
10
chatmaild/src/chatmaild/chatmail-metadata.service.f
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Chatmail dict proxy for IMAP METADATA
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
ExecStart={execpath} /run/dovecot/metadata.socket vmail {config_path}
|
||||||
|
Restart=always
|
||||||
|
RestartSec=30
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -9,6 +9,7 @@ from socketserver import (
|
|||||||
StreamRequestHandler,
|
StreamRequestHandler,
|
||||||
ThreadingMixIn,
|
ThreadingMixIn,
|
||||||
)
|
)
|
||||||
|
import pwd
|
||||||
|
|
||||||
from .database import Database
|
from .database import Database
|
||||||
from .config import read_config, Config
|
from .config import read_config, Config
|
||||||
@@ -16,10 +17,6 @@ from .config import read_config, Config
|
|||||||
NOCREATE_FILE = "/etc/chatmail-nocreate"
|
NOCREATE_FILE = "/etc/chatmail-nocreate"
|
||||||
|
|
||||||
|
|
||||||
class UnknownCommand(ValueError):
|
|
||||||
"""dictproxy handler received an unkown command"""
|
|
||||||
|
|
||||||
|
|
||||||
def encrypt_password(password: str):
|
def encrypt_password(password: str):
|
||||||
# https://doc.dovecot.org/configuration_manual/authentication/password_schemes/
|
# https://doc.dovecot.org/configuration_manual/authentication/password_schemes/
|
||||||
passhash = crypt.crypt(password, crypt.METHOD_SHA512)
|
passhash = crypt.crypt(password, crypt.METHOD_SHA512)
|
||||||
@@ -130,12 +127,8 @@ def split_and_unescape(s):
|
|||||||
|
|
||||||
|
|
||||||
def handle_dovecot_request(msg, db, config: Config):
|
def handle_dovecot_request(msg, db, config: Config):
|
||||||
# see https://doc.dovecot.org/3.0/developer_manual/design/dict_protocol/
|
|
||||||
short_command = msg[0]
|
short_command = msg[0]
|
||||||
if short_command == "H": # HELLO
|
if short_command == "L": # LOOKUP
|
||||||
# we don't do any checking on versions and just return
|
|
||||||
return
|
|
||||||
elif short_command == "L": # LOOKUP
|
|
||||||
parts = msg[1:].split("\t")
|
parts = msg[1:].split("\t")
|
||||||
|
|
||||||
# Dovecot <2.3.17 has only one part,
|
# Dovecot <2.3.17 has only one part,
|
||||||
@@ -166,7 +159,7 @@ def handle_dovecot_request(msg, db, config: Config):
|
|||||||
reply_command = "N"
|
reply_command = "N"
|
||||||
json_res = json.dumps(res) if res else ""
|
json_res = json.dumps(res) if res else ""
|
||||||
return f"{reply_command}{json_res}\n"
|
return f"{reply_command}{json_res}\n"
|
||||||
raise UnknownCommand(msg)
|
return None
|
||||||
|
|
||||||
|
|
||||||
def handle_dovecot_protocol(rfile, wfile, db: Database, config: Config):
|
def handle_dovecot_protocol(rfile, wfile, db: Database, config: Config):
|
||||||
@@ -174,14 +167,12 @@ def handle_dovecot_protocol(rfile, wfile, db: Database, config: Config):
|
|||||||
msg = rfile.readline().strip().decode()
|
msg = rfile.readline().strip().decode()
|
||||||
if not msg:
|
if not msg:
|
||||||
break
|
break
|
||||||
try:
|
res = handle_dovecot_request(msg, db, config)
|
||||||
res = handle_dovecot_request(msg, db, config)
|
if res:
|
||||||
except UnknownCommand:
|
wfile.write(res.encode("ascii"))
|
||||||
logging.warning("unknown command: %r", msg)
|
wfile.flush()
|
||||||
else:
|
else:
|
||||||
if res:
|
logging.warning("request had no answer: %r", msg)
|
||||||
wfile.write(res.encode("ascii"))
|
|
||||||
wfile.flush()
|
|
||||||
|
|
||||||
|
|
||||||
class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
||||||
@@ -190,8 +181,9 @@ class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
|||||||
|
|
||||||
def main():
|
def main():
|
||||||
socket = sys.argv[1]
|
socket = sys.argv[1]
|
||||||
db = Database(sys.argv[2])
|
passwd_entry = pwd.getpwnam(sys.argv[2])
|
||||||
config = read_config(sys.argv[3])
|
db = Database(sys.argv[3])
|
||||||
|
config = read_config(sys.argv[4])
|
||||||
|
|
||||||
class Handler(StreamRequestHandler):
|
class Handler(StreamRequestHandler):
|
||||||
def handle(self):
|
def handle(self):
|
||||||
@@ -207,6 +199,7 @@ def main():
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
with ThreadedUnixStreamServer(socket, Handler) as server:
|
with ThreadedUnixStreamServer(socket, Handler) as server:
|
||||||
|
os.chown(socket, uid=passwd_entry.pw_uid, gid=passwd_entry.pw_gid)
|
||||||
try:
|
try:
|
||||||
server.serve_forever()
|
server.serve_forever()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
|
|||||||
@@ -2,11 +2,9 @@
|
|||||||
Description=Chatmail dict authentication proxy for dovecot
|
Description=Chatmail dict authentication proxy for dovecot
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
ExecStart={execpath} /run/doveauth/doveauth.socket /home/vmail/passdb.sqlite {config_path}
|
ExecStart={execpath} /run/dovecot/doveauth.socket vmail /home/vmail/passdb.sqlite {config_path}
|
||||||
Restart=always
|
Restart=always
|
||||||
RestartSec=30
|
RestartSec=30
|
||||||
User=vmail
|
|
||||||
RuntimeDirectory=doveauth
|
|
||||||
|
|
||||||
[Install]
|
[Install]
|
||||||
WantedBy=multi-user.target
|
WantedBy=multi-user.target
|
||||||
@@ -18,14 +18,14 @@ hooks = events.HookCollection()
|
|||||||
@hooks.on(events.RawEvent)
|
@hooks.on(events.RawEvent)
|
||||||
def log_event(event):
|
def log_event(event):
|
||||||
if event.kind == EventType.INFO:
|
if event.kind == EventType.INFO:
|
||||||
logging.info("%s", event.msg)
|
logging.info(event.msg)
|
||||||
elif event.kind == EventType.WARNING:
|
elif event.kind == EventType.WARNING:
|
||||||
logging.warning("%s", event.msg)
|
logging.warning(event.msg)
|
||||||
|
|
||||||
|
|
||||||
@hooks.on(events.RawEvent(EventType.ERROR))
|
@hooks.on(events.RawEvent(EventType.ERROR))
|
||||||
def log_error(event):
|
def log_error(event):
|
||||||
logging.error("%s", event.msg)
|
logging.error(event.msg)
|
||||||
|
|
||||||
|
|
||||||
@hooks.on(events.MemberListChanged)
|
@hooks.on(events.MemberListChanged)
|
||||||
@@ -48,9 +48,6 @@ def on_group_name_changed(event):
|
|||||||
@hooks.on(events.NewMessage(func=lambda e: not e.command))
|
@hooks.on(events.NewMessage(func=lambda e: not e.command))
|
||||||
def echo(event):
|
def echo(event):
|
||||||
snapshot = event.message_snapshot
|
snapshot = event.message_snapshot
|
||||||
if snapshot.is_info:
|
|
||||||
# Ignore info messages
|
|
||||||
return
|
|
||||||
if snapshot.text or snapshot.file:
|
if snapshot.text or snapshot.file:
|
||||||
snapshot.chat.send_message(text=snapshot.text, file=snapshot.file)
|
snapshot.chat.send_message(text=snapshot.text, file=snapshot.file)
|
||||||
|
|
||||||
@@ -62,7 +59,6 @@ def help_command(event):
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
logging.basicConfig(level=logging.INFO)
|
|
||||||
path = os.environ.get("PATH")
|
path = os.environ.get("PATH")
|
||||||
venv_path = sys.argv[0].strip("echobot")
|
venv_path = sys.argv[0].strip("echobot")
|
||||||
os.environ["PATH"] = path + ":" + venv_path
|
os.environ["PATH"] = path + ":" + venv_path
|
||||||
@@ -84,4 +80,5 @@ def main():
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
main()
|
main()
|
||||||
|
|||||||
11
chatmaild/src/chatmaild/echobot.service.f
Normal file
11
chatmaild/src/chatmaild/echobot.service.f
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Chatmail echo bot for testing it works
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
ExecStart={execpath} {config_path}
|
||||||
|
Environment="PATH={remote_venv_dir}:$PATH"
|
||||||
|
Restart=always
|
||||||
|
RestartSec=30
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import os
|
|
||||||
import logging
|
|
||||||
import json
|
|
||||||
import filelock
|
|
||||||
from contextlib import contextmanager
|
|
||||||
|
|
||||||
|
|
||||||
class FileDict:
|
|
||||||
"""Concurrency-safe multi-reader/single-writer persistent dict."""
|
|
||||||
|
|
||||||
def __init__(self, path):
|
|
||||||
self.path = path
|
|
||||||
self.lock_path = path.with_name(path.name + ".lock")
|
|
||||||
|
|
||||||
@contextmanager
|
|
||||||
def modify(self):
|
|
||||||
# the OS will release the lock if the process dies,
|
|
||||||
# and the contextmanager will otherwise guarantee release
|
|
||||||
with filelock.FileLock(self.lock_path):
|
|
||||||
data = self.read()
|
|
||||||
yield data
|
|
||||||
write_path = self.path.with_name(self.path.name + ".tmp")
|
|
||||||
with write_path.open("w") as f:
|
|
||||||
json.dump(data, f)
|
|
||||||
os.rename(write_path, self.path)
|
|
||||||
|
|
||||||
def read(self):
|
|
||||||
try:
|
|
||||||
with self.path.open("r") as f:
|
|
||||||
return json.load(f)
|
|
||||||
except FileNotFoundError:
|
|
||||||
return {}
|
|
||||||
except Exception:
|
|
||||||
logging.warning("corrupt serialization state at: %r", self.path)
|
|
||||||
return {}
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
[Unit]
|
[Unit]
|
||||||
Description=Chatmail Postfix before queue filter
|
Description=Chatmail Postfix BeforeQeue filter
|
||||||
|
|
||||||
[Service]
|
[Service]
|
||||||
ExecStart={execpath} {config_path}
|
ExecStart={execpath} {config_path}
|
||||||
@@ -1,118 +1,117 @@
|
|||||||
from pathlib import Path
|
import pwd
|
||||||
|
|
||||||
|
from queue import Queue
|
||||||
|
from threading import Thread
|
||||||
from socketserver import (
|
from socketserver import (
|
||||||
UnixStreamServer,
|
UnixStreamServer,
|
||||||
StreamRequestHandler,
|
StreamRequestHandler,
|
||||||
ThreadingMixIn,
|
ThreadingMixIn,
|
||||||
)
|
)
|
||||||
|
from .config import read_config
|
||||||
import sys
|
import sys
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import requests
|
||||||
from .filedict import FileDict
|
|
||||||
from .notifier import Notifier
|
|
||||||
|
|
||||||
|
|
||||||
DICTPROXY_HELLO_CHAR = "H"
|
|
||||||
DICTPROXY_LOOKUP_CHAR = "L"
|
DICTPROXY_LOOKUP_CHAR = "L"
|
||||||
DICTPROXY_ITERATE_CHAR = "I"
|
DICTPROXY_ITERATE_CHAR = "I"
|
||||||
DICTPROXY_BEGIN_TRANSACTION_CHAR = "B"
|
|
||||||
DICTPROXY_SET_CHAR = "S"
|
DICTPROXY_SET_CHAR = "S"
|
||||||
|
DICTPROXY_BEGIN_TRANSACTION_CHAR = "B"
|
||||||
DICTPROXY_COMMIT_TRANSACTION_CHAR = "C"
|
DICTPROXY_COMMIT_TRANSACTION_CHAR = "C"
|
||||||
DICTPROXY_TRANSACTION_CHARS = "BSC"
|
DICTPROXY_TRANSACTION_CHARS = "SBC"
|
||||||
|
|
||||||
|
|
||||||
class Metadata:
|
class Notifier:
|
||||||
# each SETMETADATA on this key appends to a list of unique device tokens
|
def __init__(self):
|
||||||
# which only ever get removed if the upstream indicates the token is invalid
|
self.guid2token = {}
|
||||||
DEVICETOKEN_KEY = "devicetoken"
|
self.to_notify_queue = Queue()
|
||||||
|
|
||||||
def __init__(self, vmail_dir):
|
def set_token(self, guid, token):
|
||||||
self.vmail_dir = vmail_dir
|
self.guid2token[guid] = token
|
||||||
|
|
||||||
def get_metadata_dict(self, addr):
|
def new_message_for_guid(self, guid):
|
||||||
return FileDict(self.vmail_dir / addr / "metadata.json")
|
self.to_notify_queue.put(guid)
|
||||||
|
|
||||||
def add_token_to_addr(self, addr, token):
|
def thread_run_loop(self):
|
||||||
with self.get_metadata_dict(addr).modify() as data:
|
requests_session = requests.Session()
|
||||||
tokens = data.setdefault(self.DEVICETOKEN_KEY, [])
|
while 1:
|
||||||
if token not in tokens:
|
self.thread_run_one(requests_session)
|
||||||
tokens.append(token)
|
|
||||||
|
|
||||||
def remove_token_from_addr(self, addr, token):
|
def thread_run_one(self, requests_session):
|
||||||
with self.get_metadata_dict(addr).modify() as data:
|
guid = self.to_notify_queue.get()
|
||||||
tokens = data.get(self.DEVICETOKEN_KEY, [])
|
token = self.guid2token.get(guid)
|
||||||
if token in tokens:
|
if token:
|
||||||
tokens.remove(token)
|
response = requests_session.post(
|
||||||
|
"https://notifications.delta.chat/notify",
|
||||||
def get_tokens_for_addr(self, addr):
|
data=token,
|
||||||
mdict = self.get_metadata_dict(addr).read()
|
timeout=60,
|
||||||
return mdict.get(self.DEVICETOKEN_KEY, [])
|
)
|
||||||
|
if response.status_code == 410:
|
||||||
|
# 410 Gone status code
|
||||||
|
# means the token is no longer valid.
|
||||||
|
del self.guid2token[guid]
|
||||||
|
|
||||||
|
|
||||||
def handle_dovecot_protocol(rfile, wfile, notifier, metadata):
|
def handle_dovecot_protocol(rfile, wfile, notifier):
|
||||||
|
# HELLO message, ignored.
|
||||||
|
msg = rfile.readline().strip().decode()
|
||||||
|
|
||||||
transactions = {}
|
transactions = {}
|
||||||
while True:
|
while True:
|
||||||
msg = rfile.readline().strip().decode()
|
msg = rfile.readline().strip().decode()
|
||||||
if not msg:
|
if not msg:
|
||||||
break
|
break
|
||||||
|
|
||||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
res = handle_dovecot_request(msg, transactions, notifier)
|
||||||
if res:
|
if res:
|
||||||
wfile.write(res.encode("ascii"))
|
wfile.write(res.encode("ascii"))
|
||||||
wfile.flush()
|
wfile.flush()
|
||||||
|
|
||||||
|
|
||||||
def handle_dovecot_request(msg, transactions, notifier, metadata):
|
def handle_dovecot_request(msg, transactions, notifier):
|
||||||
# see https://doc.dovecot.org/3.0/developer_manual/design/dict_protocol/
|
# see https://doc.dovecot.org/3.0/developer_manual/design/dict_protocol/
|
||||||
short_command = msg[0]
|
short_command = msg[0]
|
||||||
parts = msg[1:].split("\t")
|
parts = msg[1:].split("\t")
|
||||||
if short_command == DICTPROXY_LOOKUP_CHAR:
|
if short_command == DICTPROXY_LOOKUP_CHAR:
|
||||||
# Lpriv/43f5f508a7ea0366dff30200c15250e3/devicetoken\tlkj123poi@c2.testrun.org
|
|
||||||
keyparts = parts[0].split("/")
|
|
||||||
if keyparts[0] == "priv":
|
|
||||||
keyname = keyparts[2]
|
|
||||||
addr = parts[1]
|
|
||||||
if keyname == metadata.DEVICETOKEN_KEY:
|
|
||||||
res = " ".join(metadata.get_tokens_for_addr(addr))
|
|
||||||
return f"O{res}\n"
|
|
||||||
logging.warning("lookup ignored: %r", msg)
|
|
||||||
return "N\n"
|
return "N\n"
|
||||||
elif short_command == DICTPROXY_ITERATE_CHAR:
|
elif short_command == DICTPROXY_ITERATE_CHAR:
|
||||||
# Empty line means ITER_FINISHED.
|
# Empty line means ITER_FINISHED.
|
||||||
# If we don't return empty line Dovecot will timeout.
|
# If we don't return empty line Dovecot will timeout.
|
||||||
return "\n"
|
return "\n"
|
||||||
elif short_command == DICTPROXY_HELLO_CHAR:
|
|
||||||
return # no version checking
|
|
||||||
|
|
||||||
if short_command not in (DICTPROXY_TRANSACTION_CHARS):
|
if short_command not in (DICTPROXY_TRANSACTION_CHARS):
|
||||||
logging.warning("unknown dictproxy request: %r", msg)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
transaction_id = parts[0]
|
transaction_id = parts[0]
|
||||||
|
|
||||||
if short_command == DICTPROXY_BEGIN_TRANSACTION_CHAR:
|
if short_command == DICTPROXY_BEGIN_TRANSACTION_CHAR:
|
||||||
addr = parts[1]
|
transactions[transaction_id] = "O\n"
|
||||||
transactions[transaction_id] = dict(addr=addr, res="O\n")
|
|
||||||
elif short_command == DICTPROXY_COMMIT_TRANSACTION_CHAR:
|
elif short_command == DICTPROXY_COMMIT_TRANSACTION_CHAR:
|
||||||
# each set devicetoken operation persists directly
|
# returns whether it failed or succeeded.
|
||||||
# and does not wait until a "commit" comes
|
return transactions.pop(transaction_id, "N\n")
|
||||||
# because our dovecot config does not involve
|
|
||||||
# multiple set-operations in a single commit
|
|
||||||
return transactions.pop(transaction_id)["res"]
|
|
||||||
elif short_command == DICTPROXY_SET_CHAR:
|
elif short_command == DICTPROXY_SET_CHAR:
|
||||||
# For documentation on key structure see
|
# See header of
|
||||||
# https://github.com/dovecot/core/blob/main/src/lib-storage/mailbox-attribute.h
|
# <https://github.com/dovecot/core/blob/5e7965632395793d9355eb906b173bf28d2a10ca/src/lib-storage/mailbox-attribute.h>
|
||||||
|
# for the documentation on the structure of the key.
|
||||||
|
|
||||||
|
# Request GETMETADATA "INBOX" /private/chatmail
|
||||||
|
# results in a query for
|
||||||
|
# priv/dd72550f05eadc65542a1200cac67ad7/chatmail
|
||||||
|
#
|
||||||
|
# Request GETMETADATA "" /private/chatmail
|
||||||
|
# results in
|
||||||
|
# priv/dd72550f05eadc65542a1200cac67ad7/vendor/vendor.dovecot/pvt/server/chatmail
|
||||||
|
|
||||||
keyname = parts[1].split("/")
|
keyname = parts[1].split("/")
|
||||||
value = parts[2] if len(parts) > 2 else ""
|
value = parts[2] if len(parts) > 2 else ""
|
||||||
addr = transactions[transaction_id]["addr"]
|
if keyname[0] == "priv" and keyname[2] == "devicetoken":
|
||||||
if keyname[0] == "priv" and keyname[2] == metadata.DEVICETOKEN_KEY:
|
notifier.set_token(keyname[1], value)
|
||||||
metadata.add_token_to_addr(addr, value)
|
|
||||||
elif keyname[0] == "priv" and keyname[2] == "messagenew":
|
elif keyname[0] == "priv" and keyname[2] == "messagenew":
|
||||||
notifier.new_message_for_addr(addr, metadata)
|
notifier.new_message_for_guid(keyname[1])
|
||||||
else:
|
else:
|
||||||
# Transaction failed.
|
# Transaction failed.
|
||||||
transactions[transaction_id]["res"] = "F\n"
|
transactions[transaction_id] = "F\n"
|
||||||
|
|
||||||
|
|
||||||
class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
||||||
@@ -120,25 +119,19 @@ class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
|||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
socket, vmail_dir = sys.argv[1:]
|
socket, username, config = sys.argv[1:]
|
||||||
|
passwd_entry = pwd.getpwnam(username)
|
||||||
|
|
||||||
vmail_dir = Path(vmail_dir)
|
# XXX config is not currently used
|
||||||
if not vmail_dir.exists():
|
config = read_config(config)
|
||||||
logging.error("vmail dir does not exist: %r", vmail_dir)
|
notifier = Notifier()
|
||||||
return 1
|
|
||||||
|
|
||||||
queue_dir = vmail_dir / "pending_notifications"
|
|
||||||
queue_dir.mkdir(exist_ok=True)
|
|
||||||
metadata = Metadata(vmail_dir)
|
|
||||||
notifier = Notifier(queue_dir)
|
|
||||||
notifier.start_notification_threads(metadata.remove_token_from_addr)
|
|
||||||
|
|
||||||
class Handler(StreamRequestHandler):
|
class Handler(StreamRequestHandler):
|
||||||
def handle(self):
|
def handle(self):
|
||||||
try:
|
try:
|
||||||
handle_dovecot_protocol(self.rfile, self.wfile, notifier, metadata)
|
handle_dovecot_protocol(self.rfile, self.wfile, notifier)
|
||||||
except Exception:
|
except Exception:
|
||||||
logging.exception("Exception in the dovecot dictproxy handler")
|
logging.exception("Exception in the handler")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -146,7 +139,15 @@ def main():
|
|||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
# start notifier thread for signalling new messages to
|
||||||
|
# Delta Chat notification server
|
||||||
|
|
||||||
|
t = Thread(target=notifier.thread_run_loop)
|
||||||
|
t.setDaemon(True)
|
||||||
|
t.start()
|
||||||
|
|
||||||
with ThreadedUnixStreamServer(socket, Handler) as server:
|
with ThreadedUnixStreamServer(socket, Handler) as server:
|
||||||
|
os.chown(socket, uid=passwd_entry.pw_uid, gid=passwd_entry.pw_gid)
|
||||||
try:
|
try:
|
||||||
server.serve_forever()
|
server.serve_forever()
|
||||||
except KeyboardInterrupt:
|
except KeyboardInterrupt:
|
||||||
|
|||||||
@@ -1,165 +0,0 @@
|
|||||||
"""
|
|
||||||
This modules provides notification machinery for transmitting device tokens to
|
|
||||||
a central notification server which in turn contacts a phone provider's notification server
|
|
||||||
to trigger Delta Chat apps to retrieve messages and provide instant notifications to users.
|
|
||||||
|
|
||||||
The Notifier class arranges the queuing of tokens in separate PriorityQueues
|
|
||||||
from which NotifyThreads take and transmit them via HTTPS
|
|
||||||
to the `notifications.delta.chat` service.
|
|
||||||
The current lack of proper HTTP/2-support in Python leads us
|
|
||||||
to use multiple threads and connections to the Rust-implemented `notifications.delta.chat`
|
|
||||||
which itself uses HTTP/2 and thus only a single connection to phone-notification providers.
|
|
||||||
|
|
||||||
If a token fails to cause a successful notification
|
|
||||||
it is moved to a retry-number specific PriorityQueue
|
|
||||||
which handles all tokens that failed a particular number of times
|
|
||||||
and which are scheduled for retry using exponential back-off timing.
|
|
||||||
If a token notification would be scheduled more than DROP_DEADLINE seconds
|
|
||||||
after its first attempt, it is dropped with a log error.
|
|
||||||
|
|
||||||
Note that tokens are completely opaque to the notification machinery here
|
|
||||||
and will in the future be encrypted foreclosing all ability to distinguish
|
|
||||||
which device token ultimately goes to which phone-provider notification service,
|
|
||||||
or to understand the relation of "device tokens" and chatmail addresses.
|
|
||||||
The meaning and format of tokens is basically a matter of Delta-Chat Core and
|
|
||||||
the `notification.delta.chat` service.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import math
|
|
||||||
import logging
|
|
||||||
from uuid import uuid4
|
|
||||||
from threading import Thread
|
|
||||||
from pathlib import Path
|
|
||||||
from queue import PriorityQueue
|
|
||||||
from dataclasses import dataclass
|
|
||||||
import requests
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class PersistentQueueItem:
|
|
||||||
path: Path
|
|
||||||
addr: str
|
|
||||||
start_ts: int
|
|
||||||
token: str
|
|
||||||
|
|
||||||
def delete(self):
|
|
||||||
self.path.unlink(missing_ok=True)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def create(cls, queue_dir, addr, start_ts, token):
|
|
||||||
queue_id = uuid4().hex
|
|
||||||
start_ts = int(start_ts)
|
|
||||||
path = queue_dir.joinpath(queue_id)
|
|
||||||
tmp_path = path.with_name(path.name + ".tmp")
|
|
||||||
tmp_path.write_text(f"{addr}\n{start_ts}\n{token}")
|
|
||||||
os.rename(tmp_path, path)
|
|
||||||
return cls(path, addr, start_ts, token)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def read_from_path(cls, path):
|
|
||||||
addr, start_ts, token = path.read_text().split("\n", maxsplit=2)
|
|
||||||
return cls(path, addr, int(start_ts), token)
|
|
||||||
|
|
||||||
def __lt__(self, other):
|
|
||||||
return self.start_ts < other.start_ts
|
|
||||||
|
|
||||||
|
|
||||||
class Notifier:
|
|
||||||
URL = "https://notifications.delta.chat/notify"
|
|
||||||
CONNECTION_TIMEOUT = 60.0 # seconds until http-request is given up
|
|
||||||
BASE_DELAY = 8.0 # base seconds for exponential back-off delay
|
|
||||||
DROP_DEADLINE = 5 * 60 * 60 # drop notifications after 5 hours
|
|
||||||
|
|
||||||
def __init__(self, queue_dir):
|
|
||||||
self.queue_dir = queue_dir
|
|
||||||
max_tries = int(math.log(self.DROP_DEADLINE, self.BASE_DELAY)) + 1
|
|
||||||
self.retry_queues = [PriorityQueue() for _ in range(max_tries)]
|
|
||||||
|
|
||||||
def compute_delay(self, retry_num):
|
|
||||||
return 0 if retry_num == 0 else pow(self.BASE_DELAY, retry_num)
|
|
||||||
|
|
||||||
def new_message_for_addr(self, addr, metadata):
|
|
||||||
start_ts = int(time.time())
|
|
||||||
for token in metadata.get_tokens_for_addr(addr):
|
|
||||||
queue_item = PersistentQueueItem.create(
|
|
||||||
self.queue_dir, addr, start_ts, token
|
|
||||||
)
|
|
||||||
self.queue_for_retry(queue_item)
|
|
||||||
|
|
||||||
def requeue_persistent_queue_items(self):
|
|
||||||
for queue_path in self.queue_dir.iterdir():
|
|
||||||
if queue_path.name.endswith(".tmp"):
|
|
||||||
logging.warning("removing spurious queue item: %r", queue_path)
|
|
||||||
queue_path.unlink()
|
|
||||||
continue
|
|
||||||
queue_item = PersistentQueueItem.read_from_path(queue_path)
|
|
||||||
self.queue_for_retry(queue_item)
|
|
||||||
|
|
||||||
def queue_for_retry(self, queue_item, retry_num=0):
|
|
||||||
delay = self.compute_delay(retry_num)
|
|
||||||
when = int(time.time()) + delay
|
|
||||||
deadline = queue_item.start_ts + self.DROP_DEADLINE
|
|
||||||
if retry_num >= len(self.retry_queues) or when > deadline:
|
|
||||||
queue_item.delete()
|
|
||||||
logging.error("notification exceeded deadline: %r", queue_item.token)
|
|
||||||
return
|
|
||||||
|
|
||||||
self.retry_queues[retry_num].put((when, queue_item))
|
|
||||||
|
|
||||||
def start_notification_threads(self, remove_token_from_addr):
|
|
||||||
self.requeue_persistent_queue_items()
|
|
||||||
threads = {}
|
|
||||||
for retry_num in range(len(self.retry_queues)):
|
|
||||||
# use 4 threads for first-try tokens and less for subsequent tries
|
|
||||||
num_threads = 4 if retry_num == 0 else 2
|
|
||||||
threads[retry_num] = []
|
|
||||||
for _ in range(num_threads):
|
|
||||||
thread = NotifyThread(self, retry_num, remove_token_from_addr)
|
|
||||||
threads[retry_num].append(thread)
|
|
||||||
thread.start()
|
|
||||||
return threads
|
|
||||||
|
|
||||||
|
|
||||||
class NotifyThread(Thread):
|
|
||||||
def __init__(self, notifier, retry_num, remove_token_from_addr):
|
|
||||||
super().__init__(daemon=True)
|
|
||||||
self.notifier = notifier
|
|
||||||
self.retry_num = retry_num
|
|
||||||
self.remove_token_from_addr = remove_token_from_addr
|
|
||||||
|
|
||||||
def stop(self):
|
|
||||||
self.notifier.retry_queues[self.retry_num].put((None, None))
|
|
||||||
|
|
||||||
def run(self):
|
|
||||||
requests_session = requests.Session()
|
|
||||||
while self.retry_one(requests_session):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def retry_one(self, requests_session, sleep=time.sleep):
|
|
||||||
when, queue_item = self.notifier.retry_queues[self.retry_num].get()
|
|
||||||
if when is None:
|
|
||||||
return False
|
|
||||||
wait_time = when - int(time.time())
|
|
||||||
if wait_time > 0:
|
|
||||||
sleep(wait_time)
|
|
||||||
self.perform_request_to_notification_server(requests_session, queue_item)
|
|
||||||
return True
|
|
||||||
|
|
||||||
def perform_request_to_notification_server(self, requests_session, queue_item):
|
|
||||||
timeout = self.notifier.CONNECTION_TIMEOUT
|
|
||||||
token = queue_item.token
|
|
||||||
try:
|
|
||||||
res = requests_session.post(self.notifier.URL, data=token, timeout=timeout)
|
|
||||||
except requests.exceptions.RequestException as e:
|
|
||||||
res = e
|
|
||||||
else:
|
|
||||||
if res.status_code in (200, 410):
|
|
||||||
if res.status_code == 410:
|
|
||||||
self.remove_token_from_addr(queue_item.addr, token)
|
|
||||||
queue_item.delete()
|
|
||||||
return
|
|
||||||
|
|
||||||
logging.warning("Notification request failed: %r", res)
|
|
||||||
self.notifier.queue_for_retry(queue_item, retry_num=self.retry_num + 1)
|
|
||||||
@@ -75,14 +75,6 @@ def test_handle_dovecot_request(db, example_config):
|
|||||||
assert userdata["password"].startswith("{SHA512-CRYPT}")
|
assert userdata["password"].startswith("{SHA512-CRYPT}")
|
||||||
|
|
||||||
|
|
||||||
def test_handle_dovecot_protocol_hello_is_skipped(db, example_config, caplog):
|
|
||||||
rfile = io.BytesIO(b"H3\t2\t0\t\tauth\n")
|
|
||||||
wfile = io.BytesIO()
|
|
||||||
handle_dovecot_protocol(rfile, wfile, db, example_config)
|
|
||||||
assert wfile.getvalue() == b""
|
|
||||||
assert not caplog.messages
|
|
||||||
|
|
||||||
|
|
||||||
def test_handle_dovecot_protocol(db, example_config):
|
def test_handle_dovecot_protocol(db, example_config):
|
||||||
rfile = io.BytesIO(
|
rfile = io.BytesIO(
|
||||||
b"H3\t2\t0\t\tauth\nLshared/userdb/foobar@chat.example.org\tfoobar@chat.example.org\n"
|
b"H3\t2\t0\t\tauth\nLshared/userdb/foobar@chat.example.org\tfoobar@chat.example.org\n"
|
||||||
|
|||||||
@@ -1,19 +0,0 @@
|
|||||||
from chatmaild.filedict import FileDict
|
|
||||||
|
|
||||||
|
|
||||||
def test_basic(tmp_path):
|
|
||||||
fdict = FileDict(tmp_path.joinpath("metadata"))
|
|
||||||
assert fdict.read() == {}
|
|
||||||
with fdict.modify() as d:
|
|
||||||
d["devicetoken"] = [1, 2, 3]
|
|
||||||
d["456"] = 4.2
|
|
||||||
new = fdict.read()
|
|
||||||
assert new["devicetoken"] == [1, 2, 3]
|
|
||||||
assert new["456"] == 4.2
|
|
||||||
|
|
||||||
|
|
||||||
def test_bad_marshal_file(tmp_path, caplog):
|
|
||||||
fdict1 = FileDict(tmp_path.joinpath("metadata"))
|
|
||||||
fdict1.path.write_bytes(b"l12k3l12k3l")
|
|
||||||
assert fdict1.read() == {}
|
|
||||||
assert "corrupt" in caplog.records[0].msg
|
|
||||||
@@ -1,179 +1,76 @@
|
|||||||
import io
|
import io
|
||||||
import pytest
|
|
||||||
import requests
|
|
||||||
import time
|
|
||||||
|
|
||||||
from chatmaild.metadata import (
|
from chatmaild.metadata import (
|
||||||
handle_dovecot_request,
|
handle_dovecot_request,
|
||||||
handle_dovecot_protocol,
|
handle_dovecot_protocol,
|
||||||
Metadata,
|
|
||||||
)
|
|
||||||
from chatmaild.notifier import (
|
|
||||||
Notifier,
|
Notifier,
|
||||||
NotifyThread,
|
|
||||||
PersistentQueueItem,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
def test_handle_dovecot_request_lookup_fails():
|
||||||
def notifier(metadata):
|
notifier = Notifier()
|
||||||
queue_dir = metadata.vmail_dir.joinpath("pending_notifications")
|
res = handle_dovecot_request("Lpriv/123/chatmail", {}, notifier)
|
||||||
queue_dir.mkdir()
|
|
||||||
return Notifier(queue_dir)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def metadata(tmp_path):
|
|
||||||
vmail_dir = tmp_path.joinpath("vmaildir")
|
|
||||||
vmail_dir.mkdir()
|
|
||||||
return Metadata(vmail_dir)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def testaddr():
|
|
||||||
return "user.name@example.org"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def testaddr2():
|
|
||||||
return "user2@example.org"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def token():
|
|
||||||
return "01234"
|
|
||||||
|
|
||||||
|
|
||||||
def get_mocked_requests(statuslist):
|
|
||||||
class ReqMock:
|
|
||||||
requests = []
|
|
||||||
|
|
||||||
def post(self, url, data, timeout):
|
|
||||||
self.requests.append((url, data, timeout))
|
|
||||||
res = statuslist.pop(0)
|
|
||||||
if isinstance(res, Exception):
|
|
||||||
raise res
|
|
||||||
|
|
||||||
class Result:
|
|
||||||
status_code = res
|
|
||||||
|
|
||||||
return Result()
|
|
||||||
|
|
||||||
return ReqMock()
|
|
||||||
|
|
||||||
|
|
||||||
def test_metadata_persistence(tmp_path, testaddr, testaddr2):
|
|
||||||
metadata1 = Metadata(tmp_path)
|
|
||||||
metadata2 = Metadata(tmp_path)
|
|
||||||
assert not metadata1.get_tokens_for_addr(testaddr)
|
|
||||||
assert not metadata2.get_tokens_for_addr(testaddr)
|
|
||||||
|
|
||||||
metadata1.add_token_to_addr(testaddr, "01234")
|
|
||||||
metadata1.add_token_to_addr(testaddr2, "456")
|
|
||||||
assert metadata2.get_tokens_for_addr(testaddr) == ["01234"]
|
|
||||||
assert metadata2.get_tokens_for_addr(testaddr2) == ["456"]
|
|
||||||
metadata2.remove_token_from_addr(testaddr, "01234")
|
|
||||||
assert not metadata1.get_tokens_for_addr(testaddr)
|
|
||||||
assert metadata1.get_tokens_for_addr(testaddr2) == ["456"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_remove_nonexisting(metadata, tmp_path, testaddr):
|
|
||||||
metadata.add_token_to_addr(testaddr, "123")
|
|
||||||
metadata.remove_token_from_addr(testaddr, "1l23k1l2k3")
|
|
||||||
assert metadata.get_tokens_for_addr(testaddr) == ["123"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_notifier_remove_without_set(metadata, testaddr):
|
|
||||||
metadata.remove_token_from_addr(testaddr, "123")
|
|
||||||
assert not metadata.get_tokens_for_addr(testaddr)
|
|
||||||
|
|
||||||
|
|
||||||
def test_handle_dovecot_request_lookup_fails(notifier, metadata, testaddr):
|
|
||||||
res = handle_dovecot_request(
|
|
||||||
f"Lpriv/123/chatmail\t{testaddr}", {}, notifier, metadata
|
|
||||||
)
|
|
||||||
assert res == "N\n"
|
assert res == "N\n"
|
||||||
|
|
||||||
|
|
||||||
def test_handle_dovecot_request_happy_path(notifier, metadata, testaddr, token):
|
def test_handle_dovecot_request_happy_path():
|
||||||
|
notifier = Notifier()
|
||||||
transactions = {}
|
transactions = {}
|
||||||
|
|
||||||
|
# lookups return the same NOTFOUND result
|
||||||
|
res = handle_dovecot_request("Lpriv/123/chatmail", transactions, notifier)
|
||||||
|
assert res == "N\n"
|
||||||
|
assert not notifier.guid2token and not transactions
|
||||||
|
|
||||||
# set device token in a transaction
|
# set device token in a transaction
|
||||||
tx = "1111"
|
tx = "1111"
|
||||||
msg = f"B{tx}\t{testaddr}"
|
msg = f"B{tx}\tuser"
|
||||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
res = handle_dovecot_request(msg, transactions, notifier)
|
||||||
assert not res and not metadata.get_tokens_for_addr(testaddr)
|
assert not res and not notifier.guid2token
|
||||||
assert transactions == {tx: dict(addr=testaddr, res="O\n")}
|
assert transactions == {tx: "O\n"}
|
||||||
|
|
||||||
msg = f"S{tx}\tpriv/guid00/devicetoken\t{token}"
|
msg = f"S{tx}\tpriv/guid00/devicetoken\t01234"
|
||||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
res = handle_dovecot_request(msg, transactions, notifier)
|
||||||
assert not res
|
assert not res
|
||||||
assert len(transactions) == 1
|
assert len(transactions) == 1
|
||||||
assert metadata.get_tokens_for_addr(testaddr) == [token]
|
assert len(notifier.guid2token) == 1
|
||||||
|
assert notifier.guid2token["guid00"] == "01234"
|
||||||
|
|
||||||
msg = f"C{tx}"
|
msg = f"C{tx}"
|
||||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
res = handle_dovecot_request(msg, transactions, notifier)
|
||||||
assert res == "O\n"
|
assert res == "O\n"
|
||||||
assert len(transactions) == 0
|
assert len(transactions) == 0
|
||||||
assert metadata.get_tokens_for_addr(testaddr) == [token]
|
assert notifier.guid2token["guid00"] == "01234"
|
||||||
|
|
||||||
# trigger notification for incoming message
|
# trigger notification for incoming message
|
||||||
tx2 = "2222"
|
assert handle_dovecot_request(f"B{tx}\tuser", transactions, notifier) is None
|
||||||
assert (
|
msg = f"S{tx}\tpriv/guid00/messagenew"
|
||||||
handle_dovecot_request(f"B{tx2}\t{testaddr}", transactions, notifier, metadata)
|
assert handle_dovecot_request(msg, transactions, notifier) is None
|
||||||
is None
|
assert notifier.to_notify_queue.get() == "guid00"
|
||||||
)
|
assert notifier.to_notify_queue.qsize() == 0
|
||||||
msg = f"S{tx2}\tpriv/guid00/messagenew"
|
assert handle_dovecot_request(f"C{tx}\tuser", transactions, notifier) == "O\n"
|
||||||
assert handle_dovecot_request(msg, transactions, notifier, metadata) is None
|
|
||||||
queue_item = notifier.retry_queues[0].get()[1]
|
|
||||||
assert queue_item.token == token
|
|
||||||
assert handle_dovecot_request(f"C{tx2}", transactions, notifier, metadata) == "O\n"
|
|
||||||
assert not transactions
|
assert not transactions
|
||||||
assert queue_item.path.exists()
|
|
||||||
|
|
||||||
|
|
||||||
def test_handle_dovecot_protocol_set_devicetoken(metadata, notifier):
|
def test_handle_dovecot_protocol_set_devicetoken():
|
||||||
rfile = io.BytesIO(
|
rfile = io.BytesIO(
|
||||||
b"\n".join(
|
b"\n".join(
|
||||||
[
|
[
|
||||||
b"HELLO",
|
b"HELLO",
|
||||||
b"Btx00\tuser@example.org",
|
b"Btx00\tuser",
|
||||||
b"Stx00\tpriv/guid00/devicetoken\t01234",
|
b"Stx00\tpriv/guid00/devicetoken\t01234",
|
||||||
b"Ctx00",
|
b"Ctx00",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
wfile = io.BytesIO()
|
wfile = io.BytesIO()
|
||||||
handle_dovecot_protocol(rfile, wfile, notifier, metadata)
|
notifier = Notifier()
|
||||||
assert wfile.getvalue() == b"O\n"
|
handle_dovecot_protocol(rfile, wfile, notifier)
|
||||||
assert metadata.get_tokens_for_addr("user@example.org") == ["01234"]
|
assert notifier.guid2token["guid00"] == "01234"
|
||||||
|
|
||||||
|
|
||||||
def test_handle_dovecot_protocol_set_get_devicetoken(metadata, notifier):
|
|
||||||
rfile = io.BytesIO(
|
|
||||||
b"\n".join(
|
|
||||||
[
|
|
||||||
b"HELLO",
|
|
||||||
b"Btx00\tuser@example.org",
|
|
||||||
b"Stx00\tpriv/guid00/devicetoken\t01234",
|
|
||||||
b"Ctx00",
|
|
||||||
]
|
|
||||||
)
|
|
||||||
)
|
|
||||||
wfile = io.BytesIO()
|
|
||||||
handle_dovecot_protocol(rfile, wfile, notifier, metadata)
|
|
||||||
assert metadata.get_tokens_for_addr("user@example.org") == ["01234"]
|
|
||||||
assert wfile.getvalue() == b"O\n"
|
assert wfile.getvalue() == b"O\n"
|
||||||
|
|
||||||
rfile = io.BytesIO(
|
|
||||||
b"\n".join([b"HELLO", b"Lpriv/0123/devicetoken\tuser@example.org"])
|
|
||||||
)
|
|
||||||
wfile = io.BytesIO()
|
|
||||||
handle_dovecot_protocol(rfile, wfile, notifier, metadata)
|
|
||||||
assert wfile.getvalue() == b"O01234\n"
|
|
||||||
|
|
||||||
|
def test_handle_dovecot_protocol_iterate():
|
||||||
def test_handle_dovecot_protocol_iterate(metadata, notifier):
|
|
||||||
rfile = io.BytesIO(
|
rfile = io.BytesIO(
|
||||||
b"\n".join(
|
b"\n".join(
|
||||||
[
|
[
|
||||||
@@ -183,116 +80,68 @@ def test_handle_dovecot_protocol_iterate(metadata, notifier):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
wfile = io.BytesIO()
|
wfile = io.BytesIO()
|
||||||
handle_dovecot_protocol(rfile, wfile, notifier, metadata)
|
notifier = Notifier()
|
||||||
|
handle_dovecot_protocol(rfile, wfile, notifier)
|
||||||
assert wfile.getvalue() == b"\n"
|
assert wfile.getvalue() == b"\n"
|
||||||
|
|
||||||
|
|
||||||
def test_notifier_thread_deletes_persistent_file(metadata, notifier, testaddr):
|
def test_handle_dovecot_protocol_messagenew():
|
||||||
reqmock = get_mocked_requests([200])
|
rfile = io.BytesIO(
|
||||||
metadata.add_token_to_addr(testaddr, "01234")
|
b"\n".join(
|
||||||
notifier.new_message_for_addr(testaddr, metadata)
|
[
|
||||||
NotifyThread(notifier, 0, None).retry_one(reqmock)
|
b"HELLO",
|
||||||
url, data, timeout = reqmock.requests[0]
|
b"Btx01\tuser",
|
||||||
|
b"Stx01\tpriv/guid00/messagenew",
|
||||||
|
b"Ctx01",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
)
|
||||||
|
wfile = io.BytesIO()
|
||||||
|
notifier = Notifier()
|
||||||
|
handle_dovecot_protocol(rfile, wfile, notifier)
|
||||||
|
assert wfile.getvalue() == b"O\n"
|
||||||
|
assert notifier.to_notify_queue.get() == "guid00"
|
||||||
|
assert notifier.to_notify_queue.qsize() == 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_notifier_thread_run():
|
||||||
|
requests = []
|
||||||
|
|
||||||
|
class ReqMock:
|
||||||
|
def post(self, url, data, timeout):
|
||||||
|
requests.append((url, data, timeout))
|
||||||
|
|
||||||
|
class Result:
|
||||||
|
status_code = 200
|
||||||
|
|
||||||
|
return Result()
|
||||||
|
|
||||||
|
notifier = Notifier()
|
||||||
|
notifier.set_token("guid00", "01234")
|
||||||
|
notifier.new_message_for_guid("guid00")
|
||||||
|
notifier.thread_run_one(ReqMock())
|
||||||
|
url, data, timeout = requests[0]
|
||||||
assert data == "01234"
|
assert data == "01234"
|
||||||
assert metadata.get_tokens_for_addr(testaddr) == ["01234"]
|
assert len(notifier.guid2token) == 1
|
||||||
notifier.requeue_persistent_queue_items()
|
|
||||||
assert notifier.retry_queues[0].qsize() == 0
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("status", [requests.exceptions.RequestException(), 404, 500])
|
def test_notifier_thread_run_gone_removes_token():
|
||||||
def test_notifier_thread_connection_failures(
|
requests = []
|
||||||
metadata, notifier, testaddr, status, caplog
|
|
||||||
):
|
|
||||||
"""test that tokens keep getting retried until they are given up."""
|
|
||||||
metadata.add_token_to_addr(testaddr, "01234")
|
|
||||||
notifier.new_message_for_addr(testaddr, metadata)
|
|
||||||
notifier.NOTIFICATION_RETRY_DELAY = 5
|
|
||||||
max_tries = len(notifier.retry_queues)
|
|
||||||
for i in range(max_tries):
|
|
||||||
caplog.clear()
|
|
||||||
reqmock = get_mocked_requests([status])
|
|
||||||
sleep_calls = []
|
|
||||||
NotifyThread(notifier, i, None).retry_one(reqmock, sleep=sleep_calls.append)
|
|
||||||
assert notifier.retry_queues[i].qsize() == 0
|
|
||||||
assert "request failed" in caplog.records[0].msg
|
|
||||||
if i > 0:
|
|
||||||
assert len(sleep_calls) == 1
|
|
||||||
if i + 1 < max_tries:
|
|
||||||
assert notifier.retry_queues[i + 1].qsize() == 1
|
|
||||||
assert len(caplog.records) == 1
|
|
||||||
else:
|
|
||||||
assert len(caplog.records) == 2
|
|
||||||
assert "deadline" in caplog.records[1].msg
|
|
||||||
notifier.requeue_persistent_queue_items()
|
|
||||||
assert notifier.retry_queues[0].qsize() == 0
|
|
||||||
|
|
||||||
|
class ReqMock:
|
||||||
|
def post(self, url, data, timeout):
|
||||||
|
requests.append((url, data, timeout))
|
||||||
|
|
||||||
def test_requeue_removes_tmp_files(notifier, metadata, testaddr, caplog):
|
class Result:
|
||||||
metadata.add_token_to_addr(testaddr, "01234")
|
status_code = 410
|
||||||
notifier.new_message_for_addr(testaddr, metadata)
|
|
||||||
p = notifier.queue_dir.joinpath("1203981203.tmp")
|
|
||||||
p.touch()
|
|
||||||
notifier2 = notifier.__class__(notifier.queue_dir)
|
|
||||||
notifier2.requeue_persistent_queue_items()
|
|
||||||
assert "spurious" in caplog.records[0].msg
|
|
||||||
assert not p.exists()
|
|
||||||
assert notifier2.retry_queues[0].qsize() == 1
|
|
||||||
when, queue_item = notifier2.retry_queues[0].get()
|
|
||||||
assert when <= int(time.time())
|
|
||||||
assert queue_item.addr == testaddr
|
|
||||||
|
|
||||||
|
return Result()
|
||||||
|
|
||||||
def test_start_and_stop_notification_threads(notifier, testaddr):
|
notifier = Notifier()
|
||||||
threads = notifier.start_notification_threads(None)
|
notifier.set_token("guid00", "01234")
|
||||||
for retry_num, threadlist in threads.items():
|
notifier.new_message_for_guid("guid00")
|
||||||
for t in threadlist:
|
assert notifier.guid2token["guid00"] == "01234"
|
||||||
t.stop()
|
notifier.thread_run_one(ReqMock())
|
||||||
t.join()
|
url, data, timeout = requests[0]
|
||||||
|
|
||||||
|
|
||||||
def test_multi_device_notifier(metadata, notifier, testaddr):
|
|
||||||
metadata.add_token_to_addr(testaddr, "01234")
|
|
||||||
metadata.add_token_to_addr(testaddr, "56789")
|
|
||||||
notifier.new_message_for_addr(testaddr, metadata)
|
|
||||||
reqmock = get_mocked_requests([200, 200])
|
|
||||||
NotifyThread(notifier, 0, None).retry_one(reqmock)
|
|
||||||
NotifyThread(notifier, 0, None).retry_one(reqmock)
|
|
||||||
assert notifier.retry_queues[0].qsize() == 0
|
|
||||||
assert notifier.retry_queues[1].qsize() == 0
|
|
||||||
url, data, timeout = reqmock.requests[0]
|
|
||||||
assert data == "01234"
|
assert data == "01234"
|
||||||
url, data, timeout = reqmock.requests[1]
|
assert len(notifier.guid2token) == 0
|
||||||
assert data == "56789"
|
|
||||||
assert metadata.get_tokens_for_addr(testaddr) == ["01234", "56789"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_notifier_thread_run_gone_removes_token(metadata, notifier, testaddr):
|
|
||||||
metadata.add_token_to_addr(testaddr, "01234")
|
|
||||||
metadata.add_token_to_addr(testaddr, "45678")
|
|
||||||
notifier.new_message_for_addr(testaddr, metadata)
|
|
||||||
|
|
||||||
reqmock = get_mocked_requests([410, 200])
|
|
||||||
NotifyThread(notifier, 0, metadata.remove_token_from_addr).retry_one(reqmock)
|
|
||||||
NotifyThread(notifier, 0, None).retry_one(reqmock)
|
|
||||||
url, data, timeout = reqmock.requests[0]
|
|
||||||
assert data == "01234"
|
|
||||||
url, data, timeout = reqmock.requests[1]
|
|
||||||
assert data == "45678"
|
|
||||||
assert metadata.get_tokens_for_addr(testaddr) == ["45678"]
|
|
||||||
assert notifier.retry_queues[0].qsize() == 0
|
|
||||||
assert notifier.retry_queues[1].qsize() == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_persistent_queue_items(tmp_path, testaddr, token):
|
|
||||||
queue_item = PersistentQueueItem.create(tmp_path, testaddr, 432, token)
|
|
||||||
assert queue_item.addr == testaddr
|
|
||||||
assert queue_item.start_ts == 432
|
|
||||||
assert queue_item.token == token
|
|
||||||
item2 = PersistentQueueItem.read_from_path(queue_item.path)
|
|
||||||
assert item2.addr == testaddr
|
|
||||||
assert item2.start_ts == 432
|
|
||||||
assert item2.token == token
|
|
||||||
assert item2 == queue_item
|
|
||||||
item2.delete()
|
|
||||||
assert not item2.path.exists()
|
|
||||||
assert not queue_item < item2 and not item2 < queue_item
|
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ dependencies = [
|
|||||||
"black",
|
"black",
|
||||||
"pytest",
|
"pytest",
|
||||||
"pytest-xdist",
|
"pytest-xdist",
|
||||||
"imap_tools",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[project.scripts]
|
[project.scripts]
|
||||||
|
|||||||
@@ -108,11 +108,8 @@ def _install_remote_venv_with_chatmaild(config) -> None:
|
|||||||
execpath=f"{remote_venv_dir}/bin/{fn}",
|
execpath=f"{remote_venv_dir}/bin/{fn}",
|
||||||
config_path=remote_chatmail_inipath,
|
config_path=remote_chatmail_inipath,
|
||||||
remote_venv_dir=remote_venv_dir,
|
remote_venv_dir=remote_venv_dir,
|
||||||
mail_domain=config.mail_domain,
|
|
||||||
)
|
|
||||||
source_path = importlib.resources.files(__package__).joinpath(
|
|
||||||
"service", f"{fn}.service.f"
|
|
||||||
)
|
)
|
||||||
|
source_path = importlib.resources.files("chatmaild").joinpath(f"{fn}.service.f")
|
||||||
content = source_path.read_text().format(**params).encode()
|
content = source_path.read_text().format(**params).encode()
|
||||||
|
|
||||||
files.put(
|
files.put(
|
||||||
@@ -135,6 +132,20 @@ def _configure_opendkim(domain: str, dkim_selector: str = "dkim") -> bool:
|
|||||||
"""Configures OpenDKIM"""
|
"""Configures OpenDKIM"""
|
||||||
need_restart = False
|
need_restart = False
|
||||||
|
|
||||||
|
server.group(name="Create opendkim group", group="opendkim", system=True)
|
||||||
|
server.user(
|
||||||
|
name="Create opendkim user",
|
||||||
|
user="opendkim",
|
||||||
|
groups=["opendkim"],
|
||||||
|
system=True,
|
||||||
|
)
|
||||||
|
server.user(
|
||||||
|
name="Add postfix user to opendkim group for socket access",
|
||||||
|
user="postfix",
|
||||||
|
groups=["opendkim"],
|
||||||
|
system=True,
|
||||||
|
)
|
||||||
|
|
||||||
main_config = files.template(
|
main_config = files.template(
|
||||||
src=importlib.resources.files(__package__).joinpath("opendkim/opendkim.conf"),
|
src=importlib.resources.files(__package__).joinpath("opendkim/opendkim.conf"),
|
||||||
dest="/etc/opendkim.conf",
|
dest="/etc/opendkim.conf",
|
||||||
@@ -339,18 +350,15 @@ def _configure_dovecot(config: Config, debug: bool = False) -> bool:
|
|||||||
need_restart |= lua_push_notification_script.changed
|
need_restart |= lua_push_notification_script.changed
|
||||||
|
|
||||||
sieve_script = files.put(
|
sieve_script = files.put(
|
||||||
src=importlib.resources.files(__package__).joinpath("dovecot/default.sieve"),
|
src=importlib.resources.files(__package__).joinpath(
|
||||||
|
"dovecot/default.sieve"
|
||||||
|
),
|
||||||
dest="/etc/dovecot/default.sieve",
|
dest="/etc/dovecot/default.sieve",
|
||||||
user="root",
|
user="root",
|
||||||
group="root",
|
group="root",
|
||||||
mode="644",
|
mode="644",
|
||||||
)
|
)
|
||||||
need_restart |= sieve_script.changed
|
need_restart |= sieve_script.changed
|
||||||
if sieve_script.changed:
|
|
||||||
server.shell(
|
|
||||||
name="compile sieve script",
|
|
||||||
commands=["/usr/bin/sievec /etc/dovecot/default.sieve"],
|
|
||||||
)
|
|
||||||
|
|
||||||
files.template(
|
files.template(
|
||||||
src=importlib.resources.files(__package__).joinpath("dovecot/expunge.cron.j2"),
|
src=importlib.resources.files(__package__).joinpath("dovecot/expunge.cron.j2"),
|
||||||
@@ -442,9 +450,7 @@ def check_config(config):
|
|||||||
blocked_words = "merlinux schmieder testrun.org".split()
|
blocked_words = "merlinux schmieder testrun.org".split()
|
||||||
for key in config.__dict__:
|
for key in config.__dict__:
|
||||||
value = config.__dict__[key]
|
value = config.__dict__[key]
|
||||||
if key.startswith("privacy") and any(
|
if key.startswith("privacy") and any(x in str(value) for x in blocked_words):
|
||||||
x in str(value) for x in blocked_words
|
|
||||||
):
|
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"please set your own privacy contacts/addresses in {config._inipath}"
|
f"please set your own privacy contacts/addresses in {config._inipath}"
|
||||||
)
|
)
|
||||||
@@ -462,29 +468,9 @@ def deploy_chatmail(config_path: Path) -> None:
|
|||||||
|
|
||||||
from .www import build_webpages
|
from .www import build_webpages
|
||||||
|
|
||||||
|
apt.update(name="apt update", cache_time=24 * 3600)
|
||||||
server.group(name="Create vmail group", group="vmail", system=True)
|
server.group(name="Create vmail group", group="vmail", system=True)
|
||||||
server.user(name="Create vmail user", user="vmail", group="vmail", system=True)
|
server.user(name="Create vmail user", user="vmail", group="vmail", system=True)
|
||||||
server.group(name="Create opendkim group", group="opendkim", system=True)
|
|
||||||
server.user(
|
|
||||||
name="Create opendkim user",
|
|
||||||
user="opendkim",
|
|
||||||
groups=["opendkim"],
|
|
||||||
system=True,
|
|
||||||
)
|
|
||||||
server.user(
|
|
||||||
name="Add postfix user to opendkim group for socket access",
|
|
||||||
user="postfix",
|
|
||||||
groups=["opendkim"],
|
|
||||||
system=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
server.shell(
|
|
||||||
name="Fix file owner in /home/vmail",
|
|
||||||
commands=["test -d /home/vmail && chown -R vmail:vmail /home/vmail"],
|
|
||||||
)
|
|
||||||
|
|
||||||
apt.update(name="apt update", cache_time=24 * 3600)
|
|
||||||
|
|
||||||
apt.packages(
|
apt.packages(
|
||||||
name="Install rsync",
|
name="Install rsync",
|
||||||
packages=["rsync"],
|
packages=["rsync"],
|
||||||
@@ -571,17 +557,6 @@ def deploy_chatmail(config_path: Path) -> None:
|
|||||||
restarted=mta_sts_need_restart,
|
restarted=mta_sts_need_restart,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Dovecot should be started before Postfix
|
|
||||||
# because it creates authentication socket
|
|
||||||
# required by Postfix.
|
|
||||||
systemd.service(
|
|
||||||
name="Start and enable Dovecot",
|
|
||||||
service="dovecot.service",
|
|
||||||
running=True,
|
|
||||||
enabled=True,
|
|
||||||
restarted=dovecot_need_restart,
|
|
||||||
)
|
|
||||||
|
|
||||||
systemd.service(
|
systemd.service(
|
||||||
name="Start and enable Postfix",
|
name="Start and enable Postfix",
|
||||||
service="postfix.service",
|
service="postfix.service",
|
||||||
@@ -590,6 +565,14 @@ def deploy_chatmail(config_path: Path) -> None:
|
|||||||
restarted=postfix_need_restart,
|
restarted=postfix_need_restart,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
systemd.service(
|
||||||
|
name="Start and enable Dovecot",
|
||||||
|
service="dovecot.service",
|
||||||
|
running=True,
|
||||||
|
enabled=True,
|
||||||
|
restarted=dovecot_need_restart,
|
||||||
|
)
|
||||||
|
|
||||||
systemd.service(
|
systemd.service(
|
||||||
name="Start and enable nginx",
|
name="Start and enable nginx",
|
||||||
service="nginx.service",
|
service="nginx.service",
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
SHELL=/bin/sh
|
SHELL=/bin/sh
|
||||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
|
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
|
||||||
MAILTO=root
|
MAILTO=root
|
||||||
20 16 * * * root /usr/bin/acmetool --batch reconcile && systemctl reload dovecot && systemctl reload postfix
|
20 16 * * * root /usr/bin/acmetool --batch reconcile
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ _submissions._tcp.{chatmail_domain}. SRV 0 1 465 {chatmail_domain}.
|
|||||||
_imap._tcp.{chatmail_domain}. SRV 0 1 143 {chatmail_domain}.
|
_imap._tcp.{chatmail_domain}. SRV 0 1 143 {chatmail_domain}.
|
||||||
_imaps._tcp.{chatmail_domain}. SRV 0 1 993 {chatmail_domain}.
|
_imaps._tcp.{chatmail_domain}. SRV 0 1 993 {chatmail_domain}.
|
||||||
{chatmail_domain}. CAA 128 issue "letsencrypt.org;accounturi={acme_account_url}"
|
{chatmail_domain}. CAA 128 issue "letsencrypt.org;accounturi={acme_account_url}"
|
||||||
{chatmail_domain}. TXT "v=spf1 a:{chatmail_domain} ~all"
|
{chatmail_domain}. TXT "v=spf1 a:{chatmail_domain} -all"
|
||||||
_dmarc.{chatmail_domain}. TXT "v=DMARC1;p=reject;adkim=s;aspf=s"
|
_dmarc.{chatmail_domain}. TXT "v=DMARC1;p=reject;adkim=s;aspf=s"
|
||||||
_mta-sts.{chatmail_domain}. TXT "v=STSv1; id={sts_id}"
|
_mta-sts.{chatmail_domain}. TXT "v=STSv1; id={sts_id}"
|
||||||
mta-sts.{chatmail_domain}. CNAME {chatmail_domain}.
|
mta-sts.{chatmail_domain}. CNAME {chatmail_domain}.
|
||||||
|
|||||||
@@ -5,17 +5,14 @@ import importlib
|
|||||||
import subprocess
|
import subprocess
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
class DNS:
|
class DNS:
|
||||||
def __init__(self, out, mail_domain):
|
def __init__(self, out, mail_domain):
|
||||||
self.session = requests.Session()
|
self.session = requests.Session()
|
||||||
self.out = out
|
self.out = out
|
||||||
self.ssh = f"ssh root@{mail_domain} -- "
|
self.ssh = f"ssh root@{mail_domain} -- "
|
||||||
self.out.shell_output(
|
|
||||||
f"{ self.ssh }'apt-get update && apt-get install -y dnsutils'",
|
|
||||||
timeout=60,
|
|
||||||
no_print=True,
|
|
||||||
)
|
|
||||||
try:
|
try:
|
||||||
self.shell(f"unbound-control flush_zone {mail_domain}")
|
self.shell(f"unbound-control flush_zone {mail_domain}")
|
||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
uri = proxy:/run/doveauth/doveauth.socket:auth
|
uri = proxy:/run/dovecot/doveauth.socket:auth
|
||||||
iterate_disable = yes
|
iterate_disable = yes
|
||||||
default_pass_scheme = plain
|
default_pass_scheme = plain
|
||||||
# %E escapes characters " (double quote), ' (single quote) and \ (backslash) with \ (backslash).
|
# %E escapes characters " (double quote), ' (single quote) and \ (backslash) with \ (backslash).
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
require ["imap4flags"];
|
require ["imap4flags"];
|
||||||
|
|
||||||
# flag the message so it doesn't cause a push notification
|
|
||||||
|
|
||||||
if header :is ["Auto-Submitted"] ["auto-replied", "auto-generated"] {
|
if header :is ["Auto-Submitted"] ["auto-replied", "auto-generated"] {
|
||||||
addflag "$Auto";
|
addflag "$Auto";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ mail_privileged_group = vmail
|
|||||||
##
|
##
|
||||||
|
|
||||||
# Pass all IMAP METADATA requests to the server implementing Dovecot's dict protocol.
|
# Pass all IMAP METADATA requests to the server implementing Dovecot's dict protocol.
|
||||||
mail_attribute_dict = proxy:/run/chatmail-metadata/metadata.socket:metadata
|
mail_attribute_dict = proxy:/run/dovecot/metadata.socket:metadata
|
||||||
|
|
||||||
# Enable IMAP COMPRESS (RFC 4978).
|
# Enable IMAP COMPRESS (RFC 4978).
|
||||||
# <https://datatracker.ietf.org/doc/html/rfc4978.html>
|
# <https://datatracker.ietf.org/doc/html/rfc4978.html>
|
||||||
|
|||||||
@@ -8,4 +8,3 @@
|
|||||||
# or only temporary (but then they shouldn't be around after {{ config.delete_mails_after }} days anyway).
|
# or only temporary (but then they shouldn't be around after {{ config.delete_mails_after }} days anyway).
|
||||||
2 0 * * * vmail find /home/vmail/mail/{{ config.mail_domain }} -path '*/tmp/*' -mtime +{{ config.delete_mails_after }} -type f -delete
|
2 0 * * * vmail find /home/vmail/mail/{{ config.mail_domain }} -path '*/tmp/*' -mtime +{{ config.delete_mails_after }} -type f -delete
|
||||||
2 0 * * * vmail find /home/vmail/mail/{{ config.mail_domain }} -path '*/.*/tmp/*' -mtime +{{ config.delete_mails_after }} -type f -delete
|
2 0 * * * vmail find /home/vmail/mail/{{ config.mail_domain }} -path '*/.*/tmp/*' -mtime +{{ config.delete_mails_after }} -type f -delete
|
||||||
3 0 * * * vmail find /home/vmail/mail/{{ config.mail_domain }} -name 'maildirsize' -type f -delete
|
|
||||||
|
|||||||
@@ -1,12 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=Chatmail dict proxy for IMAP METADATA
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
ExecStart={execpath} /run/chatmail-metadata/metadata.socket /home/vmail/mail/{mail_domain}
|
|
||||||
Restart=always
|
|
||||||
RestartSec=30
|
|
||||||
User=vmail
|
|
||||||
RuntimeDirectory=chatmail-metadata
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
[Unit]
|
|
||||||
Description=Chatmail echo bot for testing it works
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
ExecStart={execpath} {config_path}
|
|
||||||
Environment="PATH={remote_venv_dir}:$PATH"
|
|
||||||
Restart=always
|
|
||||||
RestartSec=30
|
|
||||||
|
|
||||||
# Apply security restrictions suggested by
|
|
||||||
# systemd-analyze security echobot.service
|
|
||||||
CapabilityBoundingSet=
|
|
||||||
LockPersonality=true
|
|
||||||
MemoryDenyWriteExecute=true
|
|
||||||
NoNewPrivileges=true
|
|
||||||
PrivateDevices=true
|
|
||||||
PrivateMounts=true
|
|
||||||
PrivateTmp=true
|
|
||||||
PrivateUsers=true
|
|
||||||
ProtectClock=true
|
|
||||||
ProtectControlGroups=true
|
|
||||||
ProtectHostname=true
|
|
||||||
ProtectKernelLogs=true
|
|
||||||
ProtectKernelModules=true
|
|
||||||
ProtectKernelTunables=true
|
|
||||||
ProtectProc=noaccess
|
|
||||||
|
|
||||||
# Should be "strict", but we currently write /accounts folder in a protected path
|
|
||||||
ProtectSystem=full
|
|
||||||
|
|
||||||
RemoveIPC=true
|
|
||||||
RestrictAddressFamilies=AF_INET AF_INET6
|
|
||||||
RestrictNamespaces=true
|
|
||||||
RestrictRealtime=true
|
|
||||||
RestrictSUIDSGID=true
|
|
||||||
SystemCallArchitectures=native
|
|
||||||
SystemCallFilter=~@clock
|
|
||||||
SystemCallFilter=~@cpu-emulation
|
|
||||||
SystemCallFilter=~@debug
|
|
||||||
SystemCallFilter=~@module
|
|
||||||
SystemCallFilter=~@mount
|
|
||||||
SystemCallFilter=~@obsolete
|
|
||||||
SystemCallFilter=~@raw-io
|
|
||||||
SystemCallFilter=~@reboot
|
|
||||||
SystemCallFilter=~@resources
|
|
||||||
SystemCallFilter=~@swap
|
|
||||||
UMask=0077
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
||||||
@@ -5,46 +5,6 @@ import random
|
|||||||
import pytest
|
import pytest
|
||||||
import requests
|
import requests
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import imap_tools
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def imap_mailbox(cmfactory):
|
|
||||||
(ac1,) = cmfactory.get_online_accounts(1)
|
|
||||||
user = ac1.get_config("addr")
|
|
||||||
password = ac1.get_config("mail_pw")
|
|
||||||
mailbox = imap_tools.MailBox(user.split("@")[1])
|
|
||||||
mailbox.login(user, password)
|
|
||||||
return mailbox
|
|
||||||
|
|
||||||
|
|
||||||
class TestMetadataTokens:
|
|
||||||
"Tests that use Metadata extension for storing tokens"
|
|
||||||
|
|
||||||
def test_set_get_metadata(self, imap_mailbox):
|
|
||||||
"set and get metadata token for an account"
|
|
||||||
client = imap_mailbox.client
|
|
||||||
client.send(b'a01 SETMETADATA INBOX (/private/devicetoken "1111" )\n')
|
|
||||||
res = client.readline()
|
|
||||||
assert b"OK Setmetadata completed" in res
|
|
||||||
|
|
||||||
client.send(b"a02 GETMETADATA INBOX /private/devicetoken\n")
|
|
||||||
res = client.readline()
|
|
||||||
assert res[:1] == b"*"
|
|
||||||
res = client.readline().strip().rstrip(b")")
|
|
||||||
assert res == b"1111"
|
|
||||||
assert b"Getmetadata completed" in client.readline()
|
|
||||||
|
|
||||||
client.send(b'a01 SETMETADATA INBOX (/private/devicetoken "2222" )\n')
|
|
||||||
res = client.readline()
|
|
||||||
assert b"OK Setmetadata completed" in res
|
|
||||||
|
|
||||||
client.send(b"a02 GETMETADATA INBOX /private/devicetoken\n")
|
|
||||||
res = client.readline()
|
|
||||||
assert res[:1] == b"*"
|
|
||||||
res = client.readline().strip().rstrip(b")")
|
|
||||||
assert res == b"1111 2222"
|
|
||||||
assert b"Getmetadata completed" in client.readline()
|
|
||||||
|
|
||||||
|
|
||||||
class TestEndToEndDeltaChat:
|
class TestEndToEndDeltaChat:
|
||||||
@@ -103,7 +63,7 @@ class TestEndToEndDeltaChat:
|
|||||||
|
|
||||||
addr = ac2.get_config("addr").lower()
|
addr = ac2.get_config("addr").lower()
|
||||||
saved_ok = 0
|
saved_ok = 0
|
||||||
for line in remote.iter_output("journalctl -n0 -f -u dovecot"):
|
for line in remote.iter_output("journalctl -f -u dovecot"):
|
||||||
if addr not in line:
|
if addr not in line:
|
||||||
# print(line)
|
# print(line)
|
||||||
continue
|
continue
|
||||||
@@ -115,10 +75,7 @@ class TestEndToEndDeltaChat:
|
|||||||
)
|
)
|
||||||
lp.indent("good, message sending failed because quota was exceeded")
|
lp.indent("good, message sending failed because quota was exceeded")
|
||||||
return
|
return
|
||||||
if (
|
if "saved mail to inbox" in line:
|
||||||
"stored mail into mailbox 'inbox'" in line
|
|
||||||
or "saved mail to inbox" in line
|
|
||||||
):
|
|
||||||
saved_ok += 1
|
saved_ok += 1
|
||||||
print(f"{saved_ok}: {line}")
|
print(f"{saved_ok}: {line}")
|
||||||
if saved_ok >= num_to_send:
|
if saved_ok >= num_to_send:
|
||||||
@@ -155,7 +112,7 @@ class TestEndToEndDeltaChat:
|
|||||||
lp.sec("ac1 sends a message and ac2 marks it as seen")
|
lp.sec("ac1 sends a message and ac2 marks it as seen")
|
||||||
chat = ac1.create_chat(ac2)
|
chat = ac1.create_chat(ac2)
|
||||||
msg = chat.send_text("hi")
|
msg = chat.send_text("hi")
|
||||||
m = ac2._evtracker.wait_next_incoming_message()
|
m = ac2.wait_next_incoming_message()
|
||||||
m.mark_seen()
|
m.mark_seen()
|
||||||
# we can only indirectly wait for mark-seen to cause an smtp-error
|
# we can only indirectly wait for mark-seen to cause an smtp-error
|
||||||
lp.sec("try to wait for markseen to complete and check error states")
|
lp.sec("try to wait for markseen to complete and check error states")
|
||||||
@@ -175,7 +132,7 @@ def test_hide_senders_ip_address(cmfactory):
|
|||||||
chat = cmfactory.get_accepted_chat(user1, user2)
|
chat = cmfactory.get_accepted_chat(user1, user2)
|
||||||
|
|
||||||
chat.send_text("testing submission header cleanup")
|
chat.send_text("testing submission header cleanup")
|
||||||
user2._evtracker.wait_next_incoming_message()
|
user2.wait_next_incoming_message()
|
||||||
user2.direct_imap.select_folder("Inbox")
|
user2.direct_imap.select_folder("Inbox")
|
||||||
msg = user2.direct_imap.get_all_messages()[0]
|
msg = user2.direct_imap.get_all_messages()[0]
|
||||||
assert public_ip not in msg.obj.as_string()
|
assert public_ip not in msg.obj.as_string()
|
||||||
@@ -189,5 +146,5 @@ def test_echobot(cmfactory, chatmail_config, lp):
|
|||||||
text = "hi, I hope you text me back"
|
text = "hi, I hope you text me back"
|
||||||
chat.send_text(text)
|
chat.send_text(text)
|
||||||
lp.sec("Wait for reply from echobot")
|
lp.sec("Wait for reply from echobot")
|
||||||
reply = ac._evtracker.wait_next_incoming_message()
|
reply = ac.wait_next_incoming_message()
|
||||||
assert reply.text == text
|
assert reply.text == text
|
||||||
|
|||||||
Reference in New Issue
Block a user