~gitpocket/gitpocket

4
9afcd8eac1635659eb7fea3c41a20790561c260d
mainfeed-discovery
gitpocket/flow_test.go -rw-r--r--7.9 KiB ViewLogBlameView rawPermalink 9afcd8eac1 feat(profile): link the workplace to its account 21 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
package main

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
)

func testServer(t *testing.T) (*Server, http.Handler) {
	t.Helper()
	root := t.TempDir()
	store, err := openStore(filepath.Join(root, "gitpocket.db"), false)
	if err != nil {
		t.Fatal(err)
	}
	s := newServer(store, root, "example.org", "gitpocket", "git")
	return s, s.handler()
}

func post(h http.Handler, path string, form url.Values, cookie string) *httptest.ResponseRecorder {
	r := httptest.NewRequest("POST", path, strings.NewReader(form.Encode()))
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Set("Sec-Fetch-Site", "same-origin")
	r.RemoteAddr = "192.0.2.1:1000"
	if cookie != "" {
		r.Header.Set("Cookie", "session="+cookie)
	}
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	return w
}

func get(h http.Handler, path, cookie string) *httptest.ResponseRecorder {
	r := httptest.NewRequest("GET", path, nil)
	r.RemoteAddr = "192.0.2.1:1000"
	if cookie != "" {
		r.Header.Set("Cookie", "session="+cookie)
	}
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	return w
}

func session(w *httptest.ResponseRecorder) string {
	for _, c := range w.Result().Cookies() {
		if c.Name == "session" {
			return c.Value
		}
	}
	return ""
}

func TestRegistrationModes(t *testing.T) {
	s, h := testServer(t)
	if w := post(h, "/register", url.Values{"name": {"alice"}, "password": {"correct horse"}}, ""); w.Code != http.StatusSeeOther || session(w) == "" {
		t.Fatalf("open registration failed: %d", w.Code)
	}
	s.store.SetSetting("registration", "invite")
	if w := post(h, "/register", url.Values{"name": {"bob"}, "password": {"correct horse"}}, ""); w.Code != 400 {
		t.Errorf("invite mode let bob in without a code: %d", w.Code)
	}
	code, _ := s.store.CreateInvite()
	if w := post(h, "/register", url.Values{"name": {"bob"}, "password": {"correct horse"}, "invite": {code}}, ""); w.Code != http.StatusSeeOther {
		t.Errorf("invite mode refused a valid code: %d", w.Code)
	}
	s.store.SetSetting("registration", "closed")
	if w := post(h, "/register", url.Values{"name": {"carol"}, "password": {"correct horse"}}, ""); w.Code != 403 {
		t.Errorf("closed mode allowed registration: %d", w.Code)
	}
	if w := get(h, "/", ""); strings.Contains(w.Body.String(), `href="/register"`) {
		t.Error("closed mode still links to registration")
	}
}

func TestLoginAndHeaders(t *testing.T) {
	s, h := testServer(t)
	s.store.CreateUser("alice", "correct horse")
	if w := post(h, "/login", url.Values{"name": {"alice"}, "password": {"wrong password"}}, ""); w.Code != 401 {
		t.Errorf("wrong password gave %d", w.Code)
	}
	w := post(h, "/login", url.Values{"name": {"alice"}, "password": {"correct horse"}}, "")
	if session(w) == "" {
		t.Fatal("login did not start a session")
	}
	for _, header := range []string{"Content-Security-Policy", "X-Frame-Options", "X-Content-Type-Options"} {
		if w.Header().Get(header) == "" {
			t.Errorf("missing %s", header)
		}
	}
}

func TestCrossOriginPostRefused(t *testing.T) {
	s, h := testServer(t)
	u, _ := s.store.CreateUser("alice", "correct horse")
	id, _ := s.store.CreateSession(u.ID)
	r := httptest.NewRequest("POST", "/settings/profile", strings.NewReader("display=pwned"))
	r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	r.Header.Set("Sec-Fetch-Site", "cross-site")
	r.Header.Set("Cookie", "session="+id)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	if w.Code != 403 || s.store.Profile(u.ID).Display == "pwned" {
		t.Errorf("cross site post accepted: %d", w.Code)
	}
}

func TestPermissions(t *testing.T) {
	s, h := testServer(t)
	alice, _ := s.store.CreateUser("alice", "correct horse")
	bob, _ := s.store.CreateUser("bob", "correct horse")
	secret, err := s.store.CreateRepo(alice, "secret", "", Private, "")
	if err != nil {
		t.Fatal(err)
	}
	os.MkdirAll(filepath.Dir(s.repoDir(secret)), 0o755)
	initRepo(s.repoDir(secret))
	if w := get(h, "/~alice/secret", ""); w.Code != 404 {
		t.Errorf("anonymous read of a private repo: %d", w.Code)
	}
	bobSession, _ := s.store.CreateSession(bob.ID)
	if w := get(h, "/~alice/secret", bobSession); w.Code != 404 {
		t.Errorf("stranger read a private repo: %d", w.Code)
	}
	if s.store.CanWrite(secret, &bob) {
		t.Error("stranger can write")
	}
	org, _ := s.store.CreateOrg("team")
	s.store.SetMember(org.ID, bob.ID, true)
	shared, _ := s.store.CreateRepo(org, "shared", "", Private, "")
	if !s.store.CanWrite(shared, &bob) || !s.store.Owns(shared, &bob) || s.store.CanWrite(shared, &alice) {
		t.Error("org membership not respected")
	}
	if _, ok := s.store.CheckPassword("team", ""); ok {
		t.Error("an organisation can log in")
	}
	if w := post(h, "/settings/profile", url.Values{"org": {"team"}, "display": {"x"}}, ""); w.Code != http.StatusSeeOther {
		t.Errorf("anonymous org edit not redirected to login: %d", w.Code)
	}
	aliceSession, _ := s.store.CreateSession(alice.ID)
	if w := post(h, "/settings/profile", url.Values{"org": {"team"}, "display": {"x"}}, aliceSession); w.Code != 403 {
		t.Errorf("non member edited an org: %d", w.Code)
	}
	s.store.AddRedirect("alice", "old", shared.ID)
	if w := get(h, "/~alice/old", ""); w.Code != 404 {
		t.Errorf("redirect leaked a private repo: %d", w.Code)
	}
	if w := get(h, "/~alice/old", bobSession); w.Code != http.StatusMovedPermanently || w.Header().Get("Location") != "/~team/shared" {
		t.Errorf("redirect for a member: %d %s", w.Code, w.Header().Get("Location"))
	}
	if w := get(h, "/admin", bobSession); w.Code != 404 {
		t.Errorf("admin page open to a normal user: %d", w.Code)
	}
}

func TestMergeStrategies(t *testing.T) {
	if _, err := exec.LookPath("git"); err != nil {
		t.Skip("git not installed")
	}
	dir := filepath.Join(t.TempDir(), "r.git")
	if err := initRepo(dir); err != nil {
		t.Fatal(err)
	}
	g := Git{Dir: dir}
	base := commitFile(t, g, "main", "", "a.txt", "one\n")
	feature := commitFile(t, g, "feature", base, "b.txt", "two\n")
	if !g.Mergeable("main", feature) {
		t.Fatal("clean merge reported as conflicting")
	}
	if _, err := g.Merge("main", feature, "merge", "T", "t@example.org"); err != nil {
		t.Fatal(err)
	}
	if _, err := g.Merge("main", feature, "merge", "T", "t@example.org"); err == nil {
		t.Error("merged the same head twice")
	}
	left := commitFile(t, g, "left", base, "a.txt", "left\n")
	right := commitFile(t, g, "right", base, "a.txt", "right\n")
	if _, err := g.mergeTree(base, left, right); err == nil {
		t.Error("conflict not detected")
	}
}

func commitFile(t *testing.T, g Git, branch, parent, name, content string) string {
	t.Helper()
	blob, err := g.run([]byte(content), "hash-object", "-w", "--stdin")
	if err != nil {
		t.Fatal(err)
	}
	index := filepath.Join(t.TempDir(), "index")
	env := []string{"GIT_INDEX_FILE=" + index}
	if parent != "" {
		g.runEnv(env, nil, "read-tree", parent)
	}
	if _, err := g.runEnv(env, nil, "update-index", "--add", "--cacheinfo", "100644,"+strings.TrimSpace(string(blob))+","+name); err != nil {
		t.Fatal(err)
	}
	tree, _ := g.runEnv(env, nil, "write-tree")
	args := []string{"commit-tree", strings.TrimSpace(string(tree))}
	if parent != "" {
		args = append(args, "-p", parent)
	}
	out, err := g.runEnv(ident("T", "t@example.org", timeNow()), []byte("c"), args...)
	if err != nil {
		t.Fatal(err)
	}
	hash := strings.TrimSpace(string(out))
	g.run(nil, "update-ref", "refs/heads/"+branch, hash)
	return hash
}

func TestWorkplaceLink(t *testing.T) {
	s, h := testServer(t)
	alice, _ := s.store.CreateUser("alice", "correct horse")
	s.store.CreateOrg("team")
	s.store.UpdateProfile(alice.ID, Profile{Workplace: "@Team"})
	if body := get(h, "/~alice", "").Body.String(); !strings.Contains(body, `<a href="/~team">@Team</a>`) {
		t.Error("workplace naming an org is not linked")
	}
	s.store.UpdateProfile(alice.ID, Profile{Workplace: "Nowhere Ltd"})
	if body := get(h, "/~alice", "").Body.String(); !strings.Contains(body, "Nowhere Ltd") || strings.Contains(body, `">Nowhere Ltd</a>`) {
		t.Error("unknown workplace should be plain text")
	}
}