| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/hmac" |
| 7 | "crypto/rand" |
| 8 | "crypto/sha256" |
| 9 | "crypto/subtle" |
| 10 | "encoding/hex" |
| 11 | "errors" |
| 12 | "html/template" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "os" |
| 16 | "path/filepath" |
| 17 | "strings" |
| 18 | "sync" |
| 19 | "time" |
| 20 | |
| 21 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 22 | "gitlab.com/Timfa/bluegit/internal/langpick" |
| 23 | "gitlab.com/Timfa/bluegit/internal/runnercfg" |
| 24 | "gitlab.com/Timfa/bluegit/internal/server/static" |
| 25 | ) |
| 26 | |
| 27 | // De webinterface van de runner. Standaard alleen op 127.0.0.1:8765 |
| 28 | // (ui_listen); "off" zet hem uit. Toegang met een beheertoken dat lokaal |
| 29 | // in work_dir/ui-token staat (0600). Het token komt nooit in de logs; |
| 30 | // `bluegit-runner ui-token` toont het op de machine zelf. |
| 31 | |
| 32 | const defaultUIListen = "127.0.0.1:8765" |
| 33 | |
| 34 | func uiTokenPath(cfg Config) string { return filepath.Join(cfg.WorkDir, "ui-token") } |
| 35 | |
| 36 | // ensureUIToken maakt het token bij de eerste start. |
| 37 | func ensureUIToken(cfg Config) (string, bool, error) { |
| 38 | p := uiTokenPath(cfg) |
| 39 | if b, err := os.ReadFile(p); err == nil && len(bytes.TrimSpace(b)) >= 32 { |
| 40 | return string(bytes.TrimSpace(b)), false, nil |
| 41 | } |
| 42 | raw := make([]byte, 24) |
| 43 | if _, err := rand.Read(raw); err != nil { |
| 44 | return "", false, err |
| 45 | } |
| 46 | tok := "bgru_" + hex.EncodeToString(raw) |
| 47 | if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| 48 | return "", false, err |
| 49 | } |
| 50 | if err := os.WriteFile(p, []byte(tok+"\n"), 0o600); err != nil { |
| 51 | return "", false, err |
| 52 | } |
| 53 | return tok, true, nil |
| 54 | } |
| 55 | |
| 56 | type webUI struct { |
| 57 | cfg Config |
| 58 | token string |
| 59 | h *runnercfg.Handler |
| 60 | mux *http.ServeMux |
| 61 | |
| 62 | listenMu sync.Mutex |
| 63 | hs *http.Server |
| 64 | ln net.Listener |
| 65 | } |
| 66 | |
| 67 | func (u *webUI) mac(purpose string) string { |
| 68 | m := hmac.New(sha256.New, []byte(u.token)) |
| 69 | m.Write([]byte(purpose)) |
| 70 | return hex.EncodeToString(m.Sum(nil)) |
| 71 | } |
| 72 | |
| 73 | func (u *webUI) authed(r *http.Request) bool { |
| 74 | if a := r.Header.Get("Authorization"); strings.HasPrefix(a, "Bearer ") { |
| 75 | return subtle.ConstantTimeCompare([]byte(strings.TrimPrefix(a, "Bearer ")), []byte(u.token)) == 1 |
| 76 | } |
| 77 | c, err := r.Cookie("bgru_session") |
| 78 | return err == nil && subtle.ConstantTimeCompare([]byte(c.Value), []byte(u.mac("session"))) == 1 |
| 79 | } |
| 80 | |
| 81 | func (u *webUI) lang(r *http.Request) i18n.Lang { |
| 82 | if q := r.URL.Query().Get("lang"); q != "" { |
| 83 | return i18n.Parse(q) |
| 84 | } |
| 85 | if c, err := r.Cookie("lang"); err == nil { |
| 86 | return i18n.Parse(c.Value) |
| 87 | } |
| 88 | if u.cfg.Language != "" { |
| 89 | return i18n.Parse(u.cfg.Language) |
| 90 | } |
| 91 | al := strings.ToLower(r.Header.Get("Accept-Language")) |
| 92 | for _, l := range []i18n.Lang{i18n.NL, i18n.DE, i18n.FR, i18n.EN} { |
| 93 | if strings.HasPrefix(al, string(l)) { |
| 94 | return l |
| 95 | } |
| 96 | } |
| 97 | return i18n.EN |
| 98 | } |
| 99 | |
| 100 | func newWebUI(cfg Config, token string, h *runnercfg.Handler) *webUI { |
| 101 | u := &webUI{cfg: cfg, token: token, h: h, mux: http.NewServeMux()} |
| 102 | h.Lang = u.lang |
| 103 | h.Auth = func(w http.ResponseWriter, r *http.Request, write bool) bool { |
| 104 | if u.authed(r) { |
| 105 | return true |
| 106 | } |
| 107 | if strings.HasPrefix(r.URL.Path, "/api/") { |
| 108 | w.Header().Set("Content-Type", "application/json") |
| 109 | w.WriteHeader(http.StatusUnauthorized) |
| 110 | _, _ = w.Write([]byte(`{"error":"unauthorized"}` + "\n")) |
| 111 | return false |
| 112 | } |
| 113 | http.Redirect(w, r, "/login", http.StatusSeeOther) |
| 114 | return false |
| 115 | } |
| 116 | h.CSRF = func(r *http.Request) (string, string) { return "csrf", u.mac("csrf") } |
| 117 | h.CheckCSRF = func(r *http.Request) bool { |
| 118 | if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") { |
| 119 | return true |
| 120 | } |
| 121 | return hmac.Equal([]byte(r.FormValue("csrf")), []byte(u.mac("csrf"))) |
| 122 | } |
| 123 | h.Layout = u.layout |
| 124 | h.DocsURL = "/docs" |
| 125 | h.Mount(u.mux, true) |
| 126 | u.mux.HandleFunc("GET /assets/style.css", func(w http.ResponseWriter, r *http.Request) { |
| 127 | w.Header().Set("Content-Type", "text/css; charset=utf-8") |
| 128 | _, _ = w.Write(static.StyleCSS) |
| 129 | }) |
| 130 | u.mux.HandleFunc("GET /assets/logo.svg", func(w http.ResponseWriter, r *http.Request) { |
| 131 | w.Header().Set("Content-Type", "image/svg+xml") |
| 132 | _, _ = w.Write(static.LogoSVG) |
| 133 | }) |
| 134 | for name, body := range map[string][]byte{"confirm.js": static.ConfirmJS, "tip.js": static.TipJS, "langpick.js": static.LangpickJS} { |
| 135 | b := body |
| 136 | u.mux.HandleFunc("GET /assets/"+name, func(w http.ResponseWriter, r *http.Request) { |
| 137 | w.Header().Set("Content-Type", "text/javascript; charset=utf-8") |
| 138 | _, _ = w.Write(b) |
| 139 | }) |
| 140 | } |
| 141 | u.mux.HandleFunc("POST /lang", u.switchLang) |
| 142 | u.mux.HandleFunc("GET /docs", u.docs) |
| 143 | u.mux.HandleFunc("GET /login", u.loginPage) |
| 144 | u.mux.HandleFunc("POST /login", u.login) |
| 145 | u.mux.HandleFunc("POST /logout", u.logout) |
| 146 | u.mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok\n")) }) |
| 147 | return u |
| 148 | } |
| 149 | |
| 150 | func (u *webUI) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 151 | w.Header().Set("X-Frame-Options", "DENY") |
| 152 | w.Header().Set("X-Content-Type-Options", "nosniff") |
| 153 | w.Header().Set("Referrer-Policy", "same-origin") |
| 154 | w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; form-action 'self'; frame-ancestors 'none'") |
| 155 | if q := r.URL.Query().Get("lang"); q != "" && r.Method == http.MethodGet { |
| 156 | http.SetCookie(w, &http.Cookie{Name: "lang", Value: string(i18n.Parse(q)), Path: "/", MaxAge: 365 * 86400, SameSite: http.SameSiteStrictMode}) |
| 157 | } |
| 158 | u.mux.ServeHTTP(w, r) |
| 159 | } |
| 160 | |
| 161 | // switchLang komt van de taalkiezer: taal in een cookie, terug naar back. |
| 162 | func (u *webUI) switchLang(w http.ResponseWriter, r *http.Request) { |
| 163 | l := i18n.Parse(r.FormValue("lang")) |
| 164 | http.SetCookie(w, &http.Cookie{Name: "lang", Value: string(l), Path: "/", MaxAge: 365 * 86400, SameSite: http.SameSiteStrictMode, HttpOnly: true}) |
| 165 | http.Redirect(w, r, langpick.SafeBack(r.FormValue("back")), http.StatusSeeOther) |
| 166 | } |
| 167 | |
| 168 | func (u *webUI) loginPage(w http.ResponseWriter, r *http.Request) { |
| 169 | lang := u.lang(r) |
| 170 | var b bytes.Buffer |
| 171 | _ = loginTmpl.Execute(&b, map[string]any{"Lang": lang, "Bad": r.URL.Query().Get("bad") != "", "T": tfunc(lang)}) |
| 172 | u.layout(w, r, lang, i18n.T(lang, "rui.login"), template.HTML(b.String())) |
| 173 | } |
| 174 | |
| 175 | func tfunc(lang i18n.Lang) func(string, ...any) string { |
| 176 | return func(k string, a ...any) string { return i18n.T(lang, k, a...) } |
| 177 | } |
| 178 | |
| 179 | func (u *webUI) login(w http.ResponseWriter, r *http.Request) { |
| 180 | tok := strings.TrimSpace(r.FormValue("token")) |
| 181 | if subtle.ConstantTimeCompare([]byte(tok), []byte(u.token)) != 1 { |
| 182 | time.Sleep(500 * time.Millisecond) |
| 183 | http.Redirect(w, r, "/login?bad=1", http.StatusSeeOther) |
| 184 | return |
| 185 | } |
| 186 | http.SetCookie(w, &http.Cookie{Name: "bgru_session", Value: u.mac("session"), Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, MaxAge: 30 * 86400}) |
| 187 | http.Redirect(w, r, "/", http.StatusSeeOther) |
| 188 | } |
| 189 | |
| 190 | func (u *webUI) logout(w http.ResponseWriter, r *http.Request) { |
| 191 | if !hmac.Equal([]byte(r.FormValue("csrf")), []byte(u.mac("csrf"))) { |
| 192 | http.Error(w, "csrf", http.StatusForbidden) |
| 193 | return |
| 194 | } |
| 195 | http.SetCookie(w, &http.Cookie{Name: "bgru_session", Value: "", Path: "/", MaxAge: -1}) |
| 196 | http.Redirect(w, r, "/login", http.StatusSeeOther) |
| 197 | } |
| 198 | |
| 199 | func (u *webUI) docs(w http.ResponseWriter, r *http.Request) { |
| 200 | lang := u.lang(r) |
| 201 | var b bytes.Buffer |
| 202 | _ = docsTmpl.Execute(&b, map[string]any{"T": tfunc(lang), "Sections": docSections, "Listen": u.cfg.UIListen, "Server": u.cfg.URL}) |
| 203 | u.layout(w, r, lang, i18n.T(lang, "rdoc.title"), template.HTML(b.String())) |
| 204 | } |
| 205 | |
| 206 | func (u *webUI) layout(w http.ResponseWriter, r *http.Request, lang i18n.Lang, title string, body template.HTML) { |
| 207 | w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 208 | w.Header().Set("Cache-Control", "no-store") |
| 209 | back := r.URL.Path |
| 210 | if q := r.URL.Query(); len(q) > 0 { |
| 211 | q.Del("lang") |
| 212 | if e := q.Encode(); e != "" { |
| 213 | back += "?" + e |
| 214 | } |
| 215 | } |
| 216 | _ = layoutTmpl.Execute(w, map[string]any{ |
| 217 | "Title": title, "Body": body, "T": tfunc(lang), "Lang": string(lang), "LangPick": langpick.HTML(lang, "/lang", back, "", ""), |
| 218 | "Authed": u.authed(r), "CSRF": u.mac("csrf"), |
| 219 | }) |
| 220 | } |
| 221 | |
| 222 | // serveUI start de webinterface; fouten komen in de log, niet fataal. |
| 223 | func serveUI(ctx context.Context, u *webUI, listen string, logf func(string, ...any)) error { |
| 224 | ln, err := net.Listen("tcp", listen) |
| 225 | if err != nil { |
| 226 | return err |
| 227 | } |
| 228 | srv := &http.Server{Handler: u, ReadHeaderTimeout: 10 * time.Second} |
| 229 | u.listenMu.Lock() |
| 230 | u.hs, u.ln = srv, ln |
| 231 | u.listenMu.Unlock() |
| 232 | go func() { |
| 233 | <-ctx.Done() |
| 234 | sc, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 235 | defer cancel() |
| 236 | _ = srv.Shutdown(sc) |
| 237 | }() |
| 238 | go func() { |
| 239 | if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 240 | logf("web UI", "err", err) |
| 241 | } |
| 242 | }() |
| 243 | return nil |
| 244 | } |
| 245 | |
| 246 | func relistenUI(u *webUI, addr string, logf func(string, ...any)) error { |
| 247 | ln, err := net.Listen("tcp", addr) |
| 248 | if err != nil { |
| 249 | return err |
| 250 | } |
| 251 | newHS := &http.Server{Handler: u, ReadHeaderTimeout: 10 * time.Second} |
| 252 | u.listenMu.Lock() |
| 253 | old := u.hs |
| 254 | u.hs, u.ln = newHS, ln |
| 255 | u.listenMu.Unlock() |
| 256 | go func() { |
| 257 | if err := newHS.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 258 | logf("web UI", "err", err) |
| 259 | } |
| 260 | }() |
| 261 | if old != nil { |
| 262 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 263 | defer cancel() |
| 264 | _ = old.Shutdown(ctx) |
| 265 | } |
| 266 | return nil |
| 267 | } |
| 268 | |
| 269 | var layoutTmpl = template.Must(template.New("layout").Parse(`<!DOCTYPE html> |
| 270 | <html lang="{{.Lang}}"> |
| 271 | <head> |
| 272 | <meta charset="utf-8"> |
| 273 | <meta name="viewport" content="width=device-width, initial-scale=1"> |
| 274 | <title>{{.Title}} · BlueGit runner</title> |
| 275 | <link rel="icon" href="/assets/logo.svg" type="image/svg+xml"> |
| 276 | <link rel="stylesheet" href="/assets/style.css"> |
| 277 | </head> |
| 278 | <body data-modal-title="{{call .T "modal.title"}}" data-modal-ok="{{call .T "modal.ok"}}" data-modal-cancel="{{call .T "modal.cancel"}}"> |
| 279 | <header class="top"> |
| 280 | <a class="brand" href="/"><img src="/assets/logo.svg" alt=""> {{call .T "rui.brand"}}</a> |
| 281 | <nav class="rui-nav"> |
| 282 | {{if .Authed}}<a href="/">{{call .T "rui.nav.overview"}}</a>{{end}} |
| 283 | <a href="/docs">{{call .T "rui.nav.docs"}}</a> |
| 284 | {{.LangPick}} |
| 285 | {{if .Authed}}<form method="post" action="/logout"><input type="hidden" name="csrf" value="{{.CSRF}}"><button type="submit">{{call .T "rui.nav.logout"}}</button></form>{{end}} |
| 286 | </nav> |
| 287 | </header> |
| 288 | <div class="frame"><div class="content"><main class="wide"> |
| 289 | {{.Body}} |
| 290 | </main></div></div> |
| 291 | <script src="/assets/confirm.js"></script> |
| 292 | <script src="/assets/tip.js"></script> |
| 293 | <script src="/assets/langpick.js"></script> |
| 294 | </body> |
| 295 | </html>`)) |
| 296 | |
| 297 | var loginTmpl = template.Must(template.New("login").Parse(`<section class="panel rui-login"> |
| 298 | <h1>{{call .T "rui.login"}}</h1> |
| 299 | <p class="muted">{{call .T "rui.loginLead"}}</p> |
| 300 | <pre class="code">sudo bluegit-runner ui-token</pre> |
| 301 | {{if .Bad}}<p class="flash bad">{{call .T "rui.loginBad"}}</p>{{end}} |
| 302 | <form method="post" action="/login"> |
| 303 | <label>{{call .T "rui.token"}}<input type="password" name="token" autocomplete="current-password" required autofocus></label> |
| 304 | <button type="submit">{{call .T "rui.loginBtn"}}</button> |
| 305 | </form> |
| 306 | </section>`)) |
| 307 | |
| 308 | // docSections zijn de koppen van de docs-pagina op de runner; tekst uit de catalogus. |
| 309 | var docSections = []string{"intro", "network", "ui", "settings", "presets", "pause", "upgrade", "api", "trouble"} |
| 310 | |
| 311 | var docsTmpl = template.Must(template.New("docs").Parse(`<article class="panel rui-doc readme"> |
| 312 | <div class="mdbody"> |
| 313 | <h1>{{call .T "rdoc.title"}}</h1> |
| 314 | {{range .Sections}} |
| 315 | <h2 id="{{.}}">{{call $.T (printf "rdoc.%s.h" .)}}</h2> |
| 316 | <p>{{call $.T (printf "rdoc.%s.p" .)}}</p> |
| 317 | {{end}} |
| 318 | <h2 id="commands">{{call .T "rdoc.cmd.h"}}</h2> |
| 319 | <pre><code>sudo bluegit-runner ui-token |
| 320 | journalctl -u bluegit-runner -f |
| 321 | sudo -u bluegit-runner docker info |
| 322 | curl -H "Authorization: Bearer $(sudo cat /var/lib/bluegit-runner/ui-token)" http://{{.Listen}}/api/status |
| 323 | curl -X POST -H "Authorization: Bearer …" http://{{.Listen}}/api/pause</code></pre> |
| 324 | <p>{{call .T "rdoc.more"}} <a href="{{.Server}}/help/runners">{{.Server}}/help/runners</a></p> |
| 325 | </div> |
| 326 | </article>`)) |