1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main

// The editor's API.
//
// Two properties are worth a test rather than an inspection. The block routes
// answer with the whole list after anything that can reorder, which is what
// lets the editor never compute a position; and a draft that has been sent is
// read-only on the server, not merely in the browser, because it is the record
// of what went out.

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"strconv"
	"testing"
)

// makeDraft stores a draft with the given blocks and returns it.
func makeDraft(t *testing.T, s *server, blocks ...draftBlock) *draft {
	t.Helper()
	d := &draft{
		Subject: "Re: the thing",
		Blocks:  blocks,
		Recipients: map[string]recipientSet{
			setSender: {Name: setSender, To: []Recipient{testRecipient(t, "klara@example.org")}},
		},
	}
	if err := createDraft(s.db.Write, d); err != nil {
		t.Fatalf("create draft: %v", err)
	}
	return d
}

func testRecipient(t *testing.T, addr string) Recipient {
	t.Helper()
	r, err := parseRecipient(addr)
	if err != nil {
		t.Fatalf("parse recipient: %v", err)
	}
	return r
}

// do performs a request against the routing table and returns the recorder.
func do(t *testing.T, mux *http.ServeMux, method, path string, body any) *httptest.ResponseRecorder {
	t.Helper()
	var rdr *bytes.Reader
	if body != nil {
		raw, err := json.Marshal(body)
		if err != nil {
			t.Fatalf("marshal: %v", err)
		}
		rdr = bytes.NewReader(raw)
	} else {
		rdr = bytes.NewReader(nil)
	}
	rec := httptest.NewRecorder()
	mux.ServeHTTP(rec, httptest.NewRequest(method, path, rdr))
	return rec
}

func decodeDraft(t *testing.T, rec *httptest.ResponseRecorder) draftJSON {
	t.Helper()
	var d draftJSON
	if err := json.Unmarshal(rec.Body.Bytes(), &d); err != nil {
		t.Fatalf("decode: %v (body %q)", err, rec.Body.String())
	}
	return d
}

func TestDraftAPIBlocks(t *testing.T) {
	accountName = "test"
	myAddress = "me@example.org"
	myAddresses = map[string]bool{myAddress: true}

	s := newTestServer(t)
	mux := s.routes()
	d := makeDraft(t,
		s,
		draftBlock{Kind: blockText, Content: "first"},
		draftBlock{Kind: blockText, Content: "second"},
	)
	base := "/api/drafts/" + d.Token

	// Reading it back gives the blocks in order, and says it is plain text.
	got := decodeDraft(t, do(t, mux, "GET", base, nil))
	if len(got.Blocks) != 2 || got.Blocks[0].Content != "first" {
		t.Fatalf("unexpected blocks: %+v", got.Blocks)
	}
	if got.Rich {
		t.Error("a draft of prose should not be rich")
	}

	// Adding a code block answers with the whole list, and flips the format:
	// the wire shape is derived from the contents rather than chosen.
	after := do(t, mux, "POST", base+"/blocks",
		map[string]any{"kind": blockCode, "after": 1})
	if after.Code != 200 {
		t.Fatalf("create block: %d %s", after.Code, after.Body)
	}
	withCode := decodeDraft(t, after)
	if len(withCode.Blocks) != 3 {
		t.Fatalf("want 3 blocks, got %d", len(withCode.Blocks))
	}
	if !withCode.Rich {
		t.Error("a draft holding a code listing must be sent as MIME")
	}

	// An unknown kind is the client's error, not a 500.
	if rec := do(t, mux, "POST", base+"/blocks",
		map[string]any{"kind": "haiku"}); rec.Code != 400 {
		t.Errorf("unknown kind: got %d, want 400", rec.Code)
	}

	// Moving answers with the list, renumbered densely from zero.
	last := withCode.Blocks[2]
	moved := decodeDraft(t, do(t, mux, "POST",
		base+"/blocks/"+itoa(last.ID)+"/move", map[string]any{"position": 0}))
	if moved.Blocks[0].ID != last.ID {
		t.Errorf("move: block %d should be first, got %d", last.ID, moved.Blocks[0].ID)
	}
	for i, b := range moved.Blocks {
		if b.Position != i {
			t.Errorf("positions must be dense: block %d at %d, want %d", b.ID, b.Position, i)
		}
	}

	// Editing text answers ok and no list, because it cannot reorder anything
	// and runs while somebody is typing.
	rec := do(t, mux, "PATCH", base+"/blocks/"+itoa(moved.Blocks[1].ID),
		map[string]any{"content": "edited", "meta": map[string]string{}})
	if rec.Code != 200 {
		t.Fatalf("patch: %d %s", rec.Code, rec.Body)
	}
	var ok map[string]bool
	if err := json.Unmarshal(rec.Body.Bytes(), &ok); err != nil || !ok["ok"] {
		t.Errorf("patch should answer {ok:true}, got %q", rec.Body.String())
	}
	if reread := decodeDraft(t, do(t, mux, "GET", base, nil)); reread.Blocks[1].Content != "edited" {
		t.Errorf("edit did not persist: %q", reread.Blocks[1].Content)
	}

	// Deleting closes the gap.
	deleted := decodeDraft(t, do(t, mux, "DELETE", base+"/blocks/"+itoa(last.ID), nil))
	if len(deleted.Blocks) != 2 {
		t.Errorf("want 2 blocks after delete, got %d", len(deleted.Blocks))
	}
	for i, b := range deleted.Blocks {
		if b.Position != i {
			t.Errorf("delete left a gap: block %d at %d, want %d", b.ID, b.Position, i)
		}
	}

	// A block belonging to no draft, and a block id from another draft, are
	// both "not in this draft".
	other := makeDraft(t, s, draftBlock{Kind: blockText, Content: "elsewhere"})
	otherBlocks := decodeDraft(t, do(t, mux, "GET", "/api/drafts/"+other.Token, nil))
	if rec := do(t, mux, "PATCH", base+"/blocks/"+itoa(otherBlocks.Blocks[0].ID),
		map[string]any{"content": "x"}); rec.Code != 404 {
		t.Errorf("cross-draft edit: got %d, want 404", rec.Code)
	}
}

// TestDraftAPIQuoteAttributionIsNotEditable checks that the line naming who
// wrote a quoted passage cannot be rewritten through the API.
//
// It is body text that goes to every recipient, it came out of a From: header,
// and the draft page shows it precisely so that what is displayed and what will
// be sent cannot differ. A request that could change it could make those two
// disagree.
func TestDraftAPIQuoteAttributionIsNotEditable(t *testing.T) {
	s := newTestServer(t)
	mux := s.routes()
	d := makeDraft(t, s, draftBlock{
		Kind:    blockQuote,
		Content: "their words",
		Meta: blockMeta{
			Attribution: "On 2026-08-27 12:00, Klara <klara@example.org> wrote:",
			QuoteFrom:   "klara@example.org",
			QuoteName:   "Klara",
		},
	})
	base := "/api/drafts/" + d.Token
	blocks := decodeDraft(t, do(t, mux, "GET", base, nil))

	do(t, mux, "PATCH", base+"/blocks/"+itoa(blocks.Blocks[0].ID), map[string]any{
		"content": "their words",
		"meta":    map[string]string{"attribution": "On 2026-08-27, Somebody Else wrote:"},
	})

	after := decodeDraft(t, do(t, mux, "GET", base, nil))
	if got := after.Blocks[0].Meta.Attribution; got != blocks.Blocks[0].Meta.Attribution {
		t.Errorf("attribution was rewritten to %q", got)
	}
	if got := after.Blocks[0].Meta.QuoteFrom; got != "klara@example.org" {
		t.Errorf("quote origin was rewritten to %q", got)
	}
}

// TestDraftAPISentIsReadOnly checks that a sent draft refuses every write.
//
// A sent draft is the record of what went out. Editing it would make that
// record disagree with the mail people received, so the refusal is here and not
// only in the browser, which is a courtesy to whoever is looking at the page.
func TestDraftAPISentIsReadOnly(t *testing.T) {
	s := newTestServer(t)
	mux := s.routes()
	d := makeDraft(t, s, draftBlock{Kind: blockText, Content: "went out"})
	base := "/api/drafts/" + d.Token
	blocks := decodeDraft(t, do(t, mux, "GET", base, nil))
	blockID := itoa(blocks.Blocks[0].ID)

	if err := markDraftSent(s.db.Write, d.ID, "<abc@example.org>"); err != nil {
		t.Fatalf("mark sent: %v", err)
	}

	// Reading is still allowed: that is what "kept as the record" means.
	if rec := do(t, mux, "GET", base, nil); rec.Code != 200 {
		t.Errorf("a sent draft must still be readable: %d", rec.Code)
	} else if !decodeDraft(t, rec).Sent {
		t.Error("a sent draft should say so")
	}

	for _, c := range []struct {
		method, path string
		body         any
	}{
		{"PATCH", base, map[string]any{"subject": "new"}},
		{"POST", base + "/blocks", map[string]any{"kind": blockText}},
		{"PATCH", base + "/blocks/" + blockID, map[string]any{"content": "x"}},
		{"POST", base + "/blocks/" + blockID + "/move", map[string]any{"position": 0}},
		{"DELETE", base + "/blocks/" + blockID, nil},
	} {
		rec := do(t, mux, c.method, c.path, c.body)
		if rec.Code != http.StatusConflict {
			t.Errorf("%s %s on a sent draft: got %d, want 409",
				c.method, c.path, rec.Code)
		}
	}

	// And nothing was written.
	after := decodeDraft(t, do(t, mux, "GET", base, nil))
	if len(after.Blocks) != 1 || after.Blocks[0].Content != "went out" {
		t.Errorf("a refused write changed the draft: %+v", after.Blocks)
	}
	if after.Subject != "Re: the thing" {
		t.Errorf("subject was changed to %q", after.Subject)
	}
}

// TestDraftAPIUnknownToken checks that the API discloses no more than the page
// does: a token naming nothing is 404, exactly as a discarded one is.
func TestDraftAPIUnknownToken(t *testing.T) {
	mux := newTestServer(t).routes()
	for _, path := range []string{
		"/api/drafts/nosuchtoken",
		"/api/drafts/nosuchtoken/blocks",
	} {
		method := "GET"
		if path != "/api/drafts/nosuchtoken" {
			method = "POST"
		}
		if rec := do(t, mux, method, path, map[string]any{"kind": blockText}); rec.Code != 404 {
			t.Errorf("%s %s: got %d, want 404", method, path, rec.Code)
		}
	}
}

// TestDraftsByParent checks the lookup the listings use to show a reply in
// progress beside the message it answers.
func TestDraftsByParent(t *testing.T) {
	s := newTestServer(t)

	first := &draft{ParentID: 42, Subject: "Re: one",
		Blocks: []draftBlock{{Kind: blockText}}}
	if err := createDraft(s.db.Write, first); err != nil {
		t.Fatalf("create: %v", err)
	}
	second := &draft{ParentID: 42, Subject: "Re: one again",
		Blocks: []draftBlock{{Kind: blockText}}}
	if err := createDraft(s.db.Write, second); err != nil {
		t.Fatalf("create: %v", err)
	}
	elsewhere := &draft{ParentID: 99, Subject: "Re: other",
		Blocks: []draftBlock{{Kind: blockText}}}
	if err := createDraft(s.db.Write, elsewhere); err != nil {
		t.Fatalf("create: %v", err)
	}

	got, err := draftsByParent(s.db.Read, []int64{42})
	if err != nil {
		t.Fatalf("drafts by parent: %v", err)
	}
	// Both drafts against 42, and nothing from another message.
	if len(got[42]) != 2 {
		t.Errorf("want 2 drafts for message 42, got %d", len(got[42]))
	}
	if len(got[99]) != 0 {
		t.Errorf("message 99 was not asked about, got %d", len(got[99]))
	}

	// A sent draft drops out: what it belongs beside is the copy in the Sent
	// mailbox, which the mirror holds as a message of its own.
	if err := markDraftSent(s.db.Write, first.ID, "<x@example.org>"); err != nil {
		t.Fatalf("mark sent: %v", err)
	}
	got, err = draftsByParent(s.db.Read, []int64{42})
	if err != nil {
		t.Fatalf("drafts by parent: %v", err)
	}
	if len(got[42]) != 1 || got[42][0].ID != second.ID {
		t.Errorf("a sent draft should not be listed: %+v", got[42])
	}

	// No ids is no query and no rows, rather than a malformed IN ().
	if empty, err := draftsByParent(s.db.Read, nil); err != nil || len(empty) != 0 {
		t.Errorf("empty id list: %v, %+v", err, empty)
	}
}

func itoa(n int64) string { return strconv.FormatInt(n, 10) }