~bigbes/sr-ht-dolt

ref: 3b06523cff250c254af560c8a32c339d760ffc37 sr-ht-dolt/web/web_test.go -rw-r--r-- 36.2 KiB
3b06523c — Eugene Blikh web: offer the bd command for the issue on screen 5 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
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
package web

import (
	"context"
	"crypto/rand"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/dolthub/dolt/go/libraries/doltcore/creds"
	"github.com/go-chi/chi/v5"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"sourcecraft.dev/bigbes/sr-ht-core/auth"

	"sourcecraft.dev/bigbes/sr-ht-ecore/csrf"
	"sourcecraft.dev/bigbes/sr-ht-ecore/ecoretest"
	"sourcecraft.dev/bigbes/sr-ht-ecore/pages"

	"sourcecraft.dev/bigbes/sr-ht-dolt/authn"
	"sourcecraft.dev/bigbes/sr-ht-dolt/browse"
	"sourcecraft.dev/bigbes/sr-ht-dolt/core"
	"sourcecraft.dev/bigbes/sr-ht-dolt/db"
)

// selfOrigin is what the synthetic instance config gives this service, and so
// what the chrome and the same-origin guard read as ours.
var selfOrigin = ecoretest.Origin(serviceName)

// --- fakes -------------------------------------------------------------------

type fakeStore struct {
	repos     map[string]*core.Repo // key "owner/name"
	byID      map[int]*core.Repo
	acls      map[int]map[int]core.AccessMode // repoID -> userID -> mode
	keys      map[int][]*db.DoltKey           // userID -> keys
	nextID    int
	nextKeyID int

	createErr    error
	createdCalls []*core.Repo
	deletedRepos []int
}

func newFakeStore() *fakeStore {
	return &fakeStore{
		repos:     map[string]*core.Repo{},
		byID:      map[int]*core.Repo{},
		acls:      map[int]map[int]core.AccessMode{},
		keys:      map[int][]*db.DoltKey{},
		nextID:    1,
		nextKeyID: 1,
	}
}

func (f *fakeStore) add(r *core.Repo) *core.Repo {
	r.ID = f.nextID
	f.nextID++
	f.repos[r.OwnerName+"/"+r.Name] = r
	f.byID[r.ID] = r
	return r
}

func (f *fakeStore) CreateRepo(_ context.Context, r *core.Repo) (*core.Repo, error) {
	if f.createErr != nil {
		return nil, f.createErr
	}
	if _, ok := f.repos[r.OwnerName+"/"+r.Name]; ok {
		return nil, db.ErrNameTaken
	}
	cp := *r
	out := f.add(&cp)
	f.createdCalls = append(f.createdCalls, out)
	return out, nil
}

func (f *fakeStore) GetRepoByOwnerAndName(_ context.Context, owner, name string) (*core.Repo, error) {
	r, ok := f.repos[owner+"/"+name]
	if !ok {
		return nil, db.ErrNotFound
	}
	return r, nil
}

func (f *fakeStore) ListReposByOwner(_ context.Context, owner string, viewer *core.Caller) ([]*core.Repo, error) {
	var out []*core.Repo
	for _, r := range f.repos {
		if r.OwnerName != owner {
			continue
		}
		visible := r.Visibility == core.VisibilityPublic
		if viewer != nil && (viewer.UserID == r.OwnerID || f.hasACL(r.ID, viewer.UserID)) {
			visible = true
		}
		if visible {
			out = append(out, r)
		}
	}
	return out, nil
}

func (f *fakeStore) ListReposForDashboard(_ context.Context, userID int) ([]*core.Repo, error) {
	var out []*core.Repo
	for _, r := range f.byID {
		if r.OwnerID == userID || f.hasACL(r.ID, userID) {
			out = append(out, r)
		}
	}
	return out, nil
}

func (f *fakeStore) UpdateRepo(_ context.Context, id int, description string, visibility core.Visibility) error {
	r, ok := f.byID[id]
	if !ok {
		return db.ErrNotFound
	}
	r.Description = description
	r.Visibility = visibility
	return nil
}

func (f *fakeStore) DeleteRepo(_ context.Context, id int) error {
	r, ok := f.byID[id]
	if !ok {
		return db.ErrNotFound
	}
	delete(f.byID, id)
	delete(f.repos, r.OwnerName+"/"+r.Name)
	f.deletedRepos = append(f.deletedRepos, id)
	return nil
}

func (f *fakeStore) hasACL(repoID, userID int) bool {
	m, ok := f.acls[repoID]
	if !ok {
		return false
	}
	_, ok = m[userID]
	return ok
}

func (f *fakeStore) EffectiveAccess(_ context.Context, userID, repoID int) (*core.AccessMode, error) {
	m, ok := f.acls[repoID]
	if !ok {
		return nil, nil
	}
	mode, ok := m[userID]
	if !ok {
		return nil, nil
	}
	return &mode, nil
}

func (f *fakeStore) ListACL(_ context.Context, repoID int) ([]*db.ACLEntry, error) {
	var out []*db.ACLEntry
	for uid, mode := range f.acls[repoID] {
		out = append(out, &db.ACLEntry{RepoID: repoID, UserID: uid, Username: fmt.Sprintf("user%d", uid), Mode: mode})
	}
	return out, nil
}

func (f *fakeStore) UpsertACL(_ context.Context, repoID, userID int, mode core.AccessMode) error {
	if f.acls[repoID] == nil {
		f.acls[repoID] = map[int]core.AccessMode{}
	}
	f.acls[repoID][userID] = mode
	return nil
}

func (f *fakeStore) DeleteACL(_ context.Context, repoID, userID int) error {
	if !f.hasACL(repoID, userID) {
		return db.ErrNotFound
	}
	delete(f.acls[repoID], userID)
	return nil
}

func (f *fakeStore) InsertKey(_ context.Context, userID int, kid string, pubkey []byte, comment string) (*db.DoltKey, error) {
	for _, ks := range f.keys {
		for _, k := range ks {
			if k.KID == kid {
				return nil, db.ErrKeyExists
			}
		}
	}
	k := &db.DoltKey{ID: f.nextKeyID, UserID: userID, KID: kid, PubKey: pubkey, Comment: comment, Created: time.Now()}
	f.nextKeyID++
	f.keys[userID] = append(f.keys[userID], k)
	return k, nil
}

func (f *fakeStore) ListKeysByUser(_ context.Context, userID int) ([]*db.DoltKey, error) {
	return f.keys[userID], nil
}

func (f *fakeStore) DeleteKey(_ context.Context, id, userID int) error {
	ks := f.keys[userID]
	for i, k := range ks {
		if k.ID == id {
			f.keys[userID] = append(ks[:i], ks[i+1:]...)
			return nil
		}
	}
	return db.ErrNotFound
}

type fakeStoreManager struct {
	initErr     error
	initCalls   []string
	deleteCalls []string
	evictCalls  []string
}

func (m *fakeStoreManager) InitStore(_ context.Context, absPath, _, _ string) error {
	m.initCalls = append(m.initCalls, absPath)
	return m.initErr
}
func (m *fakeStoreManager) DeleteStore(_ context.Context, _, absPath string) error {
	m.deleteCalls = append(m.deleteCalls, absPath)
	return nil
}
func (m *fakeStoreManager) Evict(diskPath string) error {
	m.evictCalls = append(m.evictCalls, diskPath)
	return nil
}

type fakeSession struct {
	branches []browse.Branch
	commits  []browse.CommitInfo
	tables   []browse.TableInfo
	rows     *browse.RowPage
	// rowsByTable, when set, lets a test return a distinct page per table name
	// (as the beads view needs). A named miss falls back to rows. A table absent
	// from a non-nil map is reported as ErrTableNotFound, mirroring the store.
	rowsByTable map[string]*browse.RowPage
	summary     *browse.CommitDiff
	// logErr, when set, makes Log fail — a store whose history cannot be read,
	// which every page reading the log for decoration has to survive.
	logErr error
	closed bool
}

func (s *fakeSession) Branches(context.Context) ([]browse.Branch, error) { return s.branches, nil }
func (s *fakeSession) Log(_ context.Context, _, _ string, _ int) ([]browse.CommitInfo, string, error) {
	if s.logErr != nil {
		return nil, "", s.logErr
	}
	return s.commits, "", nil
}
func (s *fakeSession) Tables(_ context.Context, _ string) ([]browse.TableInfo, error) {
	return s.tables, nil
}
func (s *fakeSession) Rows(_ context.Context, _, table string, _, _ int) (*browse.RowPage, error) {
	if s.rowsByTable != nil {
		if p, ok := s.rowsByTable[table]; ok {
			return p, nil
		}
		return nil, fmt.Errorf("%w: %s", browse.ErrTableNotFound, table)
	}
	return s.rows, nil
}
func (s *fakeSession) CommitSummary(_ context.Context, _ string) (*browse.CommitDiff, error) {
	return s.summary, nil
}
func (s *fakeSession) Close() error { s.closed = true; return nil }

type fakeBrowse struct{ sess *fakeSession }

func (b *fakeBrowse) Open(context.Context, string) (BrowseSession, error) {
	if b.sess == nil {
		return &fakeSession{}, nil
	}
	return b.sess, nil
}

type fakeUsers struct {
	byName map[string]*core.Caller
}

func (u *fakeUsers) LookupUser(_ context.Context, username string) (*core.Caller, error) {
	c, ok := u.byName[username]
	if !ok {
		return nil, errors.New("no such user")
	}
	return c, nil
}

// --- harness -----------------------------------------------------------------

type harness struct {
	router chi.Router
	app    *app
	store  *fakeStore
	stores *fakeStoreManager
	browse *fakeBrowse
	users  *fakeUsers
}

func newHarness(t *testing.T) *harness {
	t.Helper()
	return newHarnessWithStatic(t, "")
}

// newHarnessWithStatic is newHarness for the tests that need a real static
// tree on disk — the asset routes, and the stylesheet the layout links.
func newHarnessWithStatic(t *testing.T, staticDir string) *harness {
	t.Helper()
	store := newFakeStore()
	stores := &fakeStoreManager{}
	fb := &fakeBrowse{}
	users := &fakeUsers{byName: map[string]*core.Caller{}}

	cfg := Config{
		Conf:      ecoretest.Config(serviceName),
		ReposRoot: "/var/lib/dolt",
		StaticDir: staticDir,
		Stores:    stores,
		Repos:     store,
		Browse:    fb,
		Users:     users,
		RepoDiskPath: func(owner, name string) string {
			return "/var/lib/dolt/~" + owner + "/" + name
		},
	}
	r := chi.NewRouter()
	a, err := newApp(cfg)
	if err != nil {
		t.Fatalf("newApp: %v", err)
	}
	a.mount(r)
	return &harness{router: r, app: a, store: store, stores: stores, browse: fb, users: users}
}

// do issues a request through the router, optionally with an authenticated
// caller injected into the context (as OptionalCookieMiddleware would).
func (h *harness) do(method, target string, caller *auth.AuthContext, form url.Values) *httptest.ResponseRecorder {
	var req *http.Request
	if form != nil {
		req = httptest.NewRequest(method, target, strings.NewReader(form.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Set("Origin", selfOrigin) // same-origin by default
	} else {
		req = httptest.NewRequest(method, target, nil)
	}
	if caller != nil {
		req = req.WithContext(authn.WithCaller(req.Context(), caller))
	}
	rec := httptest.NewRecorder()
	h.router.ServeHTTP(rec, req)
	return rec
}

func testCaller(id int, name string) *auth.AuthContext {
	return &auth.AuthContext{UserID: id, Username: name, UserType: auth.USER_TYPE_USER, Email: name + "@example.com"}
}

// validDoltPubKeyStr returns a 52-char base32 dolt public key (over 32 random
// bytes) in dolt's custom alphabet, exactly the shape `dolt login` emits.
func validDoltPubKeyStr(t *testing.T) string {
	t.Helper()
	pub := make([]byte, ed25519PubKeyLen)
	if _, err := rand.Read(pub); err != nil {
		t.Fatalf("rand: %v", err)
	}
	return creds.B32CredsEncoding.EncodeToString(pub)
}

// --- tests -------------------------------------------------------------------

func TestOverviewAnonymousPublicPrivate(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "pub", OwnerID: 1, OwnerName: "alice", Path: "/p", Visibility: core.VisibilityPublic})
	h.store.add(&core.Repo{Name: "sec", OwnerID: 1, OwnerName: "alice", Path: "/s", Visibility: core.VisibilityPrivate})

	if rec := h.do("GET", "/~alice/pub", nil, nil); rec.Code != http.StatusOK {
		t.Fatalf("public overview: got %d, want 200", rec.Code)
	}
	rec := h.do("GET", "/~alice/sec", nil, nil)
	if rec.Code != http.StatusNotFound {
		t.Fatalf("private overview anon: got %d, want 404", rec.Code)
	}
	if strings.Contains(rec.Body.String(), "sec") && strings.Contains(rec.Body.String(), "clone") {
		t.Fatalf("private repo leaked details to anonymous")
	}
}

func TestPrivateVisibleToOwner(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "sec", OwnerID: 7, OwnerName: "alice", Path: "/s", Visibility: core.VisibilityPrivate})
	rec := h.do("GET", "/~alice/sec", testCaller(7, "alice"), nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("owner private overview: got %d, want 200", rec.Code)
	}
}

func TestDashboardLists(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "mine", OwnerID: 3, OwnerName: "bob", Path: "/m", Visibility: core.VisibilityPrivate})

	rec := h.do("GET", "/", testCaller(3, "bob"), nil)
	if rec.Code != http.StatusOK {
		t.Fatalf("dashboard: got %d", rec.Code)
	}
	if !strings.Contains(rec.Body.String(), "~bob/mine") {
		t.Fatalf("dashboard missing owned repo; body=%s", rec.Body.String())
	}
	if !strings.Contains(rec.Body.String(), "/create") {
		t.Fatalf("dashboard missing create link")
	}

	// Anonymous dashboard shows the blurb, not the list.
	anon := h.do("GET", "/", nil, nil)
	if !strings.Contains(anon.Body.String(), "Log in") {
		t.Fatalf("anon dashboard missing login blurb")
	}
}

func TestCreateValidationAndSuccess(t *testing.T) {
	h := newHarness(t)
	caller := testCaller(5, "carol")

	// Anonymous create is redirected to login.
	if rec := h.do("GET", "/create", nil, nil); rec.Code != http.StatusSeeOther {
		t.Fatalf("anon create form: got %d, want 303", rec.Code)
	}

	// Invalid name.
	bad := h.do("POST", "/create", caller, url.Values{"name": {"bad name!"}, "visibility": {"PUBLIC"}})
	if bad.Code != http.StatusBadRequest {
		t.Fatalf("invalid name: got %d, want 400", bad.Code)
	}

	// Success.
	ok := h.do("POST", "/create", caller, url.Values{"name": {"gooddb"}, "visibility": {"PUBLIC"}, "description": {"hi"}})
	if ok.Code != http.StatusSeeOther {
		t.Fatalf("create success: got %d, want 303; body=%s", ok.Code, ok.Body.String())
	}
	if got := ok.Header().Get("Location"); got != "/~carol/gooddb" {
		t.Fatalf("create redirect: got %q", got)
	}
	if len(h.stores.initCalls) != 1 || h.stores.initCalls[0] != "/var/lib/dolt/~carol/gooddb" {
		t.Fatalf("InitStore not called correctly: %v", h.stores.initCalls)
	}
	if _, err := h.store.GetRepoByOwnerAndName(context.Background(), "carol", "gooddb"); err != nil {
		t.Fatalf("repo row not created: %v", err)
	}
}

func TestCreateStoreFailureRollsBackRow(t *testing.T) {
	h := newHarness(t)
	h.stores.initErr = errors.New("disk full")
	caller := testCaller(5, "carol")

	rec := h.do("POST", "/create", caller, url.Values{"name": {"gooddb"}, "visibility": {"PUBLIC"}})
	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("create with store failure: got %d, want 500", rec.Code)
	}
	if _, err := h.store.GetRepoByOwnerAndName(context.Background(), "carol", "gooddb"); !errors.Is(err, db.ErrNotFound) {
		t.Fatalf("orphan repo row survived store failure: %v", err)
	}
	if len(h.store.deletedRepos) != 1 {
		t.Fatalf("row not rolled back: %v", h.store.deletedRepos)
	}
}

// The same-origin guard is sr-ht-ecore's csrf middleware on the browser group,
// and no longer three per-handler calls. What is ours to test is that it is
// mounted over every mutating route — including the one whose handler used to
// carry the check and now does not — and that a request refusing to say where
// it came from is refused rather than waved through.
func TestMutationsAreRefusedWithoutSameOriginEvidence(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 10, OwnerName: "owner", Path: "/d", Visibility: core.VisibilityPublic})
	caller := testCaller(10, "owner")

	post := func(target, origin string, form url.Values) *httptest.ResponseRecorder {
		req := httptest.NewRequest("POST", target, strings.NewReader(form.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		if origin != "" {
			req.Header.Set("Origin", origin)
		}
		req = req.WithContext(authn.WithCaller(req.Context(), caller))
		rec := httptest.NewRecorder()
		h.router.ServeHTTP(rec, req)
		return rec
	}

	for _, tc := range []struct{ name, target string }{
		{"create", "/create"},
		{"keys", "/settings/keys"},
		{"settings", "/~owner/db/settings"},
	} {
		t.Run(tc.name+" cross-origin", func(t *testing.T) {
			rec := post(tc.target, "https://evil.example", url.Values{"name": {"x"}, "visibility": {"PUBLIC"}})
			require.Equal(t, http.StatusForbidden, rec.Code)
			assert.Contains(t, rec.Body.String(), csrf.Message)
		})
		t.Run(tc.name+" no headers", func(t *testing.T) {
			// Neither Origin nor Referer: a request that will not say where it
			// came from cannot be shown to have come from us.
			rec := post(tc.target, "", url.Values{"name": {"x"}, "visibility": {"PUBLIC"}})
			assert.Equal(t, http.StatusForbidden, rec.Code)
		})
	}
}

// TestFormsReadTheBodyAndOnlyTheBody pins the two properties every mutation on
// this surface now gets from pages.FormValues.
//
// The query string is not the form. r.Form would merge it into the body's
// values, which would let a mutation be driven entirely from a URL somebody was
// linked to — and that is exactly the request the same-origin guard sees nothing
// wrong with, because it really did come from our own page.
//
// And the body is bounded. net/http's own ceiling is 10 MiB per request, three
// orders of magnitude more than any form here sends.
func TestFormsReadTheBodyAndOnlyTheBody(t *testing.T) {
	post := func(t *testing.T, target string, body io.Reader) *httptest.ResponseRecorder {
		t.Helper()
		h := newHarness(t)
		h.store.add(&core.Repo{Name: "db", OwnerID: 10, OwnerName: "owner", Path: "/d", Visibility: core.VisibilityPublic})
		req := httptest.NewRequest("POST", target, body)
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.Header.Set("Origin", selfOrigin)
		req = req.WithContext(authn.WithCaller(req.Context(), testCaller(10, "owner")))
		rec := httptest.NewRecorder()
		h.router.ServeHTTP(rec, req)
		return rec
	}

	t.Run("the query string cannot supply a field", func(t *testing.T) {
		// A delete driven from the URL: the confirmation the body does not carry
		// is offered in the query string instead. It must not be read.
		rec := post(t, "/~owner/db/settings?action=delete&confirm_name=db", strings.NewReader(""))
		assert.Equal(t, http.StatusBadRequest, rec.Code)
		assert.Contains(t, rec.Body.String(), "Unknown action.")
	})

	t.Run("an oversized body is refused", func(t *testing.T) {
		huge := "description=" + strings.Repeat("x", pages.DefaultMaxFormBytes+1)
		rec := post(t, "/~owner/db/settings", strings.NewReader(huge))
		assert.Equal(t, http.StatusBadRequest, rec.Code)
		assert.Contains(t, rec.Body.String(), "Malformed form submission.")
	})
}

// Nothing behind the login cookie may be reused for the next viewer: these URLs
// say nothing about who the page was rendered for.
func TestPagesAreNotCacheable(t *testing.T) {
	h := newHarness(t)
	rec := h.do("GET", "/", testCaller(1, "alice"), nil)
	require.Equal(t, http.StatusOK, rec.Code)
	assert.Equal(t, "private, no-store", rec.Header().Get("Cache-Control"))
	assert.Equal(t, "Cookie, Authorization", rec.Header().Get("Vary"))
}

// panicView is a View whose Build panics, which is the only route into a
// handler panic this package can reach from a test.
type panicView struct{}

func (panicView) Name() string                    { return "boom" }
func (panicView) Label() string                   { return "Boom" }
func (panicView) Template() string                { return pages.ErrorPage + ".html" }
func (panicView) Applies([]browse.TableInfo) bool { return true }
func (panicView) Build(context.Context, BrowseSession, *core.Repo, string, url.Values) (any, error) {
	panic("the store went away")
}

// A panic before the response has started is answered with the error page every
// other bug gets, and the panic value stays in the log.
func TestAPanicBecomesTheErrorPage(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = &fakeSession{
		branches: []browse.Branch{{Name: "main", Head: "abcdef1234567890"}},
		tables:   issueTables(),
	}
	setViews(t, h, panicView{})

	rec := h.do("GET", "/~alice/db/view/boom", nil, nil)
	require.Equal(t, http.StatusInternalServerError, rec.Code)
	assert.Contains(t, rec.Body.String(), pages.InternalMessage)
	assert.NotContains(t, rec.Body.String(), "the store went away")
}

func TestSettingsOwnerGate(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 10, OwnerName: "owner", Path: "/d", Visibility: core.VisibilityPublic})

	// Anonymous → login redirect.
	if rec := h.do("GET", "/~owner/db/settings", nil, nil); rec.Code != http.StatusSeeOther {
		t.Fatalf("anon settings: got %d, want 303", rec.Code)
	}
	// Non-owner on a PUBLIC repo → 403.
	if rec := h.do("GET", "/~owner/db/settings", testCaller(99, "intruder"), nil); rec.Code != http.StatusForbidden {
		t.Fatalf("non-owner settings: got %d, want 403", rec.Code)
	}
	// Owner → 200.
	if rec := h.do("GET", "/~owner/db/settings", testCaller(10, "owner"), nil); rec.Code != http.StatusOK {
		t.Fatalf("owner settings: got %d, want 200", rec.Code)
	}
}

func TestSettingsNonOwnerPrivateIs404(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 10, OwnerName: "owner", Path: "/d", Visibility: core.VisibilityPrivate})
	rec := h.do("GET", "/~owner/db/settings", testCaller(99, "intruder"), nil)
	if rec.Code != http.StatusNotFound {
		t.Fatalf("non-owner private settings: got %d, want 404", rec.Code)
	}
}

func TestSettingsUpdateAndDelete(t *testing.T) {
	h := newHarness(t)
	repo := h.store.add(&core.Repo{Name: "db", OwnerID: 10, OwnerName: "owner", Path: "/var/lib/dolt/~owner/db", Visibility: core.VisibilityPublic})
	owner := testCaller(10, "owner")

	upd := h.do("POST", "/~owner/db/settings", owner, url.Values{"action": {"update"}, "description": {"new desc"}, "visibility": {"PRIVATE"}})
	if upd.Code != http.StatusOK {
		t.Fatalf("update: got %d", upd.Code)
	}
	if repo.Description != "new desc" || repo.Visibility != core.VisibilityPrivate {
		t.Fatalf("update not applied: %+v", repo)
	}

	// Delete requires a matching name confirmation.
	badDel := h.do("POST", "/~owner/db/settings", owner, url.Values{"action": {"delete"}, "confirm_name": {"wrong"}})
	if badDel.Code != http.StatusBadRequest {
		t.Fatalf("delete wrong confirm: got %d, want 400", badDel.Code)
	}
	del := h.do("POST", "/~owner/db/settings", owner, url.Values{"action": {"delete"}, "confirm_name": {"db"}})
	if del.Code != http.StatusSeeOther {
		t.Fatalf("delete: got %d, want 303", del.Code)
	}
	if len(h.stores.deleteCalls) != 1 || len(h.stores.evictCalls) != 1 {
		t.Fatalf("store delete/evict not called: del=%v evict=%v", h.stores.deleteCalls, h.stores.evictCalls)
	}
}

func TestSettingsACLAddRemove(t *testing.T) {
	h := newHarness(t)
	repo := h.store.add(&core.Repo{Name: "db", OwnerID: 10, OwnerName: "owner", Path: "/d", Visibility: core.VisibilityPublic})
	h.users.byName["dave"] = &core.Caller{UserID: 42, Username: "dave"}
	owner := testCaller(10, "owner")

	add := h.do("POST", "/~owner/db/settings", owner, url.Values{"action": {"acl_add"}, "username": {"dave"}, "mode": {"RW"}})
	if add.Code != http.StatusOK {
		t.Fatalf("acl add: got %d; body=%s", add.Code, add.Body.String())
	}
	if !h.store.hasACL(repo.ID, 42) {
		t.Fatalf("acl not added")
	}
	// Unknown user rejected.
	if bad := h.do("POST", "/~owner/db/settings", owner, url.Values{"action": {"acl_add"}, "username": {"ghost"}, "mode": {"RO"}}); bad.Code != http.StatusBadRequest {
		t.Fatalf("acl add unknown user: got %d, want 400", bad.Code)
	}

	rm := h.do("POST", "/~owner/db/settings", owner, url.Values{"action": {"acl_remove"}, "user_id": {"42"}})
	if rm.Code != http.StatusOK {
		t.Fatalf("acl remove: got %d", rm.Code)
	}
	if h.store.hasACL(repo.ID, 42) {
		t.Fatalf("acl not removed")
	}
}

func TestKeysAddDeleteAndFragmentPage(t *testing.T) {
	h := newHarness(t)
	caller := testCaller(11, "keyuser")

	// The page renders and contains the hash-fragment JS.
	page := h.do("GET", "/settings/keys", caller, nil)
	if page.Code != http.StatusOK {
		t.Fatalf("keys page: got %d", page.Code)
	}
	if !strings.Contains(page.Body.String(), "window.location.hash") {
		t.Fatalf("keys page missing hash-fragment JS")
	}

	// Add a key using a valid dolt base32 public key.
	pub := validDoltPubKeyStr(t)
	add := h.do("POST", "/settings/keys", caller, url.Values{"pubkey": {pub}, "comment": {"laptop"}})
	if add.Code != http.StatusOK {
		t.Fatalf("key add: got %d; body=%s", add.Code, add.Body.String())
	}
	keys, _ := h.store.ListKeysByUser(context.Background(), 11)
	if len(keys) != 1 {
		t.Fatalf("key not stored: %d", len(keys))
	}

	// Invalid key rejected.
	if bad := h.do("POST", "/settings/keys", caller, url.Values{"pubkey": {"not-base32-!!"}}); bad.Code != http.StatusBadRequest {
		t.Fatalf("invalid key: got %d, want 400", bad.Code)
	}

	// Delete.
	del := h.do("POST", "/settings/keys", caller, url.Values{"delete_id": {fmt.Sprint(keys[0].ID)}})
	if del.Code != http.StatusOK {
		t.Fatalf("key delete: got %d", del.Code)
	}
	if ks, _ := h.store.ListKeysByUser(context.Background(), 11); len(ks) != 0 {
		t.Fatalf("key not deleted")
	}
}

// What the nav contains — which services appear, in what order, which one is
// marked active, where the login link points — is sr-ht-ecore's chrome and is
// tested there. What is ours is that every page is drawn through it at all, and
// that the one page we ask to be full-bleed gets its own wrapper.
func TestPagesAreDrawnThroughTheSharedChrome(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = &fakeSession{
		branches: []browse.Branch{{Name: "main", Head: "abcdef1234567890"}},
		rows:     &browse.RowPage{Columns: []string{"id"}, Rows: [][]string{{"1"}}, Total: 1},
	}

	dash := h.do("GET", "/", testCaller(1, "someone"), nil)
	require.Equal(t, http.StatusOK, dash.Code)
	body := dash.Body.String()
	// The switcher and the brand come from the shared partials; the dolt label
	// is the red service suffix chrome derives from our config section.
	assert.Contains(t, body, "https://git.example", "shared switcher not rendered")
	assert.Contains(t, body, `<span class="text-danger">dolt</span>`, "brand label not rendered")
	// The default page width, which every page but the row browser keeps.
	assert.Contains(t, body, `<div class="container">`)

	rows := h.do("GET", "/~alice/db/table/main/things", nil, nil)
	require.Equal(t, http.StatusOK, rows.Code)
	assert.Contains(t, rows.Body.String(), `<div class="container-fluid">`,
		"the row browser must be full-bleed")
}

// The 404 and 403 templates this service carried are sr-ht-ecore's error page
// now: one body, drawn through our own chrome, with the shared sentence. The
// wording matters here — a 404 that described the missing thing would tell an
// anonymous viewer which private databases exist.
func TestRefusalsRenderTheSharedErrorPage(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 10, OwnerName: "owner", Path: "/d", Visibility: core.VisibilityPublic})

	missing := h.do("GET", "/~owner/nosuch", nil, nil)
	require.Equal(t, http.StatusNotFound, missing.Code)
	assert.Contains(t, missing.Body.String(), pages.NotFoundMessage)
	assert.Contains(t, missing.Body.String(), "404 &mdash; Not Found")
	assert.Contains(t, missing.Body.String(), `<span class="text-danger">dolt</span>`,
		"the error page is drawn through our chrome")

	denied := h.do("GET", "/~owner/db/settings", testCaller(99, "intruder"), nil)
	require.Equal(t, http.StatusForbidden, denied.Code)
	assert.Contains(t, denied.Body.String(), "Only the owner may change database settings.")
}

// TestRoutingRefusalsRenderTheSharedErrorPage covers the two refusals that never
// reach a handler at all — a path this router does not serve, and a method it
// does not allow. Both used to fall through to chi's net/http default: plain
// text, no chrome, no nav, and the only refusals on this instance that did not
// look like the service they came from.
func TestRoutingRefusalsRenderTheSharedErrorPage(t *testing.T) {
	h := newHarness(t)

	unrouted := h.do("GET", "/no/such/path", nil, nil)
	require.Equal(t, http.StatusNotFound, unrouted.Code)
	assert.Contains(t, unrouted.Body.String(), pages.NotFoundMessage)
	assert.Contains(t, unrouted.Body.String(), `<span class="text-danger">dolt</span>`,
		"an unrouted URL is answered through our chrome")

	// POST to a read-only route: routed, but not for this method.
	badMethod := h.do("POST", "/~alice/anything/log", nil, url.Values{})
	require.Equal(t, http.StatusMethodNotAllowed, badMethod.Code)
	assert.Contains(t, badMethod.Body.String(), pages.MethodMessage)
}

// TestReadRoutesAnswerHead walks the routing tree and requires every GET route
// to be registered for HEAD as well.
//
// It asks the tree rather than issuing requests because the tree is the record
// that matters: a middleware that rewrote the method per request would answer
// HEAD while chi's own 405 handler, built out of the methods that were
// registered, still said the route accepts GET alone. A read route that answers
// `curl -I` with a 405 and a kilobyte of error page is a route no monitor and no
// cache can revalidate cheaply.
func TestReadRoutesAnswerHead(t *testing.T) {
	h := newHarness(t)

	methods := map[string]map[string]bool{}
	require.NoError(t, chi.Walk(h.router,
		func(method, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
			if methods[route] == nil {
				methods[route] = map[string]bool{}
			}
			methods[route][method] = true
			return nil
		}))
	require.NotEmpty(t, methods)

	for route, served := range methods {
		if served[http.MethodGet] {
			assert.True(t, served[http.MethodHead], "%s serves GET but not HEAD", route)
		}
	}
}

// TestHeadOnAPrivateDatabaseIsStillNotFound: the HEAD twin shares the GET's
// handler, so it cannot answer 200 where the GET answers 404. That equivalence
// is what keeps HEAD from becoming a cheap existence oracle for somebody else's
// private database (SPEC ch. 6.3).
func TestHeadOnAPrivateDatabaseIsStillNotFound(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "sec", OwnerID: 1, OwnerName: "alice", Path: "/s", Visibility: core.VisibilityPrivate})
	h.store.add(&core.Repo{Name: "pub", OwnerID: 1, OwnerName: "alice", Path: "/p", Visibility: core.VisibilityPublic})

	assert.Equal(t, http.StatusNotFound, h.do("HEAD", "/~alice/sec", nil, nil).Code)
	assert.Equal(t, http.StatusNotFound, h.do("HEAD", "/~alice/nosuch", nil, nil).Code,
		"a private database and a missing one must be indistinguishable to HEAD too")
	assert.Equal(t, http.StatusOK, h.do("HEAD", "/~alice/pub", nil, nil).Code)
}

// leakyView renders a page whose content block reads a field its envelope does
// not carry, so executing it fails halfway. It is the shape of the bug the old
// renderer turned into a disclosure.
type leakyView struct{}

func (leakyView) Name() string                    { return "leaky" }
func (leakyView) Label() string                   { return "Leaky" }
func (leakyView) Template() string                { return "keys.html" }
func (leakyView) Applies([]browse.TableInfo) bool { return true }
func (leakyView) Build(context.Context, BrowseSession, *core.Repo, string, url.Values) (any, error) {
	return nil, nil
}

// A template that fails halfway answers a fixed sentence. The previous renderer
// wrote "template render error: "+err.Error() into the body, which hands the
// viewer the template's name and the field path that was not there; the error
// belongs in the log and nowhere else.
func TestATemplateFailureTellsTheViewerNothing(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = &fakeSession{
		branches: []browse.Branch{{Name: "main", Head: "abcdef1234567890"}},
		tables:   issueTables(),
	}
	setViews(t, h, leakyView{})

	rec := h.do("GET", "/~alice/db/view/leaky", nil, nil)
	require.Equal(t, http.StatusInternalServerError, rec.Code)

	body := rec.Body.String()
	assert.Equal(t, "internal server error\n", body)
	assert.NotContains(t, body, "keys.html", "the template name must not reach the viewer")
	assert.NotContains(t, body, "Keys", "the field path must not reach the viewer")
	assert.NotContains(t, body, "can't evaluate")
}

// The static tree is served by sr-ht-ecore's assets handler, which is tested
// there. What is ours is that we mounted it: that the hashed stylesheet this
// build produced is the one the layout links, that a name whose bytes cannot
// change under it is cacheable and one whose bytes can is not, and that
// /static/ answers a page rather than an inventory of the build.
func TestStaticTreeIsServedWithACachePolicyAndNoListing(t *testing.T) {
	dir := t.TempDir()
	require.NoError(t, os.WriteFile(filepath.Join(dir, "main.min.0badc0de.css"), []byte("body{}"), 0o644))
	require.NoError(t, os.WriteFile(filepath.Join(dir, "logo.svg"), []byte("<svg/>"), 0o644))

	h := newHarnessWithStatic(t, dir)

	hashed := h.do("GET", "/static/main.min.0badc0de.css", nil, nil)
	require.Equal(t, http.StatusOK, hashed.Code)
	assert.Equal(t, "public, max-age=31536000, immutable", hashed.Header().Get("Cache-Control"))
	assert.Empty(t, hashed.Header().Get("Vary"), "an immutable asset must not vary on the cookie")

	unhashed := h.do("GET", "/static/logo.svg", nil, nil)
	require.Equal(t, http.StatusOK, unhashed.Code)
	assert.Equal(t, "public, max-age=3600", unhashed.Header().Get("Cache-Control"))

	listing := h.do("GET", "/static/", nil, nil)
	assert.Equal(t, http.StatusNotFound, listing.Code, "the static tree must not publish a listing")
	assert.NotContains(t, listing.Body.String(), `<a href="logo.svg"`, "no directory entries")

	// The hashed name reaches the layout; the dev fallback does not, because
	// this tree has a hashed stylesheet.
	page := h.do("GET", "/", nil, nil)
	require.Equal(t, http.StatusOK, page.Code)
	assert.Contains(t, page.Body.String(), `href="/static/main.min.0badc0de.css"`)
}

// A working copy that has only run `make static/main.css` still gets a
// stylesheet; one that has built nothing links none at all rather than an href
// that 404s on every page load.
func TestStylesheetFallsBackToTheUnhashedBuildOnlyWhenItExists(t *testing.T) {
	dir := t.TempDir()
	require.NoError(t, os.WriteFile(filepath.Join(dir, "main.css"), []byte("body{}"), 0o644))

	dev := newHarnessWithStatic(t, dir).do("GET", "/", nil, nil)
	require.Equal(t, http.StatusOK, dev.Code)
	assert.Contains(t, dev.Body.String(), `href="/static/main.css"`)

	bare := newHarnessWithStatic(t, t.TempDir()).do("GET", "/", nil, nil)
	require.Equal(t, http.StatusOK, bare.Code)
	assert.NotContains(t, bare.Body.String(), `rel="stylesheet"`)
}

// The favicon is the chrome's href now, not a literal in the layout: our own
// logo when the build ships one, and ecore's built-in data: URI when it does
// not. The href used to be written into the template unconditionally, so a
// deployment without a static tree asked for a file that was not there once per
// page.
func TestFaviconIsOursWhenShippedAndTheBuiltInOtherwise(t *testing.T) {
	dir := t.TempDir()
	require.NoError(t, os.WriteFile(filepath.Join(dir, "logo.svg"), []byte("<svg/>"), 0o644))

	shipped := newHarnessWithStatic(t, dir).do("GET", "/", nil, nil)
	require.Equal(t, http.StatusOK, shipped.Code)
	assert.Contains(t, shipped.Body.String(), `rel="icon" href="/static/logo.svg"`)

	bare := newHarnessWithStatic(t, t.TempDir()).do("GET", "/", nil, nil)
	require.Equal(t, http.StatusOK, bare.Code)
	assert.Contains(t, bare.Body.String(), `rel="icon" href="data:`,
		"a build with no logo links the shared data: URI, never a 404")
	assert.NotContains(t, bare.Body.String(), `href="/static/logo.svg"`)
}

// The listing partial's Updated and Meta are optional in practice and not only
// in ecore's doc comment: this service has no timestamp in its schema, leaves
// both zero, and must get a card with no muted footer rather than "0001-01-01".
func TestDatabaseListingRendersNoTimestampBlock(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "pub", OwnerID: 1, OwnerName: "alice", Path: "/p", Visibility: core.VisibilityPublic})

	rec := h.do("GET", "/~alice", nil, nil)
	require.Equal(t, http.StatusOK, rec.Code)
	body := rec.Body.String()
	assert.Contains(t, body, "/~alice/pub")
	assert.NotContains(t, body, "0001-01-01", "a zero Updated must render nothing at all")
	assert.NotContains(t, body, `<small class="text-muted">`)
}

func TestLogAndTablePages(t *testing.T) {
	h := newHarness(t)
	h.store.add(&core.Repo{Name: "db", OwnerID: 1, OwnerName: "alice", Path: "/d", Visibility: core.VisibilityPublic})
	h.browse.sess = &fakeSession{
		branches: []browse.Branch{{Name: "main", Head: "abcdef1234567890"}},
		commits: []browse.CommitInfo{
			{Hash: "abcdef1234567890", Author: "alice", Message: "init", Date: time.Now().Add(-2 * time.Hour)},
		},
		rows: &browse.RowPage{Columns: []string{"id", "name"}, Rows: [][]string{{"1", "<b>x</b>"}}, Total: 1},
	}

	logRec := h.do("GET", "/~alice/db/log", nil, nil)
	if logRec.Code != http.StatusOK {
		t.Fatalf("log page: got %d", logRec.Code)
	}
	if !strings.Contains(logRec.Body.String(), "abcdef12") || !strings.Contains(logRec.Body.String(), "hours ago") {
		t.Fatalf("log page missing short hash / reltime; body=%s", logRec.Body.String())
	}

	tblRec := h.do("GET", "/~alice/db/table/main/things", nil, nil)
	if tblRec.Code != http.StatusOK {
		t.Fatalf("table page: got %d", tblRec.Code)
	}
	// html/template must escape the cell content.
	if strings.Contains(tblRec.Body.String(), "<b>x</b>") {
		t.Fatalf("table cell not HTML-escaped")
	}
	if !strings.Contains(tblRec.Body.String(), "&lt;b&gt;x&lt;/b&gt;") {
		t.Fatalf("table cell escaping wrong; body=%s", tblRec.Body.String())
	}
}