Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

fix(postfix): match virtual-map entries by address token, not substring

Juan Denis7211560768a9
diff --git a/backend/app/services/postfix_service.py b/backend/app/services/postfix_service.py
index b6fa3051..60a14ea0 100644
--- a/backend/app/services/postfix_service.py
+++ b/backend/app/services/postfix_service.py
@@ -202,14 +202,44 @@ mailbox_size_limit = 0
except Exception as e:
return {'success': False, 'error': str(e)}
+ @staticmethod
+ def _mentions_domain(line: str, domain: str) -> bool:
+ """True when any address token on the map line is at exactly *domain*.
+
+ Token-suffix match, not substring: removing example.com must not
+ also delete lines for example.com.br, and sub.example.com entries
+ must survive removing example.com."""
+ suffix = '@' + domain.lower()
+ return any(token.endswith(suffix)
+ for token in re.split(r'[\s,]+', line.lower()))
+
+ @classmethod
+ def _append_map_entry(cls, path: str, entry: str) -> None:
+ """Append one map entry, guarding against a file whose last line is
+ missing its newline — tee -a would glue the entry onto that line,
+ corrupting both and making them unmatchable on removal."""
+ result = run_privileged(['cat', path])
+ content = result.stdout or ''
+ if content and not content.endswith('\n'):
+ entry = '\n' + entry
+ write_privileged_file(path, entry, append=True)
+
@classmethod
def add_domain(cls, domain: str) -> Dict:
"""Add a domain to the virtual domains map."""
try:
result = run_privileged(['cat', cls.VIRTUAL_DOMAINS_FILE])
content = result.stdout or ''
- if domain not in content:
- write_privileged_file(cls.VIRTUAL_DOMAINS_FILE, f'{domain} OK\n', append=True)
+ # Dedupe on the line's domain field, not a raw substring — with
+ # sub.example.com already mapped, adding example.com used to
+ # no-op while still reporting success.
+ existing = {line.split()[0].lower()
+ for line in content.splitlines() if line.split()}
+ if domain.lower() not in existing:
+ entry = f'{domain} OK\n'
+ if content and not content.endswith('\n'):
+ entry = '\n' + entry
+ write_privileged_file(cls.VIRTUAL_DOMAINS_FILE, entry, append=True)
run_privileged(['postmap', cls.VIRTUAL_DOMAINS_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
@@ -225,15 +255,18 @@ mailbox_size_limit = 0
write_privileged_file(cls.VIRTUAL_DOMAINS_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_DOMAINS_FILE])
- # Also remove mailboxes for this domain
+ # Also remove mailboxes for this domain (address-token match, so
+ # [email protected] mailboxes survive removing example.com)
result = run_privileged(['cat', cls.VIRTUAL_MAILBOXES_FILE])
- lines = [l for l in (result.stdout or '').splitlines() if not l.endswith(f'@{domain}') and f'@{domain} ' not in l]
+ lines = [l for l in (result.stdout or '').splitlines()
+ if not cls._mentions_domain(l, domain)]
write_privileged_file(cls.VIRTUAL_MAILBOXES_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_MAILBOXES_FILE])
# Remove aliases for this domain
result = run_privileged(['cat', cls.VIRTUAL_ALIASES_FILE])
- lines = [l for l in (result.stdout or '').splitlines() if f'@{domain}' not in l]
+ lines = [l for l in (result.stdout or '').splitlines()
+ if not cls._mentions_domain(l, domain)]
write_privileged_file(cls.VIRTUAL_ALIASES_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_ALIASES_FILE])
@@ -247,7 +280,7 @@ mailbox_size_limit = 0
"""Add a mailbox to the virtual mailbox map."""
try:
mailbox_path = f'{domain}/{username}/Maildir/'
- write_privileged_file(cls.VIRTUAL_MAILBOXES_FILE, f'{email} {mailbox_path}\n', append=True)
+ cls._append_map_entry(cls.VIRTUAL_MAILBOXES_FILE, f'{email} {mailbox_path}\n')
run_privileged(['postmap', cls.VIRTUAL_MAILBOXES_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
@@ -271,7 +304,7 @@ mailbox_size_limit = 0
def add_alias(cls, source: str, destination: str) -> Dict:
"""Add a virtual alias."""
try:
- write_privileged_file(cls.VIRTUAL_ALIASES_FILE, f'{source} {destination}\n', append=True)
+ cls._append_map_entry(cls.VIRTUAL_ALIASES_FILE, f'{source} {destination}\n')
run_privileged(['postmap', cls.VIRTUAL_ALIASES_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
diff --git a/backend/tests/test_postfix_map_roundtrip.py b/backend/tests/test_postfix_map_roundtrip.py
new file mode 100644
index 00000000..889b0ba5
--- /dev/null
+++ b/backend/tests/test_postfix_map_roundtrip.py
@@ -0,0 +1,107 @@
+"""Postfix virtual-map add ↔ remove round trip (#117 bug class).
+
+add_domain deduped with a raw substring test (`domain not in content`), so
+with sub.example.com already mapped, adding example.com no-opped while still
+reporting success; remove_domain filtered alias lines with `@{domain} in l`,
+which also deleted example.com.br entries; and appends went through tee -a
+with no trailing-newline guard, gluing entries onto a truncated last line.
+These tests drive the maps through an in-memory privileged-file store and
+assert the join both ways.
+"""
+import types
+
+import pytest
+
+from app.services import postfix_service as pf_module
+from app.services.postfix_service import PostfixService
+
+
+def map_store(monkeypatch):
+ """In-memory stand-in for the privileged read/write doors."""
+ store = {}
+
+ def fake_run(cmd, **kwargs):
+ if cmd[0] == 'cat':
+ return types.SimpleNamespace(
+ returncode=0, stdout=store.get(cmd[1], ''), stderr='')
+ # postmap / postfix reload are no-ops here
+ return types.SimpleNamespace(returncode=0, stdout='', stderr='')
+
+ def fake_write(path, content, append=False, **kwargs):
+ store[path] = (store.get(path, '') + content) if append else content
+ return {'success': True}
+
+ monkeypatch.setattr(pf_module, 'run_privileged', fake_run)
+ monkeypatch.setattr(pf_module, 'write_privileged_file', fake_write)
+ return store
+
+
+def _domains(store):
+ return store.get(PostfixService.VIRTUAL_DOMAINS_FILE, '')
+
+
+def test_add_domain_not_fooled_by_subdomain_substring(map_store):
+ assert PostfixService.add_domain('sub.example.com')['success']
+ assert PostfixService.add_domain('example.com')['success']
+
+ lines = _domains(map_store).split()
+ assert 'example.com' in lines
+ assert 'sub.example.com' in lines
+
+
+def test_add_domain_dedupes_exact_domain(map_store):
+ PostfixService.add_domain('example.com')
+ PostfixService.add_domain('example.com')
+ assert _domains(map_store).count('example.com OK') == 1
+
+
+def test_remove_domain_spares_superstring_domains(map_store):
+ PostfixService.add_alias('[email protected]', '[email protected]')
+ PostfixService.add_alias('[email protected]', '[email protected]')
+ PostfixService.add_mailbox('[email protected]', 'example.com', 'user')
+ PostfixService.add_mailbox('[email protected]', 'example.com.br', 'user')
+
+ assert PostfixService.remove_domain('example.com')['success']
+
+ aliases = map_store[PostfixService.VIRTUAL_ALIASES_FILE]
+ mailboxes = map_store[PostfixService.VIRTUAL_MAILBOXES_FILE]
+ assert '[email protected] ' not in aliases
+ assert '[email protected]' in aliases
+ assert '[email protected] ' not in mailboxes
+ assert '[email protected]' in mailboxes
+
+
+def test_remove_domain_spares_subdomain_addresses(map_store):
+ PostfixService.add_mailbox('[email protected]', 'mail.example.com', 'user')
+ PostfixService.add_mailbox('[email protected]', 'example.com', 'user')
+
+ PostfixService.remove_domain('example.com')
+
+ mailboxes = map_store[PostfixService.VIRTUAL_MAILBOXES_FILE]
+ assert '[email protected]' in mailboxes
+ assert '[email protected] ' not in mailboxes
+
+
+def test_append_heals_missing_trailing_newline(map_store):
+ # A map whose last line lost its newline must not have the next entry
+ # glued onto it — glued entries are unmatchable on removal.
+ map_store[PostfixService.VIRTUAL_ALIASES_FILE] = '[email protected] [email protected]'
+
+ PostfixService.add_alias('[email protected]', '[email protected]')
+
+ lines = map_store[PostfixService.VIRTUAL_ALIASES_FILE].splitlines()
+
+
+def test_full_domain_lifecycle(map_store):
+ PostfixService.add_domain('shop.test')
+ PostfixService.add_mailbox('[email protected]', 'shop.test', 'owner')
+ PostfixService.add_alias('[email protected]', '[email protected]')
+
+ assert PostfixService.remove_domain('shop.test')['success']
+
+ assert 'shop.test' not in _domains(map_store)
+ assert 'shop.test' not in map_store[PostfixService.VIRTUAL_MAILBOXES_FILE]
+ assert 'shop.test' not in map_store[PostfixService.VIRTUAL_ALIASES_FILE]