BlueGit

timfa bluegit

Files

bluegit / internal / server / api.go

api.go

feat: nieuw-formulier, groepsoverzicht, logo's en talen
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
Failed d1203d3b History
api.go 5.5 KiB Download Raw
1package server
2
3import (
4 "encoding/json"
5 "io"
6 "net/http"
7 "os"
8 "path/filepath"
9 "strings"
10
11 "gitlab.com/Timfa/bluegit/internal/access"
12 "gitlab.com/Timfa/bluegit/internal/gitrepo"
13 "gitlab.com/Timfa/bluegit/internal/i18n"
14 "gitlab.com/Timfa/bluegit/internal/names"
15 "gitlab.com/Timfa/bluegit/internal/store"
16 "gitlab.com/Timfa/bluegit/internal/webhook"
17)
18
19type releaseRequest struct {
20 Tag string `json:"tag"`
21 Commit string `json:"commit"`
22 Name string `json:"name"`
23 Body string `json:"body"`
24 Assets []struct {
25 Job string `json:"job"`
26 Path string `json:"path"`
27 Name string `json:"name"`
28 } `json:"assets"`
29}
30
31func (s *Server) createRelease(w http.ResponseWriter, r *http.Request) {
32 if s.StoragePath() == "" {
33 http.Error(w, s.noStorageText(r), http.StatusServiceUnavailable)
34 return
35 }
36 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
37 if err != nil {
38 http.NotFound(w, r)
39 return
40 }
41 token := bearer(r)
42 var job store.Job
43 var author int64
44 if strings.HasPrefix(token, "bgj_") {
45 job, err = s.Store.JobByToken(r.Context(), token)
46 if err != nil || job.RepoID != repo.ID || job.Status != "running" {
47 http.Error(w, s.tr(r, "err.jobToken"), http.StatusUnauthorized)
48 return
49 }
50 } else if strings.HasPrefix(token, "bg_") {
51 u, err := s.Store.UserByToken(r.Context(), token)
52 if err != nil {
53 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
54 return
55 }
56 role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
57 if err != nil || !role.AtLeast(access.RoleMaintainer) {
58 http.Error(w, s.tr(r, "err.onlyAdmin"), http.StatusForbidden)
59 return
60 }
61 author = u.ID
62 } else {
63 http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)
64 return
65 }
66 var req releaseRequest
67 if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil {
68 http.Error(w, s.tr(r, "err.json"), http.StatusBadRequest)
69 return
70 }
71 if err := names.ValidTag(req.Tag); err != nil {
72 http.Error(w, s.trErr(r, err), http.StatusBadRequest)
73 return
74 }
75 if !safeSHA(req.Commit) {
76 http.Error(w, s.tr(r, "err.commitAbsent"), http.StatusBadRequest)
77 return
78 }
79 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
80 if !gitrepo.HasCommit(r.Context(), s.Git, dir, req.Commit) {
81 http.Error(w, s.tr(r, "err.commitMissing"), http.StatusBadRequest)
82 return
83 }
84 if req.Name == "" {
85 req.Name = req.Tag
86 }
87 if job.ID == 0 && len(req.Assets) > 0 {
88 http.Error(w, s.tr(r, "err.assetsJob"), http.StatusBadRequest)
89 return
90 }
91 var assets []store.ReleaseAsset
92 for _, a := range req.Assets {
93 if a.Name == "" {
94 a.Name = filepath.Base(a.Path)
95 }
96 if err := names.ValidRepoName(strings.ReplaceAll(a.Name, ".", "x")); err != nil && strings.Contains(a.Name, "..") {
97 http.Error(w, s.tr(r, "err.assetName"), http.StatusBadRequest)
98 return
99 }
100 if strings.Contains(a.Name, "/") || strings.Contains(a.Name, "..") || a.Path == "" {
101 http.Error(w, s.tr(r, "err.assetName"), http.StatusBadRequest)
102 return
103 }
104 src, err := s.Store.ArtifactPath(r.Context(), job.PipelineID, a.Job, a.Path)
105 if err != nil {
106 http.Error(w, s.tr(r, "err.artifactMissing", a.Job, a.Path), http.StatusBadRequest)
107 return
108 }
109 info, err := os.Stat(src)
110 if err != nil {
111 http.Error(w, s.tr(r, "err.assetDisk"), http.StatusBadRequest)
112 return
113 }
114 dst := filepath.Join(s.StoragePath(), "releases", repo.OwnerPath, repo.Name, req.Tag, a.Name)
115 if err := copyRelease(src, dst); err != nil {
116 http.Error(w, s.tr(r, "err.assetCopy"), http.StatusInternalServerError)
117 return
118 }
119 assets = append(assets, store.ReleaseAsset{Name: a.Name, StoragePath: dst, Size: info.Size()})
120 }
121 if err := gitrepo.Tag(r.Context(), s.Git, dir, req.Tag, req.Commit, req.Name); err != nil {
122 http.Error(w, s.tr(r, "err.tagFail", err.Error()), http.StatusBadRequest)
123 return
124 }
125 id, err := s.Store.CreateRelease(r.Context(), repo.ID, req.Tag, req.Commit, req.Name, req.Body, author, job.ID, assets)
126 if err != nil {
127 http.Error(w, s.trErr(r, err), http.StatusBadRequest)
128 return
129 }
130 s.Dispatch(repo.ID, webhook.Event{
131 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: req.Commit,
132 ReleaseTag: req.Tag, Summary: i18n.T(i18n.EN, "hook.release", req.Tag, repo.FullPath()),
133 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/releases",
134 })
135 w.Header().Set("Content-Type", "application/json")
136 w.WriteHeader(http.StatusCreated)
137 _ = json.NewEncoder(w).Encode(map[string]any{"id": id, "tag": req.Tag, "commit": req.Commit})
138}
139
140func (s *Server) releaseAsset(w http.ResponseWriter, r *http.Request) {
141 _, repo, _, ok := s.guard(w, r, access.RoleReadonly)
142 if !ok {
143 return
144 }
145 rel, err := s.Store.ReleaseByTag(r.Context(), repo.ID, r.PathValue("tag"))
146 if err != nil {
147 http.NotFound(w, r)
148 return
149 }
150 name := r.PathValue("name")
151 for _, a := range rel.Assets {
152 if a.Name == name {
153 w.Header().Set("Content-Disposition", "attachment; filename=\""+strings.ReplaceAll(name, "\"", "")+"\"")
154 http.ServeFile(w, r, a.StoragePath)
155 return
156 }
157 }
158 http.NotFound(w, r)
159}
160
161func bearer(r *http.Request) string {
162 h := r.Header.Get("Authorization")
163 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
164 return strings.TrimSpace(h[7:])
165 }
166 return ""
167}
168
169func copyRelease(src, dst string) error {
170 if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
171 return err
172 }
173 in, err := os.Open(src)
174 if err != nil {
175 return err
176 }
177 defer in.Close()
178 out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644)
179 if err != nil {
180 return err
181 }
182 defer out.Close()
183 _, err = io.Copy(out, in)
184 return err
185}