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 data := make(map[string]interface{})
303
304 data["commit"] = diff.Commit
305 data["stat"] = diff.Stat
306 data["diff"] = diff.Diff
307 data["ref"] = ref
308 data["desc"] = getDescription(path)
309
310 writeJSON(w, data)
311 return
312}
313
314func (h *Handle) Refs(w http.ResponseWriter, r *http.Request) {
315 path := filepath.Join(h.c.Repo.ScanPath, didPath(r))
316 l := h.l.With("handler", "Refs")
317
318 gr, err := git.Open(path, "")
319 if err != nil {
320 notFound(w)
321 return
322 }
323
324 tags, err := gr.Tags()
325 if err != nil {
326 // Non-fatal, we *should* have at least one branch to show.
327 l.Error("getting tags", "error", err.Error())
328 }
329
330 branches, err := gr.Branches()
331 if err != nil {
332 l.Error("getting branches", "error", err.Error())
333 writeError(w, err.Error(), http.StatusInternalServerError)
334 return
335 }
336
337 data := make(map[string]interface{})
338
339 data["branches"] = branches
340 data["tags"] = tags
341 data["desc"] = getDescription(path)
342
343 writeJSON(w, data)
344 return
345}
346
347func (h *Handle) Keys(w http.ResponseWriter, r *http.Request) {
348 l := h.l.With("handler", "Keys")
349
350 switch r.Method {
351 case http.MethodGet:
352 keys, err := h.db.GetAllPublicKeys()
353 if err != nil {
354 writeError(w, err.Error(), http.StatusInternalServerError)
355 l.Error("getting public keys", "error", err.Error())
356 return
357 }
358
359 data := make([]map[string]interface{}, 0)
360 for _, key := range keys {
361 j := key.JSON()
362 data = append(data, j)
363 }
364 writeJSON(w, data)
365 return
366
367 case http.MethodPut:
368 pk := db.PublicKey{}
369 if err := json.NewDecoder(r.Body).Decode(&pk); err != nil {
370 writeError(w, "invalid request body", http.StatusBadRequest)
371 return
372 }
373
374 _, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pk.Key))
375 if err != nil {
376 writeError(w, "invalid pubkey", http.StatusBadRequest)
377 }
378
379 if err := h.db.AddPublicKey(pk); err != nil {
380 writeError(w, err.Error(), http.StatusInternalServerError)
381 l.Error("adding public key", "error", err.Error())
382 return
383 }
384
385 w.WriteHeader(http.StatusNoContent)
386 return
387 }
388}
389
390func (h *Handle) NewRepo(w http.ResponseWriter, r *http.Request) {
391 l := h.l.With("handler", "NewRepo")
392
393 data := struct {
394 Did string `json:"did"`
395 Name string `json:"name"`
396 }{}
397
398 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
399 writeError(w, "invalid request body", http.StatusBadRequest)
400 return
401 }
402
403 did := data.Did
404 name := data.Name
405
406 relativeRepoPath := filepath.Join(did, name)
407 repoPath := filepath.Join(h.c.Repo.ScanPath, relativeRepoPath)
408 err := git.InitBare(repoPath)
409 if err != nil {
410 l.Error("initializing bare repo", "error", err.Error())
411 writeError(w, err.Error(), http.StatusInternalServerError)
412 return
413 }
414
415 // add perms for this user to access the repo
416 err = h.e.AddRepo(did, ThisServer, relativeRepoPath)
417 if err != nil {
418 l.Error("adding repo permissions", "error", err.Error())
419 writeError(w, err.Error(), http.StatusInternalServerError)
420 return
421 }
422
423 w.WriteHeader(http.StatusNoContent)
424}
425
426func (h *Handle) AddMember(w http.ResponseWriter, r *http.Request) {
427 l := h.l.With("handler", "AddMember")
428
429 data := struct {
430 Did string `json:"did"`
431 }{}
432
433 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
434 writeError(w, "invalid request body", http.StatusBadRequest)
435 return
436 }
437
438 did := data.Did
439
440 if err := h.db.AddDid(did); err != nil {
441 l.Error("adding did", "error", err.Error())
442 writeError(w, err.Error(), http.StatusInternalServerError)
443 return
444 }
445
446 h.jc.UpdateDids([]string{did})
447 if err := h.e.AddMember(ThisServer, did); err != nil {
448 l.Error("adding member", "error", err.Error())
449 writeError(w, err.Error(), http.StatusInternalServerError)
450 return
451 }
452
453 if err := h.fetchAndAddKeys(r.Context(), did); err != nil {
454 l.Error("fetching and adding keys", "error", err.Error())
455 writeError(w, err.Error(), http.StatusInternalServerError)
456 return
457 }
458
459 w.WriteHeader(http.StatusNoContent)
460}
461
462func (h *Handle) AddRepoCollaborator(w http.ResponseWriter, r *http.Request) {
463 l := h.l.With("handler", "AddRepoCollaborator")
464
465 data := struct {
466 Did string `json:"did"`
467 }{}
468
469 ownerDid := chi.URLParam(r, "did")
470 repo := chi.URLParam(r, "name")
471
472 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
473 writeError(w, "invalid request body", http.StatusBadRequest)
474 return
475 }
476
477 if err := h.db.AddDid(data.Did); err != nil {
478 l.Error("adding did", "error", err.Error())
479 writeError(w, err.Error(), http.StatusInternalServerError)
480 return
481 }
482 h.jc.UpdateDids([]string{data.Did})
483
484 repoName := filepath.Join(ownerDid, repo)
485 if err := h.e.AddRepo(data.Did, ThisServer, repoName); err != nil {
486 l.Error("adding repo collaborator", "error", err.Error())
487 writeError(w, err.Error(), http.StatusInternalServerError)
488 return
489 }
490
491 if err := h.fetchAndAddKeys(r.Context(), data.Did); err != nil {
492 l.Error("fetching and adding keys", "error", err.Error())
493 writeError(w, err.Error(), http.StatusInternalServerError)
494 return
495 }
496
497 w.WriteHeader(http.StatusOK)
498}
499
500func (h *Handle) Init(w http.ResponseWriter, r *http.Request) {
501 l := h.l.With("handler", "Init")
502
503 if h.knotInitialized {
504 writeError(w, "knot already initialized", http.StatusConflict)
505 return
506 }
507
508 data := struct {
509 Did string `json:"did"`
510 }{}
511
512 if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
513 l.Error("failed to decode request body", "error", err.Error())
514 writeError(w, "invalid request body", http.StatusBadRequest)
515 return
516 }
517
518 if data.Did == "" {
519 l.Error("empty DID in request", "did", data.Did)
520 writeError(w, "did is empty", http.StatusBadRequest)
521 return
522 }
523
524 if err := h.db.AddDid(data.Did); err != nil {
525 l.Error("failed to add DID", "error", err.Error())
526 writeError(w, err.Error(), http.StatusInternalServerError)
527 return
528 }
529
530 h.jc.UpdateDids([]string{data.Did})
531 if err := h.e.AddOwner(ThisServer, data.Did); err != nil {
532 l.Error("adding owner", "error", err.Error())
533 writeError(w, err.Error(), http.StatusInternalServerError)
534 return
535 }
536
537 if err := h.fetchAndAddKeys(r.Context(), data.Did); err != nil {
538 l.Error("fetching and adding keys", "error", err.Error())
539 writeError(w, err.Error(), http.StatusInternalServerError)
540 return
541 }
542
543 close(h.init)
544
545 mac := hmac.New(sha256.New, []byte(h.c.Server.Secret))
546 mac.Write([]byte("ok"))
547 w.Header().Add("X-Signature", hex.EncodeToString(mac.Sum(nil)))
548
549 w.WriteHeader(http.StatusNoContent)
550}
551
552func (h *Handle) Health(w http.ResponseWriter, r *http.Request) {
553 w.Write([]byte("ok"))
554}