~bigbes/sr-ht-spec

ref: 3d811988f9960cf9057e09f30b59ceb71a7623c2 sr-ht-spec/web/comments_test.go -rw-r--r-- 18.5 KiB
3d811988 — Eugene Blikh service: wrap the merge and reject failures with culpa 9 days ago
                                                                                
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package web

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"strings"
	"testing"

	"sourcecraft.dev/bigbes/sr-ht-spec/core"
	"sourcecraft.dev/bigbes/sr-ht-spec/service"
)

// The document under review: two paragraphs under one heading, one of which the
// proposal edits. Block 1 is "The first paragraph."; block 2 is the edited one.
const (
	commentBase     = "# Storage\n\nThe first paragraph.\n\nThe second paragraph.\n"
	commentProposed = "# Storage\n\nThe first paragraph.\n\nThe second paragraph, revised.\n"
	// It has no frontmatter, so its anchoring key is its path minus the
	// extension — the archive's rule for a document with no well-formed id.
	commentDocID = "specs/0007-storage"
)

func commentDocs() []service.ProposalDoc {
	return []service.ProposalDoc{{
		Path:     "specs/0007-storage.md",
		Base:     []byte(commentBase),
		Proposed: []byte(commentProposed),
	}}
}

// seedThread hangs a thread off one block of the proposed document, anchored the
// way the service would anchor it — through service.AnchorOf, so the test cannot
// disagree with production about which block it named.
func seedThread(t *testing.T, r *fakeReader, proposalID, ordinal int, body string) *service.Thread {
	t.Helper()
	anchor, err := service.AnchorOf(commentDocID, []byte(commentProposed), ordinal, core.SideNew)
	if err != nil {
		t.Fatalf("AnchorOf: %v", err)
	}
	r.nextThread++
	th := &service.Thread{
		Root:    service.Comment{ID: r.nextThread, Author: "bigbes", Body: body},
		DocPath: "specs/0007-storage.md",
		Anchor:  anchor,
		Block:   -1,
	}
	r.threads[proposalID] = append(r.threads[proposalID], th)
	return th
}

// postForm issues a form POST with a urlencoded body, as a browser would.
func postForm(t *testing.T, h http.Handler, target, user, origin string, form url.Values) *httptest.ResponseRecorder {
	t.Helper()
	req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if user != "" {
		login(req, user)
	}
	if origin != "" {
		req.Header.Set("Origin", origin)
	}
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	return rec
}

// commentServer is a fake reader holding one open proposal with one changed
// document, plus the handler.
func commentServer(t *testing.T) (http.Handler, *fakeReader) {
	t.Helper()
	r := newFakeReader()
	seedProposal(r, openProposal(), commentDocs())
	h, reader, _ := testServerWith(t, r)
	return h, reader
}

// TestDocIDForFollowsTheArchiveAddressingRule proves a comment anchors to the
// document's frontmatter id when it has a well-formed one — which is what lets
// the comment survive a rename — and to its path when it does not.
func TestDocIDForFollowsTheArchiveAddressingRule(t *testing.T) {
	withID := []byte("---\nid: SPEC-0007\ntitle: Storage\n---\n\n# Storage\n")
	if got := docIDFor("specs/0007-storage.md", withID); got != "SPEC-0007" {
		t.Errorf("docIDFor = %q, want the frontmatter id", got)
	}
	if got := docIDFor("notes/plain.md", []byte("# Just a note\n")); got != "notes/plain" {
		t.Errorf("docIDFor = %q, want the path without its extension", got)
	}
}

// TestProposalPageDrawsComposeFormsForTheOwner proves the owner can start a
// thread on a block — including on one the proposal did not change, which is
// the whole point of rendering unchanged blocks.
func TestProposalPageDrawsComposeFormsForTheOwner(t *testing.T) {
	h, _ := commentServer(t)
	body := get(t, h, "/~bigbes/rfcs/p/7", "bigbes").Body.String()

	if !strings.Contains(body, "/p/7/comment") {
		t.Fatalf("the owner has no compose form; body:\n%s", body)
	}
	// One form per rendered block: heading, unchanged paragraph, changed one.
	if n := strings.Count(body, `action="/~bigbes/rfcs/p/7/comment"`); n != 3 {
		t.Errorf("%d compose forms, want one per rendered block (3); body:\n%s", n, body)
	}
	if !strings.Contains(body, `name="side" value="new"`) {
		t.Errorf("the compose form does not name the side it anchors to; body:\n%s", body)
	}
}

// TestProposalPageHidesOwnerControlsFromAnAgent proves a principal who may read
// and reply is not offered the two controls that are the owner's: opening a
// thread and resolving one.
func TestProposalPageHidesOwnerControlsFromAnAgent(t *testing.T) {
	h, r := commentServer(t)
	seedThread(t, r, 7, 1, "please reword this")

	body := getAgent(t, h, "/~bigbes/rfcs/p/7", agentTk).Body.String()
	if !strings.Contains(body, "please reword this") {
		t.Fatalf("an agent cannot see the comments on its own proposal; body:\n%s", body)
	}
	if strings.Contains(body, "/p/7/comment") {
		t.Errorf("an agent was offered the compose form; body:\n%s", body)
	}
	if strings.Contains(body, "/p/7/resolve") {
		t.Errorf("an agent was offered the resolve control; body:\n%s", body)
	}
	if !strings.Contains(body, "/p/7/reply") {
		t.Errorf("an agent was not offered the reply form, which is its half of the loop; body:\n%s", body)
	}
}

// TestProposalPageMarksAnEditedAnchor proves a comment whose block has changed
// since it was written is shown — the reviewer still needs it — and marked, so
// nobody reads a stale critique as a current one.
func TestProposalPageMarksAnEditedAnchor(t *testing.T) {
	h, r := commentServer(t)
	// Anchored to the second paragraph as it read before the revision, so the
	// hash misses and heading-path + index carries it: edited, not lost.
	anchor, err := service.AnchorOf(commentDocID, []byte(commentBase), 2, core.SideNew)
	if err != nil {
		t.Fatalf("AnchorOf: %v", err)
	}
	r.nextThread++
	r.threads[7] = append(r.threads[7], &service.Thread{
		Root:    service.Comment{ID: r.nextThread, Author: "bigbes", Body: "the tense is wrong"},
		DocPath: "specs/0007-storage.md",
		Anchor:  anchor,
		Block:   -1,
	})

	body := get(t, h, "/~bigbes/rfcs/p/7", "bigbes").Body.String()
	if !strings.Contains(body, "the tense is wrong") {
		t.Fatalf("an edited-anchor comment is not on the page; body:\n%s", body)
	}
	if !strings.Contains(body, "block edited since") {
		t.Errorf("an edited anchor is shown as if it still fitted; body:\n%s", body)
	}
	if strings.Contains(body, "lost their anchor") {
		t.Errorf("an edited anchor was demoted to lost; body:\n%s", body)
	}
}

// TestProposalPageKeepsAnOutdatedComment proves a comment whose block is gone is
// still on the page, in the area that says so, and is not attached to whatever
// block happens to be nearby.
func TestProposalPageKeepsAnOutdatedComment(t *testing.T) {
	h, r := commentServer(t)
	// Anchored to a paragraph that exists in neither revision on the page.
	const gone = commentBase + "\nA paragraph the revision dropped.\n"
	anchor, err := service.AnchorOf(commentDocID, []byte(gone), 3, core.SideNew)
	if err != nil {
		t.Fatalf("AnchorOf: %v", err)
	}
	r.nextThread++
	r.threads[7] = append(r.threads[7], &service.Thread{
		Root:    service.Comment{ID: r.nextThread, Author: "bigbes", Body: "this claim is unsupported"},
		DocPath: "specs/0007-storage.md",
		Anchor:  anchor,
		Block:   -1,
	})

	body := get(t, h, "/~bigbes/rfcs/p/7", "bigbes").Body.String()
	if !strings.Contains(body, "this claim is unsupported") {
		t.Fatalf("an outdated comment was dropped from the page; body:\n%s", body)
	}
	lost := strings.Index(body, "Comments that lost their anchor")
	if lost < 0 {
		t.Fatalf("no area for comments whose anchor is lost; body:\n%s", body)
	}
	// It belongs to that area and to no block: the diff ends before it.
	if strings.Index(body, "this claim is unsupported") < lost {
		t.Errorf("an outdated comment was rendered against a block; body:\n%s", body)
	}
}

// TestProposalPageKeepsCommentsOnARevertedDocument proves a thread whose
// document the proposal no longer changes — so no diff renders it at all — is
// still shown rather than silently disappearing.
func TestProposalPageKeepsCommentsOnARevertedDocument(t *testing.T) {
	h, r := commentServer(t)
	r.nextThread++
	r.threads[7] = append(r.threads[7], &service.Thread{
		Root:    service.Comment{ID: r.nextThread, Author: "bigbes", Body: "comment on a reverted file"},
		DocPath: "specs/reverted.md",
		Block:   -1,
	})

	body := get(t, h, "/~bigbes/rfcs/p/7", "bigbes").Body.String()
	if !strings.Contains(body, "comment on a reverted file") {
		t.Fatalf("a comment on a document no longer changed was dropped; body:\n%s", body)
	}
	if !strings.Contains(body, "specs/reverted.md") {
		t.Errorf("the lost comment does not say which document it came from; body:\n%s", body)
	}
}

// TestCommentBodyIsEscaped proves a comment is text: markup in a body cannot
// become markup on the page.
func TestCommentBodyIsEscaped(t *testing.T) {
	h, r := commentServer(t)
	seedThread(t, r, 7, 1, `<img src=x onerror="alert(1)">`)

	body := get(t, h, "/~bigbes/rfcs/p/7", "bigbes").Body.String()
	if strings.Contains(body, "<img src=x") {
		t.Fatalf("an unescaped comment body reached the page; body:\n%s", body)
	}
	if !strings.Contains(body, "&lt;img src=x") {
		t.Errorf("the escaped comment body is missing; body:\n%s", body)
	}
}

// TestOwnerOpensAThreadOnABlock proves the compose POST anchors through
// service.AnchorOf and redirects to what was just written.
func TestOwnerOpensAThreadOnABlock(t *testing.T) {
	h, r := commentServer(t)
	anchor, err := service.AnchorOf(commentDocID, []byte(commentProposed), 1, core.SideNew)
	if err != nil {
		t.Fatalf("AnchorOf: %v", err)
	}

	rec := postForm(t, h, "/~bigbes/rfcs/p/7/comment", "bigbes", "https://spec.example", url.Values{
		"doc":   {"specs/0007-storage.md"},
		"block": {"1"},
		"side":  {"new"},
		"hash":  {anchor.BlockHash},
		"body":  {"say why"},
	})
	if rec.Code != http.StatusSeeOther {
		t.Fatalf("status = %d, want 303; body:\n%s", rec.Code, rec.Body)
	}
	if len(r.threads[7]) != 1 {
		t.Fatalf("%d threads stored, want 1", len(r.threads[7]))
	}
	got := r.threads[7][0]
	if got.Anchor.BlockHash != anchor.BlockHash {
		t.Errorf("stored anchor hash = %q, want the block's %q", got.Anchor.BlockHash, anchor.BlockHash)
	}
	if got.Anchor.Index != anchor.Index || got.Anchor.DocID != anchor.DocID {
		t.Errorf("stored anchor = %+v, want service.AnchorOf's %+v", got.Anchor, anchor)
	}
	if loc := rec.Header().Get("Location"); loc != "/~bigbes/rfcs/p/7#thread-1" {
		t.Errorf("redirect = %q, want the new thread on the proposal page", loc)
	}
}

// TestCommentOnAStaleBlockIsRefused proves the form's block hash is a guard, not
// decoration: if the agent revised the document while the page was open, the
// comment is refused rather than attached to whatever moved into that position.
func TestCommentOnAStaleBlockIsRefused(t *testing.T) {
	h, r := commentServer(t)
	rec := postForm(t, h, "/~bigbes/rfcs/p/7/comment", "bigbes", "https://spec.example", url.Values{
		"doc":   {"specs/0007-storage.md"},
		"block": {"1"},
		"side":  {"new"},
		"hash":  {"a-hash-from-a-revision-that-is-gone"},
		"body":  {"say why"},
	})
	if rec.Code != http.StatusConflict {
		t.Fatalf("status = %d, want 409 for a block that moved under the form", rec.Code)
	}
	if len(r.threads[7]) != 0 {
		t.Errorf("a comment was stored against a stale block: %+v", r.threads[7])
	}
}

// The hash is required rather than checked-when-present, so that a template
// refactor dropping the hidden field fails here instead of silently disabling
// the staleness guard above — the comment would still store a coherent anchor,
// just not against the block the reviewer was actually reading.
func TestCommentWithoutABlockHashIsRefused(t *testing.T) {
	h, r := commentServer(t)
	rec := postForm(t, h, "/~bigbes/rfcs/p/7/comment", "bigbes", "https://spec.example", url.Values{
		"doc":   {"specs/0007-storage.md"},
		"block": {"1"},
		"side":  {"new"},
		"body":  {"say why"},
	})
	if rec.Code != http.StatusBadRequest {
		t.Fatalf("status = %d, want 400 when the form carries no block hash", rec.Code)
	}
	if len(r.threads[7]) != 0 {
		t.Errorf("a comment was stored with no staleness guard: %+v", r.threads[7])
	}
}

// TestAgentMayNotOpenAThread proves the owner-only rule is the service's and
// this page surfaces it: an agent posting the form directly gets a 403.
// The request is deliberately well-formed, block hash included: the refusal
// under test is the authority one, and a form the handler rejects before it
// ever reaches service.CommentOn would prove nothing about who may open a
// thread.
func TestAgentMayNotOpenAThread(t *testing.T) {
	h, r := commentServer(t)
	anchor, err := service.AnchorOf(commentDocID, []byte(commentProposed), 1, core.SideNew)
	if err != nil {
		t.Fatalf("AnchorOf: %v", err)
	}
	req := httptest.NewRequest(http.MethodPost, "/~bigbes/rfcs/p/7/comment",
		strings.NewReader(url.Values{
			"doc": {"specs/0007-storage.md"}, "block": {"1"}, "side": {"new"},
			"hash": {anchor.BlockHash}, "body": {"mine now"},
		}.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "Bearer "+agentTk)
	req.Header.Set("Origin", "https://spec.example")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)

	if rec.Code != http.StatusForbidden {
		t.Fatalf("status = %d, want 403 for an agent opening a thread", rec.Code)
	}
	if len(r.threads[7]) != 0 {
		t.Errorf("the thread was opened despite the refusal: %+v", r.threads[7])
	}
}

// TestAgentMayReply proves the other half of that rule: replying is how the
// agent answers a critique, and it is allowed.
func TestAgentMayReply(t *testing.T) {
	h, r := commentServer(t)
	th := seedThread(t, r, 7, 1, "please reword this")

	req := httptest.NewRequest(http.MethodPost, "/~bigbes/rfcs/p/7/reply",
		strings.NewReader(url.Values{"thread": {strconv.Itoa(th.Root.ID)}, "body": {"reworded"}}.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "Bearer "+agentTk)
	req.Header.Set("Origin", "https://spec.example")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)

	if rec.Code != http.StatusSeeOther {
		t.Fatalf("status = %d, want 303; body:\n%s", rec.Code, rec.Body)
	}
	if len(th.Replies) != 1 || th.Replies[0].Body != "reworded" {
		t.Fatalf("replies = %+v, want the agent's answer", th.Replies)
	}
	if !th.Replies[0].Agent {
		t.Errorf("the reply is not attributed to the agent: %+v", th.Replies[0])
	}
}

// TestAgentMayNotResolve proves an agent cannot clear the gate its own proposal
// is held by.
func TestAgentMayNotResolve(t *testing.T) {
	h, r := commentServer(t)
	th := seedThread(t, r, 7, 1, "please reword this")

	req := httptest.NewRequest(http.MethodPost, "/~bigbes/rfcs/p/7/resolve",
		strings.NewReader(url.Values{"thread": {strconv.Itoa(th.Root.ID)}, "resolved": {"1"}}.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", "Bearer "+agentTk)
	req.Header.Set("Origin", "https://spec.example")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)

	if rec.Code != http.StatusForbidden {
		t.Fatalf("status = %d, want 403 for an agent resolving", rec.Code)
	}
	if !th.Open() {
		t.Errorf("the thread was resolved despite the refusal")
	}
}

// TestOwnerResolvesAndReopens proves the resolve control is a toggle, and that
// the page then offers the other direction.
func TestOwnerResolvesAndReopens(t *testing.T) {
	h, r := commentServer(t)
	th := seedThread(t, r, 7, 1, "please reword this")
	form := url.Values{"thread": {strconv.Itoa(th.Root.ID)}, "resolved": {"1"}}

	if rec := postForm(t, h, "/~bigbes/rfcs/p/7/resolve", "bigbes", "https://spec.example", form); rec.Code != http.StatusSeeOther {
		t.Fatalf("status = %d, want 303; body:\n%s", rec.Code, rec.Body)
	}
	if th.Open() {
		t.Fatalf("the thread is still open after the owner resolved it")
	}
	body := get(t, h, "/~bigbes/rfcs/p/7", "bigbes").Body.String()
	if !strings.Contains(body, "Reopen") {
		t.Errorf("a resolved thread offers no way back; body:\n%s", body)
	}

	form.Set("resolved", "0")
	if rec := postForm(t, h, "/~bigbes/rfcs/p/7/resolve", "bigbes", "https://spec.example", form); rec.Code != http.StatusSeeOther {
		t.Fatalf("reopen status = %d, want 303", rec.Code)
	}
	if !th.Open() {
		t.Errorf("the thread did not reopen")
	}
}

// TestCommentRefusedCrossOrigin proves the comment writes carry the same CSRF
// defense as approve and reject.
func TestCommentRefusedCrossOrigin(t *testing.T) {
	h, r := commentServer(t)
	rec := postForm(t, h, "/~bigbes/rfcs/p/7/comment", "bigbes", "https://evil.example", url.Values{
		"doc": {"specs/0007-storage.md"}, "block": {"1"}, "side": {"new"}, "body": {"forged"},
	})
	if rec.Code != http.StatusForbidden {
		t.Fatalf("status = %d, want 403 for a cross-origin comment", rec.Code)
	}
	if len(r.threads[7]) != 0 {
		t.Errorf("a forged comment was stored: %+v", r.threads[7])
	}
}

// TestCommentThroughAnotherSpacesURLIs404 proves a comment POST is held to the
// same rule as the page it comes from: the proposal id is global, but the link
// names a space, and answering for the wrong one would let one space's URL write
// into another's review.
func TestCommentThroughAnotherSpacesURLIs404(t *testing.T) {
	h, r := commentServer(t)
	rec := postForm(t, h, "/~bigbes/other/p/7/comment", "bigbes", "https://spec.example", url.Values{
		"doc": {"specs/0007-storage.md"}, "block": {"1"}, "side": {"new"}, "body": {"wrong space"},
	})
	if rec.Code != http.StatusNotFound {
		t.Fatalf("status = %d, want 404 through another space's URL", rec.Code)
	}
	if len(r.threads[7]) != 0 {
		t.Errorf("a comment was stored through the wrong space's URL: %+v", r.threads[7])
	}
}

// TestAnonymousMayNotComment proves the comment writes are behind the read ACL
// as well as behind the service's owner rule: a viewer who may not read the
// proposal cannot write to its review either.
func TestAnonymousMayNotComment(t *testing.T) {
	h, r := commentServer(t)
	rec := postForm(t, h, "/~bigbes/rfcs/p/7/comment", "", "https://spec.example", url.Values{
		"doc": {"specs/0007-storage.md"}, "block": {"1"}, "side": {"new"}, "body": {"uninvited"},
	})
	if rec.Code != http.StatusForbidden {
		t.Fatalf("status = %d, want 403 for an anonymous comment", rec.Code)
	}
	if len(r.threads[7]) != 0 {
		t.Errorf("an anonymous comment was stored: %+v", r.threads[7])
	}
}

// TestReplyToAnotherProposalsThreadIs404 proves the thread id in a form is
// checked against the proposal in the URL: a global id must not let a reply land
// on a conversation the reviewer was never looking at.
func TestReplyToAnotherProposalsThreadIs404(t *testing.T) {
	h, r := commentServer(t)
	other := openProposal()
	other.ID = 8
	seedProposal(r, other, commentDocs())
	th := seedThread(t, r, 8, 1, "on the other proposal")

	rec := postForm(t, h, "/~bigbes/rfcs/p/7/reply", "bigbes", "https://spec.example",
		url.Values{"thread": {strconv.Itoa(th.Root.ID)}, "body": {"misdirected"}})
	if rec.Code != http.StatusNotFound {
		t.Fatalf("status = %d, want 404 for a thread on another proposal", rec.Code)
	}
	if len(th.Replies) != 0 {
		t.Errorf("the reply landed on the other proposal's thread: %+v", th.Replies)
	}
}