Something went wrong. Try again.
forked from tangled.org/core
Something went wrong. Try again.
33 kB · 1361 lines
Go
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362package knotserver
import ( "compress/gzip" "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "log" "net/http" "net/url" "os" "path" "path/filepath" "strconv" "strings" "sync"
securejoin "github.com/cyphar/filepath-securejoin" "github.com/gliderlabs/ssh" "github.com/go-chi/chi/v5" "github.com/go-enry/go-enry/v2" gogit "github.com/go-git/go-git/v5" "github.com/go-git/go-git/v5/plumbing" "github.com/go-git/go-git/v5/plumbing/object" "tangled.sh/tangled.sh/core/knotserver/db" "tangled.sh/tangled.sh/core/knotserver/git" "tangled.sh/tangled.sh/core/patchutil" "tangled.sh/tangled.sh/core/types")
func (h *Handle) Index(w http.ResponseWriter, r *http.Request) { w.Write([]byte("This is a knot server. More info at https://tangled.sh"))}
func (h *Handle) Capabilities(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json")
capabilities := map[string]any{ "pull_requests": map[string]any{ "format_patch": true, "patch_submissions": true, "branch_submissions": true, "fork_submissions": true, }, }
jsonData, err := json.Marshal(capabilities) if err != nil { http.Error(w, "Failed to serialize JSON", http.StatusInternalServerError) return }
w.Write(jsonData)}
func (h *Handle) RepoIndex(w http.ResponseWriter, r *http.Request) { path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) l := h.l.With("path", path, "handler", "RepoIndex") ref := chi.URLParam(r, "ref") ref, _ = url.PathUnescape(ref)
gr, err := git.Open(path, ref) if err != nil { plain, err2 := git.PlainOpen(path) if err2 != nil { l.Error("opening repo", "error", err2.Error()) notFound(w) return } branches, _ := plain.Branches()
log.Println(err)
if errors.Is(err, plumbing.ErrReferenceNotFound) { resp := types.RepoIndexResponse{ IsEmpty: true, Branches: branches, } writeJSON(w, resp) return } else { l.Error("opening repo", "error", err.Error()) notFound(w) return } }
var ( commits []*object.Commit total int branches []types.Branch files []types.NiceTree tags []*git.TagReference )
var wg sync.WaitGroup errorsCh := make(chan error, 5)
wg.Add(1) go func() { defer wg.Done() cs, err := gr.Commits(0, 60) if err != nil { errorsCh <- fmt.Errorf("commits: %w", err) return } commits = cs }()
wg.Add(1) go func() { defer wg.Done() t, err := gr.TotalCommits() if err != nil { errorsCh <- fmt.Errorf("calculating total: %w", err) return } total = t }()
wg.Add(1) go func() { defer wg.Done() bs, err := gr.Branches() if err != nil { errorsCh <- fmt.Errorf("fetching branches: %w", err) return } branches = bs }()
wg.Add(1) go func() { defer wg.Done() ts, err := gr.Tags() if err != nil { errorsCh <- fmt.Errorf("fetching tags: %w", err) return } tags = ts }()
wg.Add(1) go func() { defer wg.Done() fs, err := gr.FileTree(r.Context(), "") if err != nil { errorsCh <- fmt.Errorf("fetching filetree: %w", err) return } files = fs }()
wg.Wait() close(errorsCh)
// show any errors for err := range errorsCh { l.Error("loading repo", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
rtags := []*types.TagReference{} for _, tag := range tags { tr := types.TagReference{ Tag: tag.TagObject(), }
tr.Reference = types.Reference{ Name: tag.Name(), Hash: tag.Hash().String(), }
if tag.Message() != "" { tr.Message = tag.Message() }
rtags = append(rtags, &tr) }
var readmeContent string var readmeFile string for _, readme := range h.c.Repo.Readme { content, _ := gr.FileContent(readme) if len(content) > 0 { readmeContent = string(content) readmeFile = readme } }
if ref == "" { mainBranch, err := gr.FindMainBranch() if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("finding main branch", "error", err.Error()) return } ref = mainBranch }
resp := types.RepoIndexResponse{ IsEmpty: false, Ref: ref, Commits: commits, Description: getDescription(path), Readme: readmeContent, ReadmeFileName: readmeFile, Files: files, Branches: branches, Tags: rtags, TotalCommits: total, }
writeJSON(w, resp) return}
func (h *Handle) RepoTree(w http.ResponseWriter, r *http.Request) { treePath := chi.URLParam(r, "*") ref := chi.URLParam(r, "ref") ref, _ = url.PathUnescape(ref)
l := h.l.With("handler", "RepoTree", "ref", ref, "treePath", treePath)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) gr, err := git.Open(path, ref) if err != nil { notFound(w) return }
files, err := gr.FileTree(r.Context(), treePath) if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("file tree", "error", err.Error()) return }
resp := types.RepoTreeResponse{ Ref: ref, Parent: treePath, Description: getDescription(path), DotDot: filepath.Dir(treePath), Files: files, }
writeJSON(w, resp) return}
func (h *Handle) BlobRaw(w http.ResponseWriter, r *http.Request) { treePath := chi.URLParam(r, "*") ref := chi.URLParam(r, "ref") ref, _ = url.PathUnescape(ref)
l := h.l.With("handler", "BlobRaw", "ref", ref, "treePath", treePath)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) gr, err := git.Open(path, ref) if err != nil { notFound(w) return }
contents, err := gr.RawContent(treePath) if err != nil { writeError(w, err.Error(), http.StatusBadRequest) l.Error("file content", "error", err.Error()) return }
mimeType := http.DetectContentType(contents)
// exception for svg if filepath.Ext(treePath) == ".svg" { mimeType = "image/svg+xml" }
if !strings.HasPrefix(mimeType, "image/") && !strings.HasPrefix(mimeType, "video/") { l.Error("attempted to serve non-image/video file", "mimetype", mimeType) writeError(w, "only image and video files can be accessed directly", http.StatusForbidden) return }
w.Header().Set("Cache-Control", "public, max-age=86400") // cache for 24 hours w.Header().Set("ETag", fmt.Sprintf("%x", sha256.Sum256(contents))) w.Header().Set("Content-Type", mimeType) w.Write(contents)}
func (h *Handle) Blob(w http.ResponseWriter, r *http.Request) { treePath := chi.URLParam(r, "*") ref := chi.URLParam(r, "ref") ref, _ = url.PathUnescape(ref)
l := h.l.With("handler", "Blob", "ref", ref, "treePath", treePath)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) gr, err := git.Open(path, ref) if err != nil { notFound(w) return }
var isBinaryFile bool = false contents, err := gr.FileContent(treePath) if errors.Is(err, git.ErrBinaryFile) { isBinaryFile = true } else if errors.Is(err, object.ErrFileNotFound) { notFound(w) return } else if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) return }
bytes := []byte(contents) // safe := string(sanitize(bytes)) sizeHint := len(bytes)
resp := types.RepoBlobResponse{ Ref: ref, Contents: string(bytes), Path: treePath, IsBinary: isBinaryFile, SizeHint: uint64(sizeHint), }
h.showFile(resp, w, l)}
func (h *Handle) Archive(w http.ResponseWriter, r *http.Request) { name := chi.URLParam(r, "name") file := chi.URLParam(r, "file")
l := h.l.With("handler", "Archive", "name", name, "file", file)
// TODO: extend this to add more files compression (e.g.: xz) if !strings.HasSuffix(file, ".tar.gz") { notFound(w) return }
ref := strings.TrimSuffix(file, ".tar.gz")
// This allows the browser to use a proper name for the file when // downloading filename := fmt.Sprintf("%s-%s.tar.gz", name, ref) setContentDisposition(w, filename) setGZipMIME(w)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) gr, err := git.Open(path, ref) if err != nil { notFound(w) return }
gw := gzip.NewWriter(w) defer gw.Close()
prefix := fmt.Sprintf("%s-%s", name, ref) err = gr.WriteTar(gw, prefix) if err != nil { // once we start writing to the body we can't report error anymore // so we are only left with printing the error. l.Error("writing tar file", "error", err.Error()) return }
err = gw.Flush() if err != nil { // once we start writing to the body we can't report error anymore // so we are only left with printing the error. l.Error("flushing?", "error", err.Error()) return }}
func (h *Handle) Log(w http.ResponseWriter, r *http.Request) { ref := chi.URLParam(r, "ref") ref, _ = url.PathUnescape(ref)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r))
l := h.l.With("handler", "Log", "ref", ref, "path", path)
gr, err := git.Open(path, ref) if err != nil { notFound(w) return }
// Get page parameters page := 1 pageSize := 30
if pageParam := r.URL.Query().Get("page"); pageParam != "" { if p, err := strconv.Atoi(pageParam); err == nil && p > 0 { page = p } }
if pageSizeParam := r.URL.Query().Get("per_page"); pageSizeParam != "" { if ps, err := strconv.Atoi(pageSizeParam); err == nil && ps > 0 { pageSize = ps } }
// convert to offset/limit offset := (page - 1) * pageSize limit := pageSize
commits, err := gr.Commits(offset, limit) if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("fetching commits", "error", err.Error()) return }
total := len(commits)
resp := types.RepoLogResponse{ Commits: commits, Ref: ref, Description: getDescription(path), Log: true, Total: total, Page: page, PerPage: pageSize, }
writeJSON(w, resp) return}
func (h *Handle) Diff(w http.ResponseWriter, r *http.Request) { ref := chi.URLParam(r, "ref") ref, _ = url.PathUnescape(ref)
l := h.l.With("handler", "Diff", "ref", ref)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) gr, err := git.Open(path, ref) if err != nil { notFound(w) return }
diff, err := gr.Diff() if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("getting diff", "error", err.Error()) return }
resp := types.RepoCommitResponse{ Ref: ref, Diff: diff, }
writeJSON(w, resp) return}
func (h *Handle) Tags(w http.ResponseWriter, r *http.Request) { path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) l := h.l.With("handler", "Refs")
gr, err := git.Open(path, "") if err != nil { notFound(w) return }
tags, err := gr.Tags() if err != nil { // Non-fatal, we *should* have at least one branch to show. l.Warn("getting tags", "error", err.Error()) }
rtags := []*types.TagReference{} for _, tag := range tags { tr := types.TagReference{ Tag: tag.TagObject(), }
tr.Reference = types.Reference{ Name: tag.Name(), Hash: tag.Hash().String(), }
if tag.Message() != "" { tr.Message = tag.Message() }
rtags = append(rtags, &tr) }
resp := types.RepoTagsResponse{ Tags: rtags, }
writeJSON(w, resp) return}
func (h *Handle) Branches(w http.ResponseWriter, r *http.Request) { path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r))
gr, err := git.PlainOpen(path) if err != nil { notFound(w) return }
branches, _ := gr.Branches()
resp := types.RepoBranchesResponse{ Branches: branches, }
writeJSON(w, resp) return}
func (h *Handle) Branch(w http.ResponseWriter, r *http.Request) { path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) branchName := chi.URLParam(r, "branch") branchName, _ = url.PathUnescape(branchName)
l := h.l.With("handler", "Branch")
gr, err := git.PlainOpen(path) if err != nil { notFound(w) return }
ref, err := gr.Branch(branchName) if err != nil { l.Error("getting branch", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
commit, err := gr.Commit(ref.Hash()) if err != nil { l.Error("getting commit object", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
defaultBranch, err := gr.FindMainBranch() isDefault := false if err != nil { l.Error("getting default branch", "error", err.Error()) // do not quit though } else if defaultBranch == branchName { isDefault = true }
resp := types.RepoBranchResponse{ Branch: types.Branch{ Reference: types.Reference{ Name: ref.Name().Short(), Hash: ref.Hash().String(), }, Commit: commit, IsDefault: isDefault, }, }
writeJSON(w, resp) return}
func (h *Handle) Keys(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "Keys")
switch r.Method { case http.MethodGet: keys, err := h.db.GetAllPublicKeys() if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("getting public keys", "error", err.Error()) return }
data := make([]map[string]any, 0) for _, key := range keys { j := key.JSON() data = append(data, j) } writeJSON(w, data) return
case http.MethodPut: pk := db.PublicKey{} if err := json.NewDecoder(r.Body).Decode(&pk); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
_, _, _, _, err := ssh.ParseAuthorizedKey([]byte(pk.Key)) if err != nil { writeError(w, "invalid pubkey", http.StatusBadRequest) }
if err := h.db.AddPublicKey(pk); err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("adding public key", "error", err.Error()) return }
w.WriteHeader(http.StatusNoContent) return }}
func (h *Handle) NewRepo(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "NewRepo")
data := struct { Did string `json:"did"` Name string `json:"name"` DefaultBranch string `json:"default_branch,omitempty"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
if data.DefaultBranch == "" { data.DefaultBranch = h.c.Repo.MainBranch }
did := data.Did name := data.Name defaultBranch := data.DefaultBranch
if err := validateRepoName(name); err != nil { l.Error("creating repo", "error", err.Error()) writeError(w, err.Error(), http.StatusBadRequest) return }
relativeRepoPath := filepath.Join(did, name) repoPath, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, relativeRepoPath) err := git.InitBare(repoPath, defaultBranch) if err != nil { l.Error("initializing bare repo", "error", err.Error()) if errors.Is(err, gogit.ErrRepositoryAlreadyExists) { writeError(w, "That repo already exists!", http.StatusConflict) return } else { writeError(w, err.Error(), http.StatusInternalServerError) return } }
// add perms for this user to access the repo err = h.e.AddRepo(did, ThisServer, relativeRepoPath) if err != nil { l.Error("adding repo permissions", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
w.WriteHeader(http.StatusNoContent)}
func (h *Handle) RepoForkAheadBehind(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "RepoForkSync")
data := struct { Did string `json:"did"` Source string `json:"source"` Name string `json:"name,omitempty"` HiddenRef string `json:"hiddenref"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
did := data.Did source := data.Source
if did == "" || source == "" { l.Error("invalid request body, empty did or name") w.WriteHeader(http.StatusBadRequest) return }
var name string if data.Name != "" { name = data.Name } else { name = filepath.Base(source) }
branch := chi.URLParam(r, "branch") branch, _ = url.PathUnescape(branch)
relativeRepoPath := filepath.Join(did, name) repoPath, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, relativeRepoPath)
gr, err := git.PlainOpen(repoPath) if err != nil { log.Println(err) notFound(w) return }
forkCommit, err := gr.ResolveRevision(branch) if err != nil { l.Error("error resolving ref revision", "msg", err.Error()) writeError(w, fmt.Sprintf("error resolving revision %s", branch), http.StatusBadRequest) return }
sourceCommit, err := gr.ResolveRevision(data.HiddenRef) if err != nil { l.Error("error resolving hidden ref revision", "msg", err.Error()) writeError(w, fmt.Sprintf("error resolving revision %s", data.HiddenRef), http.StatusBadRequest) return }
status := types.UpToDate if forkCommit.Hash.String() != sourceCommit.Hash.String() { isAncestor, err := forkCommit.IsAncestor(sourceCommit) if err != nil { log.Printf("error resolving whether %s is ancestor of %s: %s", branch, data.HiddenRef, err) return }
if isAncestor { status = types.FastForwardable } else { status = types.Conflict } }
w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(types.AncestorCheckResponse{Status: status})}
func (h *Handle) RepoLanguages(w http.ResponseWriter, r *http.Request) { path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) ref := chi.URLParam(r, "ref") ref, _ = url.PathUnescape(ref)
l := h.l.With("handler", "RepoLanguages")
gr, err := git.Open(path, ref) if err != nil { l.Error("opening repo", "error", err.Error()) notFound(w) return }
languageFileCount := make(map[string]int)
err = recurseEntireTree(r.Context(), gr, func(absPath string) { lang, safe := enry.GetLanguageByExtension(absPath) if len(lang) == 0 || !safe { content, _ := gr.FileContentN(absPath, 1024) if !safe { lang = enry.GetLanguage(absPath, content) } else { lang, _ = enry.GetLanguageByContent(absPath, content) if len(lang) == 0 { return } } }
v, ok := languageFileCount[lang] if ok { languageFileCount[lang] = v + 1 } else { languageFileCount[lang] = 1 } }, "") if err != nil { l.Error("failed to recurse file tree", "error", err.Error()) writeError(w, err.Error(), http.StatusNoContent) return }
resp := types.RepoLanguageResponse{Languages: languageFileCount}
writeJSON(w, resp) return}
func recurseEntireTree(ctx context.Context, git *git.GitRepo, callback func(absPath string), filePath string) error { files, err := git.FileTree(ctx, filePath) if err != nil { log.Println(err) return err }
for _, file := range files { absPath := path.Join(filePath, file.Name) if !file.IsFile { return recurseEntireTree(ctx, git, callback, absPath) } callback(absPath) }
return nil}
func (h *Handle) RepoForkSync(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "RepoForkSync")
data := struct { Did string `json:"did"` Source string `json:"source"` Name string `json:"name,omitempty"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
did := data.Did source := data.Source
if did == "" || source == "" { l.Error("invalid request body, empty did or name") w.WriteHeader(http.StatusBadRequest) return }
var name string if data.Name != "" { name = data.Name } else { name = filepath.Base(source) }
branch := chi.URLParam(r, "branch") branch, _ = url.PathUnescape(branch)
relativeRepoPath := filepath.Join(did, name) repoPath, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, relativeRepoPath)
gr, err := git.PlainOpen(repoPath) if err != nil { log.Println(err) notFound(w) return }
err = gr.Sync(branch) if err != nil { l.Error("error syncing repo fork", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
w.WriteHeader(http.StatusNoContent)}
func (h *Handle) RepoFork(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "RepoFork")
data := struct { Did string `json:"did"` Source string `json:"source"` Name string `json:"name,omitempty"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
did := data.Did source := data.Source
if did == "" || source == "" { l.Error("invalid request body, empty did or name") w.WriteHeader(http.StatusBadRequest) return }
var name string if data.Name != "" { name = data.Name } else { name = filepath.Base(source) }
relativeRepoPath := filepath.Join(did, name) repoPath, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, relativeRepoPath)
err := git.Fork(repoPath, source) if err != nil { l.Error("forking repo", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
// add perms for this user to access the repo err = h.e.AddRepo(did, ThisServer, relativeRepoPath) if err != nil { l.Error("adding repo permissions", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
w.WriteHeader(http.StatusNoContent)}
func (h *Handle) RemoveRepo(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "RemoveRepo")
data := struct { Did string `json:"did"` Name string `json:"name"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
did := data.Did name := data.Name
if did == "" || name == "" { l.Error("invalid request body, empty did or name") w.WriteHeader(http.StatusBadRequest) return }
relativeRepoPath := filepath.Join(did, name) repoPath, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, relativeRepoPath) err := os.RemoveAll(repoPath) if err != nil { l.Error("removing repo", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
w.WriteHeader(http.StatusNoContent)
}func (h *Handle) Merge(w http.ResponseWriter, r *http.Request) { path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r))
data := types.MergeRequest{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, err.Error(), http.StatusBadRequest) h.l.Error("git: failed to unmarshal json patch", "handler", "Merge", "error", err) return }
mo := &git.MergeOptions{ AuthorName: data.AuthorName, AuthorEmail: data.AuthorEmail, CommitBody: data.CommitBody, CommitMessage: data.CommitMessage, }
patch := data.Patch branch := data.Branch gr, err := git.Open(path, branch) if err != nil { notFound(w) return }
mo.FormatPatch = patchutil.IsFormatPatch(patch)
if err := gr.MergeWithOptions([]byte(patch), branch, mo); err != nil { var mergeErr *git.ErrMerge if errors.As(err, &mergeErr) { conflicts := make([]types.ConflictInfo, len(mergeErr.Conflicts)) for i, conflict := range mergeErr.Conflicts { conflicts[i] = types.ConflictInfo{ Filename: conflict.Filename, Reason: conflict.Reason, } } response := types.MergeCheckResponse{ IsConflicted: true, Conflicts: conflicts, Message: mergeErr.Message, } writeConflict(w, response) h.l.Error("git: merge conflict", "handler", "Merge", "error", mergeErr) } else { writeError(w, err.Error(), http.StatusBadRequest) h.l.Error("git: failed to merge", "handler", "Merge", "error", err.Error()) } return }
w.WriteHeader(http.StatusOK)}
func (h *Handle) MergeCheck(w http.ResponseWriter, r *http.Request) { path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r))
var data struct { Patch string `json:"patch"` Branch string `json:"branch"` }
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, err.Error(), http.StatusBadRequest) h.l.Error("git: failed to unmarshal json patch", "handler", "MergeCheck", "error", err) return }
patch := data.Patch branch := data.Branch gr, err := git.Open(path, branch) if err != nil { notFound(w) return }
err = gr.MergeCheck([]byte(patch), branch) if err == nil { response := types.MergeCheckResponse{ IsConflicted: false, } writeJSON(w, response) return }
var mergeErr *git.ErrMerge if errors.As(err, &mergeErr) { conflicts := make([]types.ConflictInfo, len(mergeErr.Conflicts)) for i, conflict := range mergeErr.Conflicts { conflicts[i] = types.ConflictInfo{ Filename: conflict.Filename, Reason: conflict.Reason, } } response := types.MergeCheckResponse{ IsConflicted: true, Conflicts: conflicts, Message: mergeErr.Message, } writeConflict(w, response) h.l.Error("git: merge conflict", "handler", "MergeCheck", "error", mergeErr.Error()) return } writeError(w, err.Error(), http.StatusInternalServerError) h.l.Error("git: failed to check merge", "handler", "MergeCheck", "error", err.Error())}
func (h *Handle) Compare(w http.ResponseWriter, r *http.Request) { rev1 := chi.URLParam(r, "rev1") rev1, _ = url.PathUnescape(rev1)
rev2 := chi.URLParam(r, "rev2") rev2, _ = url.PathUnescape(rev2)
l := h.l.With("handler", "Compare", "r1", rev1, "r2", rev2)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) gr, err := git.PlainOpen(path) if err != nil { notFound(w) return }
commit1, err := gr.ResolveRevision(rev1) if err != nil { l.Error("error resolving revision 1", "msg", err.Error()) writeError(w, fmt.Sprintf("error resolving revision %s", rev1), http.StatusBadRequest) return }
commit2, err := gr.ResolveRevision(rev2) if err != nil { l.Error("error resolving revision 2", "msg", err.Error()) writeError(w, fmt.Sprintf("error resolving revision %s", rev2), http.StatusBadRequest) return }
mergeBase, err := gr.MergeBase(commit1, commit2) if err != nil { l.Error("failed to find merge-base", "msg", err.Error()) writeError(w, "failed to calculate diff", http.StatusBadRequest) return }
rawPatch, formatPatch, err := gr.FormatPatch(mergeBase, commit2) if err != nil { l.Error("error comparing revisions", "msg", err.Error()) writeError(w, "error comparing revisions", http.StatusBadRequest) return }
writeJSON(w, types.RepoFormatPatchResponse{ Rev1: commit1.Hash.String(), Rev2: commit2.Hash.String(), FormatPatch: formatPatch, MergeBase: mergeBase.Hash.String(), Patch: rawPatch, }) return}
func (h *Handle) NewHiddenRef(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "NewHiddenRef")
forkRef := chi.URLParam(r, "forkRef") forkRef, _ = url.PathUnescape(forkRef)
remoteRef := chi.URLParam(r, "remoteRef") remoteRef, _ = url.PathUnescape(remoteRef)
path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r)) gr, err := git.PlainOpen(path) if err != nil { notFound(w) return }
err = gr.TrackHiddenRemoteRef(forkRef, remoteRef) if err != nil { l.Error("error tracking hidden remote ref", "msg", err.Error()) writeError(w, "error tracking hidden remote ref", http.StatusBadRequest) return }
w.WriteHeader(http.StatusNoContent) return}
func (h *Handle) AddMember(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "AddMember")
data := struct { Did string `json:"did"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
did := data.Did
if err := h.db.AddDid(did); err != nil { l.Error("adding did", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return } h.jc.AddDid(did)
if err := h.e.AddMember(ThisServer, did); err != nil { l.Error("adding member", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
if err := h.fetchAndAddKeys(r.Context(), did); err != nil { l.Error("fetching and adding keys", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
w.WriteHeader(http.StatusNoContent)}
func (h *Handle) AddRepoCollaborator(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "AddRepoCollaborator")
data := struct { Did string `json:"did"` }{}
ownerDid := chi.URLParam(r, "did") repo := chi.URLParam(r, "name")
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, "invalid request body", http.StatusBadRequest) return }
if err := h.db.AddDid(data.Did); err != nil { l.Error("adding did", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return } h.jc.AddDid(data.Did)
repoName, _ := securejoin.SecureJoin(ownerDid, repo) if err := h.e.AddCollaborator(data.Did, ThisServer, repoName); err != nil { l.Error("adding repo collaborator", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
if err := h.fetchAndAddKeys(r.Context(), data.Did); err != nil { l.Error("fetching and adding keys", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
w.WriteHeader(http.StatusNoContent)}
func (h *Handle) DefaultBranch(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "DefaultBranch") path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r))
gr, err := git.Open(path, "") if err != nil { notFound(w) return }
branch, err := gr.FindMainBranch() if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("getting default branch", "error", err.Error()) return }
writeJSON(w, types.RepoDefaultBranchResponse{ Branch: branch, })}
func (h *Handle) SetDefaultBranch(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "SetDefaultBranch") path, _ := securejoin.SecureJoin(h.c.Repo.ScanPath, didPath(r))
data := struct { Branch string `json:"branch"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { writeError(w, err.Error(), http.StatusBadRequest) return }
gr, err := git.PlainOpen(path) if err != nil { notFound(w) return }
err = gr.SetDefaultBranch(data.Branch) if err != nil { writeError(w, err.Error(), http.StatusInternalServerError) l.Error("setting default branch", "error", err.Error()) return }
w.WriteHeader(http.StatusNoContent)}
func (h *Handle) Init(w http.ResponseWriter, r *http.Request) { l := h.l.With("handler", "Init")
if h.knotInitialized { writeError(w, "knot already initialized", http.StatusConflict) return }
data := struct { Did string `json:"did"` }{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil { l.Error("failed to decode request body", "error", err.Error()) writeError(w, "invalid request body", http.StatusBadRequest) return }
if data.Did == "" { l.Error("empty DID in request", "did", data.Did) writeError(w, "did is empty", http.StatusBadRequest) return }
if err := h.db.AddDid(data.Did); err != nil { l.Error("failed to add DID", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return } h.jc.AddDid(data.Did)
if err := h.e.AddOwner(ThisServer, data.Did); err != nil { l.Error("adding owner", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
if err := h.fetchAndAddKeys(r.Context(), data.Did); err != nil { l.Error("fetching and adding keys", "error", err.Error()) writeError(w, err.Error(), http.StatusInternalServerError) return }
close(h.init)
mac := hmac.New(sha256.New, []byte(h.c.Server.Secret)) mac.Write([]byte("ok")) w.Header().Add("X-Signature", hex.EncodeToString(mac.Sum(nil)))
w.WriteHeader(http.StatusNoContent)}
func (h *Handle) Health(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok"))}
func validateRepoName(name string) error { // check for path traversal attempts if name == "." || name == ".." || strings.Contains(name, "/") || strings.Contains(name, "\\") { return fmt.Errorf("Repository name contains invalid path characters") }
// check for sequences that could be used for traversal when normalized if strings.Contains(name, "./") || strings.Contains(name, "../") || strings.HasPrefix(name, ".") || strings.HasSuffix(name, ".") { return fmt.Errorf("Repository name contains invalid path sequence") }
// then continue with character validation for _, char := range name { if !((char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || char == '-' || char == '_' || char == '.') { return fmt.Errorf("Repository name can only contain alphanumeric characters, periods, hyphens, and underscores") } }
// additional check to prevent multiple sequential dots if strings.Contains(name, "..") { return fmt.Errorf("Repository name cannot contain sequential dots") }
// if all checks pass return nil}