BlueGit

timfa bluegit

Files

bluegit / internal / backupserver / server / actions.go

actions.go

actions.go 13.8 KiB Download Raw
1package server
2
3import (
4 "context"
5 "crypto/subtle"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "net/http"
11 "sort"
12 "strconv"
13 "strings"
14
15 "git.timfalken.com/timfa/bluegit-backup/internal/archive"
16 "git.timfalken.com/timfa/bluegit-backup/internal/config"
17 "git.timfalken.com/timfa/bluegit-backup/internal/mirror"
18 "git.timfalken.com/timfa/bluegit-backup/internal/protocol"
19)
20
21// Input is de invoer van een actie: JSON-velden, querystring, formulier of
22// padwaarden, allemaal als tekst.
23type Input map[string]string
24
25// Action is één beheerhandeling. De API, de webinterface en BlueGit lopen
26// allemaal via deze lijst, zodat ze precies hetzelfde kunnen.
27type Action struct {
28 // Name is de naam in de webinterface (/ui/act/<name>).
29 Name string `json:"name"`
30 Method string `json:"method"`
31 Path string `json:"path"`
32 // Title is de knoptekst of beschrijving.
33 Title string `json:"title"`
34 // Signed: ook de gekoppelde BlueGit mag dit (ondertekend verzoek).
35 Signed bool `json:"bluegit"`
36 // Params zijn de padwaarden, bijvoorbeeld {name}.
37 Params []string `json:"params,omitempty"`
38 // Fields zijn de invoervelden (documentatie en de lijst in /api/v1/admin/actions).
39 Fields []string `json:"fields,omitempty"`
40 Do func(ctx context.Context, in Input) (int, any) `json:"-"`
41}
42
43// fileResult laat de API een bestand sturen in plaats van JSON.
44type fileResult struct{ path, name string }
45
46func errBody(err error) map[string]string { return map[string]string{"error": err.Error()} }
47
48// Actions is de volledige lijst met beheerhandelingen.
49func (s *Server) Actions() []Action {
50 return []Action{
51 {Name: "status", Method: "GET", Path: "/api/v1/admin/status", Title: "Status", Signed: true,
52 Do: func(ctx context.Context, in Input) (int, any) { return 200, s.Status() }},
53 {Name: "actions", Method: "GET", Path: "/api/v1/admin/actions", Title: "Alle acties", Signed: true,
54 Do: func(ctx context.Context, in Input) (int, any) { return 200, map[string]any{"actions": s.Actions()} }},
55 {Name: "config", Method: "GET", Path: "/api/v1/admin/config", Title: "Instellingen", Signed: true,
56 Do: func(ctx context.Context, in Input) (int, any) { return 200, s.ConfigView() }},
57 {Name: "config.update", Method: "PUT", Path: "/api/v1/admin/config", Title: "Instellingen opslaan", Signed: true,
58 Fields: fieldKeys(), Do: s.actConfigUpdate},
59 {Name: "connect", Method: "POST", Path: "/api/v1/admin/connect", Title: "Koppelen",
60 Fields: []string{"url", "key", "on_conflict"}, Do: s.actConnect},
61 {Name: "disconnect", Method: "POST", Path: "/api/v1/admin/disconnect", Title: "Ontkoppelen", Signed: true,
62 Do: s.actDisconnect},
63 {Name: "sync", Method: "POST", Path: "/api/v1/admin/sync", Title: "Nu synchroniseren", Signed: true,
64 Fields: []string{"wait"}, Do: s.actSync},
65 {Name: "archive", Method: "POST", Path: "/api/v1/admin/archive", Title: "Nu archiveren", Signed: true,
66 Do: func(ctx context.Context, in Input) (int, any) {
67 a, err := s.ArchiveNow()
68 if err != nil {
69 return 409, errBody(err)
70 }
71 return 201, a
72 }},
73 {Name: "prune", Method: "POST", Path: "/api/v1/admin/prune", Title: "Nu opruimen", Signed: true,
74 Do: func(ctx context.Context, in Input) (int, any) {
75 removed, err := s.Prune()
76 if err != nil {
77 return 500, errBody(err)
78 }
79 if removed == nil {
80 removed = []string{}
81 }
82 return 200, map[string]any{"removed": removed}
83 }},
84 {Name: "archives", Method: "GET", Path: "/api/v1/admin/archives", Title: "Archieven", Signed: true,
85 Do: func(ctx context.Context, in Input) (int, any) {
86 list, err := s.archives.List()
87 if err != nil {
88 return 500, errBody(err)
89 }
90 return 200, map[string]any{"archives": list}
91 }},
92 {Name: "archive.download", Method: "GET", Path: "/api/v1/admin/archives/{name}/download", Title: "Downloaden",
93 Params: []string{"name"}, Do: func(ctx context.Context, in Input) (int, any) {
94 p, err := s.archives.Path(in["name"])
95 if err != nil {
96 return 404, errBody(err)
97 }
98 return 200, fileResult{path: p, name: in["name"]}
99 }},
100 {Name: "archive.delete", Method: "DELETE", Path: "/api/v1/admin/archives/{name}", Title: "Verwijderen", Signed: true,
101 Params: []string{"name"}, Do: s.actArchiveDelete},
102 {Name: "rollback", Method: "POST", Path: "/api/v1/admin/rollback", Title: "Rollback", Signed: true,
103 Fields: []string{"archive", "confirm"}, Do: s.actRollback},
104 }
105}
106
107func fieldKeys() []string {
108 out := make([]string, 0, len(config.Fields))
109 for _, f := range config.Fields {
110 out = append(out, f.Key)
111 }
112 return out
113}
114
115func (s *Server) action(name string) (Action, bool) {
116 for _, a := range s.Actions() {
117 if a.Name == name {
118 return a, true
119 }
120 }
121 return Action{}, false
122}
123
124// ConfigView is GET /api/v1/admin/config.
125type ConfigView struct {
126 Fields []ConfigField `json:"fields"`
127 DataDir string `json:"data_dir"`
128 // Restart: er staat een wijziging klaar die pas na een herstart geldt.
129 Restart bool `json:"restart_pending"`
130}
131
132// ConfigField is een veld met zijn waarde.
133type ConfigField struct {
134 config.Field
135 Value string `json:"value"`
136}
137
138// ConfigView geeft alle instellingen met hun huidige waarde.
139func (s *Server) ConfigView() ConfigView {
140 s.mu.Lock()
141 defer s.mu.Unlock()
142 v := ConfigView{DataDir: s.Cfg.DataDir, Restart: s.restartPending}
143 for _, f := range config.Fields {
144 val := s.Cfg.Get(f.Key)
145 if f.Restart {
146 if p, ok := s.settings[f.Key]; ok {
147 val = p
148 }
149 }
150 v.Fields = append(v.Fields, ConfigField{Field: f, Value: val})
151 }
152 return v
153}
154
155// UpdateConfig past instellingen toe en bewaart ze in settings.yml. Velden
156// met Restart gelden pas na een herstart.
157func (s *Server) UpdateConfig(set map[string]string) (ConfigView, error) {
158 s.mu.Lock()
159 next := s.Cfg
160 if err := next.Apply(set); err != nil {
161 s.mu.Unlock()
162 return ConfigView{}, err
163 }
164 merged := map[string]string{}
165 for k, v := range s.settings {
166 merged[k] = v
167 }
168 for k := range set {
169 merged[k] = next.Get(k)
170 }
171 if err := config.SaveSettings(next.DataDir, merged); err != nil {
172 s.mu.Unlock()
173 return ConfigView{}, err
174 }
175 for _, f := range config.Fields {
176 if f.Restart {
177 if _, ok := set[f.Key]; ok && next.Get(f.Key) != s.Cfg.Get(f.Key) {
178 s.restartPending = true
179 }
180 // De draaiende waarde blijft tot de herstart.
181 _ = next.Set(f.Key, s.Cfg.Get(f.Key))
182 }
183 }
184 s.settings = merged
185 s.Cfg = next
186 s.mu.Unlock()
187 s.limiter.SetRate(next.RateLimitKiB << 10)
188 keys := make([]string, 0, len(set))
189 for k := range set {
190 keys = append(keys, k)
191 }
192 sort.Strings(keys)
193 s.Log.Info("instellingen gewijzigd", "keys", strings.Join(keys, ","))
194 // Kortere intervallen meteen laten gelden.
195 s.Kick()
196 return s.ConfigView(), nil
197}
198
199func (s *Server) actConfigUpdate(ctx context.Context, in Input) (int, any) {
200 set := map[string]string{}
201 for k, v := range in {
202 set[k] = v
203 }
204 if len(set) == 0 {
205 return 400, errBody(errors.New("geen instellingen meegegeven"))
206 }
207 v, err := s.UpdateConfig(set)
208 if err != nil {
209 return 400, errBody(err)
210 }
211 return 200, v
212}
213
214func (s *Server) actConnect(ctx context.Context, in Input) (int, any) {
215 res, conflict, err := s.Connect(ctx, ConnectRequest{URL: in["url"], Key: in["key"], OnConflict: in["on_conflict"]})
216 if conflict != nil {
217 return http.StatusConflict, conflict
218 }
219 if err != nil {
220 var he *mirror.HTTPError
221 code := 502
222 if errors.As(err, &he) && he.Status == 401 {
223 code = 401
224 }
225 if errors.Is(err, errBadRequest) {
226 code = 400
227 }
228 return code, errBody(err)
229 }
230 return 200, res
231}
232
233// Disconnect vergeet de gekoppelde BlueGit. De kopie en de archieven blijven
234// staan; een volgende koppeling met een andere BlueGit vraagt dan weer om
235// wissen of herstellen.
236func (s *Server) Disconnect() error {
237 s.work.Lock()
238 defer s.work.Unlock()
239 st := s.getState()
240 keep := State{InstanceID: st.InstanceID, BlueGitURL: st.BlueGitURL}
241 if err := saveState(s.Cfg.DataDir, keep); err != nil {
242 return err
243 }
244 s.mu.Lock()
245 s.state = keep
246 s.mu.Unlock()
247 s.Log.Warn("ontkoppeld", "bluegit", st.BlueGitURL)
248 return nil
249}
250
251func (s *Server) actDisconnect(ctx context.Context, in Input) (int, any) {
252 if !s.getState().Connected() {
253 return 409, errBody(errors.New("er is geen BlueGit gekoppeld"))
254 }
255 if err := s.Disconnect(); err != nil {
256 return 500, errBody(err)
257 }
258 return 200, map[string]any{"connected": false}
259}
260
261func (s *Server) actSync(ctx context.Context, in Input) (int, any) {
262 if !s.getState().Connected() {
263 return 409, errBody(errors.New("geen BlueGit gekoppeld"))
264 }
265 if in["wait"] == "false" || in["wait"] == "0" {
266 s.Kick()
267 return 202, map[string]string{"state": "started"}
268 }
269 stats, err := s.SyncNow(ctx)
270 if err != nil {
271 return 502, errBody(err)
272 }
273 return 200, stats
274}
275
276func (s *Server) actArchiveDelete(ctx context.Context, in Input) (int, any) {
277 name := in["name"]
278 if !archive.ValidName(name) {
279 return 400, errBody(errors.New("ongeldige archiefnaam"))
280 }
281 s.work.Lock()
282 err := s.archives.Delete(name)
283 s.work.Unlock()
284 if err != nil {
285 return 404, errBody(err)
286 }
287 s.Log.Info("archief verwijderd met de hand", "archive", name)
288 return 200, map[string]string{"deleted": name}
289}
290
291func (s *Server) actRollback(ctx context.Context, in Input) (int, any) {
292 name := in["archive"]
293 if !archive.ValidName(name) {
294 return 400, errBody(errors.New("ongeldige archiefnaam"))
295 }
296 if in["confirm"] != name {
297 return 400, errBody(errors.New("bevestig met de archiefnaam in confirm; een rollback kan niet ongedaan worden gemaakt"))
298 }
299 return s.startRollback(name)
300}
301
302// startRollback start een rollback op de achtergrond.
303func (s *Server) startRollback(name string) (int, any) {
304 if _, err := s.archives.Path(name); err != nil {
305 return 404, errBody(err)
306 }
307 if !s.getState().Connected() {
308 return 409, errBody(errors.New("geen BlueGit gekoppeld"))
309 }
310 s.mu.Lock()
311 busy := s.rollback.State == "running"
312 if !busy {
313 s.rollback = RollbackStatus{State: "running", Archive: name, At: s.now().UTC()}
314 }
315 s.mu.Unlock()
316 if busy {
317 return 409, errBody(errors.New("er loopt al een rollback"))
318 }
319 s.Log.Warn("rollback gestart", "archive", name)
320 go func() {
321 if err := s.Rollback(context.Background(), name); err != nil {
322 s.Log.Error("rollback mislukt", "archive", name, "err", err)
323 }
324 }()
325 return http.StatusAccepted, map[string]string{"state": "running", "archive": name}
326}
327
328// ---------- HTTP ----------
329
330// Handler is de webinterface en de HTTP-API.
331func (s *Server) Handler() http.Handler {
332 mux := http.NewServeMux()
333 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok\n")) })
334 // Van BlueGit, ondertekend (vaste protocolroutes).
335 mux.HandleFunc("POST /api/v1/notify", s.signed(s.apiNotify))
336 mux.HandleFunc("GET /api/v1/archives", s.signed(s.apiArchives))
337 mux.HandleFunc("GET /api/v1/status", s.signed(s.apiStatus))
338 mux.HandleFunc("POST /api/v1/rollback", s.signed(s.apiRollback))
339 // Beheer: admin.token, een sessie van de webinterface, of BlueGit.
340 for _, a := range s.Actions() {
341 mux.HandleFunc(a.Method+" "+a.Path, s.apiAction(a))
342 }
343 s.mountUI(mux)
344 return securityHeaders(mux)
345}
346
347func securityHeaders(h http.Handler) http.Handler {
348 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
349 w.Header().Set("X-Content-Type-Options", "nosniff")
350 w.Header().Set("Referrer-Policy", "same-origin")
351 h.ServeHTTP(w, r)
352 })
353}
354
355// apiAction voert een actie uit voor de API.
356func (s *Server) apiAction(a Action) http.HandlerFunc {
357 return func(w http.ResponseWriter, r *http.Request) {
358 body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
359 if err != nil {
360 writeErr(w, 400, "body")
361 return
362 }
363 if code, msg := s.authorize(r, a, body); code != 0 {
364 writeErr(w, code, msg)
365 return
366 }
367 in, err := parseInput(r, body)
368 if err != nil {
369 writeErr(w, 400, err.Error())
370 return
371 }
372 for _, p := range a.Params {
373 in[p] = r.PathValue(p)
374 }
375 code, out := a.Do(r.Context(), in)
376 if f, ok := out.(fileResult); ok {
377 w.Header().Set("Content-Type", "application/gzip")
378 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", f.name))
379 http.ServeFile(w, r, f.path)
380 return
381 }
382 writeJSON(w, code, out)
383 }
384}
385
386// authorize: 0 is toegestaan, anders de foutcode.
387func (s *Server) authorize(r *http.Request, a Action, body []byte) (int, string) {
388 if tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer "); ok {
389 if subtle.ConstantTimeCompare([]byte(strings.TrimSpace(tok)), []byte(s.adminToken)) == 1 {
390 return 0, ""
391 }
392 return 401, "ongeldig token"
393 }
394 if r.Header.Get(protocol.HeaderSignature) != "" {
395 if !a.Signed {
396 return 403, "BlueGit mag dit niet"
397 }
398 st := s.getState()
399 if !st.Connected() {
400 return 401, "niet gekoppeld"
401 }
402 if r.Header.Get(protocol.HeaderInstance) != st.InstanceID {
403 return 401, "andere BlueGit-instantie"
404 }
405 if err := protocol.Verify(r, protocol.SigningSecret(st.Key), body, s.now()); err != nil {
406 return 401, err.Error()
407 }
408 return 0, ""
409 }
410 if sess, ok := s.session(r); ok {
411 if r.Method != http.MethodGet && r.Method != http.MethodHead {
412 if subtle.ConstantTimeCompare([]byte(r.Header.Get("X-CSRF-Token")), []byte(sess.csrf)) != 1 {
413 return 403, "X-CSRF-Token ontbreekt of klopt niet"
414 }
415 }
416 return 0, ""
417 }
418 return 401, "admin.token, sessie of BlueGit-handtekening nodig"
419}
420
421// parseInput leest de querystring en een JSON-object (waarden als tekst).
422func parseInput(r *http.Request, body []byte) (Input, error) {
423 in := Input{}
424 for k, v := range r.URL.Query() {
425 if len(v) > 0 {
426 in[k] = v[0]
427 }
428 }
429 if len(strings.TrimSpace(string(body))) == 0 {
430 return in, nil
431 }
432 var raw map[string]any
433 if err := json.Unmarshal(body, &raw); err != nil {
434 return nil, errors.New("ongeldige JSON: verwacht een object")
435 }
436 for k, v := range raw {
437 switch t := v.(type) {
438 case string:
439 in[k] = t
440 case float64:
441 in[k] = strconv.FormatFloat(t, 'f', -1, 64)
442 case bool:
443 in[k] = strconv.FormatBool(t)
444 case nil:
445 in[k] = ""
446 default:
447 return nil, fmt.Errorf("veld %s: verwacht tekst, getal of boolean", k)
448 }
449 }
450 return in, nil
451}