BlueGit

timfa bluegit

Files

bluegit / internal / backupserver / server / ui.go

ui.go

ui.go 8.2 KiB Download Raw
1package server
2
3import (
4 "crypto/rand"
5 "crypto/subtle"
6 "embed"
7 "encoding/hex"
8 "encoding/json"
9 "fmt"
10 "html/template"
11 "net"
12 "net/http"
13 "net/url"
14 "strings"
15 "time"
16
17 "git.timfalken.com/timfa/bluegit-backup/internal/archive"
18)
19
20//go:embed web/*
21var webFS embed.FS
22
23var uiTmpl = template.Must(template.New("").Funcs(template.FuncMap{
24 "bytes": humanBytes,
25 "when": func(t time.Time) string {
26 if t.IsZero() {
27 return "nog niet"
28 }
29 return t.Local().Format("2006-01-02 15:04:05")
30 },
31 "json": func(v any) string { b, _ := json.MarshalIndent(v, "", " "); return string(b) },
32}).ParseFS(webFS, "web/*.html"))
33
34const (
35 sessionCookie = "bbsession"
36 sessionTTL = 12 * time.Hour
37)
38
39type session struct {
40 csrf string
41 expires time.Time
42 flash string
43 isErr bool
44}
45
46func randHex(n int) string {
47 b := make([]byte, n)
48 _, _ = rand.Read(b)
49 return hex.EncodeToString(b)
50}
51
52func humanBytes(n int64) string {
53 const unit = 1024
54 if n < unit {
55 return fmt.Sprintf("%d B", n)
56 }
57 div, exp := int64(unit), 0
58 for m := n / unit; m >= unit; m /= unit {
59 div *= unit
60 exp++
61 }
62 return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp])
63}
64
65func (s *Server) session(r *http.Request) (session, bool) {
66 c, err := r.Cookie(sessionCookie)
67 if err != nil || c.Value == "" {
68 return session{}, false
69 }
70 s.mu.Lock()
71 defer s.mu.Unlock()
72 sess, ok := s.sessions[c.Value]
73 if !ok || s.now().After(sess.expires) {
74 delete(s.sessions, c.Value)
75 return session{}, false
76 }
77 return sess, true
78}
79
80func (s *Server) setFlash(r *http.Request, msg string, isErr bool) {
81 c, err := r.Cookie(sessionCookie)
82 if err != nil {
83 return
84 }
85 s.mu.Lock()
86 defer s.mu.Unlock()
87 if sess, ok := s.sessions[c.Value]; ok {
88 sess.flash, sess.isErr = msg, isErr
89 s.sessions[c.Value] = sess
90 }
91}
92
93func (s *Server) takeFlash(r *http.Request) (string, bool) {
94 c, err := r.Cookie(sessionCookie)
95 if err != nil {
96 return "", false
97 }
98 s.mu.Lock()
99 defer s.mu.Unlock()
100 sess, ok := s.sessions[c.Value]
101 if !ok {
102 return "", false
103 }
104 msg, isErr := sess.flash, sess.isErr
105 sess.flash, sess.isErr = "", false
106 s.sessions[c.Value] = sess
107 return msg, isErr
108}
109
110func clientIP(r *http.Request) string {
111 h, _, err := net.SplitHostPort(r.RemoteAddr)
112 if err != nil {
113 return r.RemoteAddr
114 }
115 return h
116}
117
118// loginAllowed: hoogstens 5 foute pogingen per minuut per IP-adres.
119func (s *Server) loginAllowed(ip string, failed bool) bool {
120 s.mu.Lock()
121 defer s.mu.Unlock()
122 if s.loginFails == nil {
123 s.loginFails = map[string][]time.Time{}
124 }
125 cut := s.now().Add(-time.Minute)
126 keep := s.loginFails[ip][:0]
127 for _, t := range s.loginFails[ip] {
128 if t.After(cut) {
129 keep = append(keep, t)
130 }
131 }
132 if failed {
133 keep = append(keep, s.now())
134 }
135 s.loginFails[ip] = keep
136 return len(keep) < 5
137}
138
139func (s *Server) mountUI(mux *http.ServeMux) {
140 mux.HandleFunc("GET /{$}", s.uiIndex)
141 mux.HandleFunc("GET /login", s.uiLoginPage)
142 mux.HandleFunc("POST /login", s.uiLogin)
143 mux.HandleFunc("POST /logout", s.uiLogout)
144 mux.HandleFunc("POST /ui/act/{name}", s.uiAct)
145}
146
147func (s *Server) render(w http.ResponseWriter, name string, data any) {
148 w.Header().Set("Content-Type", "text/html; charset=utf-8")
149 w.Header().Set("Cache-Control", "no-store")
150 w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'none'; frame-ancestors 'none'; form-action 'self'")
151 w.Header().Set("X-Frame-Options", "DENY")
152 if err := uiTmpl.ExecuteTemplate(w, name, data); err != nil {
153 s.Log.Error("template", "name", name, "err", err)
154 }
155}
156
157func (s *Server) uiLoginPage(w http.ResponseWriter, r *http.Request) {
158 if _, ok := s.session(r); ok {
159 http.Redirect(w, r, "/", http.StatusSeeOther)
160 return
161 }
162 s.render(w, "login.html", map[string]any{"Error": r.URL.Query().Get("fout") != "", "Version": Version})
163}
164
165func (s *Server) uiLogin(w http.ResponseWriter, r *http.Request) {
166 ip := clientIP(r)
167 if !s.loginAllowed(ip, false) {
168 http.Error(w, "te veel pogingen, wacht een minuut", http.StatusTooManyRequests)
169 return
170 }
171 tok := strings.TrimSpace(r.PostFormValue("token"))
172 if subtle.ConstantTimeCompare([]byte(tok), []byte(s.adminToken)) != 1 {
173 s.loginAllowed(ip, true)
174 http.Redirect(w, r, "/login?fout=1", http.StatusSeeOther)
175 return
176 }
177 id := randHex(32)
178 s.mu.Lock()
179 for k, v := range s.sessions {
180 if s.now().After(v.expires) {
181 delete(s.sessions, k)
182 }
183 }
184 s.sessions[id] = session{csrf: randHex(16), expires: s.now().Add(sessionTTL)}
185 s.mu.Unlock()
186 http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: id, Path: "/", HttpOnly: true,
187 SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https",
188 MaxAge: int(sessionTTL / time.Second)})
189 http.Redirect(w, r, "/", http.StatusSeeOther)
190}
191
192func (s *Server) uiLogout(w http.ResponseWriter, r *http.Request) {
193 if sess, ok := s.session(r); ok && r.PostFormValue("csrf") == sess.csrf {
194 c, _ := r.Cookie(sessionCookie)
195 s.mu.Lock()
196 delete(s.sessions, c.Value)
197 s.mu.Unlock()
198 }
199 http.SetCookie(w, &http.Cookie{Name: sessionCookie, Value: "", Path: "/", MaxAge: -1, HttpOnly: true})
200 http.Redirect(w, r, "/login", http.StatusSeeOther)
201}
202
203// pageData is wat de webinterface toont: precies de uitkomst van de
204// GET-acties uit Actions.
205type pageData struct {
206 CSRF string
207 Flash string
208 FlashErr bool
209 Status Status
210 Config ConfigView
211 Archives []archive.Archive
212 Actions []Action
213 Version string
214}
215
216func (s *Server) uiIndex(w http.ResponseWriter, r *http.Request) {
217 sess, ok := s.session(r)
218 if !ok {
219 http.Redirect(w, r, "/login", http.StatusSeeOther)
220 return
221 }
222 d := pageData{CSRF: sess.csrf, Status: s.Status(), Config: s.ConfigView(), Actions: s.Actions(), Version: Version}
223 d.Archives, _ = s.archives.List()
224 d.Flash, d.FlashErr = s.takeFlash(r)
225 s.render(w, "index.html", d)
226}
227
228// uiAct voert een actie uit vanuit een formulier, via dezelfde code als de API.
229func (s *Server) uiAct(w http.ResponseWriter, r *http.Request) {
230 sess, ok := s.session(r)
231 if !ok {
232 http.Redirect(w, r, "/login", http.StatusSeeOther)
233 return
234 }
235 if err := r.ParseForm(); err != nil {
236 http.Error(w, "formulier", 400)
237 return
238 }
239 if subtle.ConstantTimeCompare([]byte(r.PostFormValue("csrf")), []byte(sess.csrf)) != 1 {
240 http.Error(w, "CSRF-token klopt niet; laad de pagina opnieuw", http.StatusForbidden)
241 return
242 }
243 a, ok := s.action(r.PathValue("name"))
244 if !ok || a.Method == http.MethodGet {
245 http.NotFound(w, r)
246 return
247 }
248 in := Input{}
249 for k, v := range r.PostForm {
250 if k == "csrf" || k == "understood" || len(v) == 0 {
251 continue
252 }
253 in[k] = v[0]
254 }
255 anchor := "#" + strings.SplitN(a.Name, ".", 2)[0]
256 if a.Name == "rollback" && r.PostFormValue("understood") == "" {
257 s.setFlash(r, "Vink aan dat je begrijpt dat een rollback niet ongedaan kan worden gemaakt.", true)
258 http.Redirect(w, r, "/#archives", http.StatusSeeOther)
259 return
260 }
261 if a.Name == "sync" {
262 in["wait"] = "false"
263 }
264 code, out := a.Do(r.Context(), in)
265 msg, isErr := describe(a, code, out)
266 s.setFlash(r, msg, isErr)
267 http.Redirect(w, r, "/"+anchor, http.StatusSeeOther)
268}
269
270func describe(a Action, code int, out any) (string, bool) {
271 if code >= 400 {
272 switch v := out.(type) {
273 case *ConflictError:
274 return fmt.Sprintf("%s (vorige: %s, %d archieven). Kies hieronder ‘oude backups wissen’ of ‘nieuwe BlueGit herstellen’ en koppel opnieuw.", v.Error, v.PreviousURL, v.Archives), true
275 case map[string]string:
276 return a.Title + " mislukt: " + v["error"], true
277 }
278 return fmt.Sprintf("%s mislukt (HTTP %d)", a.Title, code), true
279 }
280 switch a.Name {
281 case "sync":
282 return "Synchronisatie gestart.", false
283 case "archive":
284 if v, ok := out.(archive.Archive); ok {
285 return "Archief gemaakt: " + v.Name, false
286 }
287 case "prune":
288 if v, ok := out.(map[string]any); ok {
289 return fmt.Sprintf("Opgeruimd: %d archieven.", len(v["removed"].([]string))), false
290 }
291 case "rollback":
292 return "Rollback gestart. BlueGit herstart zodra de data er staat.", false
293 case "config.update":
294 if v, ok := out.(ConfigView); ok && v.Restart {
295 return "Instellingen opgeslagen. Een deel geldt pas na een herstart.", false
296 }
297 return "Instellingen opgeslagen.", false
298 }
299 return a.Title + ": gelukt.", false
300}
301
302// UIPath is het formulieradres van een actie in de webinterface.
303func UIPath(a Action) string { return "/ui/act/" + url.PathEscape(a.Name) }