diff --git a/.env.example b/.env.example index 94c8b78..9818bd5 100644 --- a/.env.example +++ b/.env.example @@ -1,5 +1,7 @@ # Documentation only. Run `mailctl init`; do not deploy this file as `.env`. MEOVV_VERSION=0.1.0 MAIL_HOSTNAME=mail.example.com +MEOVV_HTTP_BIND=127.0.0.1:8080 +STALWART_HTTP_BIND=127.0.0.1:8081 STALWART_RECOVERY_ADMIN= API_SUBMISSION_USER= diff --git a/CHANGELOG.md b/CHANGELOG.md index 64227d4..a5f4a96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,8 @@ All notable project changes will be recorded here. This project follows ### Added -- Initial three-container self-hosted appliance architecture. +- Initial two-container self-hosted appliance architecture with external Nginx + and Certbot integration. - React/Vite mailbox, setup, authentication, and administration interfaces. - Go control plane, REST send API, JMAP session proxy, delivery events, and signed webhook delivery. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b189d7b..bd054af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,7 +19,8 @@ corrections are welcome while that policy is finalized. ## Development checks -Install Node.js 22+, Go 1.24+, and Docker with Compose. Then run: +Install Node.js 22+, Go 1.24+, and Docker with Compose. Production deployments +also require host-managed Nginx and Certbot. Then run: ```bash npm ci diff --git a/README.md b/README.md index 9bc35c5..41abfaa 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ MEOVV Mail is a single-tenant, self-hosted email appliance for one organization. It combines a polished web inbox and administration experience with a pinned Stalwart mail core, -a Go control plane, and automatic HTTPS through Caddy. +a Go control plane, and your host-managed Nginx and Certbot edge. > [!IMPORTANT] > MEOVV Mail is pre-1.0 software under active development. The architecture, @@ -19,12 +19,16 @@ and a scoped REST send API. POP3 and plaintext IMAP are not published. ## Architecture -The production bundle runs exactly three containers: +The production bundle runs exactly two containers: -- `caddy` terminates public TLS, publishes discovery routes, and sends product traffic to MEOVV. - `meovv` serves the web application, encrypted OAuth sessions, REST API, setup, delivery metadata, webhook jobs, audit events, and operational endpoints. - `stalwart` stores accounts and all mailbox data and provides SMTP, IMAP, JMAP, filtering, queues, and delivery telemetry. +Nginx and Certbot remain host infrastructure outside Compose. Nginx terminates +HTTPS and routes loopback-only upstreams to the two services. Stalwart receives +a controlled copy of the Certbot certificate for SMTP and IMAP TLS. See +[`docs/nginx-certbot.md`](docs/nginx-certbot.md). + Stalwart is pinned to `v0.16.17` and multi-architecture digest `sha256:a8108e19bd927e172d4d8c128907b8dfc93fd180ae8ee07dccdd42cb97eb9dfa`. Mail bodies and attachments never enter the MEOVV SQLite database. @@ -32,6 +36,7 @@ Mail bodies and attachments never enter the MEOVV SQLite database. - Ubuntu 24.04 or Debian 13 on amd64 or arm64 - Docker Engine with the Compose plugin +- Host-managed Nginx and Certbot - 4 vCPU, 8 GB RAM, and SSD storage for the reference 500-account deployment - A public static IP and control of DNS for direct delivery - Inbound TCP 25, 80, 443, 465, 587, and 993 @@ -41,20 +46,29 @@ Direct delivery also needs working reverse DNS and acceptable IP reputation. If ## Install -Build the local operator utility, initialize the bundle, and start it: +Build the local operator utility and initialize the bundle: ```bash go build -o mailctl ./cmd/mailctl ./mailctl init --hostname mail.example.com -docker compose up -d --build ``` -`mailctl init` prints a one-time browser bootstrap token and temporary Stalwart recovery credential. Store both securely. Visit `https://mail.example.com`, complete the three-step wizard, and save the one-time result shown on the final screen. +`mailctl init` prints a one-time browser bootstrap token and temporary Stalwart +recovery credential. Store both securely. Next, issue the hostname certificate, +install the provided Nginx route split, and copy the Certbot lineage by following +[`docs/nginx-certbot.md`](docs/nginx-certbot.md). Then start the appliance: + +```bash +docker compose up -d --build --remove-orphans +``` + +Visit `https://mail.example.com`, complete the three-step wizard, and save the +one-time result shown on the final screen. After setup: ```bash -docker compose restart stalwart meovv +./mailctl configure-tls ./mailctl doctor --hostname mail.example.com ``` @@ -109,7 +123,7 @@ Create a consistency-safe backup: ./mailctl backup ``` -The command stops Stalwart and MEOVV writers, archives all five named volumes plus Compose configuration and secrets, writes SHA-256 checksums, and restarts the services. Restore is intentionally destructive and only accepts a backup from the same MEOVV and Stalwart release: +The command stops Stalwart and MEOVV writers, archives all three named volumes plus Compose configuration and secrets, writes SHA-256 checksums, and restarts the services. Host-managed Nginx and Certbot configuration remains part of the host backup policy. Restore is intentionally destructive and only accepts a backup from the same MEOVV and Stalwart release: ```bash ./mailctl restore --from backups/20260812T103000Z --yes diff --git a/cmd/mailctl/main.go b/cmd/mailctl/main.go index 1ee5a0c..a791c63 100644 --- a/cmd/mailctl/main.go +++ b/cmd/mailctl/main.go @@ -2,6 +2,7 @@ package main import ( "archive/tar" + "bytes" "compress/gzip" "context" "crypto/ed25519" @@ -15,6 +16,8 @@ import ( "fmt" "io" "net" + "net/http" + "net/url" "os" "os/exec" "path/filepath" @@ -35,8 +38,6 @@ const ( ) var volumeArchives = map[string]string{ - "meovv-mail-caddy-data": "caddy-data.tgz", - "meovv-mail-caddy-config": "caddy-config.tgz", "meovv-mail-app-data": "meovv-data.tgz", "meovv-mail-stalwart-config": "stalwart-config.tgz", "meovv-mail-stalwart-data": "stalwart-data.tgz", @@ -63,6 +64,8 @@ func main() { err = doctor(os.Args[2:]) case "create-api-key": err = createAPIKey(os.Args[2:]) + case "configure-tls": + err = configureTLS(os.Args[2:]) case "backup": err = backup(os.Args[2:]) case "restore": @@ -94,6 +97,7 @@ Usage: mailctl [options] init Create .env and one-time installation secrets doctor Check DNS, ports, files, and the running appliance create-api-key Create a hashed REST API key (run inside app container) + configure-tls Register the Certbot certificate with Stalwart backup Stop mail writers and create a checksummed backup restore Verify and restore a same-release backup upgrade Verify compatibility, back up, and apply an approved release @@ -126,6 +130,9 @@ func initialize(args []string) error { if err = os.MkdirAll(secretDir, 0o700); err != nil { return err } + if err = os.MkdirAll(filepath.Join(secretDir, "tls"), 0o700); err != nil { + return err + } values := map[string]string{ "bootstrap_token": randomSecret(32), "session_key": randomSecret(32), @@ -138,11 +145,11 @@ func initialize(args []string) error { } } recovery := "admin:" + randomSecret(24) - env := fmt.Sprintf("MEOVV_VERSION=%s\nMAIL_HOSTNAME=%s\nSTALWART_RECOVERY_ADMIN=%s\nAPI_SUBMISSION_USER=api-sender@%s\n", version, *hostname, recovery, strings.TrimPrefix(*hostname, "mail.")) + env := fmt.Sprintf("MEOVV_VERSION=%s\nMAIL_HOSTNAME=%s\nMEOVV_HTTP_BIND=127.0.0.1:8080\nSTALWART_HTTP_BIND=127.0.0.1:8081\nSTALWART_RECOVERY_ADMIN=%s\nAPI_SUBMISSION_USER=api-sender@%s\n", version, *hostname, recovery, strings.TrimPrefix(*hostname, "mail.")) if err = writeExclusive(filepath.Join(root, ".env"), []byte(env), 0o600); err != nil { return err } - fmt.Printf("Initialized %s\nBootstrap token: %s\nTemporary Stalwart recovery user: admin\nTemporary Stalwart recovery password: %s\n\nStore these values securely. Run 'docker compose up -d --build', complete setup, create a permanent administrator, then run 'mailctl harden'.\n", root, values["bootstrap_token"], strings.TrimPrefix(recovery, "admin:")) + fmt.Printf("Initialized %s\nBootstrap token: %s\nTemporary Stalwart recovery user: admin\nTemporary Stalwart recovery password: %s\n\nStore these values securely. Configure host Nginx/Certbot, run 'docker compose up -d --build --remove-orphans', complete setup, then run 'mailctl configure-tls' before 'mailctl harden'.\n", root, values["bootstrap_token"], strings.TrimPrefix(recovery, "admin:")) return nil } @@ -171,6 +178,12 @@ func doctor(args []string) error { check("Compose bundle", err) _, err = os.Stat(filepath.Join(root, "secrets", "session_key")) check("Secrets", err) + _, err = os.Stat(filepath.Join(root, "secrets", "tls", "fullchain.pem")) + check("TLS certificate", err) + _, err = os.Stat(filepath.Join(root, "secrets", "tls", "privkey.pem")) + check("TLS private key", err) + _, err = os.Stat(filepath.Join(root, "secrets", "tls", "certificate_id")) + check("Stalwart TLS link", err) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() addresses, err := net.DefaultResolver.LookupHost(ctx, *hostname) @@ -236,6 +249,183 @@ func createAPIKey(args []string) error { return nil } +func configureTLS(args []string) error { + fs := flag.NewFlagSet("configure-tls", flag.ContinueOnError) + dir := fs.String("directory", ".", "Compose bundle directory") + endpoint := fs.String("url", "http://127.0.0.1:8081/api", "loopback Stalwart management endpoint") + certificatePath := fs.String("certificate-path", "/etc/stalwart/tls/fullchain.pem", "certificate path inside the Stalwart container") + privateKeyPath := fs.String("private-key-path", "/etc/stalwart/tls/privkey.pem", "private key path inside the Stalwart container") + if err := fs.Parse(args); err != nil { + return err + } + root, _ := filepath.Abs(*dir) + managementURL, err := url.Parse(*endpoint) + if err != nil || managementURL.Scheme != "http" || managementURL.Path != "/api" || managementURL.User != nil || managementURL.RawQuery != "" || managementURL.Fragment != "" { + return errors.New("--url must be a loopback HTTP URL ending in /api") + } + managementHost := managementURL.Hostname() + managementIP := net.ParseIP(managementHost) + if managementHost != "localhost" && (managementIP == nil || !managementIP.IsLoopback()) { + return errors.New("--url must use localhost or a loopback IP so the recovery credential is never sent over a network") + } + for _, name := range []string{"fullchain.pem", "privkey.pem"} { + if _, err := os.Stat(filepath.Join(root, "secrets", "tls", name)); err != nil { + return fmt.Errorf("secrets/tls/%s is unavailable; copy the Certbot lineage first: %w", name, err) + } + } + env, err := readEnv(filepath.Join(root, ".env")) + if err != nil { + return err + } + recovery := env["STALWART_RECOVERY_ADMIN"] + if parts := strings.SplitN(recovery, ":", 2); len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return errors.New("STALWART_RECOVERY_ADMIN is required; run configure-tls before mailctl harden") + } + idPath := filepath.Join(root, "secrets", "tls", "certificate_id") + idBytes, readErr := os.ReadFile(idPath) + certificateID := strings.TrimSpace(string(idBytes)) + certificate := map[string]any{"@type": "File", "filePath": *certificatePath} + privateKey := map[string]any{"@type": "File", "filePath": *privateKeyPath} + var payload map[string]any + creating := errors.Is(readErr, os.ErrNotExist) || certificateID == "" + if readErr != nil && !errors.Is(readErr, os.ErrNotExist) { + return readErr + } + if creating { + payload = jmapPayload("x:Certificate/set", map[string]any{"create": map[string]any{"certbot": map[string]any{"certificate": certificate, "privateKey": privateKey}}}, "certificate") + } else { + payload = jmapPayload("x:Certificate/set", map[string]any{"update": map[string]any{certificateID: map[string]any{"certificate": certificate, "privateKey": privateKey}}}, "certificate") + } + raw, err := callStalwart(*endpoint, recovery, payload) + if err != nil { + return err + } + if creating { + certificateID, err = createdObjectID(raw, "certbot") + } else { + err = jmapSucceeded(raw) + } + if err != nil { + return fmt.Errorf("register Certbot certificate: %w", err) + } + if creating { + if err = writeExclusive(idPath, []byte(certificateID+"\n"), 0o600); err != nil { + return err + } + } + payload = jmapPayload("x:SystemSettings/set", map[string]any{"update": map[string]any{"singleton": map[string]any{"defaultCertificateId": certificateID}}}, "settings") + raw, err = callStalwart(*endpoint, recovery, payload) + if err != nil { + return err + } + if err = jmapSucceeded(raw); err != nil { + return fmt.Errorf("select default certificate: %w", err) + } + if err = run(root, "docker", "compose", "restart", "stalwart"); err != nil { + return fmt.Errorf("certificate registered, but Stalwart could not be restarted: %w", err) + } + fmt.Println("Certbot certificate registered as Stalwart's default TLS certificate.") + return nil +} + +func jmapPayload(method string, arguments map[string]any, callID string) map[string]any { + return map[string]any{ + "using": []string{"urn:ietf:params:jmap:core", "urn:stalwart:jmap"}, + "methodCalls": []any{[]any{method, arguments, callID}}, + } +} + +func callStalwart(endpoint, recovery string, payload any) ([]byte, error) { + raw, err := json.Marshal(payload) + if err != nil { + return nil, err + } + req, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(raw)) + if err != nil { + return nil, err + } + parts := strings.SplitN(recovery, ":", 2) + req.SetBasicAuth(parts[0], parts[1]) + req.Header.Set("Content-Type", "application/json") + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + client := &http.Client{ + Timeout: 20 * time.Second, + Transport: transport, + CheckRedirect: func(_ *http.Request, _ []*http.Request) error { + return http.ErrUseLastResponse + }, + } + response, err := client.Do(req) + if err != nil { + return nil, fmt.Errorf("contact Stalwart management endpoint: %w", err) + } + defer response.Body.Close() + body, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) + if err != nil { + return nil, err + } + if response.StatusCode/100 != 2 { + return nil, fmt.Errorf("Stalwart returned %s: %s", response.Status, strings.TrimSpace(string(body))) + } + return body, nil +} + +func jmapMethodBody(raw []byte) (string, json.RawMessage, error) { + var response struct { + MethodResponses [][]json.RawMessage `json:"methodResponses"` + } + if err := json.Unmarshal(raw, &response); err != nil { + return "", nil, err + } + if len(response.MethodResponses) != 1 || len(response.MethodResponses[0]) < 2 { + return "", nil, fmt.Errorf("unexpected JMAP response: %s", strings.TrimSpace(string(raw))) + } + var method string + if err := json.Unmarshal(response.MethodResponses[0][0], &method); err != nil { + return "", nil, err + } + return method, response.MethodResponses[0][1], nil +} + +func jmapSucceeded(raw []byte) error { + method, body, err := jmapMethodBody(raw) + if err != nil { + return err + } + if method == "error" || bytes.Contains(body, []byte(`"notUpdated"`)) || bytes.Contains(body, []byte(`"notCreated"`)) { + return fmt.Errorf("Stalwart rejected the change: %s", strings.TrimSpace(string(body))) + } + return nil +} + +func createdObjectID(raw []byte, clientID string) (string, error) { + method, body, err := jmapMethodBody(raw) + if err != nil { + return "", err + } + if method == "error" { + return "", fmt.Errorf("Stalwart rejected the change: %s", strings.TrimSpace(string(body))) + } + var result struct { + Created map[string]struct { + ID string `json:"id"` + } `json:"created"` + NotCreated map[string]json.RawMessage `json:"notCreated"` + } + if err = json.Unmarshal(body, &result); err != nil { + return "", err + } + if failure := result.NotCreated[clientID]; len(failure) > 0 { + return "", fmt.Errorf("Stalwart rejected the certificate: %s", strings.TrimSpace(string(failure))) + } + id := result.Created[clientID].ID + if id == "" { + return "", fmt.Errorf("certificate id missing from response: %s", strings.TrimSpace(string(body))) + } + return id, nil +} + func backup(args []string) error { fs := flag.NewFlagSet("backup", flag.ContinueOnError) dir := fs.String("directory", ".", "Compose bundle directory") @@ -306,7 +496,7 @@ func restore(args []string) error { if manifest.MEOVVVersion != version || manifest.StalwartVersion != stalwartVersion { return fmt.Errorf("backup release is MEOVV %s / Stalwart %s; this binary is %s / %s", manifest.MEOVVVersion, manifest.StalwartVersion, version, stalwartVersion) } - if err = run(root, "docker", "compose", "stop", "meovv", "stalwart", "caddy"); err != nil { + if err = run(root, "docker", "compose", "stop", "meovv", "stalwart"); err != nil { return err } for volume, archive := range volumeArchives { @@ -469,7 +659,7 @@ func archiveConfiguration(root, destination string) error { defer gz.Close() tw := tar.NewWriter(gz) defer tw.Close() - paths := []string{".env", "compose.yaml", "deploy/caddy/Caddyfile"} + paths := []string{".env", "compose.yaml"} _ = filepath.WalkDir(filepath.Join(root, "secrets"), func(path string, entry os.DirEntry, walkErr error) error { if walkErr == nil && !entry.IsDir() { rel, _ := filepath.Rel(root, path) @@ -522,7 +712,7 @@ func restoreConfiguration(root, archive string) error { return err } clean := filepath.Clean(header.Name) - if filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") || (clean != ".env" && clean != "compose.yaml" && clean != "deploy/caddy/Caddyfile" && !strings.HasPrefix(clean, "secrets/")) { + if filepath.IsAbs(clean) || strings.HasPrefix(clean, "..") || (clean != ".env" && clean != "compose.yaml" && !strings.HasPrefix(clean, "secrets/")) { return fmt.Errorf("unsafe configuration archive entry %q", header.Name) } target := filepath.Join(root, clean) diff --git a/cmd/mailctl/main_test.go b/cmd/mailctl/main_test.go index 3cc0bf0..aa6ea75 100644 --- a/cmd/mailctl/main_test.go +++ b/cmd/mailctl/main_test.go @@ -1,9 +1,52 @@ package main -import "testing" +import ( + "strings" + "testing" +) func TestSignedCompatibilityManifest(t *testing.T) { if err := verifyCompatibility("../../release/compatibility.json", "../../release/compatibility.sig"); err != nil { t.Fatal(err) } } + +func TestCreatedObjectID(t *testing.T) { + raw := []byte(`{"methodResponses":[["x:Certificate/set",{"created":{"certbot":{"id":"cert_123"}}},"certificate"]]}`) + id, err := createdObjectID(raw, "certbot") + if err != nil { + t.Fatal(err) + } + if id != "cert_123" { + t.Fatalf("got %q", id) + } +} + +func TestCreatedObjectIDRejectsNotCreated(t *testing.T) { + raw := []byte(`{"methodResponses":[["x:Certificate/set",{"notCreated":{"certbot":{"type":"invalidProperties"}}},"certificate"]]}`) + _, err := createdObjectID(raw, "certbot") + if err == nil || !strings.Contains(err.Error(), "invalidProperties") { + t.Fatalf("expected Stalwart error, got %v", err) + } +} + +func TestJMAPSucceededRejectsFailedUpdate(t *testing.T) { + raw := []byte(`{"methodResponses":[["x:SystemSettings/set",{"notUpdated":{"singleton":{"type":"forbidden"}}},"settings"]]}`) + if err := jmapSucceeded(raw); err == nil || !strings.Contains(err.Error(), "forbidden") { + t.Fatalf("expected forbidden update, got %v", err) + } +} + +func TestConfigureTLSRejectsRemoteManagementURL(t *testing.T) { + err := configureTLS([]string{"--directory", t.TempDir(), "--url", "http://mail.example.com/api"}) + if err == nil || !strings.Contains(err.Error(), "loopback") { + t.Fatalf("expected loopback URL rejection, got %v", err) + } +} + +func TestConfigureTLSRejectsHTTPSManagementURL(t *testing.T) { + err := configureTLS([]string{"--directory", t.TempDir(), "--url", "https://127.0.0.1:8081/api"}) + if err == nil || !strings.Contains(err.Error(), "loopback HTTP URL") { + t.Fatalf("expected plain loopback HTTP requirement, got %v", err) + } +} diff --git a/compose.yaml b/compose.yaml index 0cd85fc..c8a2ee3 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,25 +1,6 @@ name: meovv-mail services: - caddy: - image: caddy:2.10.2-alpine - restart: unless-stopped - environment: - MAIL_HOSTNAME: ${MAIL_HOSTNAME:?Set MAIL_HOSTNAME in .env} - ports: - - "80:80" - - "443:443" - volumes: - - ./deploy/caddy/Caddyfile:/etc/caddy/Caddyfile:ro - - caddy_data:/data - - caddy_config:/config - networks: [mail] - depends_on: - meovv: - condition: service_healthy - stalwart: - condition: service_started - meovv: build: context: . @@ -32,9 +13,9 @@ services: MEOVV_BOOTSTRAP_TOKEN_FILE: /run/secrets/bootstrap_token MEOVV_INTERNAL_WEBHOOK_SECRET_FILE: /run/secrets/internal_webhook_secret MEOVV_SESSION_KEY_FILE: /run/secrets/session_key - STALWART_URL: https://stalwart:443 + STALWART_URL: http://stalwart:8080 STALWART_BOOTSTRAP_URL: http://stalwart:8080 - STALWART_TLS_INSECURE: "true" + STALWART_TLS_INSECURE: "false" STALWART_RECOVERY_ADMIN: ${STALWART_RECOVERY_ADMIN:-} STALWART_SMTP_ADDRESS: stalwart:587 STALWART_TLS_SERVER_NAME: ${MAIL_HOSTNAME} @@ -43,6 +24,8 @@ services: volumes: - meovv_data:/var/lib/meovv-mail - ./secrets:/run/secrets:ro + ports: + - "${MEOVV_HTTP_BIND:-127.0.0.1:8080}:8080" networks: [mail] depends_on: stalwart: @@ -60,6 +43,7 @@ services: STALWART_PUBLIC_URL: https://${MAIL_HOSTNAME} STALWART_RECOVERY_ADMIN: ${STALWART_RECOVERY_ADMIN:-} ports: + - "${STALWART_HTTP_BIND:-127.0.0.1:8081}:8080" - "25:25" - "465:465" - "587:587" @@ -67,6 +51,7 @@ services: volumes: - stalwart_config:/etc/stalwart - stalwart_data:/var/lib/stalwart + - ./secrets/tls:/etc/stalwart/tls:ro networks: [mail] networks: @@ -74,10 +59,6 @@ networks: driver: bridge volumes: - caddy_data: - name: meovv-mail-caddy-data - caddy_config: - name: meovv-mail-caddy-config meovv_data: name: meovv-mail-app-data stalwart_config: diff --git a/deploy/caddy/Caddyfile b/deploy/caddy/Caddyfile deleted file mode 100644 index cc76ae9..0000000 --- a/deploy/caddy/Caddyfile +++ /dev/null @@ -1,26 +0,0 @@ -{$MAIL_HOSTNAME} { - encode zstd gzip - - @meovv path / /assets/* /favicon.svg /health/* /metrics /api/setup/* /api/session/* /api/mail/* /api/admin/* /api/internal/* /api/v1/* - handle @meovv { - reverse_proxy meovv:8080 - } - - @stalwart path /.well-known/* /jmap /jmap/* /auth/* /api/auth /api/discover/* /api/account /api/token/* /mail/config-v1.1.xml /autodiscover/* - handle @stalwart { - reverse_proxy https://stalwart:443 { - transport http { - tls_insecure_skip_verify - } - } - } - - handle { - reverse_proxy meovv:8080 - } - - header { - Strict-Transport-Security "max-age=31536000; includeSubDomains" - -Server - } -} diff --git a/docs/architecture.md b/docs/architecture.md index 3e287d9..d64ea7c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2,9 +2,19 @@ ## Trust and data boundaries -Public HTTPS reaches Caddy first. Caddy sends product UI, session, administration, health, and REST API routes to the Go service. Standards discovery, OAuth authorization, public JMAP, mail-client configuration, and ACME challenge routes go to Stalwart. Mail protocols reach Stalwart directly on their dedicated TLS-capable ports, so Stalwart obtains its own certificate for SMTP and IMAP while Caddy independently manages the public web certificate. +Public HTTPS reaches host-managed Nginx first. Nginx sends product UI, session, +administration, health, and REST API routes to the loopback MEOVV upstream. +Standards discovery, OAuth authorization, public JMAP, and mail-client +configuration routes go to the loopback Stalwart HTTP upstream. Neither upstream +port is publicly bound. -The branded sign-in form posts the password directly to same-origin `/api/auth`, which Caddy routes to Stalwart. The browser creates a PKCE verifier and sends only the one-time authorization code and verifier to MEOVV. The Go service exchanges that code, encrypts access and refresh tokens with AES-GCM, and returns an opaque Secure, HttpOnly, SameSite cookie. User passwords are never sent to or persisted by MEOVV. +Mail protocols reach Stalwart directly on their dedicated TLS-capable ports. +Certbot remains the single certificate authority client: its deploy hook copies +the hostname certificate into the appliance's protected `secrets/tls` directory. +Stalwart loads that certificate through file-backed `Certificate` fields for +SMTP and IMAP, while Nginx reads the original Certbot lineage for HTTPS. + +The branded sign-in form posts the password directly to same-origin `/api/auth`, which Nginx routes to Stalwart. The browser creates a PKCE verifier and sends only the one-time authorization code and verifier to MEOVV. The Go service exchanges that code, encrypts access and refresh tokens with AES-GCM, and returns an opaque Secure, HttpOnly, SameSite cookie. User passwords are never sent to or persisted by MEOVV. Authenticated browser JMAP calls go through `/api/mail/jmap`; discovery goes through `/api/mail/session`; the event stream uses `/api/mail/events`. The Stalwart adapter is the only Go package that knows these upstream routes, which contains pre-1.0 compatibility changes. diff --git a/docs/operations.md b/docs/operations.md index 71c68b8..2e89f70 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -4,9 +4,17 @@ Direct delivery is the default. Use it only when the host has a stable public IP, outbound TCP 25, correct PTR, and an IP range suitable for email. Relay mode sends through an authenticated TLS smart host and is the supported fallback. Changing mode does not require reinstalling; update the delivery configuration and run diagnostics before switching traffic. +## Edge proxy and certificates + +Nginx and Certbot are operated outside Compose. The required path split, +loopback bindings, initial certificate registration, and renewal hook are in +[`nginx-certbot.md`](nginx-certbot.md). After every Nginx or certificate-policy +change, verify HTTPS plus TLS on ports 465 and 993; success on HTTPS alone does +not prove mail clients receive the renewed certificate. + ## Backups and restore drills -`mailctl backup` stops the two data writers, archives every named volume and the host configuration/secrets, computes checksums, and starts the services again. Copy the resulting directory to storage that is encrypted, access-controlled, and separate from the mail host. +`mailctl backup` stops the two data writers, archives the three appliance volumes and appliance configuration/secrets, computes checksums, and starts the services again. Nginx configuration and the canonical Certbot lineage are external host state and must be covered by the host's backup policy. Copy the resulting directory to storage that is encrypted, access-controlled, and separate from the mail host. Run a restore drill for every release: diff --git a/docs/security.md b/docs/security.md index 066bf2b..a7c5fc0 100644 --- a/docs/security.md +++ b/docs/security.md @@ -11,14 +11,19 @@ - Email HTML is sanitized, remote content is blocked by default, and attachment filenames are reduced to safe basenames. - Webhooks require public HTTPS and reject loopback, private, link-local, unspecified, and multicast resolutions. - External webhooks sign `{timestamp}.{raw_body}` with HMAC-SHA256 and retain event IDs across retries. -- Caddy adds HSTS; the application adds CSP, anti-framing, MIME-sniffing, referrer, and permissions policies. +- The provided Nginx template adds HSTS and response hardening; the application adds CSP, anti-framing, MIME-sniffing, referrer, and permissions policies. - Only 25, 465, 587, and 993 are published for mail. POP3 and plaintext IMAP are absent. ## Deployment invariants Before exposure, confirm that unauthenticated SMTP cannot relay to a third-party domain, sender authorization is enforced on submission, recovery administrator access is removed, and Stalwart's spam/phishing, SPF, DKIM, DMARC, TLS, abuse-ban, and rate-limit defaults remain enabled. -The internal Docker network is not a trust substitute. Stalwart delivery events use a separate shared HMAC secret. The Stalwart management API is not routed publicly by Caddy; administrators use the authenticated Go adapter. +The internal Docker network is not a trust substitute. Stalwart delivery events use a separate shared HMAC secret. The Stalwart management API is not routed publicly by Nginx; administrators use the authenticated Go adapter. Compose binds recovery HTTP to loopback only, and `mailctl configure-tls` rejects non-loopback management URLs before sending the temporary recovery credential. + +The operator must configure Stalwart to trust forwarded HTTP headers only from +the exact Docker bridge used by the host Nginx connection. Never trust arbitrary +public networks, and never publish the Stalwart HTTP binding on a non-loopback +host address. ## Audit and response diff --git a/internal/stalwart/client.go b/internal/stalwart/client.go index 84934c1..0765a48 100644 --- a/internal/stalwart/client.go +++ b/internal/stalwart/client.go @@ -20,7 +20,7 @@ type Client struct { func New(base string, insecure bool) *Client { transport := http.DefaultTransport.(*http.Transport).Clone() - transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecure} // Internal Docker TLS; public TLS terminates at Caddy. + transport.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: insecure} // #nosec G402 -- explicitly controlled for deployments that re-encrypt to a private Stalwart endpoint. return &Client{BaseURL: strings.TrimRight(base, "/"), HTTP: &http.Client{Timeout: 15 * time.Second, Transport: transport}} } @@ -32,7 +32,7 @@ func (c *Client) Bootstrap(ctx context.Context, bootstrapURL, recoveryAdmin, hos payload := map[string]any{ "using": []string{"urn:ietf:params:jmap:core", "urn:stalwart:jmap"}, "methodCalls": []any{[]any{"x:Bootstrap/set", map[string]any{"update": map[string]any{"singleton": map[string]any{ - "serverHostname": hostname, "defaultDomain": domain, "requestTlsCertificate": true, "generateDkimKeys": true, + "serverHostname": hostname, "defaultDomain": domain, "requestTlsCertificate": false, "generateDkimKeys": true, "dataStore": map[string]any{"@type": "RocksDb", "path": "/var/lib/stalwart/"}, "blobStore": map[string]any{"@type": "Default"}, "searchStore": map[string]any{"@type": "Default"}, "inMemoryStore": map[string]any{"@type": "Default"}, "directory": map[string]any{"@type": "Internal"}, "tracer": map[string]any{"@type": "Console"}, "dnsServer": map[string]any{"@type": "Manual"}, diff --git a/tests/rendered-html.test.mjs b/tests/rendered-html.test.mjs index cf24a81..2ac0e36 100644 --- a/tests/rendered-html.test.mjs +++ b/tests/rendered-html.test.mjs @@ -14,11 +14,13 @@ test("builds the standalone MEOVV application shell", async () => { }); test("includes production auth, JMAP, sanitization, and responsive UI paths", async () => { - const [page, css, openapi, standalone] = await Promise.all([ + const [page, css, openapi, standalone, compose, nginx] = await Promise.all([ readFile(new URL("../app/page.tsx", import.meta.url), "utf8"), readFile(new URL("../app/globals.css", import.meta.url), "utf8"), readFile(new URL("../api/openapi.yaml", import.meta.url), "utf8"), readFile(new URL("../web-dist/index.html", import.meta.url), "utf8"), + readFile(new URL("../compose.yaml", import.meta.url), "utf8"), + readFile(new URL("../deploy/nginx/meovv-mail.conf.example", import.meta.url), "utf8"), ]); assert.match(page, /crypto\.subtle\.digest\("SHA-256"/); assert.match(page, /fetch\("\/api\/auth"/); @@ -33,4 +35,8 @@ test("includes production auth, JMAP, sanitization, and responsive UI paths", as assert.match(openapi, /Idempotency-Key/); assert.match(standalone, /
<\/div>/); await access(new URL("../web-dist/assets", import.meta.url)); + assert.match(compose, /127\.0\.0\.1:8080/); + assert.match(compose, /127\.0\.0\.1:8081/); + assert.match(nginx, /proxy_pass http:\/\/127\.0\.0\.1:8080/); + assert.match(nginx, /proxy_pass http:\/\/127\.0\.0\.1:8081/); });