~gitpocket/gitpocket

1
2ab005c6546c3764b9caa9d0d13f3b721d7873cc
mainfeed-discovery
gitpocket/edit.go -rw-r--r--7.6 KiB ViewLogBlameView rawPermalink 9055e1efa3 fix(security): escape readme link bases, validate branches and emails, strip header controls, add csp and throttling 4 hours 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
package main

import (
	"bufio"
	"errors"
	"fmt"
	"html/template"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
)

func installHook(root, dir string) {
	binary, err := os.Executable()
	if err != nil {
		return
	}
	hooks := filepath.Join(dir, "hooks")
	os.MkdirAll(hooks, 0o755)
	script := fmt.Sprintf("#!/bin/sh\nd=$(cd \"$(dirname \"$0\")/..\" && pwd)\nexec %s -root %s hook pre-receive \"$(basename \"$(dirname \"$d\")\")|$(basename \"$d\")\"\n", binary, root)
	os.WriteFile(filepath.Join(hooks, "pre-receive"), []byte(script), 0o755)
}

func (s *Server) installHooks() {
	owners, err := os.ReadDir(filepath.Join(s.root, "repos"))
	if err != nil {
		return
	}
	for _, o := range owners {
		repos, _ := os.ReadDir(filepath.Join(s.root, "repos", o.Name()))
		for _, r := range repos {
			if strings.HasSuffix(r.Name(), ".git") {
				installHook(s.root, filepath.Join(s.root, "repos", o.Name(), r.Name()))
			}
		}
	}
}

func hook(root, kind, spec string) int {
	if kind != "pre-receive" {
		return 0
	}
	owner, repoDir, ok := strings.Cut(spec, "|")
	if !ok {
		return 0
	}
	name := strings.TrimSuffix(repoDir, ".git")
	store, err := openStore(filepath.Join(root, "gitpocket.db"), true)
	if err != nil {
		fmt.Fprintln(os.Stderr, "gitpocket: database unavailable, push refused")
		return 1
	}
	repo, err := store.RepoByPath(owner, name)
	if err != nil {
		fmt.Fprintln(os.Stderr, "gitpocket: unknown repository, push refused")
		return 1
	}
	for _, kv := range os.Environ() {
		if strings.HasPrefix(kv, "GIT_OBJECT_DIRECTORY=") || strings.HasPrefix(kv, "GIT_ALTERNATE_OBJECT_DIRECTORIES=") || strings.HasPrefix(kv, "GIT_QUARANTINE_PATH=") {
			passEnv = append(passEnv, kv)
		}
	}
	g := Git{Dir: filepath.Join(root, "repos", owner, repoDir)}
	zero := strings.Repeat("0", 40)
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		f := strings.Fields(scanner.Text())
		if len(f) != 3 || !strings.HasPrefix(f[2], "refs/heads/") {
			continue
		}
		branch := strings.TrimPrefix(f[2], "refs/heads/")
		prot, ok := store.Protection(repo.ID, branch)
		if !ok {
			continue
		}
		if f[1] == zero {
			fmt.Fprintf(os.Stderr, "gitpocket: %s is protected and cannot be deleted\n", branch)
			return 1
		}
		if prot.RequirePR && f[0] != zero {
			fmt.Fprintf(os.Stderr, "gitpocket: %s only accepts changes through pull requests\n", branch)
			return 1
		}
		if f[0] != zero {
			if _, err := g.run(nil, "merge-base", "--is-ancestor", f[0], f[1]); err != nil {
				fmt.Fprintf(os.Stderr, "gitpocket: %s is protected, force pushes are refused\n", branch)
				return 1
			}
		}
	}
	return 0
}

func (g Git) Commit1(branch, parent, filePath string, content []byte, remove bool, message, name, email string) (string, error) {
	index, err := os.CreateTemp("", "gitpocket-index")
	if err != nil {
		return "", err
	}
	index.Close()
	defer os.Remove(index.Name())
	env := []string{"GIT_INDEX_FILE=" + index.Name()}
	if _, err := g.runEnv(env, nil, "read-tree", parent); err != nil {
		return "", err
	}
	if remove {
		if _, err := g.runEnv(env, []byte("0 "+strings.Repeat("0", 40)+"\t"+filePath+"\n"), "update-index", "--index-info"); err != nil {
			return "", err
		}
	} else {
		blob, err := g.run(content, "hash-object", "-w", "--stdin")
		if err != nil {
			return "", err
		}
		if _, err := g.runEnv(env, nil, "update-index", "--add", "--cacheinfo", "100644,"+strings.TrimSpace(string(blob))+","+filePath); err != nil {
			return "", err
		}
	}
	tree, err := g.runEnv(env, nil, "write-tree")
	if err != nil {
		return "", err
	}
	commit, err := g.runEnv(ident(name, email, timeNow()), []byte(message), "commit-tree", strings.TrimSpace(string(tree)), "-p", parent)
	if err != nil {
		return "", err
	}
	hash := strings.TrimSpace(string(commit))
	if _, err := g.run(nil, "update-ref", "refs/heads/"+branch, hash, parent); err != nil {
		return "", errors.New("the branch moved while you were editing, reload and try again")
	}
	return hash, nil
}

func (s *Server) editAllowed(w http.ResponseWriter, r *http.Request, repo Repo, branch string) (repoPage, Git, bool) {
	rp, g, err := s.repoPage(r, repo, branch)
	if err != nil {
		s.fail(w, r, 404, "No such branch")
		return rp, g, false
	}
	if rp.User == nil {
		http.Redirect(w, r, "/login", http.StatusSeeOther)
		return rp, g, false
	}
	if !rp.Owner {
		s.fail(w, r, 403, "You cannot write to this repository")
		return rp, g, false
	}
	if repo.Archived {
		s.fail(w, r, 403, "This repository is archived")
		return rp, g, false
	}
	if _, err := g.Resolve("refs/heads/" + branch); err != nil || !validBranch(branch) {
		s.fail(w, r, 404, "Edits need a branch, not a tag or commit")
		return rp, g, false
	}
	if prot, ok := s.store.Protection(repo.ID, branch); ok && prot.RequirePR {
		s.fail(w, r, 403, branch+" only accepts changes through pull requests")
		return rp, g, false
	}
	rp.Tab = "tree"
	return rp, g, true
}

func (s *Server) edit(w http.ResponseWriter, r *http.Request, repo Repo, spec string, create bool) {
	g := Git{Dir: s.repoDir(repo)}
	branch, filePath, ok := s.splitRef(g, spec)
	if !ok {
		s.fail(w, r, 404, "No such branch")
		return
	}
	filePath, ok = cleanPath(filePath)
	if !ok {
		s.fail(w, r, 404, "No such path")
		return
	}
	rp, g, ok := s.editAllowed(w, r, repo, branch)
	if !ok {
		return
	}
	data := map[string]any{"Page": rp, "Path": filePath, "Create": create, "Dir": filePath}
	if r.Method == "GET" {
		if !create {
			if g.Kind(rp.Commit, filePath) != "blob" {
				s.fail(w, r, 404, "No such file")
				return
			}
			content, err := g.Blob(rp.Commit, filePath)
			if err != nil || isBinary(content) || len(content) > maxRender {
				s.fail(w, r, 400, "Only text files under 4 MiB can be edited here")
				return
			}
			data["Content"] = string(content)
			data["Message"] = "Update " + path.Base(filePath)
		} else {
			data["Message"] = "Create "
		}
		s.render(w, r, "edit", page{Title: "Edit " + filePath, Data: data})
		return
	}
	target := filePath
	if create {
		name, ok := cleanPath(strings.TrimSpace(r.FormValue("name")))
		if !ok || name == "" {
			s.fail(w, r, 400, "Give the new file a name")
			return
		}
		target = path.Join(filePath, name)
		if g.Kind(rp.Commit, target) != "" {
			s.fail(w, r, 400, target+" already exists")
			return
		}
	}
	content := strings.ReplaceAll(r.FormValue("content"), "\r\n", "\n")
	message := strings.TrimSpace(r.FormValue("message"))
	if message == "" {
		message = "Update " + path.Base(target)
	}
	hash, err := g.Commit1(branch, rp.Commit, target, []byte(content), false, message, rp.User.Name, rp.User.Name+"@"+s.host)
	if err != nil {
		data["Content"], data["Message"], data["Name"] = r.FormValue("content"), message, r.FormValue("name")
		w.WriteHeader(400)
		s.render(w, r, "edit", page{Title: "Edit " + filePath, Error: err.Error(), Data: data})
		return
	}
	_ = hash
	http.Redirect(w, r, "/"+repo.Path()+"/tree/"+branch+"/"+target, http.StatusSeeOther)
}

func (s *Server) removeFile(w http.ResponseWriter, r *http.Request, repo Repo, spec string) {
	g := Git{Dir: s.repoDir(repo)}
	branch, filePath, ok := s.splitRef(g, spec)
	if !ok {
		s.fail(w, r, 404, "No such branch")
		return
	}
	filePath, ok = cleanPath(filePath)
	if !ok || filePath == "" {
		s.fail(w, r, 404, "No such path")
		return
	}
	rp, g, ok := s.editAllowed(w, r, repo, branch)
	if !ok {
		return
	}
	if g.Kind(rp.Commit, filePath) != "blob" {
		s.fail(w, r, 404, "No such file")
		return
	}
	if _, err := g.Commit1(branch, rp.Commit, filePath, nil, true, "Delete "+path.Base(filePath), rp.User.Name, rp.User.Name+"@"+s.host); err != nil {
		s.fail(w, r, 400, template.HTMLEscapeString(err.Error()))
		return
	}
	dir := path.Dir(filePath)
	if dir == "." {
		dir = ""
	}
	http.Redirect(w, r, "/"+repo.Path()+"/tree/"+branch+"/"+dir, http.StatusSeeOther)
}