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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"regexp"
	"strings"
	"testing"
)

// storeOne puts a submission in the database and returns its token.
func storeOne(t *testing.T, s *server, audio []byte) string {
	t.Helper()
	sub := &Submission{MIME: "audio/mp4", Filename: "reply.m4a"}
	if err := insertSubmission(s.db, sub, audio); err != nil {
		t.Fatalf("insertSubmission: %v", err)
	}
	return sub.Token
}

// getReview calls the handler directly with the token as a path value. The
// request URL is a fixed placeholder: a token is whatever arrives in that path
// segment, including bytes that would not survive URL parsing, and the point
// is to exercise the handler with those.
func getReview(t *testing.T, s *server, token string) *httptest.ResponseRecorder {
	t.Helper()
	w := httptest.NewRecorder()
	r := httptest.NewRequest("GET", "/inbox/x", nil)
	r.SetPathValue("token", token)
	s.handleReview(w, r)
	return w
}

func TestReviewShowsSubmission(t *testing.T) {
	s := newTestServer(t)
	token := storeOne(t, s, m4aBytes(500))

	w := getReview(t, s, token)
	if w.Code != http.StatusOK {
		t.Fatalf("status = %d", w.Code)
	}
	body := w.Body.String()
	for _, want := range []string{`<audio controls`, "reply.m4a", "Delete this submission"} {
		if !strings.Contains(body, want) {
			t.Errorf("review page lacks %q", want)
		}
	}
}

// The token is a credential in a URL, so the page must not be indexed,
// cached by anything shared, or able to leak through a Referer.
func TestReviewSetsNoLeakHeaders(t *testing.T) {
	s := newTestServer(t)
	token := storeOne(t, s, m4aBytes(100))

	for _, w := range []*httptest.ResponseRecorder{
		getReview(t, s, token),
		func() *httptest.ResponseRecorder {
			w := httptest.NewRecorder()
			r := httptest.NewRequest("GET", "/inbox/x/audio", nil)
			r.SetPathValue("token", token)
			s.handleReviewAudio(w, r)
			return w
		}(),
	} {
		h := w.Header()
		if !strings.Contains(h.Get("X-Robots-Tag"), "noindex") {
			t.Errorf("X-Robots-Tag = %q", h.Get("X-Robots-Tag"))
		}
		if !strings.Contains(h.Get("Cache-Control"), "no-store") {
			t.Errorf("Cache-Control = %q", h.Get("Cache-Control"))
		}
		if h.Get("Referrer-Policy") != "no-referrer" {
			t.Errorf("Referrer-Policy = %q", h.Get("Referrer-Policy"))
		}
	}
}

// The review page must not link anywhere off-site, or the token would travel
// in a Referer header despite the policy above.
func TestReviewPageLinksNowhere(t *testing.T) {
	s := newTestServer(t)
	token := storeOne(t, s, m4aBytes(100))
	body := getReview(t, s, token).Body.String()

	if strings.Contains(body, "http://") || strings.Contains(body, "https://") {
		t.Errorf("review page contains an absolute URL:\n%s", body)
	}
}

// A transcription failure is reported with the message the API returned, and
// those messages carry URLs: Google's names its billing console. The text may
// appear, but never as something clickable — following it would carry the
// token off-site in a Referer.
func TestTranscriptErrorIsNotLinked(t *testing.T) {
	s := newTestServer(t)
	token := storeConsented(t, s, true)
	if err := setTranscriptError(s.db, token,
		"credits depleted, see https://ai.studio/projects to manage billing"); err != nil {
		t.Fatal(err)
	}
	body := getReview(t, s, token).Body.String()

	if !strings.Contains(body, "ai.studio/projects") {
		t.Fatalf("the reason was not shown at all:\n%s", body)
	}
	if strings.Contains(body, "<a ") || strings.Contains(body, "href") {
		t.Errorf("the review page grew a link:\n%s", body)
	}
}

// The page's links have to resolve to the real routes from the URL that is
// actually clicked, which is the slashless one the notification mail carries.
//
// This is a regression test. Both /inbox/{token} and /inbox/{token}/ are
// registered, so ServeMux does not redirect between them, and a relative
// src="audio" on the slashless page resolves against /inbox/ rather than
// /inbox/TOKEN/: the player asked for /inbox/audio and got a 404, and the
// delete button posted into the same hole. Checking the string in the template
// would not have caught it — the resolution against the page URL is the bug.
func TestReviewLinksResolveToTheRealRoutes(t *testing.T) {
	s := newTestServer(t)
	token := storeOne(t, s, m4aBytes(100))
	body := getReview(t, s, token).Body.String()

	audioRef := attr(t, body, `<audio[^>]*\ssrc="([^"]+)"`, "audio src")
	deleteRef := attr(t, body, `<form[^>]*\saction="([^"]+)"`, "form action")

	// Both forms are routable and reachable, so both have to work.
	for _, page := range []string{
		"https://observations.profpatsch.de/inbox/" + token,
		"https://observations.profpatsch.de/inbox/" + token + "/",
	} {
		base, err := url.Parse(page)
		if err != nil {
			t.Fatal(err)
		}
		for _, c := range []struct{ ref, want string }{
			{audioRef, "/inbox/" + token + "/audio"},
			{deleteRef, "/inbox/" + token + "/delete"},
		} {
			ref, err := url.Parse(c.ref)
			if err != nil {
				t.Fatalf("page emitted an unparseable URL %q: %v", c.ref, err)
			}
			if got := base.ResolveReference(ref).Path; got != c.want {
				t.Errorf("on %s, %q resolves to %q, want %q", page, c.ref, got, c.want)
			}
		}
	}
}

func attr(t *testing.T, body, pattern, what string) string {
	t.Helper()
	m := regexp.MustCompile(pattern).FindStringSubmatch(body)
	if m == nil {
		t.Fatalf("review page has no %s:\n%s", what, body)
	}
	return m[1]
}

// An unknown token, a malformed one and a deleted one must be indistinguishable
// from each other: anything else is an oracle.
func TestUnknownTokensAllLookTheSame(t *testing.T) {
	s := newTestServer(t)
	live := storeOne(t, s, m4aBytes(100))
	deleted := storeOne(t, s, m4aBytes(100))
	if err := deleteSubmission(s.db, deleted); err != nil {
		t.Fatal(err)
	}

	valid := strings.Repeat("A", len(live)) // right shape, never issued
	for name, token := range map[string]string{
		"never issued": valid,
		"deleted":      deleted,
		"too short":    "abc",
		"empty":        "",
		"not base64":   strings.Repeat("!", len(live)),
		"sql-ish":      "' OR 1=1 --",
		"traversal":    "../../etc/passwd",
	} {
		w := getReview(t, s, token)
		if w.Code != http.StatusNotFound {
			t.Errorf("%s: status = %d, want 404", name, w.Code)
		}
		if b := w.Body.String(); strings.Contains(strings.ToLower(b), "deleted") {
			t.Errorf("%s: response distinguishes a deleted token: %q", name, b)
		}
	}
}

// Deleting must actually remove the audio, not merely hide the row: freeing
// the quota is the point.
func TestDeleteRemovesAudioAndFreesQuota(t *testing.T) {
	s := newTestServer(t)
	token := storeOne(t, s, m4aBytes(10_000))

	used, _ := usedBytes(s.db)
	if used == 0 {
		t.Fatal("submission did not count against the quota")
	}

	w := httptest.NewRecorder()
	r := httptest.NewRequest("POST", "/inbox/x/delete", nil)
	r.SetPathValue("token", token)
	s.handleReviewDelete(w, r)
	if w.Code != http.StatusOK {
		t.Fatalf("delete status = %d", w.Code)
	}

	if used, _ := usedBytes(s.db); used != 0 {
		t.Errorf("quota still holds %d bytes after delete", used)
	}
	var n int
	if err := s.db.QueryRow(
		`SELECT COUNT(*) FROM submission WHERE audio IS NOT NULL`).Scan(&n); err != nil {
		t.Fatal(err)
	}
	if n != 0 {
		t.Error("audio survived the delete")
	}
	// The row itself stays, so the token cannot be told apart from one that
	// never existed.
	if err := s.db.QueryRow(`SELECT COUNT(*) FROM submission`).Scan(&n); err != nil {
		t.Fatal(err)
	}
	if n != 1 {
		t.Errorf("row count = %d, want the row to survive", n)
	}

	// Deleting twice is not an error the caller can learn from.
	w = httptest.NewRecorder()
	r = httptest.NewRequest("POST", "/inbox/x/delete", nil)
	r.SetPathValue("token", token)
	s.handleReviewDelete(w, r)
	if w.Code != http.StatusNotFound {
		t.Errorf("second delete status = %d, want 404", w.Code)
	}
}

// Seeking in the player depends on Range support.
func TestAudioSupportsRangeRequests(t *testing.T) {
	s := newTestServer(t)
	audio := m4aBytes(10_000)
	token := storeOne(t, s, audio)

	w := httptest.NewRecorder()
	r := httptest.NewRequest("GET", "/inbox/x/audio", nil)
	r.SetPathValue("token", token)
	r.Header.Set("Range", "bytes=100-199")
	s.handleReviewAudio(w, r)

	if w.Code != http.StatusPartialContent {
		t.Fatalf("status = %d, want 206", w.Code)
	}
	if got := w.Body.Len(); got != 100 {
		t.Errorf("served %d bytes, want 100", got)
	}
	if !strings.HasPrefix(w.Header().Get("Content-Range"), "bytes 100-199/") {
		t.Errorf("Content-Range = %q", w.Header().Get("Content-Range"))
	}
}

func TestAudioServesExactBytes(t *testing.T) {
	s := newTestServer(t)
	audio := m4aBytes(3000)
	token := storeOne(t, s, audio)

	w := httptest.NewRecorder()
	r := httptest.NewRequest("GET", "/inbox/x/audio", nil)
	r.SetPathValue("token", token)
	s.handleReviewAudio(w, r)

	if w.Code != http.StatusOK {
		t.Fatalf("status = %d", w.Code)
	}
	if got := w.Body.Bytes(); string(got) != string(audio) {
		t.Errorf("served %d bytes, stored %d", len(got), len(audio))
	}
	if ct := w.Header().Get("Content-Type"); ct != "audio/mp4" {
		t.Errorf("Content-Type = %q", ct)
	}
}

// Tokens must be unguessable and never repeat.
func TestTokensAreUniqueAndOpaque(t *testing.T) {
	seen := map[string]bool{}
	for i := 0; i < 500; i++ {
		tok, err := newToken()
		if err != nil {
			t.Fatal(err)
		}
		if seen[tok] {
			t.Fatalf("token repeated after %d draws", i)
		}
		seen[tok] = true
		if !plausibleToken(tok) {
			t.Fatalf("generated token %q fails its own validity check", tok)
		}
		if len(tok) < 40 {
			t.Fatalf("token %q is too short to be unguessable", tok)
		}
	}
}

func TestPlausibleTokenRejectsJunk(t *testing.T) {
	for _, bad := range []string{
		"", "abc", strings.Repeat("A", 10), strings.Repeat("A", 100),
		"../../etc/passwd", "' OR 1=1 --", strings.Repeat("!", 43),
	} {
		if plausibleToken(bad) {
			t.Errorf("plausibleToken(%q) = true", bad)
		}
	}
}

// Nothing in the store may offer a way to enumerate submissions; the mail is
// the only listing.
func TestNoListingRoute(t *testing.T) {
	s := newTestServer(t)
	storeOne(t, s, m4aBytes(100))
	storeOne(t, s, m4aBytes(100))

	mux := http.NewServeMux()
	mux.HandleFunc("POST /submit", s.handleSubmit)
	mux.HandleFunc("GET /submit", s.handleSubmitStatus)
	mux.HandleFunc("GET /inbox/{token}", s.handleReview)
	mux.HandleFunc("GET /inbox/{token}/", s.handleReview)
	mux.HandleFunc("GET /inbox/{token}/audio", s.handleReviewAudio)
	mux.HandleFunc("POST /inbox/{token}/delete", s.handleReviewDelete)

	for _, path := range []string{"/inbox", "/inbox/", "/", "/submissions", "/inbox/all"} {
		w := httptest.NewRecorder()
		mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
		if w.Code == http.StatusOK {
			t.Errorf("%s returned 200; there must be no listing", path)
		}
	}
}

// The status endpoint is public, so it must not reveal how much is stored or
// how many submissions exist.
func TestSubmitStatusLeaksNothing(t *testing.T) {
	s := newTestServer(t)
	token := storeOne(t, s, m4aBytes(12_345))

	w := httptest.NewRecorder()
	s.handleSubmitStatus(w, httptest.NewRequest("GET", "/submit", nil))
	body := w.Body.String()

	for _, leak := range []string{token, "12345", "usedBytes", "used"} {
		if strings.Contains(body, leak) {
			t.Errorf("status response leaks %q: %s", leak, body)
		}
	}
}

func TestDurationText(t *testing.T) {
	for ms, want := range map[int64]string{
		0:       "",
		65_000:  "1:05",
		600_000: "10:00",
		9_000:   "0:09",
	} {
		s := &Submission{}
		if ms > 0 {
			s.DurationMs.Valid = true
			s.DurationMs.Int64 = ms
		}
		if got := durationText(s); got != want {
			t.Errorf("durationText(%d) = %q, want %q", ms, got, want)
		}
	}
}

// The note comes from a stranger and is rendered into HTML.
func TestReviewEscapesSubmittedText(t *testing.T) {
	s := newTestServer(t)
	sub := &Submission{
		MIME:     "audio/mp4",
		Filename: `<img src=x onerror=alert(1)>.m4a`,
		Note:     `<script>alert("xss")</script>`,
	}
	if err := insertSubmission(s.db, sub, m4aBytes(100)); err != nil {
		t.Fatal(err)
	}
	body := getReview(t, s, sub.Token).Body.String()

	// The dangerous forms are the ones that survive as markup. The escaped
	// text still contains the substring "onerror=alert", which is harmless,
	// so the check has to be for an actual tag rather than for the payload.
	for _, danger := range []string{"<script", "<img "} {
		if strings.Contains(body, danger) {
			t.Errorf("submitted text produced live markup (%q):\n%s", danger, body)
		}
	}
	if !strings.Contains(body, "&lt;script&gt;") {
		t.Errorf("note is missing from the page entirely:\n%s", body)
	}
	if !strings.Contains(body, "&lt;img src=x") {
		t.Errorf("filename is missing from the page entirely:\n%s", body)
	}
}

func TestTranscriptStoredAndShown(t *testing.T) {
	s := newTestServer(t)
	token := storeOne(t, s, m4aBytes(100))
	if err := setTranscript(s.db, token, "hello from the transcript"); err != nil {
		t.Fatal(err)
	}
	body := getReview(t, s, token).Body.String()
	if !strings.Contains(body, "hello from the transcript") {
		t.Error("transcript not shown on the review page")
	}
}

// storeConsented puts a submission in the database with a consent flag of its
// own, which storeOne does not vary.
func storeConsented(t *testing.T, s *server, consented bool) string {
	t.Helper()
	sub := &Submission{MIME: "audio/mp4", Filename: "reply.m4a", Consented: consented}
	if err := insertSubmission(s.db, sub, m4aBytes(100)); err != nil {
		t.Fatalf("insertSubmission: %v", err)
	}
	return sub.Token
}

// A missing transcript has four causes and the page has to tell them apart.
//
// This is a regression test. A failed transcription used to render exactly what
// a successful-but-empty one did — the consent line and then nothing — so a
// submission whose transcription had died of an API error was indistinguishable
// from one that was simply waiting, and the reason existed only in a log that
// rotates and a mail that had already been sent.
func TestReviewDistinguishesEveryTranscriptState(t *testing.T) {
	s := newTestServer(t)

	notPermitted := storeConsented(t, s, false)

	transcribed := storeConsented(t, s, true)
	if err := setTranscript(s.db, transcribed, "hello from the transcript"); err != nil {
		t.Fatal(err)
	}

	failed := storeConsented(t, s, true)
	if err := setTranscriptError(s.db, failed, "prepayment credits are depleted"); err != nil {
		t.Fatal(err)
	}

	// Consented, nothing recorded either way: still running, or a row from
	// before there was a column to record a reason in.
	nothingYet := storeConsented(t, s, true)

	bodies := map[string]string{}
	for name, token := range map[string]string{
		"not permitted": notPermitted,
		"transcribed":   transcribed,
		"failed":        failed,
		"nothing yet":   nothingYet,
	} {
		w := getReview(t, s, token)
		if w.Code != http.StatusOK {
			t.Fatalf("%s: status = %d", name, w.Code)
		}
		// The token differs per submission and would make every page unique
		// on its own, which is not the distinction being tested.
		bodies[name] = strings.ReplaceAll(w.Body.String(), token, "TOKEN")
	}

	// The failure has to name its cause: "it failed" without the reason is
	// only marginally better than the silence this replaced.
	if !strings.Contains(bodies["failed"], "prepayment credits are depleted") {
		t.Errorf("the recorded reason is not on the page:\n%s", bodies["failed"])
	}
	// And it has to say nothing will pick it up again, because nothing will.
	if !strings.Contains(bodies["failed"], "not tried again") {
		t.Errorf("the page does not say the failure is final:\n%s", bodies["failed"])
	}
	if !strings.Contains(bodies["transcribed"], "hello from the transcript") {
		t.Errorf("transcript not shown:\n%s", bodies["transcribed"])
	}
	// A page must never carry both a transcript and a reason there is none.
	if strings.Contains(bodies["transcribed"], "Transcription failed") {
		t.Errorf("a transcribed submission claims it failed:\n%s", bodies["transcribed"])
	}
	// Nothing may be invented for the state that has nothing recorded.
	for _, unwanted := range []string{"Transcription failed", "not permitted"} {
		if strings.Contains(bodies["nothing yet"], unwanted) {
			t.Errorf("an unfinished transcription claims %q:\n%s", unwanted, bodies["nothing yet"])
		}
	}

	for a, ba := range bodies {
		for b, bb := range bodies {
			if a < b && ba == bb {
				t.Errorf("%q and %q render identically:\n%s", a, b, ba)
			}
		}
	}
}

// The reason comes from an API and is rendered into HTML like everything else
// that was not written here.
func TestReviewEscapesTranscriptError(t *testing.T) {
	s := newTestServer(t)
	token := storeConsented(t, s, true)
	if err := setTranscriptError(s.db, token, `<script>alert("boom")</script>`); err != nil {
		t.Fatal(err)
	}
	body := getReview(t, s, token).Body.String()
	if strings.Contains(body, "<script") {
		t.Errorf("a transcript error produced live markup:\n%s", body)
	}
	if !strings.Contains(body, "&lt;script&gt;") {
		t.Errorf("the reason is missing from the page entirely:\n%s", body)
	}
}

// The two columns answer the same question, so a row must never hold both.
func TestTranscriptClearsAnEarlierError(t *testing.T) {
	s := newTestServer(t)
	token := storeConsented(t, s, true)
	if err := setTranscriptError(s.db, token, "it went wrong once"); err != nil {
		t.Fatal(err)
	}
	if err := setTranscript(s.db, token, "and then it worked"); err != nil {
		t.Fatal(err)
	}
	sub, err := submissionByToken(s.db, token)
	if err != nil {
		t.Fatal(err)
	}
	if sub.TranscriptError.Valid {
		t.Errorf("transcript_error survived a successful transcription: %q",
			sub.TranscriptError.String)
	}
	if body := getReview(t, s, token).Body.String(); strings.Contains(body, "it went wrong once") {
		t.Errorf("the page shows a transcript and a stale failure:\n%s", body)
	}
}

// The message comes from a third party and is otherwise unbounded, in a
// database with a 50 MB ceiling.
func TestTranscriptErrorIsBounded(t *testing.T) {
	s := newTestServer(t)
	token := storeConsented(t, s, true)
	if err := setTranscriptError(s.db, token, strings.Repeat("x", 100_000)); err != nil {
		t.Fatal(err)
	}
	sub, err := submissionByToken(s.db, token)
	if err != nil {
		t.Fatal(err)
	}
	if got := len(sub.TranscriptError.String); got > transcriptErrorMax {
		t.Errorf("stored reason is %d bytes, want at most %d", got, transcriptErrorMax)
	}
}

func TestHumanBytes(t *testing.T) {
	for n, want := range map[int64]string{
		512:        "512 B",
		2048:       "2.0 kB",
		5 << 20:    "5.0 MB",
		11_672_176: "11.1 MB",
	} {
		if got := humanBytes(n); got != want {
			t.Errorf("humanBytes(%d) = %q, want %q", n, got, want)
		}
	}
}

var _ = fmt.Sprintf