BlueGit

timfa bluegit

Files

bluegit / internal / server / selfupdate.go

selfupdate.go

fix: accepteer een checkout van een andere uid en toon het update-log
timfa project_87923614_bot_3aff574f6f98414b945a8799374f9092 · pushed by timfa · 3 weeks ago
71de6a16 History
selfupdate.go 5.0 KiB Download Raw
1package server
2
3import (
4 "context"
5 "encoding/json"
6 "io"
7 "net"
8 "net/http"
9 "strings"
10 "sync"
11 "time"
12
13 "gitlab.com/Timfa/bluegit/internal/i18n"
14 "gitlab.com/Timfa/bluegit/internal/update"
15)
16
17const (
18 updateLimit = 5
19 updateWindow = time.Minute
20 updateRunning = 30 * time.Minute
21)
22
23// UpdateView is de laatste self-update op de Info- en setup-pagina.
24type UpdateView struct {
25 When, SHA, Result, ResultLabel, Error string
26 Has bool
27}
28
29// UpdateStarter start de unit. Tests zetten een stub. Nil gebruikt systemctl.
30type UpdateStarter func(ctx context.Context, ref string) error
31
32type updateLimiter struct {
33 mu sync.Mutex
34 at map[string][]time.Time
35}
36
37func (l *updateLimiter) allow(ip string, now time.Time) bool {
38 l.mu.Lock()
39 defer l.mu.Unlock()
40 if l.at == nil {
41 l.at = map[string][]time.Time{}
42 }
43 cut := now.Add(-updateWindow)
44 keep := l.at[ip][:0]
45 for _, ts := range l.at[ip] {
46 if ts.After(cut) {
47 keep = append(keep, ts)
48 }
49 }
50 if len(keep) >= updateLimit {
51 l.at[ip] = keep
52 return false
53 }
54 l.at[ip] = append(keep, now)
55 return true
56}
57
58func (s *Server) selfUpdate(w http.ResponseWriter, r *http.Request) {
59 if !update.Enabled() {
60 http.NotFound(w, r)
61 return
62 }
63 if !s.updateHits.allow(clientIP(r), time.Now()) {
64 http.Error(w, "too many requests\n", http.StatusTooManyRequests)
65 return
66 }
67 if !update.Equal(update.Token(), bearer(r)) {
68 http.Error(w, "unauthorized\n", http.StatusUnauthorized)
69 return
70 }
71 ref, err := updateRef(r)
72 if err != nil {
73 http.Error(w, "bad request\n", http.StatusBadRequest)
74 return
75 }
76 if !update.ValidRef(ref) {
77 http.Error(w, "bad request\n", http.StatusBadRequest)
78 return
79 }
80 st, _ := update.ReadStatus(s.StateDir)
81 if update.FreshRunning(st, time.Now(), updateRunning) {
82 http.Error(w, "update already running\n", http.StatusConflict)
83 return
84 }
85 if err := update.WriteRequest(s.StateDir, ref); err != nil {
86 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
87 return
88 }
89 start := s.UpdateStarter
90 if start == nil {
91 start = func(ctx context.Context, _ string) error { return update.StartSystemd(ctx) }
92 }
93 if err := start(r.Context(), ref); err != nil {
94 _ = update.WriteStatus(s.StateDir, update.Status{
95 Time: time.Now().UTC().Format(time.RFC3339), SHA: ref, Result: "failed", Error: "start",
96 })
97 http.Error(w, "start failed\n", http.StatusBadGateway)
98 return
99 }
100 if s.Log != nil {
101 s.Log.Info("self-update gestart", "ref", ref)
102 }
103 w.Header().Set("Content-Type", "application/json; charset=utf-8")
104 w.WriteHeader(http.StatusAccepted)
105 _ = json.NewEncoder(w).Encode(map[string]string{"status": "accepted", "ref": ref})
106}
107
108func (s *Server) selfUpdateStatus(w http.ResponseWriter, r *http.Request) {
109 if !update.Enabled() {
110 http.NotFound(w, r)
111 return
112 }
113 if !update.Equal(update.Token(), bearer(r)) {
114 http.Error(w, "unauthorized\n", http.StatusUnauthorized)
115 return
116 }
117 running := 0
118 if s.Store != nil {
119 n, err := s.Store.CountRunningJobs(r.Context())
120 if err != nil {
121 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
122 return
123 }
124 running = n
125 }
126 st, err := update.ReadStatus(s.StateDir)
127 if err != nil {
128 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
129 return
130 }
131 logText, err := update.ReadLogTail(s.StateDir, update.LogTailLines)
132 if err != nil {
133 http.Error(w, "unavailable\n", http.StatusServiceUnavailable)
134 return
135 }
136 w.Header().Set("Content-Type", "application/json; charset=utf-8")
137 w.Header().Set("Cache-Control", "no-store")
138 var upd any
139 if st.Result != "" {
140 upd = st
141 }
142 body := map[string]any{
143 "running": running,
144 "status": st.Result,
145 "sha": st.SHA,
146 "started_at": st.Time,
147 "result": st.Result,
148 "log": logText,
149 "update": upd,
150 }
151 if st.Error != "" {
152 body["error"] = st.Error
153 }
154 _ = json.NewEncoder(w).Encode(body)
155}
156
157func updateRef(r *http.Request) (string, error) {
158 raw, err := io.ReadAll(io.LimitReader(r.Body, 4096))
159 if err != nil {
160 return "", err
161 }
162 if strings.TrimSpace(string(raw)) == "" {
163 return "", nil
164 }
165 var body struct {
166 Ref string `json:"ref"`
167 SHA string `json:"sha"`
168 }
169 if err := json.Unmarshal(raw, &body); err != nil {
170 return "", err
171 }
172 ref := strings.TrimSpace(body.Ref)
173 sha := strings.TrimSpace(body.SHA)
174 if ref != "" && sha != "" && ref != sha {
175 return "", errMismatch
176 }
177 if ref == "" {
178 ref = sha
179 }
180 return ref, nil
181}
182
183var errMismatch = errString("ref")
184
185type errString string
186
187func (e errString) Error() string { return string(e) }
188
189func clientIP(r *http.Request) string {
190 host, _, err := net.SplitHostPort(r.RemoteAddr)
191 if err != nil {
192 return r.RemoteAddr
193 }
194 return host
195}
196
197func (s *Server) attachUpdate(v *View, lang i18n.Lang) {
198 if v.User == nil || !v.User.InstanceAdmin {
199 return
200 }
201 v.ShowUpdate = true
202 st, err := update.ReadStatus(s.StateDir)
203 if err != nil || st.Result == "" {
204 return
205 }
206 label := i18n.T(lang, "update.result."+st.Result)
207 if label == "update.result."+st.Result {
208 label = st.Result
209 }
210 v.Update = &UpdateView{
211 When: st.Time, SHA: st.SHA, Result: st.Result, ResultLabel: label, Error: st.Error, Has: true,
212 }
213}