2 Commits
Author SHA1 Message Date
lyrathorpeandEmma Thorpe f1e1373fd3 feat: add Python packaging metadata and a Nix flake (#16)
Build and publish container / build (push) Successful in 6m4s
## What

- `pyproject.toml` — setuptools metadata with a `legacy-email-proxy` console script. Runtime dependencies are read dynamically from `requirements.txt`, so the Docker build and the package cannot drift apart.
- `proxy_server.run()` — a synchronous entry point for that console script; `main` is a coroutine and cannot be referenced by one. The `__main__` path behaves as before.
- `flake.nix` / `package.nix` — the package, `overlays.default`, a dev shell, and `checks`. The pytest suite runs as part of the build.
- `module.nix` — a NixOS module: `services.legacy-email-proxy` with freeform `settings` (environment variables) and a separate `environmentFile` for credentials, so secrets stay out of the Nix store. Runs under `DynamicUser`, takes `CAP_NET_BIND_SERVICE` only while a listener is on a privileged port, and opens no firewall ports.
- README: pip install, Nix usage, and a NixOS service example.

## Why

The proxy could only be consumed as a container. Anyone deploying it on NixOS had to vendor a package definition into their own configuration — which is exactly what happened downstream, and is now deleted there in favour of this.

## Not in scope

- The `Dockerfile` and its CI workflow are untouched.
- No Nix job in CI; the runner has no Nix. The build is reproducible locally with `nix flake check`.
- `version` is static and tracks the latest tag (`0.3.0`); bump it with the tag.

## Verification

- `nix flake check` — package builds, 14 tests pass inside the build.
- Consumed from a downstream NixOS host with `--override-input`: the unit's `ExecStart` resolves to the module's own build, and that flake's checks pass too.

---------

Co-authored-by: Emma Thorpe <emma.thorpe@citrix.com>
Reviewed-on: #16
2026-08-21 13:26:51 +01:00
lyrathorpe 4bde4f884d feat: respect BACKEND_MUTATE to avoid mutating backend mailboxes by default; add tests and docs
Build and publish container / build (push) Successful in 7m8s
2026-06-17 18:43:22 +01:00
9 changed files with 480 additions and 6 deletions
+7
View File
@@ -0,0 +1,7 @@
result
result-*
__pycache__/
*.pyc
.venv/
.pytest_cache/
*.egg-info/
+66
View File
@@ -30,6 +30,11 @@ Proxy an unauthenticated, unencrypted POP3 / SMTP server to authenticated IMAPS
- `BACKEND_SMTP_USE_SSL` (default `true`) - `BACKEND_SMTP_USE_SSL` (default `true`)
- `BACKEND_SMTP_USE_TLS` (default `false`) - `BACKEND_SMTP_USE_TLS` (default `false`)
- `BACKEND_MUTATE` (default `false`) - when `true`, POP3 deletions are propagated to the
backend IMAP server (STORE +FLAGS / EXPUNGE). Default behaviour is to never mutate
the backend mailbox on POP client deletions; the proxy only hides messages for the
duration of the client session.
## Build and run ## Build and run
This project targets the latest Python LTS release. The included `Dockerfile` uses `python:3.12-slim`, which is compatible with Python 3.12 and later LTS releases. This project targets the latest Python LTS release. The included `Dockerfile` uses `python:3.12-slim`, which is compatible with Python 3.12 and later LTS releases.
@@ -48,6 +53,67 @@ docker run --rm -p 110:110 -p 25:25 \
legacy-email-proxy legacy-email-proxy
``` ```
The project is also a standard Python package (`pyproject.toml`), so it
installs without Docker. This puts a `legacy-email-proxy` command on `PATH`:
```bash
pip install .
legacy-email-proxy
```
`requirements.txt` remains the single source of runtime dependencies;
`pyproject.toml` reads it, so the Docker build and the package cannot drift.
## Nix
The repository is a flake. It exposes the package, an overlay, and a NixOS
module.
```bash
nix run .#legacy-email-proxy # run it
nix build .#legacy-email-proxy # build it; the test suite runs as part of the build
nix develop # dev shell with pytest
```
As a NixOS service, with the proxy's own flake as an input:
```nix
{
inputs.legacy-email-proxy.url = "git+https://code.emmathe.dev/lyrathorpe/legacy-email-proxy";
# optionally: inputs.legacy-email-proxy.inputs.nixpkgs.follows = "nixpkgs";
}
```
```nix
{
imports = [ inputs.legacy-email-proxy.nixosModules.default ];
services.legacy-email-proxy = {
enable = true;
settings = {
POP3_BIND_ADDR = "10.0.0.1";
SMTP_BIND_ADDR = "10.0.0.1";
BACKEND_IMAP_HOST = "imap.example.com";
BACKEND_IMAP_USER = "someone@example.com";
BACKEND_SMTP_HOST = "smtp.example.com";
BACKEND_SMTP_USER = "someone@example.com";
};
# Credentials belong here, not in `settings` -- anything in `settings`
# lands in the world-readable Nix store.
environmentFile = "/var/lib/legacy-email-proxy/backend.env";
};
}
```
`settings` accepts any of the environment variables listed above; booleans and
integers are converted for you. The service runs under `DynamicUser`, with
`CAP_NET_BIND_SERVICE` granted only while a listener is on a privileged port.
It opens no firewall ports — see "Security".
Prefer to manage the package yourself? `overlays.default` provides
`pkgs.legacy-email-proxy`, and `nixosModules.legacy-email-proxy` is the same
module without the package default wired to this flake.
## Tests ## Tests
Install development dependencies and run the test suite: Install development dependencies and run the test suite:
Generated
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1787135253,
"narHash": "sha256-RD2kNWCG+Bjo6h+JVjWVNntZs2GtRoeY2xHjts/FNkA=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "ffb3c9b700e759be2ef13237c9d8f953b32a1e46",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+54
View File
@@ -0,0 +1,54 @@
{
description = "Unauthenticated POP3/SMTP front end proxied to authenticated IMAPS/SMTPS backends";
inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
outputs =
{ self, nixpkgs }:
let
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
forAllSystems = fn: nixpkgs.lib.genAttrs systems (system: fn nixpkgs.legacyPackages.${system});
in
{
overlays.default = final: _prev: {
legacy-email-proxy = final.callPackage ./package.nix { };
};
packages = forAllSystems (pkgs: rec {
legacy-email-proxy = pkgs.callPackage ./package.nix { };
default = legacy-email-proxy;
});
# The NixOS module with its package option pointed at this flake's build,
# so consumers need no overlay. Use nixosModules.legacy-email-proxy
# instead if you would rather apply overlays.default yourself.
nixosModules.default =
{ lib, pkgs, ... }:
{
imports = [ ./module.nix ];
services.legacy-email-proxy.package =
lib.mkDefault
self.packages.${pkgs.stdenv.hostPlatform.system}.legacy-email-proxy;
};
nixosModules.legacy-email-proxy = ./module.nix;
# The package builds only if the test suite passes, so this covers both.
checks = forAllSystems (pkgs: {
inherit (self.packages.${pkgs.system}) legacy-email-proxy;
});
devShells = forAllSystems (pkgs: {
default = pkgs.mkShellNoCC {
inputsFrom = [ self.packages.${pkgs.system}.legacy-email-proxy ];
packages = [ pkgs.python3Packages.pytest ];
};
});
formatter = forAllSystems (pkgs: pkgs.nixfmt-tree);
};
}
+129
View File
@@ -0,0 +1,129 @@
# NixOS module for legacy-email-proxy.
#
# Consumed either through this flake's nixosModules.default (which defaults the
# package to the flake's own build) or directly, alongside overlays.default.
{
config,
lib,
pkgs,
...
}:
let
cfg = config.services.legacy-email-proxy;
renderValue =
value:
if lib.isBool value then
lib.boolToString value # the proxy accepts 1/true/yes/on
else
toString value;
environment = lib.mapAttrs (_name: renderValue) (lib.filterAttrs (_: v: v != null) cfg.settings);
# The default listeners are 110 and 25, so the service normally needs
# CAP_NET_BIND_SERVICE. Drop it when both are configured above 1024.
portOf =
name: default:
let
value = cfg.settings.${name} or default;
in
if lib.isInt value then value else lib.toInt (toString value);
needsPrivilegedPorts = portOf "POP3_BIND_PORT" 110 < 1024 || portOf "SMTP_BIND_PORT" 25 < 1024;
in
{
options.services.legacy-email-proxy = {
enable = lib.mkEnableOption "the legacy POP3/SMTP proxy";
package = lib.mkPackageOption pkgs "legacy-email-proxy" { };
settings = lib.mkOption {
type =
with lib.types;
attrsOf (
nullOr (oneOf [
bool
int
str
])
);
default = { };
example = lib.literalExpression ''
{
POP3_BIND_ADDR = "10.0.0.1";
BACKEND_IMAP_HOST = "imap.example.com";
BACKEND_IMAP_USER = "someone@example.com";
BACKEND_MUTATE = false;
}
'';
description = ''
Environment variables for the proxy, passed to the service as-is.
Booleans render as `true`/`false`, which the proxy accepts. The full
list of variables is in the project README.
Everything set here lands in the Nix store and is world-readable. Put
credentials in {option}`services.legacy-email-proxy.environmentFile`
instead.
'';
};
environmentFile = lib.mkOption {
type = lib.types.nullOr lib.types.path;
default = null;
example = "/var/lib/legacy-email-proxy/backend.env";
description = ''
Path to a systemd `EnvironmentFile` holding the backend credentials
(`BACKEND_IMAP_PASS`, `BACKEND_SMTP_PASS` and anything else that should
not be in the Nix store). Read by systemd at start, not by the service
user, so it can be root-owned and mode 0600.
'';
};
};
config = lib.mkIf cfg.enable {
systemd.services.legacy-email-proxy = {
description = "Legacy POP3/SMTP proxy to authenticated IMAPS/SMTPS backends";
wantedBy = [ "multi-user.target" ];
after = [ "network.target" ];
environment = environment // {
PYTHONUNBUFFERED = "1";
};
serviceConfig = {
ExecStart = lib.getExe cfg.package;
Restart = "always";
RestartSec = 5;
DynamicUser = true;
AmbientCapabilities = lib.optional needsPrivilegedPorts "CAP_NET_BIND_SERVICE";
CapabilityBoundingSet = lib.optional needsPrivilegedPorts "CAP_NET_BIND_SERVICE";
NoNewPrivileges = true;
PrivateDevices = true;
PrivateTmp = true;
ProtectControlGroups = true;
ProtectHome = true;
ProtectKernelModules = true;
ProtectKernelTunables = true;
ProtectSystem = "strict";
# AF_NETLINK is not gratuitous: glibc's getaddrinfo opens a netlink
# socket to sort resolver results, and backends are reached by name.
RestrictAddressFamilies = [
"AF_INET"
"AF_INET6"
"AF_UNIX"
"AF_NETLINK"
];
RestrictNamespaces = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
SystemCallArchitectures = "native";
SystemCallFilter = [ "@system-service" ];
}
// lib.optionalAttrs (cfg.environmentFile != null) {
EnvironmentFile = cfg.environmentFile;
};
};
};
}
+40
View File
@@ -0,0 +1,40 @@
{
lib,
python3Packages,
}:
python3Packages.buildPythonApplication {
pname = "legacy-email-proxy";
inherit ((lib.importTOML ./pyproject.toml).project) version;
pyproject = true;
# Only the files that affect the build, so editing the README or the CI
# workflow does not invalidate it.
src = lib.fileset.toSource {
root = ./.;
fileset = lib.fileset.unions [
./proxy_server.py
./pyproject.toml
./requirements.txt
./pytest.ini
./tests
];
};
build-system = [ python3Packages.setuptools ];
dependencies = [ python3Packages.aiosmtpd ];
nativeCheckInputs = [ python3Packages.pytestCheckHook ];
meta = {
description = "Unauthenticated POP3/SMTP front end proxied to authenticated IMAPS/SMTPS backends";
longDescription = ''
Exposes cleartext POP3 and SMTP to clients that cannot speak TLS or
modern authentication, and forwards them to an authenticated IMAPS/SMTPS
backend. The front-end listeners are unauthenticated by design and must
be confined to a trusted network.
'';
homepage = "https://code.emmathe.dev/lyrathorpe/legacy-email-proxy";
mainProgram = "legacy-email-proxy";
platforms = lib.platforms.unix;
};
}
+17 -1
View File
@@ -51,6 +51,10 @@ class Settings:
BACKEND_SMTP_PASS = os.getenv("BACKEND_SMTP_PASS") BACKEND_SMTP_PASS = os.getenv("BACKEND_SMTP_PASS")
BACKEND_SMTP_USE_SSL = env_bool("BACKEND_SMTP_USE_SSL", True) BACKEND_SMTP_USE_SSL = env_bool("BACKEND_SMTP_USE_SSL", True)
BACKEND_SMTP_USE_TLS = env_bool("BACKEND_SMTP_USE_TLS", False) BACKEND_SMTP_USE_TLS = env_bool("BACKEND_SMTP_USE_TLS", False)
# When false (default) the proxy will not mutate backend mailboxes
# (no STORE +FLAGS / EXPUNGE). Set to true only when deletions should
# be propagated to the backend IMAP server.
BACKEND_MUTATE = env_bool("BACKEND_MUTATE", False)
@classmethod @classmethod
def validate(cls): def validate(cls):
@@ -376,9 +380,12 @@ class POP3Session:
async def handle_quit(self): async def handle_quit(self):
if self._imap: if self._imap:
# Only propagate deletes to the backend when explicitly enabled.
if Settings.BACKEND_MUTATE:
for uid in self.deleted: for uid in self.deleted:
await asyncio.to_thread(self._imap.mark_deleted, uid) await asyncio.to_thread(self._imap.mark_deleted, uid)
await asyncio.to_thread(self._imap.expunge) await asyncio.to_thread(self._imap.expunge)
# Always logout the backend connection.
self._imap.logout() self._imap.logout()
await self.send_line("+OK Goodbye") await self.send_line("+OK Goodbye")
@@ -451,8 +458,17 @@ async def main():
await pop3_server.serve_forever() await pop3_server.serve_forever()
if __name__ == "__main__": def run():
"""Run the proxy until interrupted.
Entry point for the ``legacy-email-proxy`` console script; ``main`` is a
coroutine and cannot be referenced directly by one.
"""
try: try:
asyncio.run(main()) asyncio.run(main())
except KeyboardInterrupt: except KeyboardInterrupt:
logger.info("Shutdown requested") logger.info("Shutdown requested")
if __name__ == "__main__":
run()
+25
View File
@@ -0,0 +1,25 @@
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "legacy-email-proxy"
version = "0.3.0"
description = "Unauthenticated POP3/SMTP front end proxied to authenticated IMAPS/SMTPS backends"
readme = "README.md"
requires-python = ">=3.12"
dynamic = ["dependencies"]
[project.scripts]
legacy-email-proxy = "proxy_server:run"
[project.urls]
Homepage = "https://code.emmathe.dev/lyrathorpe/legacy-email-proxy"
# requirements.txt stays the single source of runtime dependencies, so the
# Dockerfile and this file cannot drift apart.
[tool.setuptools.dynamic]
dependencies = { file = ["requirements.txt"] }
[tool.setuptools]
py-modules = ["proxy_server"]
+112 -2
View File
@@ -143,6 +143,95 @@ def test_smtp_proxy_handler_forwards_message_over_ssl(monkeypatch):
Settings.BACKEND_SMTP_PASS = previous_pass Settings.BACKEND_SMTP_PASS = previous_pass
def test_pop3_quit_does_not_mutate_backend_by_default():
import asyncio
class DummyBackend:
def __init__(self):
self.deleted_called = []
self.expunge_called = False
self.logged_out = False
def mark_deleted(self, uid):
self.deleted_called.append(uid)
def expunge(self):
self.expunge_called = True
def logout(self):
self.logged_out = True
session = POP3Session(None, None)
backend = DummyBackend()
session._imap = backend
session.deleted = {b"1", b"2"}
# Provide a dummy writer so send_line can be awaited without a socket.
class DummyWriter:
def __init__(self):
self.buf = b""
self.closed = False
def write(self, data):
self.buf += data
async def drain(self):
return None
def close(self):
self.closed = True
async def wait_closed(self):
return None
session.writer = DummyWriter()
# Ensure default is not to mutate
previous_mutate = Settings.BACKEND_MUTATE
Settings.BACKEND_MUTATE = False
asyncio.run(session.handle_quit())
Settings.BACKEND_MUTATE = previous_mutate
assert backend.deleted_called == []
assert backend.expunge_called is False
assert backend.logged_out is True
def test_pop3_quit_mutates_backend_when_enabled():
import asyncio
class DummyBackend:
def __init__(self):
self.deleted_called = []
self.expunge_called = False
self.logged_out = False
def mark_deleted(self, uid):
self.deleted_called.append(uid)
def expunge(self):
self.expunge_called = True
def logout(self):
self.logged_out = True
session = POP3Session(None, None)
backend = DummyBackend()
session._imap = backend
session.deleted = {b"1", b"2"}
session.writer = DummyWriter()
previous_mutate = Settings.BACKEND_MUTATE
Settings.BACKEND_MUTATE = True
asyncio.run(session.handle_quit())
Settings.BACKEND_MUTATE = previous_mutate
assert set(backend.deleted_called) == {b"1", b"2"}
assert backend.expunge_called is True
assert backend.logged_out is True
class FakeWriter: class FakeWriter:
def __init__(self): def __init__(self):
self.buffer = bytearray() self.buffer = bytearray()
@@ -160,6 +249,26 @@ class FakeWriter:
pass pass
class DummyWriter:
"""Simple writer used by tests where we only need write/drain/close."""
def __init__(self):
self.buf = b""
self.closed = False
def write(self, data):
self.buf += data
async def drain(self):
return None
def close(self):
self.closed = True
async def wait_closed(self):
return None
class RecordingIMAP: class RecordingIMAP:
"""In-memory IMAPBackend stand-in for POP3 session tests.""" """In-memory IMAPBackend stand-in for POP3 session tests."""
@@ -278,6 +387,7 @@ def test_dele_survives_stat_list_uidl_until_quit():
asyncio.run(session.handle_list([])) asyncio.run(session.handle_list([]))
asyncio.run(session.handle_uidl([])) asyncio.run(session.handle_uidl([]))
assert b"2" in session.deleted assert b"2" in session.deleted
# Default behaviour is not to mutate the backend mailbox on QUIT.
asyncio.run(session.handle_quit()) asyncio.run(session.handle_quit())
assert session._imap.marked == [b"2"] assert session._imap.marked == []
assert session._imap.expunged is True assert session._imap.expunged is False