Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions scripts/verify-email-data-recovery/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@ import (

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

var (
errSessionJSON = errors.New("session-json")
errSessionAccount = errors.New("session-account")
)

func forwardPort(line string) (string, bool) {
match := forwardAddressPattern.FindStringSubmatch(line)
if len(match) != 2 {
Expand All @@ -27,13 +32,13 @@ func forwardPort(line string) (string, bool) {
func sessionAccount(data []byte, expected string) (string, error) {
var session object
if json.Unmarshal(data, &session) != nil {
return "", errors.New("session-json")
return "", errSessionJSON
}
account := text(child(session, "primaryAccounts"), "urn:ietf:params:jmap:mail")
accounts := child(session, "accounts")
entry, ok := accounts[account].(map[string]any)
if !mailboxIDPattern.MatchString(account) || (expected != "" && expected != account) || !ok || (entry["isReadOnly"] != nil && entry["isReadOnly"] != false) {
return "", errors.New("session-account")
return "", errSessionAccount
}
return account, nil
}
Expand All @@ -50,6 +55,35 @@ func (c *mailboxClient) session(ctx context.Context) error {
return nil
}

// Report an allow-listed transport or session result. Response bodies,
// redirects and mailbox identities never enter the workflow receipt.
func sourceSessionFailure(err error) string {
switch {
case errors.Is(err, errMailboxTransport):
return "source-session-transport"
case errors.Is(err, errMailboxResponse):
return "source-session-response"
case errors.Is(err, errSessionJSON):
return "source-session-json"
case errors.Is(err, errSessionAccount):
return "source-session-account"
}
var status mailboxHTTPStatus
if errors.As(err, &status) {
switch status {
case http.StatusUnauthorized:
return "source-session-unauthorized"
case http.StatusForbidden:
return "source-session-forbidden"
case http.StatusNotFound:
return "source-session-not-found"
default:
return "source-session-http"
}
}
return "source-session"
}

// A connection before the reader starts listening can close kubectl's entire
// forwarding stream. Reopen it through the same identity check on transport
// failure. An HTTP response means the tunnel can still carry the next probe.
Expand Down
30 changes: 30 additions & 0 deletions scripts/verify-email-data-recovery/forward_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,33 @@ func TestMailboxSessionMustPreserveTheOriginalAccount(t *testing.T) {
}
}
}

func TestSourceSessionFailureReportsOnlyTheApprovedCategory(t *testing.T) {
for _, tc := range []struct {
status int
body string
want string
}{
{http.StatusUnauthorized, "private provider error", "source-session-unauthorized"},
{http.StatusForbidden, "private provider error", "source-session-forbidden"},
{http.StatusNotFound, "private provider error", "source-session-not-found"},
{http.StatusTemporaryRedirect, "private provider error", "source-session-http"},
{http.StatusOK, "private provider error", "source-session-json"},
{http.StatusOK, `{"accounts":{}}`, "source-session-account"},
} {
t.Run(tc.want, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(tc.status)
_, _ = w.Write([]byte(tc.body))
}))
defer server.Close()
client, err := newMailboxClient(server.URL, "fixture-only")
if err != nil {
t.Fatal(err)
}
if got := sourceSessionFailure(client.session(t.Context())); got != tc.want {
t.Fatalf("unexpected session failure category: %q", got)
}
})
}
}
44 changes: 25 additions & 19 deletions scripts/verify-email-data-recovery/mailbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,15 @@ const companyMailbox = "ned@devantler.tech"

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

var (
errMailboxTransport = errors.New("mailbox-transport")
errMailboxResponse = errors.New("mailbox-response")
)

type mailboxHTTPStatus int

func (mailboxHTTPStatus) Error() string { return "mailbox-http" }

type mailboxClient struct {
account, endpoint, password string
http *http.Client
Expand Down Expand Up @@ -47,23 +56,23 @@ func (c *mailboxClient) request(ctx context.Context, method, path, contentType s
}
response, err := c.http.Do(req)
if err != nil {
return nil, errors.New("mailbox-transport")
return nil, errMailboxTransport
}
defer func() { _ = response.Body.Close() }()
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated {
return nil, errors.New("mailbox-http")
return nil, mailboxHTTPStatus(response.StatusCode)
}
data, err := io.ReadAll(io.LimitReader(response.Body, (4<<20)+1))
if err != nil || len(data) > 4<<20 {
return nil, errors.New("mailbox-response")
return nil, errMailboxResponse
}
return data, nil
}

// mailboxMethods names the JMAP capability of each permitted method. Census
// reads that can initialize defaults require an unchanged collection state.
var mailboxMethods = map[string]string{
"Email/get": jmapMail, "Email/query": jmapMail, "Email/import": jmapMail, "Email/set": jmapMail,
"Email/get": jmapMail, "Email/query": jmapMail, "Email/set": jmapMail,
"Mailbox/get": jmapMail, "Mailbox/set": jmapMail, "Mailbox/query": jmapMail,
"Calendar/get": "urn:ietf:params:jmap:calendars", "CalendarEvent/query": "urn:ietf:params:jmap:calendars", "CalendarEvent/get": "urn:ietf:params:jmap:calendars",
"Calendar/changes": "urn:ietf:params:jmap:calendars",
Expand Down Expand Up @@ -141,29 +150,26 @@ func (c *mailboxClient) createMarker(ctx context.Context, nonce string) (*mailbo
marker.uncertain = true
return marker, errors.New("marker-mailbox")
}
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"
data, err := c.request(ctx, http.MethodPost, "/jmap/upload/"+c.account+"/", "message/rfc822", []byte(message))
if err != nil {
return marker, err
}
var upload object
if json.Unmarshal(data, &upload) != nil || text(upload, "accountId") != c.account || !mailboxIDPattern.MatchString(text(upload, "blobId")) {
return marker, errors.New("marker-upload")
}
marker.identity.blob = text(upload, "blobId")
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}}}})
// The production listener refuses blob uploads. A text-only draft stays
// inside the diagnostic mailbox and does not need upload or submission.
const partID = "verification"
created, err = c.call(ctx, "Email/set", object{"create": object{"proof": object{
"mailboxIds": object{marker.identity.mailbox: true}, "keywords": object{"$draft": true, "$seen": true},
"from": []any{object{"email": companyMailbox}}, "subject": "Email recovery verification",
"header:Message-ID:asMessageIds": []any{marker.identity.messageID},
"textBody": []any{object{"partId": partID, "type": "text/plain"}},
"bodyValues": object{partID: object{"value": marker.identity.body}},
}}})
if err != nil {
marker.uncertain = true
return marker, err
}
createdEmail := child(child(imported, "created"), "proof")
createdEmail := child(child(created, "created"), "proof")
marker.identity.email = text(createdEmail, "id")
// Import may normalize or relink an uploaded blob. Its returned Email
// identity, rather than the temporary upload identity, binds later reads.
marker.identity.blob = text(createdEmail, "blobId")
if !mailboxIDPattern.MatchString(marker.identity.email) || !mailboxIDPattern.MatchString(marker.identity.blob) {
marker.uncertain = true
return marker, errors.New("marker-import")
return marker, errors.New("marker-create")
}
if _, err = c.verifyMessage(ctx, marker.identity); err != nil {
return marker, err
Expand Down
39 changes: 22 additions & 17 deletions scripts/verify-email-data-recovery/mailbox_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,10 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
const nonce = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
for _, foreign := range []bool{false, true} {
t.Run(map[bool]string{false: "owned", true: "foreign-message"}[foreign], func(t *testing.T) {
imported, mailDeleted, boxDeleted := false, false, false
markerCreated, mailDeleted, boxDeleted := false, false, false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/jmap/upload/company-account/" {
data, _ := io.ReadAll(r.Body)
if !strings.Contains(string(data), "Message-ID: <email-recovery-"+nonce+"@example.invalid>") {
t.Error("uploaded message lost its unique identity")
}
_, _ = io.WriteString(w, `{"accountId":"company-account","blobId":"upload-blob"}`)
if r.URL.Path != "/jmap" {
http.Error(w, "forbidden route", http.StatusForbidden)
return
}
var envelope object
Expand Down Expand Up @@ -137,18 +133,11 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
boxDeleted = true
result["destroyed"] = []any{"owned-box"}
}
case "Email/import":
imported = true
email := child(child(args, "emails"), "proof")
if text(email, "blobId") != "upload-blob" || child(email, "mailboxIds")["owned-box"] != true {
t.Error("import escaped its own mailbox")
}
result["created"] = object{"proof": object{"id": "owned-email", "blobId": "owned-blob"}}
case "Email/get":
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}}}}
case "Email/query":
ids := []any{}
if imported && !mailDeleted {
if markerCreated && !mailDeleted {
ids = append(ids, "owned-email")
}
if foreign {
Expand All @@ -157,6 +146,22 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
result["ids"] = ids
result["total"] = len(ids)
case "Email/set":
if args["create"] != nil {
email := child(child(args, "create"), "proof")
ids, _ := email["header:Message-ID:asMessageIds"].([]any)
mailboxes := child(email, "mailboxIds")
body := items(email, "textBody")
if len(mailboxes) != 1 || mailboxes["owned-box"] != true ||
child(email, "keywords")["$draft"] != true || email["to"] != nil ||
len(ids) != 1 || ids[0] != "email-recovery-"+nonce+"@example.invalid" ||
len(body) != 1 || text(body[0], "type") != "text/plain" ||
text(child(child(email, "bodyValues"), text(body[0], "partId")), "value") != "Email recovery verification "+nonce {
t.Error("recovery draft lost its identity, body or isolated mailbox")
}
markerCreated = true
result["created"] = object{"proof": object{"id": "owned-email", "blobId": "owned-blob"}}
break
}
ids, _ := args["destroy"].([]any)
if len(ids) != 1 || ids[0] != "owned-email" || args["ifInState"] != "s1" {
t.Error("message cleanup lost its identity/state fence")
Expand All @@ -174,8 +179,8 @@ func TestRecoveryMarkerCleanupCannotDeleteOtherMessages(t *testing.T) {
client, _ := newMailboxClient(server.URL, "fixture-only")
client.account = "company-account"
marker, err := client.createMarker(context.Background(), nonce)
if err != nil || !imported {
t.Fatal("own recovery marker was not imported")
if err != nil || !markerCreated {
t.Fatal("own recovery marker was not created while uploads were blocked")
}
err = client.cleanupMarker(context.Background(), marker)
if foreign {
Expand Down
4 changes: 2 additions & 2 deletions scripts/verify-email-data-recovery/native_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func TestNativeRecoveryMarkerLifecycle(t *testing.T) {
if marker != nil && marker.identity.email != "" {
logNativeMessageShape(ctx, t, client, marker.identity)
}
t.Fatalf("native marker import: %s", err)
t.Fatalf("native marker creation: %s", err)
}
window.before = time.Now().UTC().Truncate(time.Second).Add(time.Second)
if _, err = client.verifyMessage(ctx, marker.identity); err != nil {
Expand Down Expand Up @@ -105,7 +105,7 @@ func TestNativeRecoveryMarkerLifecycle(t *testing.T) {
if err = client.cleanupMarker(ctx, marker); err != nil {
t.Fatalf("native marker cleanup: %s", err)
}
t.Log("EMAIL_RECOVERY_NATIVE_MARKER=PASS import=VERIFIED read=VERIFIED cleanup=VERIFIED")
t.Log("EMAIL_RECOVERY_NATIVE_MARKER=PASS draft=VERIFIED read=VERIFIED cleanup=VERIFIED")
}

// Failure diagnostics reveal only comparisons and types from synthetic data.
Expand Down
1 change: 1 addition & 0 deletions scripts/verify-email-data-recovery/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ func (d *recoveryDriver) openSource(ctx context.Context) (*mailboxClient, func()
}
if err != nil {
stopSource()
d.stage = sourceSessionFailure(err)
return nil, nil, err
}
return original, stopSource, nil
Expand Down
Loading