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