| 1 | package server |
| 2 | |
| 3 | import ( |
| 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. |
| 23 | type 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. |
| 27 | type 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. |
| 44 | type fileResult struct{ path, name string } |
| 45 | |
| 46 | func errBody(err error) map[string]string { return map[string]string{"error": err.Error()} } |
| 47 | |
| 48 | // Actions is de volledige lijst met beheerhandelingen. |
| 49 | func (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 | |
| 107 | func 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 | |
| 115 | func (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. |
| 125 | type 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. |
| 133 | type ConfigField struct { |
| 134 | config.Field |
| 135 | Value string `json:"value"` |
| 136 | } |
| 137 | |
| 138 | // ConfigView geeft alle instellingen met hun huidige waarde. |
| 139 | func (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. |
| 157 | func (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 | |
| 199 | func (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 | |
| 214 | func (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. |
| 236 | func (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.bluegitKnown = false |
| 247 | s.mu.Unlock() |
| 248 | s.Log.Warn("ontkoppeld", "bluegit", st.BlueGitURL) |
| 249 | return nil |
| 250 | } |
| 251 | |
| 252 | func (s *Server) actDisconnect(ctx context.Context, in Input) (int, any) { |
| 253 | if !s.getState().Connected() { |
| 254 | return 409, errBody(errors.New("er is geen BlueGit gekoppeld")) |
| 255 | } |
| 256 | if err := s.Disconnect(); err != nil { |
| 257 | return 500, errBody(err) |
| 258 | } |
| 259 | return 200, map[string]any{"connected": false} |
| 260 | } |
| 261 | |
| 262 | func (s *Server) actSync(ctx context.Context, in Input) (int, any) { |
| 263 | if !s.getState().Connected() { |
| 264 | return 409, errBody(errors.New("geen BlueGit gekoppeld")) |
| 265 | } |
| 266 | if in["wait"] == "false" || in["wait"] == "0" { |
| 267 | s.Kick() |
| 268 | return 202, map[string]string{"state": "started"} |
| 269 | } |
| 270 | stats, err := s.SyncNow(ctx) |
| 271 | if errors.Is(err, ErrIncompatible) { |
| 272 | return http.StatusConflict, errBody(err) |
| 273 | } |
| 274 | if err != nil { |
| 275 | return 502, errBody(err) |
| 276 | } |
| 277 | return 200, stats |
| 278 | } |
| 279 | |
| 280 | func (s *Server) actArchiveDelete(ctx context.Context, in Input) (int, any) { |
| 281 | name := in["name"] |
| 282 | if !archive.ValidName(name) { |
| 283 | return 400, errBody(errors.New("ongeldige archiefnaam")) |
| 284 | } |
| 285 | s.work.Lock() |
| 286 | err := s.archives.Delete(name) |
| 287 | s.work.Unlock() |
| 288 | if err != nil { |
| 289 | return 404, errBody(err) |
| 290 | } |
| 291 | s.Log.Info("archief verwijderd met de hand", "archive", name) |
| 292 | return 200, map[string]string{"deleted": name} |
| 293 | } |
| 294 | |
| 295 | func (s *Server) actRollback(ctx context.Context, in Input) (int, any) { |
| 296 | name := in["archive"] |
| 297 | if !archive.ValidName(name) { |
| 298 | return 400, errBody(errors.New("ongeldige archiefnaam")) |
| 299 | } |
| 300 | if in["confirm"] != name { |
| 301 | return 400, errBody(errors.New("bevestig met de archiefnaam in confirm; een rollback kan niet ongedaan worden gemaakt")) |
| 302 | } |
| 303 | return s.startRollback(name) |
| 304 | } |
| 305 | |
| 306 | // startRollback start een rollback op de achtergrond. |
| 307 | func (s *Server) startRollback(name string) (int, any) { |
| 308 | if _, err := s.archives.Path(name); err != nil { |
| 309 | return 404, errBody(err) |
| 310 | } |
| 311 | if !s.getState().Connected() { |
| 312 | return 409, errBody(errors.New("geen BlueGit gekoppeld")) |
| 313 | } |
| 314 | if c, p := s.compat(); c != "" && c != protocol.CompatOK { |
| 315 | return 409, errBody(fmt.Errorf("%w: %s", ErrIncompatible, compatMessage(c, p))) |
| 316 | } |
| 317 | s.mu.Lock() |
| 318 | busy := s.rollback.State == "running" |
| 319 | if !busy { |
| 320 | s.rollback = RollbackStatus{State: "running", Archive: name, At: s.now().UTC()} |
| 321 | } |
| 322 | s.mu.Unlock() |
| 323 | if busy { |
| 324 | return 409, errBody(errors.New("er loopt al een rollback")) |
| 325 | } |
| 326 | s.Log.Warn("rollback gestart", "archive", name) |
| 327 | go func() { |
| 328 | if err := s.Rollback(context.Background(), name); err != nil { |
| 329 | s.Log.Error("rollback mislukt", "archive", name, "err", err) |
| 330 | } |
| 331 | }() |
| 332 | return http.StatusAccepted, map[string]string{"state": "running", "archive": name} |
| 333 | } |
| 334 | |
| 335 | // ---------- HTTP ---------- |
| 336 | |
| 337 | // Handler is de webinterface en de HTTP-API. |
| 338 | func (s *Server) Handler() http.Handler { |
| 339 | mux := http.NewServeMux() |
| 340 | mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok\n")) }) |
| 341 | // Van BlueGit, ondertekend (vaste protocolroutes). |
| 342 | mux.HandleFunc("POST /api/v1/notify", s.signed(s.apiNotify)) |
| 343 | mux.HandleFunc("GET /api/v1/archives", s.signed(s.apiArchives)) |
| 344 | mux.HandleFunc("GET /api/v1/status", s.signed(s.apiStatus)) |
| 345 | mux.HandleFunc("POST /api/v1/rollback", s.signed(s.apiRollback)) |
| 346 | // Beheer: admin.token, een sessie van de webinterface, of BlueGit. |
| 347 | for _, a := range s.Actions() { |
| 348 | mux.HandleFunc(a.Method+" "+a.Path, s.apiAction(a)) |
| 349 | } |
| 350 | s.mountUI(mux) |
| 351 | return securityHeaders(mux) |
| 352 | } |
| 353 | |
| 354 | func securityHeaders(h http.Handler) http.Handler { |
| 355 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 356 | protocol.SetOwnHeaders(w.Header(), Version) |
| 357 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 358 | w.Header().Set("Referrer-Policy", "same-origin") |
| 359 | h.ServeHTTP(w, r) |
| 360 | }) |
| 361 | } |
| 362 | |
| 363 | // apiAction voert een actie uit voor de API. |
| 364 | func (s *Server) apiAction(a Action) http.HandlerFunc { |
| 365 | return func(w http.ResponseWriter, r *http.Request) { |
| 366 | body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) |
| 367 | if err != nil { |
| 368 | writeErr(w, 400, "body") |
| 369 | return |
| 370 | } |
| 371 | if code, msg := s.authorize(r, a, body); code != 0 { |
| 372 | writeErr(w, code, msg) |
| 373 | return |
| 374 | } |
| 375 | in, err := parseInput(r, body) |
| 376 | if err != nil { |
| 377 | writeErr(w, 400, err.Error()) |
| 378 | return |
| 379 | } |
| 380 | for _, p := range a.Params { |
| 381 | in[p] = r.PathValue(p) |
| 382 | } |
| 383 | code, out := a.Do(r.Context(), in) |
| 384 | if f, ok := out.(fileResult); ok { |
| 385 | w.Header().Set("Content-Type", "application/gzip") |
| 386 | w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", f.name)) |
| 387 | http.ServeFile(w, r, f.path) |
| 388 | return |
| 389 | } |
| 390 | writeJSON(w, code, out) |
| 391 | } |
| 392 | } |
| 393 | |
| 394 | // authorize: 0 is toegestaan, anders de foutcode. |
| 395 | func (s *Server) authorize(r *http.Request, a Action, body []byte) (int, string) { |
| 396 | if tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer "); ok { |
| 397 | if subtle.ConstantTimeCompare([]byte(strings.TrimSpace(tok)), []byte(s.adminToken)) == 1 { |
| 398 | return 0, "" |
| 399 | } |
| 400 | return 401, "ongeldig token" |
| 401 | } |
| 402 | if r.Header.Get(protocol.HeaderSignature) != "" { |
| 403 | if !a.Signed { |
| 404 | return 403, "BlueGit mag dit niet" |
| 405 | } |
| 406 | st := s.getState() |
| 407 | if !st.Connected() { |
| 408 | return 401, "niet gekoppeld" |
| 409 | } |
| 410 | if r.Header.Get(protocol.HeaderInstance) != st.InstanceID { |
| 411 | return 401, "andere BlueGit-instantie" |
| 412 | } |
| 413 | if err := protocol.Verify(r, protocol.SigningSecret(st.Key), body, s.now()); err != nil { |
| 414 | return 401, err.Error() |
| 415 | } |
| 416 | p, _ := protocol.BlueGitFromHeader(r.Header) |
| 417 | s.setBlueGit(p) |
| 418 | return 0, "" |
| 419 | } |
| 420 | if sess, ok := s.session(r); ok { |
| 421 | if r.Method != http.MethodGet && r.Method != http.MethodHead { |
| 422 | if subtle.ConstantTimeCompare([]byte(r.Header.Get("X-CSRF-Token")), []byte(sess.csrf)) != 1 { |
| 423 | return 403, "X-CSRF-Token ontbreekt of klopt niet" |
| 424 | } |
| 425 | } |
| 426 | return 0, "" |
| 427 | } |
| 428 | return 401, "admin.token, sessie of BlueGit-handtekening nodig" |
| 429 | } |
| 430 | |
| 431 | // parseInput leest de querystring en een JSON-object (waarden als tekst). |
| 432 | func parseInput(r *http.Request, body []byte) (Input, error) { |
| 433 | in := Input{} |
| 434 | for k, v := range r.URL.Query() { |
| 435 | if len(v) > 0 { |
| 436 | in[k] = v[0] |
| 437 | } |
| 438 | } |
| 439 | if len(strings.TrimSpace(string(body))) == 0 { |
| 440 | return in, nil |
| 441 | } |
| 442 | var raw map[string]any |
| 443 | if err := json.Unmarshal(body, &raw); err != nil { |
| 444 | return nil, errors.New("ongeldige JSON: verwacht een object") |
| 445 | } |
| 446 | for k, v := range raw { |
| 447 | switch t := v.(type) { |
| 448 | case string: |
| 449 | in[k] = t |
| 450 | case float64: |
| 451 | in[k] = strconv.FormatFloat(t, 'f', -1, 64) |
| 452 | case bool: |
| 453 | in[k] = strconv.FormatBool(t) |
| 454 | case nil: |
| 455 | in[k] = "" |
| 456 | default: |
| 457 | return nil, fmt.Errorf("veld %s: verwacht tekst, getal of boolean", k) |
| 458 | } |
| 459 | } |
| 460 | return in, nil |
| 461 | } |