Skip to content

Commit 428e911

Browse files
committed
fix(email): verify recovery with an unsent JMAP draft
1 parent d310e03 commit 428e911

6 files changed

Lines changed: 116 additions & 40 deletions

File tree

‎scripts/verify-email-data-recovery/forward.go‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ import (
1616

1717
var forwardAddressPattern = regexp.MustCompile(`^Forwarding from 127\.0\.0\.1:([0-9]{1,5}) -> 8080$`)
1818

19+
var (
20+
errSessionJSON = errors.New("session-json")
21+
errSessionAccount = errors.New("session-account")
22+
)
23+
1924
func forwardPort(line string) (string, bool) {
2025
match := forwardAddressPattern.FindStringSubmatch(line)
2126
if len(match) != 2 {
@@ -27,13 +32,13 @@ func forwardPort(line string) (string, bool) {
2732
func sessionAccount(data []byte, expected string) (string, error) {
2833
var session object
2934
if json.Unmarshal(data, &session) != nil {
30-
return "", errors.New("session-json")
35+
return "", errSessionJSON
3136
}
3237
account := text(child(session, "primaryAccounts"), "urn:ietf:params:jmap:mail")
3338
accounts := child(session, "accounts")
3439
entry, ok := accounts[account].(map[string]any)
3540
if !mailboxIDPattern.MatchString(account) || (expected != "" && expected != account) || !ok || (entry["isReadOnly"] != nil && entry["isReadOnly"] != false) {
36-
return "", errors.New("session-account")
41+
return "", errSessionAccount
3742
}
3843
return account, nil
3944
}
@@ -50,6 +55,35 @@ func (c *mailboxClient) session(ctx context.Context) error {
5055
return nil
5156
}
5257

58+
// Report an allow-listed transport or session result. Response bodies,
59+
// redirects and mailbox identities never enter the workflow receipt.
60+
func sourceSessionFailure(err error) string {
61+
switch {
62+
case errors.Is(err, errMailboxTransport):
63+
return "source-session-transport"
64+
case errors.Is(err, errMailboxResponse):
65+
return "source-session-response"
66+
case errors.Is(err, errSessionJSON):
67+
return "source-session-json"
68+
case errors.Is(err, errSessionAccount):
69+
return "source-session-account"
70+
}
71+
var status mailboxHTTPStatus
72+
if errors.As(err, &status) {
73+
switch status {
74+
case http.StatusUnauthorized:
75+
return "source-session-unauthorized"
76+
case http.StatusForbidden:
77+
return "source-session-forbidden"
78+
case http.StatusNotFound:
79+
return "source-session-not-found"
80+
default:
81+
return "source-session-http"
82+
}
83+
}
84+
return "source-session"
85+
}
86+
5387
// A connection before the reader starts listening can close kubectl's entire
5488
// forwarding stream. Reopen it through the same identity check on transport
5589
// failure. An HTTP response means the tunnel can still carry the next probe.

‎scripts/verify-email-data-recovery/forward_test.go‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,3 +62,33 @@ func TestMailboxSessionMustPreserveTheOriginalAccount(t *testing.T) {
6262
}
6363
}
6464
}
65+
66+
func TestSourceSessionFailureReportsOnlyTheApprovedCategory(t *testing.T) {
67+
for _, tc := range []struct {
68+
status int
69+
body string
70+
want string
71+
}{
72+
{http.StatusUnauthorized, "private provider error", "source-session-unauthorized"},
73+
{http.StatusForbidden, "private provider error", "source-session-forbidden"},
74+
{http.StatusNotFound, "private provider error", "source-session-not-found"},
75+
{http.StatusTemporaryRedirect, "private provider error", "source-session-http"},
76+
{http.StatusOK, "private provider error", "source-session-json"},
77+
{http.StatusOK, `{"accounts":{}}`, "source-session-account"},
78+
} {
79+
t.Run(tc.want, func(t *testing.T) {
80+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
81+
w.WriteHeader(tc.status)
82+
_, _ = w.Write([]byte(tc.body))
83+
}))
84+
defer server.Close()
85+
client, err := newMailboxClient(server.URL, "fixture-only")
86+
if err != nil {
87+
t.Fatal(err)
88+
}
89+
if got := sourceSessionFailure(client.session(t.Context())); got != tc.want {
90+
t.Fatalf("unexpected session failure category: %q", got)
91+
}
92+
})
93+
}
94+
}

‎scripts/verify-email-data-recovery/mailbox.go‎

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,15 @@ const companyMailbox = "ned@devantler.tech"
1818

1919
var mailboxIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,512}$`)
2020

21+
var (
22+
errMailboxTransport = errors.New("mailbox-transport")
23+
errMailboxResponse = errors.New("mailbox-response")
24+
)
25+
26+
type mailboxHTTPStatus int
27+
28+
func (mailboxHTTPStatus) Error() string { return "mailbox-http" }
29+
2130
type mailboxClient struct {
2231
account, endpoint, password string
2332
http *http.Client
@@ -47,23 +56,23 @@ func (c *mailboxClient) request(ctx context.Context, method, path, contentType s
4756
}
4857
response, err := c.http.Do(req)
4958
if err != nil {
50-
return nil, errors.New("mailbox-transport")
59+
return nil, errMailboxTransport
5160
}
5261
defer func() { _ = response.Body.Close() }()
5362
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated {
54-
return nil, errors.New("mailbox-http")
63+
return nil, mailboxHTTPStatus(response.StatusCode)
5564
}
5665
data, err := io.ReadAll(io.LimitReader(response.Body, (4<<20)+1))
5766
if err != nil || len(data) > 4<<20 {
58-
return nil, errors.New("mailbox-response")
67+
return nil, errMailboxResponse
5968
}
6069
return data, nil
6170
}
6271

6372
// mailboxMethods names the JMAP capability of each permitted method. Census
6473
// reads that can initialize defaults require an unchanged collection state.
6574
var mailboxMethods = map[string]string{
66-
"Email/get": jmapMail, "Email/query": jmapMail, "Email/import": jmapMail, "Email/set": jmapMail,
75+
"Email/get": jmapMail, "Email/query": jmapMail, "Email/set": jmapMail,
6776
"Mailbox/get": jmapMail, "Mailbox/set": jmapMail, "Mailbox/query": jmapMail,
6877
"Calendar/get": "urn:ietf:params:jmap:calendars", "CalendarEvent/query": "urn:ietf:params:jmap:calendars", "CalendarEvent/get": "urn:ietf:params:jmap:calendars",
6978
"Calendar/changes": "urn:ietf:params:jmap:calendars",
@@ -141,29 +150,26 @@ func (c *mailboxClient) createMarker(ctx context.Context, nonce string) (*mailbo
141150
marker.uncertain = true
142151
return marker, errors.New("marker-mailbox")
143152
}
144-
message := "From: Email recovery diagnostic <email-recovery@example.invalid>\r\nTo: email-recovery@example.invalid\r\nSubject: Email recovery verification\r\nMessage-ID: <" + marker.identity.messageID + ">\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n" + marker.identity.body + "\r\n"
145-
data, err := c.request(ctx, http.MethodPost, "/jmap/upload/"+c.account+"/", "message/rfc822", []byte(message))
146-
if err != nil {
147-
return marker, err
148-
}
149-
var upload object
150-
if json.Unmarshal(data, &upload) != nil || text(upload, "accountId") != c.account || !mailboxIDPattern.MatchString(text(upload, "blobId")) {
151-
return marker, errors.New("marker-upload")
152-
}
153-
marker.identity.blob = text(upload, "blobId")
154-
imported, err := c.call(ctx, "Email/import", object{"emails": object{"proof": object{"blobId": marker.identity.blob, "mailboxIds": object{marker.identity.mailbox: true}, "keywords": object{"$seen": true}}}})
153+
// The production listener refuses blob uploads. A text-only draft stays
154+
// inside the diagnostic mailbox and does not need upload or submission.
155+
const partID = "verification"
156+
created, err = c.call(ctx, "Email/set", object{"create": object{"proof": object{
157+
"mailboxIds": object{marker.identity.mailbox: true}, "keywords": object{"$draft": true, "$seen": true},
158+
"from": []any{object{"email": companyMailbox}}, "subject": "Email recovery verification",
159+
"header:Message-ID:asMessageIds": []any{marker.identity.messageID},
160+
"textBody": []any{object{"partId": partID, "type": "text/plain"}},
161+
"bodyValues": object{partID: object{"value": marker.identity.body}},
162+
}}})
155163
if err != nil {
156164
marker.uncertain = true
157165
return marker, err
158166
}
159-
createdEmail := child(child(imported, "created"), "proof")
167+
createdEmail := child(child(created, "created"), "proof")
160168
marker.identity.email = text(createdEmail, "id")
161-
// Import may normalize or relink an uploaded blob. Its returned Email
162-
// identity, rather than the temporary upload identity, binds later reads.
163169
marker.identity.blob = text(createdEmail, "blobId")
164170
if !mailboxIDPattern.MatchString(marker.identity.email) || !mailboxIDPattern.MatchString(marker.identity.blob) {
165171
marker.uncertain = true
166-
return marker, errors.New("marker-import")
172+
return marker, errors.New("marker-create")
167173
}
168174
if _, err = c.verifyMessage(ctx, marker.identity); err != nil {
169175
return marker, err

‎scripts/verify-email-data-recovery/mailbox_test.go‎

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -100,14 +100,10 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
100100
const nonce = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
101101
for _, foreign := range []bool{false, true} {
102102
t.Run(map[bool]string{false: "owned", true: "foreign-message"}[foreign], func(t *testing.T) {
103-
imported, mailDeleted, boxDeleted := false, false, false
103+
markerCreated, mailDeleted, boxDeleted := false, false, false
104104
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
105-
if r.URL.Path == "/jmap/upload/company-account/" {
106-
data, _ := io.ReadAll(r.Body)
107-
if !strings.Contains(string(data), "Message-ID: <email-recovery-"+nonce+"@example.invalid>") {
108-
t.Error("uploaded message lost its unique identity")
109-
}
110-
_, _ = io.WriteString(w, `{"accountId":"company-account","blobId":"upload-blob"}`)
105+
if r.URL.Path != "/jmap" {
106+
http.Error(w, "forbidden route", http.StatusForbidden)
111107
return
112108
}
113109
var envelope object
@@ -137,18 +133,11 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
137133
boxDeleted = true
138134
result["destroyed"] = []any{"owned-box"}
139135
}
140-
case "Email/import":
141-
imported = true
142-
email := child(child(args, "emails"), "proof")
143-
if text(email, "blobId") != "upload-blob" || child(email, "mailboxIds")["owned-box"] != true {
144-
t.Error("import escaped its own mailbox")
145-
}
146-
result["created"] = object{"proof": object{"id": "owned-email", "blobId": "owned-blob"}}
147136
case "Email/get":
148137
result["list"] = []any{object{"id": "owned-email", "blobId": "owned-blob", "messageId": []any{"email-recovery-" + nonce + "@example.invalid"}, "mailboxIds": object{"owned-box": true}, "textBody": []any{object{"partId": "1"}}, "bodyValues": object{"1": object{"value": "Email recovery verification " + nonce + "\r\n", "isTruncated": false}}}}
149138
case "Email/query":
150139
ids := []any{}
151-
if imported && !mailDeleted {
140+
if markerCreated && !mailDeleted {
152141
ids = append(ids, "owned-email")
153142
}
154143
if foreign {
@@ -157,6 +146,22 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
157146
result["ids"] = ids
158147
result["total"] = len(ids)
159148
case "Email/set":
149+
if args["create"] != nil {
150+
email := child(child(args, "create"), "proof")
151+
ids, _ := email["header:Message-ID:asMessageIds"].([]any)
152+
mailboxes := child(email, "mailboxIds")
153+
body := items(email, "textBody")
154+
if len(mailboxes) != 1 || mailboxes["owned-box"] != true ||
155+
child(email, "keywords")["$draft"] != true || email["to"] != nil ||
156+
len(ids) != 1 || ids[0] != "email-recovery-"+nonce+"@example.invalid" ||
157+
len(body) != 1 || text(body[0], "type") != "text/plain" ||
158+
text(child(child(email, "bodyValues"), text(body[0], "partId")), "value") != "Email recovery verification "+nonce {
159+
t.Error("recovery draft lost its identity, body or isolated mailbox")
160+
}
161+
markerCreated = true
162+
result["created"] = object{"proof": object{"id": "owned-email", "blobId": "owned-blob"}}
163+
break
164+
}
160165
ids, _ := args["destroy"].([]any)
161166
if len(ids) != 1 || ids[0] != "owned-email" || args["ifInState"] != "s1" {
162167
t.Error("message cleanup lost its identity/state fence")
@@ -174,8 +179,8 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
174179
client, _ := newMailboxClient(server.URL, "fixture-only")
175180
client.account = "company-account"
176181
marker, err := client.createMarker(context.Background(), nonce)
177-
if err != nil || !imported {
178-
t.Fatal("own recovery marker was not imported")
182+
if err != nil || !markerCreated {
183+
t.Fatal("own recovery marker was not created while uploads were blocked")
179184
}
180185
err = client.cleanupMarker(context.Background(), marker)
181186
if foreign {

‎scripts/verify-email-data-recovery/native_test.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ func TestNativeRecoveryMarkerLifecycle(t *testing.T) {
7070
if marker != nil && marker.identity.email != "" {
7171
logNativeMessageShape(ctx, t, client, marker.identity)
7272
}
73-
t.Fatalf("native marker import: %s", err)
73+
t.Fatalf("native marker creation: %s", err)
7474
}
7575
window.before = time.Now().UTC().Truncate(time.Second).Add(time.Second)
7676
if _, err = client.verifyMessage(ctx, marker.identity); err != nil {
@@ -105,7 +105,7 @@ func TestNativeRecoveryMarkerLifecycle(t *testing.T) {
105105
if err = client.cleanupMarker(ctx, marker); err != nil {
106106
t.Fatalf("native marker cleanup: %s", err)
107107
}
108-
t.Log("EMAIL_RECOVERY_NATIVE_MARKER=PASS import=VERIFIED read=VERIFIED cleanup=VERIFIED")
108+
t.Log("EMAIL_RECOVERY_NATIVE_MARKER=PASS draft=VERIFIED read=VERIFIED cleanup=VERIFIED")
109109
}
110110

111111
// Failure diagnostics reveal only comparisons and types from synthetic data.

‎scripts/verify-email-data-recovery/run.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ func (d *recoveryDriver) openSource(ctx context.Context) (*mailboxClient, func()
130130
}
131131
if err != nil {
132132
stopSource()
133+
d.stage = sourceSessionFailure(err)
133134
return nil, nil, err
134135
}
135136
return original, stopSource, nil

0 commit comments

Comments
 (0)