this repo has no description
1package knotserver
2
3import (
4 "compress/gzip"
5 "crypto/hmac"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "html/template"
12 "net/http"
13 "path/filepath"
14 "strconv"
15 "strings"
16
17 "github.com/gliderlabs/ssh"
18 "github.com/go-chi/chi/v5"
19 "github.com/go-git/go-git/v5/plumbing"
20 "github.com/go-git/go-git/v5/plumbing/object"
21 "github.com/russross/blackfriday/v2"
22 "github.com/sotangled/tangled/knotserver/db"
23 "github.com/sotangled/tangled/knotserver/git"
24 "github.com/sotangled/tangled/types"
25)
26
27func (h *Handle) Index(w http.ResponseWriter, r *http.Request) {
28 w.Write([]byte("This is a knot, part of the wider Tangle network: https://tangled.sh"))
29}
30
31func (h *Handle) RepoIndex(w http.ResponseWriter, r *http.Request) {
32 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
33 l := h.l.With("path", path, "handler", "RepoIndex")
34
35 gr, err := git.Open(path, "")
36 if err != nil {
37 if errors.Is(err, plumbing.ErrReferenceNotFound) {
38 resp := types.RepoIndexResponse{
39 IsEmpty: true,
40 }
41 writeJSON(w, resp)
42 return
43 } else {
44 l.Error("opening repo", "error", err.Error())
45 notFound(w)
46 return
47 }
48 }
49 commits, err := gr.Commits()
50 if err != nil {
51 writeError(w, err.Error(), http.StatusInternalServerError)
52 l.Error("fetching commits", "error", err.Error())
53 return
54 }
55
56 var readmeContent template.HTML
57 for _, readme := range h.c.Repo.Readme {
58 ext := filepath.Ext(readme)
59 content, _ := gr.FileContent(readme)
60 if len(content) > 0 {
61 switch ext {
62 case ".md", ".mkd", ".markdown":
63 unsafe := blackfriday.Run(
64 []byte(content),
65 blackfriday.WithExtensions(blackfriday.CommonExtensions),
66 )
67 html := sanitize(unsafe)
68 readmeContent = template.HTML(html)
69 default:
70 safe := sanitize([]byte(content))
71 readmeContent = template.HTML(
72 fmt.Sprintf(`<pre>%s</pre>`, safe),
73 )
74 }
75 break
76 }
77 }
78
79 if readmeContent == "" {
80 l.Warn("no readme found")
81 }
82
83 mainBranch, err := gr.FindMainBranch(h.c.Repo.MainBranch)
84 if err != nil {
85 writeError(w, err.Error(), http.StatusInternalServerError)
86 l.Error("finding main branch", "error", err.Error())
87 return
88 }
89
90 if len(commits) >= 3 {
91 commits = commits[:3]
92 }
93 resp := types.RepoIndexResponse{
94 IsEmpty: false,
95 Ref: mainBranch,
96 Commits: commits,
97 Description: getDescription(path),
98 Readme: readmeContent,
99 }
100
101 writeJSON(w, resp)
102 return
103}
104
105func (h *Handle) RepoTree(w http.ResponseWriter, r *http.Request) {
106 treePath := chi.URLParam(r, "*")
107 ref := chi.URLParam(r, "ref")
108
109 l := h.l.With("handler", "RepoTree", "ref", ref, "treePath", treePath)
110
111 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
112 gr, err := git.Open(path, ref)
113 if err != nil {
114 notFound(w)
115 return
116 }
117
118 files, err := gr.FileTree(treePath)
119 if err != nil {
120 writeError(w, err.Error(), http.StatusInternalServerError)
121 l.Error("file tree", "error", err.Error())
122 return
123 }
124
125 data := make(map[string]any)
126 data["ref"] = ref
127 data["parent"] = treePath
128 data["desc"] = getDescription(path)
129 data["dotdot"] = filepath.Dir(treePath)
130
131 h.listFiles(files, data, w)
132 return
133}
134
135func (h *Handle) FileContent(w http.ResponseWriter, r *http.Request) {
136 var raw bool
137 if rawParam, err := strconv.ParseBool(r.URL.Query().Get("raw")); err == nil {
138 raw = rawParam
139 }
140
141 treePath := chi.URLParam(r, "*")
142 ref := chi.URLParam(r, "ref")
143
144 l := h.l.With("handler", "FileContent", "ref", ref, "treePath", treePath)
145
146 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
147 gr, err := git.Open(path, ref)
148 if err != nil {
149 notFound(w)
150 return
151 }
152
153 contents, err := gr.FileContent(treePath)
154 if err != nil {
155 writeError(w, err.Error(), http.StatusInternalServerError)
156 return
157 }
158 data := make(map[string]any)
159 data["ref"] = ref
160 data["desc"] = getDescription(path)
161 data["path"] = treePath
162
163 safe := sanitize([]byte(contents))
164
165 if raw {
166 h.showRaw(string(safe), w)
167 } else {
168 h.showFile(string(safe), data, w, l)
169 }
170}
171
172func (h *Handle) Archive(w http.ResponseWriter, r *http.Request) {
173 name := chi.URLParam(r, "name")
174 file := chi.URLParam(r, "file")
175
176 l := h.l.With("handler", "Archive", "name", name, "file", file)
177
178 // TODO: extend this to add more files compression (e.g.: xz)
179 if !strings.HasSuffix(file, ".tar.gz") {
180 notFound(w)
181 return
182 }
183
184 ref := strings.TrimSuffix(file, ".tar.gz")
185
186 // This allows the browser to use a proper name for the file when
187 // downloading
188 filename := fmt.Sprintf("%s-%s.tar.gz", name, ref)
189 setContentDisposition(w, filename)
190 setGZipMIME(w)
191
192 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
193 gr, err := git.Open(path, ref)
194 if err != nil {
195 notFound(w)
196 return
197 }
198
199 gw := gzip.NewWriter(w)
200 defer gw.Close()
201
202 prefix := fmt.Sprintf("%s-%s", name, ref)
203 err = gr.WriteTar(gw, prefix)
204 if err != nil {
205 // once we start writing to the body we can't report error anymore
206 // so we are only left with printing the error.
207 l.Error("writing tar file", "error", err.Error())
208 return
209 }
210
211 err = gw.Flush()
212 if err != nil {
213 // once we start writing to the body we can't report error anymore
214 // so we are only left with printing the error.
215 l.Error("flushing?", "error", err.Error())
216 return
217 }
218}
219
220func (h *Handle) Log(w http.ResponseWriter, r *http.Request) {
221 ref := chi.URLParam(r, "ref")
222 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
223
224 l := h.l.With("handler", "Log", "ref", ref, "path", path)
225
226 gr, err := git.Open(path, ref)
227 if err != nil {
228 notFound(w)
229 return
230 }
231
232 commits, err := gr.Commits()
233 if err != nil {
234 writeError(w, err.Error(), http.StatusInternalServerError)
235 l.Error("fetching commits", "error", err.Error())
236 return
237 }
238
239 // Get page parameters
240 page := 1
241 pageSize := 30
242
243 if pageParam := r.URL.Query().Get("page"); pageParam != "" {
244 if p, err := strconv.Atoi(pageParam); err == nil && p > 0 {
245 page = p
246 }
247 }
248
249 if pageSizeParam := r.URL.Query().Get("per_page"); pageSizeParam != "" {
250 if ps, err := strconv.Atoi(pageSizeParam); err == nil && ps > 0 {
251 pageSize = ps
252 }
253 }
254
255 // Calculate pagination
256 start := (page - 1) * pageSize
257 end := start + pageSize
258 total := len(commits)
259
260 if start >= total {
261 commits = []*object.Commit{}
262 } else {
263 if end > total {
264 end = total
265 }
266 commits = commits[start:end]
267 }
268
269 resp := types.RepoLogResponse{
270 Commits: commits,
271 Ref: ref,
272 Description: getDescription(path),
273 Log: true,
274 Total: total,
275 Page: page,
276 PerPage: pageSize,
277 }
278
279 writeJSON(w, resp)
280 return
281}
282
283func (h *Handle) Diff(w http.ResponseWriter, r *http.Request) {
284 ref := chi.URLParam(r, "ref")
285
286 l := h.l.With("handler", "Diff", "ref", ref)
287
288 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
289 gr, err := git.Open(path, ref)
290 if err != nil {
291 notFound(w)
292 return
293 }
294
295 diff, err := gr.Diff()
296 if err != nil {
297 writeError(w, err.Error(), http.StatusInternalServerError)
298 l.Error("getting diff", "error", err.Error())
299 return
300 }
301
302 resp := types.RepoCommitResponse{
303 Ref: ref,
304 Diff: diff,
305 }
306
307 writeJSON(w, resp)
308 return
309}
310
311func (h *Handle) Refs(w http.ResponseWriter, r *http.Request) {
312 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
313 l := h.l.With("handler", "Refs")
314
315 gr, err := git.Open(path, "")
316 if err != nil {
317 notFound(w)
318 return
319 }
320
321 tags, err := gr.Tags()
322 if err != nil {
323 // Non-fatal, we *should* have at least one branch to show.
324 l.Error("getting tags", "error", err.Error())
325 }
326
327 branches, err := gr.Branches()
328 if err != nil {
329 l.Error("getting branches", "error", err.Error())
330 writeError(w, err.Error(), http.StatusInternalServerError)
331 return
332 }
333
334 data := make(map[string]interface{})
335
336 data["branches"] = branches
337 data["tags"] = tags
338 data["desc"] = getDescription(path)
339
340 writeJSON(w, data)
341 return
342}
343
344func (h *Handle) Keys(w http.ResponseWriter, r *http.Request) {
345 l := h.l.With("handler", "Keys")
346
347 switch r.Method {
348 case http.MethodGet:
349 keys, err := h.db.GetAllPublicKeys()
350 if err != nil {
351 writeError(w, err.Error(), http.StatusInternalServerError)
352 l.Error("getting public keys", "error", err.Error())
353 return
354 }
355
356 data := make([]map[string]interface{}, 0)
357 for _, key := range keys {
358 j := key.JSON()
359 data = append(data, j)
360 }
361 writeJSON(w, data)
362 return
363
364 case http.MethodPut:
365 pk := db.PublicKey{}
366 if err := json.NewDecoder(r.Body).Decode(&pk); err != nil {
367 writeError(w, "invalid request body", http.StatusBadRequest)
368 return
369 }
370
371 _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pk.Key))
372 if err != nil {
373 writeError(w, "invalid pubkey", http.StatusBadRequest)
374 }
375
376 if err := h.db.AddPublicKey(pk); err != nil {
377 writeError(w, err.Error(), http.StatusInternalServerError)
378 l.Error("adding public key", "error", err.Error())
379 return
380 }
381
382 w.WriteHeader(http.StatusNoContent)
383 return
384 }
385}
386
387func (h *Handle) NewRepo(w http.ResponseWriter, r *http.Request) {
388 l := h.l.With("handler", "NewRepo")
389
390 data := struct {
391 Did string `json:"did"`
392 Name string `json:"name"`
393 }{}
394
395 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
396 writeError(w, "invalid request body", http.StatusBadRequest)
397 return
398 }
399
400 did := data.Did
401 name := data.Name
402
403 relativeRepoPath := filepath.Join(did, name)
404 repoPath := filepath.Join(h.c.Repo.ScanPath, relativeRepoPath)
405 err := git.InitBare(repoPath)
406 if err != nil {
407 l.Error("initializing bare repo", "error", err.Error())
408 writeError(w, err.Error(), http.StatusInternalServerError)
409 return
410 }
411
412 // add perms for this user to access the repo
413 err = h.e.AddRepo(did, ThisServer, relativeRepoPath)
414 if err != nil {
415 l.Error("adding repo permissions", "error", err.Error())
416 writeError(w, err.Error(), http.StatusInternalServerError)
417 return
418 }
419
420 w.WriteHeader(http.StatusNoContent)
421}
422
423func (h *Handle) AddMember(w http.ResponseWriter, r *http.Request) {
424 l := h.l.With("handler", "AddMember")
425
426 data := struct {
427 Did string `json:"did"`
428 }{}
429
430 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
431 writeError(w, "invalid request body", http.StatusBadRequest)
432 return
433 }
434
435 did := data.Did
436
437 if err := h.db.AddDid(did); err != nil {
438 l.Error("adding did", "error", err.Error())
439 writeError(w, err.Error(), http.StatusInternalServerError)
440 return
441 }
442
443 h.jc.UpdateDids([]string{did})
444 if err := h.e.AddMember(ThisServer, did); err != nil {
445 l.Error("adding member", "error", err.Error())
446 writeError(w, err.Error(), http.StatusInternalServerError)
447 return
448 }
449
450 if err := h.fetchAndAddKeys(r.Context(), did); err != nil {
451 l.Error("fetching and adding keys", "error", err.Error())
452 writeError(w, err.Error(), http.StatusInternalServerError)
453 return
454 }
455
456 w.WriteHeader(http.StatusNoContent)
457}
458
459func (h *Handle) AddRepoCollaborator(w http.ResponseWriter, r *http.Request) {
460 l := h.l.With("handler", "AddRepoCollaborator")
461
462 data := struct {
463 Did string `json:"did"`
464 }{}
465
466 ownerDid := chi.URLParam(r, "did")
467 repo := chi.URLParam(r, "name")
468
469 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
470 writeError(w, "invalid request body", http.StatusBadRequest)
471 return
472 }
473
474 if err := h.db.AddDid(data.Did); err != nil {
475 l.Error("adding did", "error", err.Error())
476 writeError(w, err.Error(), http.StatusInternalServerError)
477 return
478 }
479 h.jc.UpdateDids([]string{data.Did})
480
481 repoName := filepath.Join(ownerDid, repo)
482 if err := h.e.AddRepo(data.Did, ThisServer, repoName); err != nil {
483 l.Error("adding repo collaborator", "error", err.Error())
484 writeError(w, err.Error(), http.StatusInternalServerError)
485 return
486 }
487
488 if err := h.fetchAndAddKeys(r.Context(), data.Did); err != nil {
489 l.Error("fetching and adding keys", "error", err.Error())
490 writeError(w, err.Error(), http.StatusInternalServerError)
491 return
492 }
493
494 w.WriteHeader(http.StatusOK)
495}
496
497func (h *Handle) Init(w http.ResponseWriter, r *http.Request) {
498 l := h.l.With("handler", "Init")
499
500 if h.knotInitialized {
501 writeError(w, "knot already initialized", http.StatusConflict)
502 return
503 }
504
505 data := struct {
506 Did string `json:"did"`
507 }{}
508
509 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
510 l.Error("failed to decode request body", "error", err.Error())
511 writeError(w, "invalid request body", http.StatusBadRequest)
512 return
513 }
514
515 if data.Did == "" {
516 l.Error("empty DID in request", "did", data.Did)
517 writeError(w, "did is empty", http.StatusBadRequest)
518 return
519 }
520
521 if err := h.db.AddDid(data.Did); err != nil {
522 l.Error("failed to add DID", "error", err.Error())
523 writeError(w, err.Error(), http.StatusInternalServerError)
524 return
525 }
526
527 h.jc.UpdateDids([]string{data.Did})
528 if err := h.e.AddOwner(ThisServer, data.Did); err != nil {
529 l.Error("adding owner", "error", err.Error())
530 writeError(w, err.Error(), http.StatusInternalServerError)
531 return
532 }
533
534 if err := h.fetchAndAddKeys(r.Context(), data.Did); err != nil {
535 l.Error("fetching and adding keys", "error", err.Error())
536 writeError(w, err.Error(), http.StatusInternalServerError)
537 return
538 }
539
540 close(h.init)
541
542 mac := hmac.New(sha256.New, []byte(h.c.Server.Secret))
543 mac.Write([]byte("ok"))
544 w.Header().Add("X-Signature", hex.EncodeToString(mac.Sum(nil)))
545
546 w.WriteHeader(http.StatusNoContent)
547}
548
549func (h *Handle) Health(w http.ResponseWriter, r *http.Request) {
550 w.Write([]byte("ok"))
551}