70 lines
2.7 KiB
Python
70 lines
2.7 KiB
Python
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
|
|
|
|
REPO = Path(__file__).resolve().parents[2]
|
|
|
|
|
|
class MailCertificateHookTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory(prefix='moonwell-mail-hook-')
|
|
self.addCleanup(self.tmp.cleanup)
|
|
self.root = Path(self.tmp.name)
|
|
self.bin = self.root / 'bin'
|
|
self.bin.mkdir()
|
|
self.trace = self.root / 'docker.log'
|
|
docker = self.bin / 'docker'
|
|
docker.write_text('#!/bin/sh\nprintf "%s\\n" "$*" >> "$MAIL_TEST_TRACE"\n')
|
|
docker.chmod(0o755)
|
|
install = self.bin / 'install'
|
|
install.write_text('''#!/usr/bin/env python3
|
|
import pathlib, shutil, sys
|
|
if '-d' in sys.argv:
|
|
pathlib.Path(sys.argv[-1]).mkdir(parents=True, exist_ok=True)
|
|
else:
|
|
shutil.copyfile(sys.argv[-2], sys.argv[-1])
|
|
''')
|
|
install.chmod(0o755)
|
|
|
|
def run_hook(self, hostname):
|
|
lineage = self.root / 'lineage'
|
|
lineage.mkdir()
|
|
subprocess.run([
|
|
'openssl', 'req', '-x509', '-newkey', 'ec',
|
|
'-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-days', '1',
|
|
'-keyout', str(lineage / 'privkey.pem'),
|
|
'-out', str(lineage / 'fullchain.pem'),
|
|
'-subj', '/CN=' + hostname,
|
|
'-addext', 'subjectAltName=DNS:' + hostname,
|
|
], check=True, capture_output=True)
|
|
env = dict(os.environ, PATH=str(self.bin) + ':' + os.environ['PATH'],
|
|
RENEWED_LINEAGE=str(lineage), MAIL_TLS_DIR=str(self.root / 'tls'),
|
|
MAIL_TEST_TRACE=str(self.trace))
|
|
return subprocess.run(['bash', str(REPO / 'scripts/deploy-mail-certificate.sh')],
|
|
env=env, capture_output=True, text=True)
|
|
|
|
def test_unrelated_website_renewal_never_overwrites_mail_certificate_or_restarts_mail(self):
|
|
result = self.run_hook('moon-well.online')
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
self.assertIn('Skipping certificate', result.stdout)
|
|
self.assertFalse((self.root / 'tls').exists())
|
|
self.assertFalse(self.trace.exists())
|
|
|
|
def test_mail_renewal_installs_matching_certificate_and_restarts_only_stalwart(self):
|
|
result = self.run_hook('mail.moon-well.online')
|
|
self.assertEqual(result.returncode, 0, result.stderr)
|
|
for name in ['fullchain.pem', 'privkey.pem']:
|
|
self.assertEqual((self.root / 'tls' / name).read_bytes(),
|
|
(self.root / 'lineage' / name).read_bytes())
|
|
self.assertEqual(self.trace.read_text().splitlines(), [
|
|
'container inspect moonwell-web-stalwart-1',
|
|
'restart moonwell-web-stalwart-1',
|
|
])
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|