Monorepo for Tangled
tangled.org
1package knotserver
2
3import (
4 "compress/gzip"
5 "fmt"
6 "io"
7 "net/http"
8 "os"
9 "path/filepath"
10 "strings"
11
12 securejoin "github.com/cyphar/filepath-securejoin"
13 "github.com/go-chi/chi/v5"
14 "tangled.org/core/knotserver/git/service"
15)
16
17func (h *Knot) resolveRepoPath(r *http.Request) (string, string, error) {
18 did := chi.URLParam(r, "did")
19 name := chi.URLParam(r, "name")
20
21 if name == "" && strings.HasPrefix(did, "did:") {
22 repoPath, _, repoName, err := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, did)
23 if err != nil {
24 return "", "", fmt.Errorf("unknown repo DID: %w", err)
25 }
26 return repoPath, repoName, nil
27 }
28
29 alias, err := h.db.ResolveAlias(did, name)
30 if err == nil && alias != nil {
31 repoPath, _, _, resolveErr := h.db.ResolveRepoDIDOnDisk(h.c.Repo.ScanPath, alias.RepoDid)
32 if resolveErr == nil {
33 return repoPath, name, nil
34 }
35 }
36
37 repoPath, joinErr := securejoin.SecureJoin(h.c.Repo.ScanPath, filepath.Join(did, name))
38 if joinErr != nil {
39 return "", "", fmt.Errorf("repo not found: %w", joinErr)
40 }
41 if _, statErr := os.Stat(repoPath); statErr != nil {
42 return "", "", fmt.Errorf("repo not found: %w", statErr)
43 }
44 return repoPath, name, nil
45}
46
47func (h *Knot) repoNotFound(w http.ResponseWriter, r *http.Request) {
48 w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
49 w.WriteHeader(http.StatusNotFound)
50 fmt.Fprint(w, "repository not found\n")
51}
52
53func (h *Knot) InfoRefs(w http.ResponseWriter, r *http.Request) {
54 repoPath, name, err := h.resolveRepoPath(r)
55 if err != nil {
56 h.repoNotFound(w, r)
57 h.l.Error("git: failed to resolve repo path", "handler", "InfoRefs", "error", err)
58 return
59 }
60
61 cmd := service.ServiceCommand{
62 GitProtocol: r.Header.Get("Git-Protocol"),
63 Dir: repoPath,
64 Stdout: w,
65 }
66
67 serviceName := r.URL.Query().Get("service")
68 switch serviceName {
69 case "git-upload-pack":
70 w.Header().Set("Content-Type", "application/x-git-upload-pack-advertisement")
71 w.Header().Set("Connection", "Keep-Alive")
72 w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
73 w.WriteHeader(http.StatusOK)
74
75 if err := cmd.InfoRefs(); err != nil {
76 gitError(w, err.Error(), http.StatusInternalServerError)
77 h.l.Error("git: process failed", "handler", "InfoRefs", "service", serviceName, "error", err)
78 return
79 }
80 case "git-receive-pack":
81 h.RejectPush(w, r, name)
82 default:
83 gitError(w, fmt.Sprintf("service unsupported: '%s'", serviceName), http.StatusForbidden)
84 }
85}
86
87func (h *Knot) UploadArchive(w http.ResponseWriter, r *http.Request) {
88 repo, _, err := h.resolveRepoPath(r)
89 if err != nil {
90 h.repoNotFound(w, r)
91 h.l.Error("git: failed to resolve repo path", "handler", "UploadArchive", "error", err)
92 return
93 }
94
95 const expectedContentType = "application/x-git-upload-archive-request"
96 contentType := r.Header.Get("Content-Type")
97 if contentType != expectedContentType {
98 gitError(w, fmt.Sprintf("Expected Content-Type: '%s', but received '%s'.", expectedContentType, contentType), http.StatusUnsupportedMediaType)
99 }
100
101 var bodyReader io.ReadCloser = r.Body
102 if r.Header.Get("Content-Encoding") == "gzip" {
103 gzipReader, err := gzip.NewReader(r.Body)
104 if err != nil {
105 gitError(w, err.Error(), http.StatusInternalServerError)
106 h.l.Error("git: failed to create gzip reader", "handler", "UploadArchive", "error", err)
107 return
108 }
109 defer gzipReader.Close()
110 bodyReader = gzipReader
111 }
112
113 w.Header().Set("Content-Type", "application/x-git-upload-archive-result")
114
115 h.l.Info("git: executing git-upload-archive", "handler", "UploadArchive", "repo", repo)
116
117 cmd := service.ServiceCommand{
118 GitProtocol: r.Header.Get("Git-Protocol"),
119 Dir: repo,
120 Stdout: w,
121 Stdin: bodyReader,
122 }
123
124 w.WriteHeader(http.StatusOK)
125
126 if err := cmd.UploadArchive(); err != nil {
127 h.l.Error("git: failed to execute git-upload-pack", "handler", "UploadPack", "error", err)
128 return
129 }
130}
131
132func (h *Knot) UploadPack(w http.ResponseWriter, r *http.Request) {
133 repo, _, err := h.resolveRepoPath(r)
134 if err != nil {
135 h.repoNotFound(w, r)
136 h.l.Error("git: failed to resolve repo path", "handler", "UploadPack", "error", err)
137 return
138 }
139
140 const expectedContentType = "application/x-git-upload-pack-request"
141 contentType := r.Header.Get("Content-Type")
142 if contentType != expectedContentType {
143 gitError(w, fmt.Sprintf("Expected Content-Type: '%s', but received '%s'.", expectedContentType, contentType), http.StatusUnsupportedMediaType)
144 }
145
146 var bodyReader io.ReadCloser = r.Body
147 if r.Header.Get("Content-Encoding") == "gzip" {
148 gzipReader, err := gzip.NewReader(r.Body)
149 if err != nil {
150 gitError(w, err.Error(), http.StatusInternalServerError)
151 h.l.Error("git: failed to create gzip reader", "handler", "UploadPack", "error", err)
152 return
153 }
154 defer gzipReader.Close()
155 bodyReader = gzipReader
156 }
157
158 w.Header().Set("Content-Type", "application/x-git-upload-pack-result")
159 w.Header().Set("Connection", "Keep-Alive")
160 w.Header().Set("Cache-Control", "no-cache, max-age=0, must-revalidate")
161
162 h.l.Info("git: executing git-upload-pack", "handler", "UploadPack", "repo", repo)
163
164 cmd := service.ServiceCommand{
165 GitProtocol: r.Header.Get("Git-Protocol"),
166 Dir: repo,
167 Stdout: w,
168 Stdin: bodyReader,
169 }
170
171 w.WriteHeader(http.StatusOK)
172
173 if err := cmd.UploadPack(); err != nil {
174 h.l.Error("git: failed to execute git-upload-pack", "handler", "UploadPack", "error", err)
175 return
176 }
177}
178
179func (h *Knot) ReceivePack(w http.ResponseWriter, r *http.Request) {
180 _, name, err := h.resolveRepoPath(r)
181 if err != nil {
182 h.repoNotFound(w, r)
183 h.l.Error("git: failed to resolve repo path", "handler", "ReceivePack", "error", err)
184 return
185 }
186
187 h.RejectPush(w, r, name)
188}
189
190func (h *Knot) RejectPush(w http.ResponseWriter, r *http.Request, unqualifiedRepoName string) {
191 // A text/plain response will cause git to print each line of the body
192 // prefixed with "remote: ".
193 w.Header().Set("content-type", "text/plain; charset=UTF-8")
194 w.WriteHeader(http.StatusForbidden)
195
196 fmt.Fprintf(w, "Pushes are only supported over SSH.")
197
198 // If the appview gave us the repository owner's handle we can attempt to
199 // construct the correct ssh url.
200 ownerHandle := r.Header.Get("x-tangled-repo-owner-handle")
201 ownerHandle = strings.TrimPrefix(ownerHandle, "@")
202 if ownerHandle != "" && !strings.ContainsAny(ownerHandle, ":") {
203 hostname := h.c.Server.Hostname
204 if strings.Contains(hostname, ":") {
205 hostname = strings.Split(hostname, ":")[0]
206 }
207
208 if hostname == "knot1.tangled.sh" {
209 hostname = "tangled.sh"
210 }
211
212 fmt.Fprintf(w, " Try:\ngit remote set-url --push origin git@%s:%s/%s\n\n... and push again.", hostname, ownerHandle, unqualifiedRepoName)
213 }
214 fmt.Fprintf(w, "\n\n")
215}
216
217func isDir(path string) (bool, error) {
218 info, err := os.Stat(path)
219 if err == nil && info.IsDir() {
220 return true, nil
221 }
222 if os.IsNotExist(err) {
223 return false, nil
224 }
225 return false, err
226}
227
228func gitError(w http.ResponseWriter, msg string, status int) {
229 w.Header().Set("content-type", "text/plain; charset=UTF-8")
230 w.WriteHeader(status)
231 fmt.Fprintf(w, "%s\n", msg)
232}