Files
stalwart-migrator/internal/cutover/unit_test.go
T
jcoffey-dev 7e04351b0f Add cutover; drop rollback in favour of operator-provided recovery
Two changes that arrived together: the cutover phase (ARCHITECTURE.md 4.5)
is implemented, and the rollback phase is deleted. Recovery from a failed
migration is now explicitly the operator's own snapshot or backup, and out
of scope for this tool.

internal/cutover implements 4.5 as seven checkpointed steps: verify the
staged binary's version, install it, preserve and rewrite the service
definition, reload, start, wait for a healthy JMAP session, recalculate
quotas.

The unit is rewritten in place rather than generated from a template. An
operator's unit carries hardening options, limits and dependencies this
tool has no business having an opinion about, and regenerating it would
silently drop them. It repoints ExecStart (preserving systemd's -@:+!
prefix characters and every argument after the executable), updates
--config, and strips recovery-mode Environment lines - leaving
STALWART_RECOVERY_MODE=1 set would recovery-boot the service on every
restart, forever. It refuses on a unit with no ExecStart, and on an
Environment line mixing a recovery variable with others: a line it only
partly understands is one it must not edit.

Quota recalculation is the one step allowed to fail without failing the
phase. Its wire format is grounded in Stalwart's x:Task schema reference -
Task/set creating one AccountMaintenance per account with maintenanceType
recalculateQuota - but the upgrade guide only documents the WebUI path, so
two details remain inferred and are called out in stalwartapi/task.go:
whether the schema's "read-only" annotation on accountId/maintenanceType
means "immutable after creation", and whether a finished task simply leaves
the queue (TaskStatus documents Pending/Retry/Failed with no success
state). Warning rather than failing is the honest response to that
uncertainty, and stale counters are an accounting problem next to calling
for a restore of a machine that is otherwise migrated and serving mail.

Docker deployments are refused outright: cutting a container over means
pulling an image and recreating it, not swapping a binary.

On removing rollback. The implementation worked and was tested, and it was
removed because restoring bytes correctly is not the hard part. It copied
file contents and permissions and verified every restored file against a
manifest - and did not preserve ownership. Run as root, as this tool
requires, it would have produced a byte-perfect, checksum-verified,
root-owned data directory that Stalwart, running as its own user, could not
open, and it would have reported success. The PostgreSQL path was worse:
pg_dump without --clean emits CREATE TABLE + COPY, which fails replaying
into a database whose tables still exist, and the ON_ERROR_STOP=1 added so
a half-applied restore couldn't be reported as success turned that into a
hard failure. None of it had ever run against a real server. A filesystem
snapshot has none of these failure modes, because it never lost the
metadata to begin with.

So cutover's gate is no longer rollback.CanRollBack but an explicit
RecoveryPointConfirmed acknowledgement. That is an assertion, not a check -
this tool cannot verify someone else's snapshot - and its only value is
that nobody migrates a production mail server having never been asked the
question. Two consequences are accepted deliberately: restoring any
pre-migration recovery point discards mail delivered since, and a failed
migration now stops and reports rather than undoing itself.

What the tool still does to make a manual restore easier: the old binary is
preserved and never deleted, the original service definition is preserved
before the rewrite, the settings and principals dumps stay on disk, and
every artifact path and checksum stays in the checkpoint where `status
<run-id>` can print it.

Also removed: the `confirm` command stub and RollbackWindowClosed, whose
only purpose was closing a rollback window that no longer exists, and
checkpoint.PhaseRollback. Old state.json files still load - JSON ignores
the now-unknown field.

Still open, and recorded in 8: cutover ignores systemd drop-ins, so an
ExecStart or Environment override in stalwart.service.d/*.conf is invisible
to the rewrite - including the recovery variable it exists to strip;
nothing prevents concurrent runs on the same run-id; and nothing in this
repo has ever run against a real Stalwart, real systemd, or a real store.
2026-08-23 17:52:47 -07:00

128 lines
4.3 KiB
Go

package cutover
import (
"strings"
"testing"
)
const realisticUnit = `[Unit]
Description=Stalwart Mail Server
After=network.target
[Service]
Type=simple
User=stalwart
ExecStart=/usr/local/bin/stalwart --config /etc/stalwart/config.toml
Restart=on-failure
LimitNOFILE=65536
ProtectSystem=strict
ReadWritePaths=/var/lib/stalwart
[Install]
WantedBy=multi-user.target
`
func TestRewriteUnitRepointsExecStart(t *testing.T) {
got, err := RewriteUnit(realisticUnit, "/usr/local/bin/stalwart", "/etc/stalwart/config.json")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(got, "ExecStart=/usr/local/bin/stalwart --config /etc/stalwart/config.json") {
t.Errorf("ExecStart not repointed:\n%s", got)
}
}
// The operator's unit is theirs: hardening options, limits and paths this
// tool has no opinion about must survive untouched.
func TestRewriteUnitPreservesEverythingElse(t *testing.T) {
got, err := RewriteUnit(realisticUnit, "/opt/stalwart/bin/stalwart", "")
if err != nil {
t.Fatal(err)
}
for _, want := range []string{
"Description=Stalwart Mail Server", "User=stalwart", "Restart=on-failure",
"LimitNOFILE=65536", "ProtectSystem=strict", "ReadWritePaths=/var/lib/stalwart",
"WantedBy=multi-user.target",
} {
if !strings.Contains(got, want) {
t.Errorf("rewrite dropped %q:\n%s", want, got)
}
}
if !strings.Contains(got, "ExecStart=/opt/stalwart/bin/stalwart --config /etc/stalwart/config.toml") {
t.Errorf("existing --config should be preserved when no new one is given:\n%s", got)
}
}
func TestRewriteUnitAddsConfigWhenTheUnitHasNone(t *testing.T) {
got, err := RewriteUnit("[Service]\nExecStart=/usr/local/bin/stalwart\n", "/usr/local/bin/stalwart", "/etc/stalwart/config.json")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(got, "ExecStart=/usr/local/bin/stalwart --config /etc/stalwart/config.json") {
t.Errorf("--config not added:\n%s", got)
}
}
func TestRewriteUnitKeepsSystemdExecPrefixes(t *testing.T) {
got, err := RewriteUnit("[Service]\nExecStart=-@/old/stalwart --config /c\n", "/new/stalwart", "")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(got, "ExecStart=-@/new/stalwart --config /c") {
t.Errorf("systemd exec prefix characters were dropped, changing what the unit means:\n%s", got)
}
}
// Leaving STALWART_RECOVERY_MODE=1 in the unit is the documented footgun
// from §4.5: the service would recovery-boot on every restart, forever.
func TestRewriteUnitStripsRecoveryEnvironmentLines(t *testing.T) {
unit := `[Service]
Environment=STALWART_RECOVERY_MODE=1
Environment="STALWART_RECOVERY_ADMIN=admin:hunter2"
Environment=RUST_LOG=info
ExecStart=/usr/local/bin/stalwart
`
got, err := RewriteUnit(unit, "/usr/local/bin/stalwart", "")
if err != nil {
t.Fatal(err)
}
for _, gone := range []string{"STALWART_RECOVERY_MODE", "STALWART_RECOVERY_ADMIN"} {
if strings.Contains(got, gone) {
t.Errorf("%s survived the rewrite - the service would recovery-boot on every restart:\n%s", gone, got)
}
}
if !strings.Contains(got, "Environment=RUST_LOG=info") {
t.Errorf("unrelated Environment line was dropped:\n%s", got)
}
}
// A line this tool only partly understands is one it must not edit.
func TestRewriteUnitRefusesAMixedEnvironmentLine(t *testing.T) {
unit := "[Service]\nEnvironment=RUST_LOG=info STALWART_RECOVERY_MODE=1\nExecStart=/usr/local/bin/stalwart\n"
_, err := RewriteUnit(unit, "/usr/local/bin/stalwart", "")
if err == nil {
t.Fatal("want refusal for an Environment line mixing recovery and other variables, got nil")
}
if !strings.Contains(err.Error(), "by hand") {
t.Errorf("error %q should tell the operator what to do about it", err)
}
}
func TestRewriteUnitRefusesAUnitWithNoExecStart(t *testing.T) {
_, err := RewriteUnit("[Unit]\nDescription=Something else entirely\n", "/usr/local/bin/stalwart", "")
if err == nil {
t.Fatal("want refusal for a unit with no ExecStart, got nil")
}
if !strings.Contains(err.Error(), "right unit file") {
t.Errorf("error %q should question whether this is the right file", err)
}
}
func TestRewriteUnitHandlesMultipleExecStartLines(t *testing.T) {
unit := "[Service]\nExecStart=\nExecStart=/old/stalwart --config /c\n"
got, err := RewriteUnit(unit, "/new/stalwart", "")
if err == nil {
t.Fatalf("an empty ExecStart= names no executable and should be refused, got:\n%s", got)
}
}