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