Files
stalwart-migrator/internal/stalwartapi/mailbox.go
T
jcoffey-dev 4568f9abbf Capture the pre-migration snapshot from 0.15.x, and stop claiming counts match when none were compared
Found by running preflight against a real Stalwart 0.15.5 in a VM. Two
defects, the second worse than the first.

1. AccountSnapshot could not read the version this tool migrates FROM.
   0.15.5 advertises no urn:stalwart:jmap capability and POST /api returns
   404 - the JMAP management API and x:Account are 0.16 features. 0.15.x
   exposes a REST API at GET /api/principal instead. So preflight's
   account-snapshot check warned and moved on, and every run against a real
   source instance had no "before" data at all.

   AccountSnapshot now dispatches on the capability the session document
   advertises - a positive signal, not an inference from a failed call -
   and internal/stalwartapi/principal.go implements the 0.15.x REST path,
   including its 1-based page/limit pagination so an install larger than
   one page isn't silently truncated.

2. With no "before" counts, the content-integrity comparison iterated an
   empty map, checked nothing, and reported "all message counts match".
   That is the strongest claim this tool makes - ARCHITECTURE 4.7 calls it
   the actual no-data-loss guarantee - made vacuously, and it would have
   passed on a migration that lost every message.

   The comparison now derives its account set from whatever the source
   could report, verifies every account and domain survived either way, and
   carries MessageCountsCompared so the report says plainly "MESSAGE COUNTS
   NOT COMPARED ... no-data-loss is NOT verified here" rather than implying
   otherwise.

What can and cannot be checked across the 0.15/0.16 boundary, now that a
real server has answered: 0.15.x has no per-mailbox message count at any
endpoint, and the impersonation login 0.16 offers returns 401 there, so
before/after message counts are impossible for the boundary migration this
tool exists for. Both versions do report per-account used quota (usedQuota
in 0.15's REST list, usedDiskQuota on 0.16's x:Account), so that is
captured on both sides. It is recorded and reported, not asserted on:
4.5 notes the 0.16 migration resets quotas to zero pending recalculation,
so comparing those bytes across the boundary would be a false alarm
generator.

Test servers across preflight, validate and stalwartapi now advertise
urn:stalwart:jmap, since they stand in for 0.16 instances and that
capability is what says so.

Verified end to end against the smoke VM: all nine preflight checks pass,
and the checkpoint records 2 accounts, 1 domain and per-account used quota
where it previously recorded nothing.
2026-08-23 18:51:19 -07:00

120 lines
4.8 KiB
Go

// SPDX-FileCopyrightText: 2026 LINUXexpert-org
// SPDX-License-Identifier: GPL-3.0-or-later
package stalwartapi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
)
// jmapSession is the subset of RFC 8620 §2's Session object this package
// needs: apiUrl (where to POST standard JMAP method calls - a different
// endpoint from Stalwart's /api management API, confirmed in
// docs/ref/object/account.md) and primaryAccounts (which accountId the
// urn:ietf:params:jmap:mail capability maps to for the authenticated
// identity).
type jmapSession struct {
APIURL string `json:"apiUrl"`
PrimaryAccounts map[string]string `json:"primaryAccounts"`
// Capabilities is what the instance says it supports. Its contents
// decide which management API this client speaks - see
// stalwartManagementCapability.
Capabilities map[string]json.RawMessage `json:"capabilities"`
}
const jmapMailCapability = "urn:ietf:params:jmap:mail"
// fetchSession performs JMAP session discovery (RFC 8620 §2,
// /.well-known/jmap) with the given credentials.
func (c *Client) fetchSession(ctx context.Context, username, password string) (*jmapSession, error) {
url := strings.TrimRight(c.BaseURL, "/") + "/.well-known/jmap"
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(username, password)
resp, err := c.httpClient().Do(req)
if err != nil {
return nil, fmt.Errorf("session discovery at %s: %w", url, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("session discovery at %s returned %s", url, resp.Status)
}
var session jmapSession
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil {
return nil, fmt.Errorf("parse session document from %s: %w", url, err)
}
if session.APIURL == "" {
return nil, fmt.Errorf("session document from %s has no apiUrl", url)
}
return &session, nil
}
type mailboxGetEntry struct {
Name string `json:"name"`
TotalEmails int `json:"totalEmails"`
}
// MailboxSnapshot captures every mailbox's message count for one account,
// authenticating as that account via Stalwart's documented impersonation
// mechanism rather than assuming this Client's own credentials get direct
// cross-account access. That assumption would be wrong: Stalwart's JMAP
// session `accounts`/`primaryAccounts` map is built only from the
// authenticated identity's own membership and sharing grants - it is NOT
// expanded for a superuser (confirmed against
// crates/jmap/src/api/session.rs), so a plain Mailbox/get call for an
// arbitrary accountId under this Client's own login would be rejected.
//
// Instead, this Client's Username must hold Stalwart's `impersonate`
// permission (see docs/auth/authorization/administrator.md), and this
// method logs in AS the target account using the documented composite
// login format "<target>%<impersonator>" with the impersonator's password,
// then calls standard RFC 8621 Mailbox/get - reading the exact wire
// property name `totalEmails` - against the URL that account's own JMAP
// session document reports as apiUrl (not the /api management endpoint
// x:Account/* uses; confirmed as a distinct endpoint in
// docs/ref/object/account.md).
func (c *Client) MailboxSnapshot(ctx context.Context, targetEmail string) ([]MailboxCount, error) {
impersonatedUser := fmt.Sprintf("%s%%%s", targetEmail, c.Username)
session, err := c.fetchSession(ctx, impersonatedUser, c.Password)
if err != nil {
return nil, fmt.Errorf("stalwartapi: impersonate %s: %w", targetEmail, err)
}
accountID, ok := session.PrimaryAccounts[jmapMailCapability]
if !ok || accountID == "" {
return nil, fmt.Errorf("stalwartapi: impersonated session for %s has no %s account", targetEmail, jmapMailCapability)
}
responses, err := c.callAs(ctx, impersonatedUser, c.Password, session.APIURL,
[]string{"urn:ietf:params:jmap:core", jmapMailCapability},
[]any{[]any{"Mailbox/get", map[string]any{"accountId": accountID, "properties": []string{"name", "totalEmails"}}, "m"}},
)
if err != nil {
return nil, fmt.Errorf("stalwartapi: Mailbox/get for %s: %w", targetEmail, err)
}
if len(responses) == 0 {
return nil, fmt.Errorf("stalwartapi: Mailbox/get for %s returned no method responses", targetEmail)
}
if responses[0].Name == "error" {
return nil, fmt.Errorf("stalwartapi: Mailbox/get for %s error: %s", targetEmail, responses[0].Args)
}
var result struct {
List []mailboxGetEntry `json:"list"`
}
if err := json.Unmarshal(responses[0].Args, &result); err != nil {
return nil, fmt.Errorf("stalwartapi: parse Mailbox/get response for %s: %w", targetEmail, err)
}
counts := make([]MailboxCount, len(result.List))
for i, m := range result.List {
counts[i] = MailboxCount{Mailbox: m.Name, Messages: m.TotalEmails}
}
return counts, nil
}