mirror of
https://github.com/chatmail/relay.git
synced 2026-05-10 16:04:37 +00:00
Compare commits
77 Commits
hpk/change
...
link2xt/do
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5591920cdc | ||
|
|
ecb5ef8a10 | ||
|
|
824c3dc1d7 | ||
|
|
9b76d46558 | ||
|
|
cc4920ddc7 | ||
|
|
2af10175fa | ||
|
|
ae455fa9e1 | ||
|
|
60d7e516dd | ||
|
|
bf18905e02 | ||
|
|
4d6f520f18 | ||
|
|
9da626dfc8 | ||
|
|
1cca9aa441 | ||
|
|
3d054847a0 | ||
|
|
a31d998e67 | ||
|
|
d313bea97f | ||
|
|
da04226594 | ||
|
|
eb2de26638 | ||
|
|
f5652cdbc4 | ||
|
|
13172c92f3 | ||
|
|
09df636183 | ||
|
|
2b45ace3ba | ||
|
|
9e05a7d1eb | ||
|
|
21e7c09c43 | ||
|
|
14d96e0a9b | ||
|
|
459ffcabd6 | ||
|
|
75cc3fdab0 | ||
|
|
2d26a40c2b | ||
|
|
a78d4e6198 | ||
|
|
2a1e004962 | ||
|
|
5e55cc205d | ||
|
|
476c732373 | ||
|
|
71c50b7936 | ||
|
|
79cb390f16 | ||
|
|
c1452c9c6f | ||
|
|
6e903d7498 | ||
|
|
221f4a2b0c | ||
|
|
080ae058d8 | ||
|
|
edb84c0b3b | ||
|
|
04ef477d51 | ||
|
|
5696788d3a | ||
|
|
1c2bf919ed | ||
|
|
d15c22c1e8 | ||
|
|
9c6e90ae27 | ||
|
|
481791c277 | ||
|
|
a25c7981f9 | ||
|
|
53519f2865 | ||
|
|
3a50d82657 | ||
|
|
c640087498 | ||
|
|
2089f3ab58 | ||
|
|
cbaa6924c1 | ||
|
|
6ab3e9657d | ||
|
|
16f237dc60 | ||
|
|
554c33423f | ||
|
|
5d5e2b199c | ||
|
|
989ce70f97 | ||
|
|
f5dc4cb71e | ||
|
|
76512dfa2d | ||
|
|
850112502f | ||
|
|
888fa88aa3 | ||
|
|
15e7458666 | ||
|
|
0a93c76e66 | ||
|
|
312f86223c | ||
|
|
27a60418ad | ||
|
|
46d31a91da | ||
|
|
a8765d8847 | ||
|
|
8ee6ca1b80 | ||
|
|
1a2b73a862 | ||
|
|
c44f4efced | ||
|
|
9fdf4fd2af | ||
|
|
33353ccaf6 | ||
|
|
5fe3a269be | ||
|
|
0b4770018d | ||
|
|
75fcbd03ce | ||
|
|
377121bdee | ||
|
|
e5e58f4e38 | ||
|
|
04517f284c | ||
|
|
e32fb37b5d |
56
.github/workflows/test-and-deploy.yaml
vendored
56
.github/workflows/test-and-deploy.yaml
vendored
@@ -4,12 +4,17 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- staging-ci
|
||||
pull_request:
|
||||
paths-ignore:
|
||||
- 'scripts/**'
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: deploy on staging.testrun.org, and run tests
|
||||
runs-on: ubuntu-latest
|
||||
concurrency:
|
||||
group: staging-deploy
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
@@ -19,48 +24,57 @@ jobs:
|
||||
echo "${{ secrets.STAGING_SSH_KEY }}" >> ~/.ssh/id_ed25519
|
||||
chmod 600 ~/.ssh/id_ed25519
|
||||
ssh-keyscan staging.testrun.org > ~/.ssh/known_hosts
|
||||
# rsync -avz root@staging.testrun.org:/var/lib/acme . || true
|
||||
# rsync -avz root@staging.testrun.org:/var/lib/rspamd/dkim . || true
|
||||
# save previous acme & dkim state
|
||||
rsync -avz root@staging.testrun.org:/var/lib/acme . || 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
|
||||
# run: |
|
||||
# curl -X POST \
|
||||
# -H "Authorization: Bearer ${{ secrets.HETZNER_API_TOKEN }}" \
|
||||
# -H "Content-Type: application/json" \
|
||||
# -d '{"image":"debian-12"}' \
|
||||
# "https://api.hetzner.cloud/v1/servers/${{ secrets.STAGING_SERVER_ID }}/actions/rebuild"
|
||||
- name: rebuild staging.testrun.org to have a clean VPS
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Authorization: Bearer ${{ secrets.HETZNER_API_TOKEN }}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"image":"debian-12"}' \
|
||||
"https://api.hetzner.cloud/v1/servers/${{ secrets.STAGING_SERVER_ID }}/actions/rebuild"
|
||||
|
||||
- run: scripts/initenv.sh
|
||||
|
||||
- name: append venv/bin to 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
|
||||
run: cmdeploy fmt -v
|
||||
|
||||
- name: run deploy-chatmail offline tests
|
||||
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 run
|
||||
|
||||
- name: set DNS entries
|
||||
run: |
|
||||
#ssh -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org chown _rspamd:_rspamd -R /var/lib/rspamd/dkim
|
||||
ssh -o StrictHostKeyChecking=accept-new -v root@staging.testrun.org chown opendkim:opendkim -R /etc/dkimkeys
|
||||
cmdeploy dns --zonefile staging-generated.zone
|
||||
cat staging-generated.zone >> .github/workflows/staging.testrun.org-default.zone
|
||||
cat .github/workflows/staging.testrun.org-default.zone
|
||||
scp -o StrictHostKeyChecking=accept-new .github/workflows/staging.testrun.org-default.zone root@ns.testrun.org:/etc/nsd/staging.testrun.org.zone
|
||||
scp .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 systemctl reload nsd
|
||||
|
||||
|
||||
52
CHANGELOG.md
Normal file
52
CHANGELOG.md
Normal file
@@ -0,0 +1,52 @@
|
||||
# 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,4 +159,27 @@ While this file is present, account creation will be blocked.
|
||||
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.
|
||||
|
||||
## 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,4 +1,3 @@
|
||||
include src/chatmaild/*.f
|
||||
include src/chatmaild/ini/*.ini.f
|
||||
include src/chatmaild/ini/*.ini
|
||||
include src/chatmaild/tests/mail-data/*
|
||||
|
||||
@@ -10,6 +10,7 @@ dependencies = [
|
||||
"iniconfig",
|
||||
"deltachat-rpc-server",
|
||||
"deltachat-rpc-client",
|
||||
"filelock",
|
||||
"requests",
|
||||
]
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
[Unit]
|
||||
Description=Chatmail dict proxy for IMAP METADATA
|
||||
|
||||
[Service]
|
||||
ExecStart={execpath} /run/dovecot/metadata.socket vmail {config_path} /home/vmail/metadata
|
||||
Restart=always
|
||||
RestartSec=30
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -9,7 +9,6 @@ from socketserver import (
|
||||
StreamRequestHandler,
|
||||
ThreadingMixIn,
|
||||
)
|
||||
import pwd
|
||||
|
||||
from .database import Database
|
||||
from .config import read_config, Config
|
||||
@@ -17,6 +16,10 @@ from .config import read_config, Config
|
||||
NOCREATE_FILE = "/etc/chatmail-nocreate"
|
||||
|
||||
|
||||
class UnknownCommand(ValueError):
|
||||
"""dictproxy handler received an unkown command"""
|
||||
|
||||
|
||||
def encrypt_password(password: str):
|
||||
# https://doc.dovecot.org/configuration_manual/authentication/password_schemes/
|
||||
passhash = crypt.crypt(password, crypt.METHOD_SHA512)
|
||||
@@ -127,8 +130,12 @@ def split_and_unescape(s):
|
||||
|
||||
|
||||
def handle_dovecot_request(msg, db, config: Config):
|
||||
# see https://doc.dovecot.org/3.0/developer_manual/design/dict_protocol/
|
||||
short_command = msg[0]
|
||||
if short_command == "L": # LOOKUP
|
||||
if short_command == "H": # HELLO
|
||||
# we don't do any checking on versions and just return
|
||||
return
|
||||
elif short_command == "L": # LOOKUP
|
||||
parts = msg[1:].split("\t")
|
||||
|
||||
# Dovecot <2.3.17 has only one part,
|
||||
@@ -159,7 +166,7 @@ def handle_dovecot_request(msg, db, config: Config):
|
||||
reply_command = "N"
|
||||
json_res = json.dumps(res) if res else ""
|
||||
return f"{reply_command}{json_res}\n"
|
||||
return None
|
||||
raise UnknownCommand(msg)
|
||||
|
||||
|
||||
def handle_dovecot_protocol(rfile, wfile, db: Database, config: Config):
|
||||
@@ -167,12 +174,14 @@ def handle_dovecot_protocol(rfile, wfile, db: Database, config: Config):
|
||||
msg = rfile.readline().strip().decode()
|
||||
if not msg:
|
||||
break
|
||||
res = handle_dovecot_request(msg, db, config)
|
||||
if res:
|
||||
wfile.write(res.encode("ascii"))
|
||||
wfile.flush()
|
||||
try:
|
||||
res = handle_dovecot_request(msg, db, config)
|
||||
except UnknownCommand:
|
||||
logging.warning("unknown command: %r", msg)
|
||||
else:
|
||||
logging.warning("request had no answer: %r", msg)
|
||||
if res:
|
||||
wfile.write(res.encode("ascii"))
|
||||
wfile.flush()
|
||||
|
||||
|
||||
class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
||||
@@ -181,9 +190,8 @@ class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
||||
|
||||
def main():
|
||||
socket = sys.argv[1]
|
||||
passwd_entry = pwd.getpwnam(sys.argv[2])
|
||||
db = Database(sys.argv[3])
|
||||
config = read_config(sys.argv[4])
|
||||
db = Database(sys.argv[2])
|
||||
config = read_config(sys.argv[3])
|
||||
|
||||
class Handler(StreamRequestHandler):
|
||||
def handle(self):
|
||||
@@ -199,7 +207,6 @@ def main():
|
||||
pass
|
||||
|
||||
with ThreadedUnixStreamServer(socket, Handler) as server:
|
||||
os.chown(socket, uid=passwd_entry.pw_uid, gid=passwd_entry.pw_gid)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
|
||||
@@ -18,14 +18,14 @@ hooks = events.HookCollection()
|
||||
@hooks.on(events.RawEvent)
|
||||
def log_event(event):
|
||||
if event.kind == EventType.INFO:
|
||||
logging.info(event.msg)
|
||||
logging.info("%s", event.msg)
|
||||
elif event.kind == EventType.WARNING:
|
||||
logging.warning(event.msg)
|
||||
logging.warning("%s", event.msg)
|
||||
|
||||
|
||||
@hooks.on(events.RawEvent(EventType.ERROR))
|
||||
def log_error(event):
|
||||
logging.error(event.msg)
|
||||
logging.error("%s", event.msg)
|
||||
|
||||
|
||||
@hooks.on(events.MemberListChanged)
|
||||
@@ -48,6 +48,9 @@ def on_group_name_changed(event):
|
||||
@hooks.on(events.NewMessage(func=lambda e: not e.command))
|
||||
def echo(event):
|
||||
snapshot = event.message_snapshot
|
||||
if snapshot.is_info:
|
||||
# Ignore info messages
|
||||
return
|
||||
if snapshot.text or snapshot.file:
|
||||
snapshot.chat.send_message(text=snapshot.text, file=snapshot.file)
|
||||
|
||||
@@ -59,6 +62,7 @@ def help_command(event):
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
path = os.environ.get("PATH")
|
||||
venv_path = sys.argv[0].strip("echobot")
|
||||
os.environ["PATH"] = path + ":" + venv_path
|
||||
@@ -80,5 +84,4 @@ def main():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
main()
|
||||
|
||||
@@ -1,11 +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
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
35
chatmaild/src/chatmaild/filedict.py
Normal file
35
chatmaild/src/chatmaild/filedict.py
Normal file
@@ -0,0 +1,35 @@
|
||||
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,144 +1,118 @@
|
||||
import pwd
|
||||
|
||||
import pathlib
|
||||
from queue import Queue
|
||||
from threading import Thread
|
||||
from pathlib import Path
|
||||
from socketserver import (
|
||||
UnixStreamServer,
|
||||
StreamRequestHandler,
|
||||
ThreadingMixIn,
|
||||
)
|
||||
from .config import read_config
|
||||
import sys
|
||||
import logging
|
||||
import os
|
||||
import requests
|
||||
import marshal
|
||||
|
||||
from .filedict import FileDict
|
||||
from .notifier import Notifier
|
||||
|
||||
|
||||
DICTPROXY_HELLO_CHAR = "H"
|
||||
DICTPROXY_LOOKUP_CHAR = "L"
|
||||
DICTPROXY_ITERATE_CHAR = "I"
|
||||
DICTPROXY_SET_CHAR = "S"
|
||||
DICTPROXY_BEGIN_TRANSACTION_CHAR = "B"
|
||||
DICTPROXY_SET_CHAR = "S"
|
||||
DICTPROXY_COMMIT_TRANSACTION_CHAR = "C"
|
||||
DICTPROXY_TRANSACTION_CHARS = "SBC"
|
||||
DICTPROXY_TRANSACTION_CHARS = "BSC"
|
||||
|
||||
|
||||
class Notifier:
|
||||
def __init__(self, metadata_dir):
|
||||
self.metadata_dir = metadata_dir
|
||||
self.to_notify_queue = Queue()
|
||||
class Metadata:
|
||||
# each SETMETADATA on this key appends to a list of unique device tokens
|
||||
# which only ever get removed if the upstream indicates the token is invalid
|
||||
DEVICETOKEN_KEY = "devicetoken"
|
||||
|
||||
def get_metadata(self, guid):
|
||||
guid_path = self.metadata_dir.joinpath(guid)
|
||||
if guid_path.exists():
|
||||
with guid_path.open("rb") as f:
|
||||
return marshal.load(f)
|
||||
return {}
|
||||
def __init__(self, vmail_dir):
|
||||
self.vmail_dir = vmail_dir
|
||||
|
||||
def set_metadata(self, guid, guid_data):
|
||||
guid_path = self.metadata_dir.joinpath(guid)
|
||||
write_path = guid_path.with_suffix(".tmp")
|
||||
with write_path.open("wb") as f:
|
||||
marshal.dump(guid_data, f)
|
||||
os.rename(write_path, guid_path)
|
||||
def get_metadata_dict(self, addr):
|
||||
return FileDict(self.vmail_dir / addr / "metadata.json")
|
||||
|
||||
def set_token(self, guid, token):
|
||||
guid_data = self.get_metadata(guid)
|
||||
guid_data["token"] = token
|
||||
self.set_metadata(guid, guid_data)
|
||||
def add_token_to_addr(self, addr, token):
|
||||
with self.get_metadata_dict(addr).modify() as data:
|
||||
tokens = data.setdefault(self.DEVICETOKEN_KEY, [])
|
||||
if token not in tokens:
|
||||
tokens.append(token)
|
||||
|
||||
def del_token(self, guid):
|
||||
guid_data = self.get_metadata(guid)
|
||||
if "token" in guid_data:
|
||||
del guid_data["token"]
|
||||
self.set_metadata(guid, guid_data)
|
||||
def remove_token_from_addr(self, addr, token):
|
||||
with self.get_metadata_dict(addr).modify() as data:
|
||||
tokens = data.get(self.DEVICETOKEN_KEY, [])
|
||||
if token in tokens:
|
||||
tokens.remove(token)
|
||||
|
||||
def get_token(self, guid):
|
||||
return self.get_metadata(guid).get("token")
|
||||
|
||||
def new_message_for_guid(self, guid):
|
||||
self.to_notify_queue.put(guid)
|
||||
|
||||
def thread_run_loop(self):
|
||||
requests_session = requests.Session()
|
||||
while 1:
|
||||
self.thread_run_one(requests_session)
|
||||
|
||||
def thread_run_one(self, requests_session):
|
||||
guid = self.to_notify_queue.get()
|
||||
token = self.get_token(guid)
|
||||
if token:
|
||||
response = requests_session.post(
|
||||
"https://notifications.delta.chat/notify",
|
||||
data=token,
|
||||
timeout=60,
|
||||
)
|
||||
if response.status_code == 410:
|
||||
# 410 Gone status code
|
||||
# means the token is no longer valid.
|
||||
self.del_token(guid)
|
||||
def get_tokens_for_addr(self, addr):
|
||||
mdict = self.get_metadata_dict(addr).read()
|
||||
return mdict.get(self.DEVICETOKEN_KEY, [])
|
||||
|
||||
|
||||
def handle_dovecot_protocol(rfile, wfile, notifier):
|
||||
# HELLO message, ignored.
|
||||
msg = rfile.readline().strip().decode()
|
||||
|
||||
def handle_dovecot_protocol(rfile, wfile, notifier, metadata):
|
||||
transactions = {}
|
||||
while True:
|
||||
msg = rfile.readline().strip().decode()
|
||||
if not msg:
|
||||
break
|
||||
|
||||
res = handle_dovecot_request(msg, transactions, notifier)
|
||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
||||
if res:
|
||||
wfile.write(res.encode("ascii"))
|
||||
wfile.flush()
|
||||
|
||||
|
||||
def handle_dovecot_request(msg, transactions, notifier):
|
||||
def handle_dovecot_request(msg, transactions, notifier, metadata):
|
||||
# see https://doc.dovecot.org/3.0/developer_manual/design/dict_protocol/
|
||||
short_command = msg[0]
|
||||
parts = msg[1:].split("\t")
|
||||
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"
|
||||
elif short_command == DICTPROXY_ITERATE_CHAR:
|
||||
# Empty line means ITER_FINISHED.
|
||||
# If we don't return empty line Dovecot will timeout.
|
||||
return "\n"
|
||||
elif short_command == DICTPROXY_HELLO_CHAR:
|
||||
return # no version checking
|
||||
|
||||
if short_command not in (DICTPROXY_TRANSACTION_CHARS):
|
||||
logging.warning("unknown dictproxy request: %r", msg)
|
||||
return
|
||||
|
||||
transaction_id = parts[0]
|
||||
|
||||
if short_command == DICTPROXY_BEGIN_TRANSACTION_CHAR:
|
||||
transactions[transaction_id] = "O\n"
|
||||
addr = parts[1]
|
||||
transactions[transaction_id] = dict(addr=addr, res="O\n")
|
||||
elif short_command == DICTPROXY_COMMIT_TRANSACTION_CHAR:
|
||||
# returns whether it failed or succeeded.
|
||||
return transactions.pop(transaction_id, "N\n")
|
||||
# each set devicetoken operation persists directly
|
||||
# and does not wait until a "commit" comes
|
||||
# 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:
|
||||
# See header of
|
||||
# <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
|
||||
# For documentation on key structure see
|
||||
# https://github.com/dovecot/core/blob/main/src/lib-storage/mailbox-attribute.h
|
||||
|
||||
keyname = parts[1].split("/")
|
||||
value = parts[2] if len(parts) > 2 else ""
|
||||
if keyname[0] == "priv" and keyname[2] == "devicetoken":
|
||||
notifier.set_token(keyname[1], value)
|
||||
addr = transactions[transaction_id]["addr"]
|
||||
if keyname[0] == "priv" and keyname[2] == metadata.DEVICETOKEN_KEY:
|
||||
metadata.add_token_to_addr(addr, value)
|
||||
elif keyname[0] == "priv" and keyname[2] == "messagenew":
|
||||
notifier.new_message_for_guid(keyname[1])
|
||||
notifier.new_message_for_addr(addr, metadata)
|
||||
else:
|
||||
# Transaction failed.
|
||||
transactions[transaction_id] = "F\n"
|
||||
transactions[transaction_id]["res"] = "F\n"
|
||||
|
||||
|
||||
class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
||||
@@ -146,22 +120,25 @@ class ThreadedUnixStreamServer(ThreadingMixIn, UnixStreamServer):
|
||||
|
||||
|
||||
def main():
|
||||
socket, username, config, metadata_dir = sys.argv[1:]
|
||||
passwd_entry = pwd.getpwnam(username)
|
||||
socket, vmail_dir = sys.argv[1:]
|
||||
|
||||
# XXX config is not currently used
|
||||
config = read_config(config)
|
||||
metadata_dir = pathlib.Path(metadata_dir)
|
||||
if not metadata_dir.exists():
|
||||
metadata_dir.mkdir()
|
||||
notifier = Notifier(metadata_dir)
|
||||
vmail_dir = Path(vmail_dir)
|
||||
if not vmail_dir.exists():
|
||||
logging.error("vmail dir does not exist: %r", vmail_dir)
|
||||
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):
|
||||
def handle(self):
|
||||
try:
|
||||
handle_dovecot_protocol(self.rfile, self.wfile, notifier)
|
||||
handle_dovecot_protocol(self.rfile, self.wfile, notifier, metadata)
|
||||
except Exception:
|
||||
logging.exception("Exception in the handler")
|
||||
logging.exception("Exception in the dovecot dictproxy handler")
|
||||
raise
|
||||
|
||||
try:
|
||||
@@ -169,15 +146,7 @@ def main():
|
||||
except FileNotFoundError:
|
||||
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:
|
||||
os.chown(socket, uid=passwd_entry.pw_uid, gid=passwd_entry.pw_gid)
|
||||
try:
|
||||
server.serve_forever()
|
||||
except KeyboardInterrupt:
|
||||
|
||||
165
chatmaild/src/chatmaild/notifier.py
Normal file
165
chatmaild/src/chatmaild/notifier.py
Normal file
@@ -0,0 +1,165 @@
|
||||
"""
|
||||
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,6 +75,14 @@ def test_handle_dovecot_request(db, example_config):
|
||||
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):
|
||||
rfile = io.BytesIO(
|
||||
b"H3\t2\t0\t\tauth\nLshared/userdb/foobar@chat.example.org\tfoobar@chat.example.org\n"
|
||||
|
||||
19
chatmaild/src/chatmaild/tests/test_filedict.py
Normal file
19
chatmaild/src/chatmaild/tests/test_filedict.py
Normal file
@@ -0,0 +1,19 @@
|
||||
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,96 +1,179 @@
|
||||
import io
|
||||
import pytest
|
||||
import requests
|
||||
import time
|
||||
|
||||
from chatmaild.metadata import (
|
||||
handle_dovecot_request,
|
||||
handle_dovecot_protocol,
|
||||
Metadata,
|
||||
)
|
||||
from chatmaild.notifier import (
|
||||
Notifier,
|
||||
NotifyThread,
|
||||
PersistentQueueItem,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def notifier(tmp_path):
|
||||
metadata_dir = tmp_path.joinpath("metadata")
|
||||
metadata_dir.mkdir()
|
||||
return Notifier(metadata_dir)
|
||||
def notifier(metadata):
|
||||
queue_dir = metadata.vmail_dir.joinpath("pending_notifications")
|
||||
queue_dir.mkdir()
|
||||
return Notifier(queue_dir)
|
||||
|
||||
|
||||
def test_notifier_persistence(tmp_path):
|
||||
metadata_dir = tmp_path.joinpath("metadata")
|
||||
metadata_dir.mkdir()
|
||||
notifier1 = Notifier(metadata_dir)
|
||||
notifier2 = Notifier(metadata_dir)
|
||||
assert notifier1.get_token(guid="guid00") is None
|
||||
assert notifier2.get_token(guid="guid00") is None
|
||||
|
||||
notifier1.set_token("guid00", "01234")
|
||||
notifier1.set_token("guid03", "456")
|
||||
assert notifier2.get_token("guid00") == "01234"
|
||||
assert notifier2.get_token("guid03") == "456"
|
||||
notifier2.del_token("guid00")
|
||||
assert notifier1.get_token("guid00") is None
|
||||
@pytest.fixture
|
||||
def metadata(tmp_path):
|
||||
vmail_dir = tmp_path.joinpath("vmaildir")
|
||||
vmail_dir.mkdir()
|
||||
return Metadata(vmail_dir)
|
||||
|
||||
|
||||
def test_handle_dovecot_request_lookup_fails(notifier):
|
||||
res = handle_dovecot_request("Lpriv/123/chatmail", {}, notifier)
|
||||
@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"
|
||||
|
||||
|
||||
def test_handle_dovecot_request_happy_path(notifier):
|
||||
def test_handle_dovecot_request_happy_path(notifier, metadata, testaddr, token):
|
||||
transactions = {}
|
||||
|
||||
# lookups return the same NOTFOUND result
|
||||
res = handle_dovecot_request("Lpriv/123/chatmail", transactions, notifier)
|
||||
assert res == "N\n"
|
||||
assert notifier.get_token("guid00") is None and not transactions
|
||||
|
||||
# set device token in a transaction
|
||||
tx = "1111"
|
||||
msg = f"B{tx}\tuser"
|
||||
res = handle_dovecot_request(msg, transactions, notifier)
|
||||
assert not res and notifier.get_token("guid00") is None
|
||||
assert transactions == {tx: "O\n"}
|
||||
msg = f"B{tx}\t{testaddr}"
|
||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
||||
assert not res and not metadata.get_tokens_for_addr(testaddr)
|
||||
assert transactions == {tx: dict(addr=testaddr, res="O\n")}
|
||||
|
||||
msg = f"S{tx}\tpriv/guid00/devicetoken\t01234"
|
||||
res = handle_dovecot_request(msg, transactions, notifier)
|
||||
msg = f"S{tx}\tpriv/guid00/devicetoken\t{token}"
|
||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
||||
assert not res
|
||||
assert len(transactions) == 1
|
||||
assert notifier.get_token("guid00") == "01234"
|
||||
assert metadata.get_tokens_for_addr(testaddr) == [token]
|
||||
|
||||
msg = f"C{tx}"
|
||||
res = handle_dovecot_request(msg, transactions, notifier)
|
||||
res = handle_dovecot_request(msg, transactions, notifier, metadata)
|
||||
assert res == "O\n"
|
||||
assert len(transactions) == 0
|
||||
assert notifier.get_token("guid00") == "01234"
|
||||
assert metadata.get_tokens_for_addr(testaddr) == [token]
|
||||
|
||||
# trigger notification for incoming message
|
||||
assert handle_dovecot_request(f"B{tx}\tuser", transactions, notifier) is None
|
||||
msg = f"S{tx}\tpriv/guid00/messagenew"
|
||||
assert handle_dovecot_request(msg, transactions, notifier) is None
|
||||
assert notifier.to_notify_queue.get() == "guid00"
|
||||
assert notifier.to_notify_queue.qsize() == 0
|
||||
assert handle_dovecot_request(f"C{tx}\tuser", transactions, notifier) == "O\n"
|
||||
tx2 = "2222"
|
||||
assert (
|
||||
handle_dovecot_request(f"B{tx2}\t{testaddr}", transactions, notifier, metadata)
|
||||
is None
|
||||
)
|
||||
msg = f"S{tx2}\tpriv/guid00/messagenew"
|
||||
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 queue_item.path.exists()
|
||||
|
||||
|
||||
def test_handle_dovecot_protocol_set_devicetoken(notifier):
|
||||
def test_handle_dovecot_protocol_set_devicetoken(metadata, notifier):
|
||||
rfile = io.BytesIO(
|
||||
b"\n".join(
|
||||
[
|
||||
b"HELLO",
|
||||
b"Btx00\tuser",
|
||||
b"Btx00\tuser@example.org",
|
||||
b"Stx00\tpriv/guid00/devicetoken\t01234",
|
||||
b"Ctx00",
|
||||
]
|
||||
)
|
||||
)
|
||||
wfile = io.BytesIO()
|
||||
handle_dovecot_protocol(rfile, wfile, notifier)
|
||||
assert notifier.get_token("guid00") == "01234"
|
||||
handle_dovecot_protocol(rfile, wfile, notifier, metadata)
|
||||
assert wfile.getvalue() == b"O\n"
|
||||
assert metadata.get_tokens_for_addr("user@example.org") == ["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"
|
||||
|
||||
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(notifier):
|
||||
|
||||
def test_handle_dovecot_protocol_iterate(metadata, notifier):
|
||||
rfile = io.BytesIO(
|
||||
b"\n".join(
|
||||
[
|
||||
@@ -100,64 +183,116 @@ def test_handle_dovecot_protocol_iterate(notifier):
|
||||
)
|
||||
)
|
||||
wfile = io.BytesIO()
|
||||
handle_dovecot_protocol(rfile, wfile, notifier)
|
||||
handle_dovecot_protocol(rfile, wfile, notifier, metadata)
|
||||
assert wfile.getvalue() == b"\n"
|
||||
|
||||
|
||||
def test_handle_dovecot_protocol_messagenew(notifier):
|
||||
rfile = io.BytesIO(
|
||||
b"\n".join(
|
||||
[
|
||||
b"HELLO",
|
||||
b"Btx01\tuser",
|
||||
b"Stx01\tpriv/guid00/messagenew",
|
||||
b"Ctx01",
|
||||
]
|
||||
)
|
||||
)
|
||||
wfile = io.BytesIO()
|
||||
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(notifier):
|
||||
requests = []
|
||||
|
||||
class ReqMock:
|
||||
def post(self, url, data, timeout):
|
||||
requests.append((url, data, timeout))
|
||||
|
||||
class Result:
|
||||
status_code = 200
|
||||
|
||||
return Result()
|
||||
|
||||
notifier.set_token("guid00", "01234")
|
||||
notifier.new_message_for_guid("guid00")
|
||||
notifier.thread_run_one(ReqMock())
|
||||
url, data, timeout = requests[0]
|
||||
def test_notifier_thread_deletes_persistent_file(metadata, notifier, testaddr):
|
||||
reqmock = get_mocked_requests([200])
|
||||
metadata.add_token_to_addr(testaddr, "01234")
|
||||
notifier.new_message_for_addr(testaddr, metadata)
|
||||
NotifyThread(notifier, 0, None).retry_one(reqmock)
|
||||
url, data, timeout = reqmock.requests[0]
|
||||
assert data == "01234"
|
||||
assert notifier.get_token("guid00") == "01234"
|
||||
assert metadata.get_tokens_for_addr(testaddr) == ["01234"]
|
||||
notifier.requeue_persistent_queue_items()
|
||||
assert notifier.retry_queues[0].qsize() == 0
|
||||
|
||||
|
||||
def test_notifier_thread_run_gone_removes_token(notifier):
|
||||
requests = []
|
||||
@pytest.mark.parametrize("status", [requests.exceptions.RequestException(), 404, 500])
|
||||
def test_notifier_thread_connection_failures(
|
||||
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))
|
||||
|
||||
class Result:
|
||||
status_code = 410
|
||||
def test_requeue_removes_tmp_files(notifier, metadata, testaddr, caplog):
|
||||
metadata.add_token_to_addr(testaddr, "01234")
|
||||
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()
|
||||
|
||||
notifier.set_token("guid00", "01234")
|
||||
notifier.new_message_for_guid("guid00")
|
||||
assert notifier.get_token("guid00") == "01234"
|
||||
notifier.thread_run_one(ReqMock())
|
||||
url, data, timeout = requests[0]
|
||||
def test_start_and_stop_notification_threads(notifier, testaddr):
|
||||
threads = notifier.start_notification_threads(None)
|
||||
for retry_num, threadlist in threads.items():
|
||||
for t in threadlist:
|
||||
t.stop()
|
||||
t.join()
|
||||
|
||||
|
||||
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 notifier.get_token("guid00") is None
|
||||
url, data, timeout = reqmock.requests[1]
|
||||
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,6 +19,7 @@ dependencies = [
|
||||
"black",
|
||||
"pytest",
|
||||
"pytest-xdist",
|
||||
"imap_tools",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
|
||||
@@ -108,8 +108,11 @@ def _install_remote_venv_with_chatmaild(config) -> None:
|
||||
execpath=f"{remote_venv_dir}/bin/{fn}",
|
||||
config_path=remote_chatmail_inipath,
|
||||
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()
|
||||
|
||||
files.put(
|
||||
@@ -132,20 +135,6 @@ def _configure_opendkim(domain: str, dkim_selector: str = "dkim") -> bool:
|
||||
"""Configures OpenDKIM"""
|
||||
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(
|
||||
src=importlib.resources.files(__package__).joinpath("opendkim/opendkim.conf"),
|
||||
dest="/etc/opendkim.conf",
|
||||
@@ -350,9 +339,7 @@ def _configure_dovecot(config: Config, debug: bool = False) -> bool:
|
||||
need_restart |= lua_push_notification_script.changed
|
||||
|
||||
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",
|
||||
user="root",
|
||||
group="root",
|
||||
@@ -361,10 +348,8 @@ def _configure_dovecot(config: Config, debug: bool = False) -> bool:
|
||||
need_restart |= sieve_script.changed
|
||||
if sieve_script.changed:
|
||||
server.shell(
|
||||
name=f"compile sieve script",
|
||||
commands=[
|
||||
f"/usr/bin/sievec /etc/dovecot/default.sieve"
|
||||
],
|
||||
name="compile sieve script",
|
||||
commands=["/usr/bin/sievec /etc/dovecot/default.sieve"],
|
||||
)
|
||||
|
||||
files.template(
|
||||
@@ -457,7 +442,9 @@ def check_config(config):
|
||||
blocked_words = "merlinux schmieder testrun.org".split()
|
||||
for key in config.__dict__:
|
||||
value = config.__dict__[key]
|
||||
if key.startswith("privacy") and any(x in str(value) for x in blocked_words):
|
||||
if key.startswith("privacy") and any(
|
||||
x in str(value) for x in blocked_words
|
||||
):
|
||||
raise ValueError(
|
||||
f"please set your own privacy contacts/addresses in {config._inipath}"
|
||||
)
|
||||
@@ -475,9 +462,29 @@ def deploy_chatmail(config_path: Path) -> None:
|
||||
|
||||
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.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(
|
||||
name="Install rsync",
|
||||
packages=["rsync"],
|
||||
@@ -564,14 +571,9 @@ def deploy_chatmail(config_path: Path) -> None:
|
||||
restarted=mta_sts_need_restart,
|
||||
)
|
||||
|
||||
systemd.service(
|
||||
name="Start and enable Postfix",
|
||||
service="postfix.service",
|
||||
running=True,
|
||||
enabled=True,
|
||||
restarted=postfix_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",
|
||||
@@ -580,6 +582,14 @@ def deploy_chatmail(config_path: Path) -> None:
|
||||
restarted=dovecot_need_restart,
|
||||
)
|
||||
|
||||
systemd.service(
|
||||
name="Start and enable Postfix",
|
||||
service="postfix.service",
|
||||
running=True,
|
||||
enabled=True,
|
||||
restarted=postfix_need_restart,
|
||||
)
|
||||
|
||||
systemd.service(
|
||||
name="Start and enable nginx",
|
||||
service="nginx.service",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
SHELL=/bin/sh
|
||||
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
|
||||
MAILTO=root
|
||||
20 16 * * * root /usr/bin/acmetool --batch reconcile
|
||||
20 16 * * * root /usr/bin/acmetool --batch reconcile && systemctl reload dovecot && systemctl reload postfix
|
||||
|
||||
@@ -5,14 +5,17 @@ import importlib
|
||||
import subprocess
|
||||
import datetime
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class DNS:
|
||||
def __init__(self, out, mail_domain):
|
||||
self.session = requests.Session()
|
||||
self.out = out
|
||||
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:
|
||||
self.shell(f"unbound-control flush_zone {mail_domain}")
|
||||
except subprocess.CalledProcessError:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
uri = proxy:/run/dovecot/doveauth.socket:auth
|
||||
uri = proxy:/run/doveauth/doveauth.socket:auth
|
||||
iterate_disable = yes
|
||||
default_pass_scheme = plain
|
||||
# %E escapes characters " (double quote), ' (single quote) and \ (backslash) with \ (backslash).
|
||||
|
||||
@@ -78,7 +78,7 @@ mail_privileged_group = vmail
|
||||
##
|
||||
|
||||
# Pass all IMAP METADATA requests to the server implementing Dovecot's dict protocol.
|
||||
mail_attribute_dict = proxy:/run/dovecot/metadata.socket:metadata
|
||||
mail_attribute_dict = proxy:/run/chatmail-metadata/metadata.socket:metadata
|
||||
|
||||
# Enable IMAP COMPRESS (RFC 4978).
|
||||
# <https://datatracker.ietf.org/doc/html/rfc4978.html>
|
||||
|
||||
12
cmdeploy/src/cmdeploy/service/chatmail-metadata.service.f
Normal file
12
cmdeploy/src/cmdeploy/service/chatmail-metadata.service.f
Normal file
@@ -0,0 +1,12 @@
|
||||
[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
|
||||
@@ -2,9 +2,11 @@
|
||||
Description=Chatmail dict authentication proxy for dovecot
|
||||
|
||||
[Service]
|
||||
ExecStart={execpath} /run/dovecot/doveauth.socket vmail /home/vmail/passdb.sqlite {config_path}
|
||||
ExecStart={execpath} /run/doveauth/doveauth.socket /home/vmail/passdb.sqlite {config_path}
|
||||
Restart=always
|
||||
RestartSec=30
|
||||
User=vmail
|
||||
RuntimeDirectory=doveauth
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
50
cmdeploy/src/cmdeploy/service/echobot.service.f
Normal file
50
cmdeploy/src/cmdeploy/service/echobot.service.f
Normal file
@@ -0,0 +1,50 @@
|
||||
[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
|
||||
@@ -1,5 +1,5 @@
|
||||
[Unit]
|
||||
Description=Chatmail Postfix BeforeQeue filter
|
||||
Description=Chatmail Postfix before queue filter
|
||||
|
||||
[Service]
|
||||
ExecStart={execpath} {config_path}
|
||||
@@ -5,6 +5,46 @@ import random
|
||||
import pytest
|
||||
import requests
|
||||
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:
|
||||
@@ -63,7 +103,7 @@ class TestEndToEndDeltaChat:
|
||||
|
||||
addr = ac2.get_config("addr").lower()
|
||||
saved_ok = 0
|
||||
for line in remote.iter_output("journalctl -f -u dovecot"):
|
||||
for line in remote.iter_output("journalctl -n0 -f -u dovecot"):
|
||||
if addr not in line:
|
||||
# print(line)
|
||||
continue
|
||||
@@ -75,7 +115,10 @@ class TestEndToEndDeltaChat:
|
||||
)
|
||||
lp.indent("good, message sending failed because quota was exceeded")
|
||||
return
|
||||
if "saved mail to inbox" in line:
|
||||
if (
|
||||
"stored mail into mailbox 'inbox'" in line
|
||||
or "saved mail to inbox" in line
|
||||
):
|
||||
saved_ok += 1
|
||||
print(f"{saved_ok}: {line}")
|
||||
if saved_ok >= num_to_send:
|
||||
@@ -112,7 +155,7 @@ class TestEndToEndDeltaChat:
|
||||
lp.sec("ac1 sends a message and ac2 marks it as seen")
|
||||
chat = ac1.create_chat(ac2)
|
||||
msg = chat.send_text("hi")
|
||||
m = ac2.wait_next_incoming_message()
|
||||
m = ac2._evtracker.wait_next_incoming_message()
|
||||
m.mark_seen()
|
||||
# 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")
|
||||
@@ -132,7 +175,7 @@ def test_hide_senders_ip_address(cmfactory):
|
||||
chat = cmfactory.get_accepted_chat(user1, user2)
|
||||
|
||||
chat.send_text("testing submission header cleanup")
|
||||
user2.wait_next_incoming_message()
|
||||
user2._evtracker.wait_next_incoming_message()
|
||||
user2.direct_imap.select_folder("Inbox")
|
||||
msg = user2.direct_imap.get_all_messages()[0]
|
||||
assert public_ip not in msg.obj.as_string()
|
||||
@@ -146,5 +189,5 @@ def test_echobot(cmfactory, chatmail_config, lp):
|
||||
text = "hi, I hope you text me back"
|
||||
chat.send_text(text)
|
||||
lp.sec("Wait for reply from echobot")
|
||||
reply = ac.wait_next_incoming_message()
|
||||
reply = ac._evtracker.wait_next_incoming_message()
|
||||
assert reply.text == text
|
||||
|
||||
Reference in New Issue
Block a user