package web import ( "context" "crypto/rand" "crypto/subtle" "encoding/hex" "encoding/json" "fmt" "html/template" "log" "math" "net/http" "strings" "sync" "time" "gitea.dooplex.hu/admin/felhom-hub/internal/assets" "gitea.dooplex.hu/admin/felhom-hub/internal/gitea" "gitea.dooplex.hu/admin/felhom-hub/internal/offsite" "gitea.dooplex.hu/admin/felhom-hub/internal/semver" "gitea.dooplex.hu/admin/felhom-hub/internal/store" "golang.org/x/crypto/bcrypt" ) // Generic-package names + the artifact filename inside each version (used to resolve version lists + // sha256 from Gitea for the Day-0 artifact manifest UI). const ( pkgAgent = "felhom-agent" fileAgent = "felhom-agent" pkgGolden = "felhom-golden" fileGolden = "golden.tar.zst" ) // artifactChoice is one selectable artifact version + its Gitea-resolved sha256 (for the dropdown + // the read-only sha display). type artifactChoice struct { Version string SHA256 string } // hubSession holds per-session auth and CSRF data. type hubSession struct { expiresAt time.Time csrfToken string } // Server handles the dashboard web UI. type Server struct { store *store.Store passwordHash string apiKey string // report API key — used for controller callbacks version string logger *log.Logger templates *template.Template staleThreshold time.Duration versionChecker *VersionChecker templateFetcher *TemplateFetcher assetsMgr *assets.Manager gitea *gitea.Client // optional; enables the Day-0 artifact version dropdowns offsite *offsite.Provisioner // optional; enables Hetzner offsite provisioning (SLICE 1) tenantsync tenancyProvisioner // optional; enables PBS DR tier provisioning (web/pbsdr.go) sessions map[string]*hubSession sessionsMu sync.RWMutex } // New creates a new web server. func New(store *store.Store, passwordHash, apiKey, version string, staleThreshold time.Duration, logger *log.Logger) *Server { funcMap := template.FuncMap{ "timeAgo": timeAgo, "timeAgoPtr": func(t *time.Time) string { if t == nil { return "—" } return timeAgo(*t) }, "statusColor": statusColor, "formatFloat": func(f float64) string { return fmt.Sprintf("%.0f", f) }, "joinStrings": func(s []string, sep string) string { return strings.Join(s, sep) }, "json": func(v interface{}) template.JS { b, _ := json.Marshal(v) return template.JS(b) }, "hubVersion": func() string { return version }, "add": func(a, b int) int { return a + b }, "mapGet": func(m map[string]int, key string) int { if m == nil { return 0 } return m[key] }, "memoryColor": memoryColor, "accuracyClass": accuracyClass, "gt": func(a, b int) bool { return a > b }, } tmpl := template.Must(template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/*.html")) return &Server{ store: store, passwordHash: passwordHash, apiKey: apiKey, version: version, logger: logger, templates: tmpl, staleThreshold: staleThreshold, sessions: make(map[string]*hubSession), } } // CleanupSessions removes expired sessions. Call with: go s.CleanupSessions(ctx). func (s *Server) CleanupSessions(ctx context.Context) { ticker := time.NewTicker(15 * time.Minute) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: s.sessionsMu.Lock() now := time.Now() for t, sess := range s.sessions { if now.After(sess.expiresAt) { delete(s.sessions, t) } } s.sessionsMu.Unlock() } } } // SetVersionChecker sets the version checker (optional, may be nil if no registry credentials). func (s *Server) SetVersionChecker(vc *VersionChecker) { s.versionChecker = vc } // SetTemplateFetcher sets the template fetcher for config generation (optional). func (s *Server) SetTemplateFetcher(tf *TemplateFetcher) { s.templateFetcher = tf } // SetAssetManager sets the asset manager for the Configuration page (optional). func (s *Server) SetAssetManager(am *assets.Manager) { s.assetsMgr = am } // SetOffsiteProvisioner enables Hetzner offsite provisioning (optional). Without it, saving a config with // offsite enabled returns an error (offsite not configured on this hub). func (s *Server) SetOffsiteProvisioner(p *offsite.Provisioner) { s.offsite = p } // SetGiteaClient enables the Day-0 artifact version dropdowns (optional). Without it the artifact form // degrades to manual text entry. func (s *Server) SetGiteaClient(c *gitea.Client) { s.gitea = c } // artifactChoices resolves the currently-available versions of a generic package + each one's sha256 // from Gitea, newest first, for the Day-0 artifact dropdown. Returns nil (→ manual text-entry // fallback) when no Gitea client is configured or Gitea is unreachable. A failed sha lookup for a // single version drops just that version, not the whole list. func (s *Server) artifactChoices(ctx context.Context, pkg, file string) []artifactChoice { if s.gitea == nil { return nil } vers, err := s.gitea.ListVersions(ctx, pkg) if err != nil { s.logger.Printf("[WARN] artifact versions (%s): %v", pkg, err) return nil } const maxChoices = 20 if len(vers) > maxChoices { s.logger.Printf("[INFO] artifact versions (%s): showing newest %d of %d", pkg, maxChoices, len(vers)) vers = vers[:maxChoices] } out := make([]artifactChoice, 0, len(vers)) for _, v := range vers { sha, err := s.gitea.FileSHA256(ctx, pkg, v, file) if err != nil { s.logger.Printf("[WARN] artifact sha (%s/%s): %v", pkg, v, err) continue } out = append(out, artifactChoice{Version: v, SHA256: sha}) } return out } // ServeHTTP routes web requests. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { path := r.URL.Path // CSRF protection for all state-changing requests (web routes only). // API routes (/api/v1/) are Bearer-token authenticated and exempt. if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodOptions { if path != "/login" && s.passwordHash != "" { if !s.validateCSRF(r) { s.logger.Printf("[WARN] CSRF rejected: %s %s from %s", r.Method, path, r.RemoteAddr) http.Error(w, "CSRF token missing or invalid. Please reload the page.", http.StatusForbidden) return } } } switch { case path == "/": s.handleDashboard(w, r) case path == "/style.css": s.handleCSS(w, r) case path == "/static/chart.min.js": w.Header().Set("Content-Type", "application/javascript") w.Header().Set("Cache-Control", "public, max-age=86400") w.Write(chartJS) case strings.HasPrefix(path, "/static/fonts/"): // Vendored brand fonts (design system v2) — embedded, no CDN. name := strings.TrimPrefix(path, "/static/fonts/") data, err := fontFS.ReadFile("static/fonts/" + name) if err != nil { http.NotFound(w, r) return } w.Header().Set("Content-Type", "font/woff2") w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") w.Write(data) case path == "/configuration": if r.Method == http.MethodPost { s.handleConfigurationAction(w, r) } else { s.handleConfiguration(w, r) } case path == "/apps" || path == "/apps/": s.handleApps(w, r) case strings.HasPrefix(path, "/apps/") && strings.HasSuffix(path, "/reset-telemetry"): appName := strings.TrimPrefix(path, "/apps/") appName = strings.TrimSuffix(appName, "/reset-telemetry") if r.Method == http.MethodPost { s.handleResetAppTelemetry(w, r, appName) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/apps/") && strings.HasSuffix(path, "/dismiss-issues"): appName := strings.TrimPrefix(path, "/apps/") appName = strings.TrimSuffix(appName, "/dismiss-issues") if r.Method == http.MethodPost { s.handleDismissAppIssues(w, r, appName) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/apps/"): appName := strings.TrimPrefix(path, "/apps/") s.handleAppDetail(w, r, appName) // Offsite — read-only WG endpoint + peer registry (S2). Mutations stay on the admin API. case path == "/offsite": s.handleOffsite(w, r) // Hosts — read-only fleet view (audit F-M1) + the v0.46.0 log-bundle actions. case path == "/hosts" || path == "/hosts/": s.handleHostsList(w, r) case strings.HasPrefix(path, "/hosts/") && strings.HasSuffix(path, "/request-logs"): hostID := strings.TrimSuffix(strings.TrimPrefix(path, "/hosts/"), "/request-logs") if r.Method == http.MethodPost { s.handleRequestLogBundle(w, r, hostID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/hosts/") && strings.Contains(path, "/log-bundles/"): rest := strings.TrimPrefix(path, "/hosts/") if i := strings.Index(rest, "/log-bundles/"); i > 0 { s.handleLogBundleView(w, r, rest[:i], rest[i+len("/log-bundles/"):]) } else { http.NotFound(w, r) } case strings.HasPrefix(path, "/hosts/"): hostID := strings.TrimPrefix(path, "/hosts/") s.handleHostDetail(w, r, hostID) case path == "/login": s.handleLogin(w, r) case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/block"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/block") if r.Method == http.MethodPost { s.handleBlockCustomer(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/unblock"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/unblock") if r.Method == http.MethodPost { s.handleUnblockCustomer(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/geo/disable"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/geo/disable") if r.Method == http.MethodPost { s.handleGeoDisable(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/floor"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/floor") if r.Method == http.MethodPost { s.handleSetCustomerFloor(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/create-config"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/create-config") if r.Method == http.MethodPost { s.handleCreateConfigFromReport(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/dr-recipe.json"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/dr-recipe.json") s.handleDRRecipeDownload(w, r, customerID) case strings.HasPrefix(path, "/customers/") && strings.HasSuffix(path, "/request-log-tail"): customerID := strings.TrimPrefix(path, "/customers/") customerID = strings.TrimSuffix(customerID, "/request-log-tail") if r.Method == http.MethodPost { s.handleRequestLogTail(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/customers/") && strings.Contains(path, "/log-tail/"): rest := strings.TrimPrefix(path, "/customers/") parts := strings.SplitN(rest, "/log-tail/", 2) if len(parts) != 2 { http.NotFound(w, r) return } s.handleLogTailView(w, r, parts[0], parts[1]) case strings.HasPrefix(path, "/customers/"): customerID := strings.TrimPrefix(path, "/customers/") s.handleCustomerUnified(w, r, customerID) // Config management routes — exact matches first, then prefix matches case path == "/configs": s.handleConfigList(w, r) case path == "/configs/new": if r.Method == http.MethodPost { s.handleConfigCreate(w, r) } else { s.handleConfigNewForm(w, r) } // Global settings live under the Configuration tab (moved from Customers). case path == "/configuration/global-floor/impact": if r.Method == http.MethodGet { s.handleGlobalFloorImpact(w, r) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case path == "/configuration/global-floor": if r.Method == http.MethodPost { s.handleSetGlobalFloor(w, r) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case path == "/configuration/artifacts": if r.Method == http.MethodPost { s.handleSetArtifacts(w, r) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/delete"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/delete") if r.Method == http.MethodPost { s.handleConfigDelete(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/edit"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/edit") if r.Method == http.MethodPost { s.handleConfigUpdate(w, r, customerID) } else { s.handleConfigEditForm(w, r, customerID) } case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/offsite-reissue"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/offsite-reissue") if r.Method == http.MethodPost { s.handleOffsiteReissue(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/pbsdr-reissue"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/pbsdr-reissue") if r.Method == http.MethodPost { s.handlePBSDRReissue(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/offsite-freeze"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/offsite-freeze") if r.Method == http.MethodPost { s.handleOffsiteFreeze(w, r, customerID, r.FormValue("unfreeze") != "1") } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/preview"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/preview") s.handleConfigPreview(w, r, customerID) case strings.HasPrefix(path, "/configs/") && strings.HasSuffix(path, "/regen-password"): customerID := strings.TrimPrefix(path, "/configs/") customerID = strings.TrimSuffix(customerID, "/regen-password") if r.Method == http.MethodPost { s.handleConfigRegenPassword(w, r, customerID) } else { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) } case strings.HasPrefix(path, "/configs/"): // Redirect old config detail URL to unified customer page customerID := strings.TrimPrefix(path, "/configs/") http.Redirect(w, r, "/customers/"+customerID, http.StatusSeeOther) default: http.NotFound(w, r) } } // RequireAuth wraps a handler with session or basic authentication. func (s *Server) RequireAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Skip auth if no password configured if s.passwordHash == "" { next.ServeHTTP(w, r) return } // Always allow the login page through (GET and POST) if r.URL.Path == "/login" { next.ServeHTTP(w, r) return } // Check session cookie (random token stored server-side) if cookie, err := r.Cookie("hub_session"); err == nil { s.sessionsMu.RLock() sess, ok := s.sessions[cookie.Value] s.sessionsMu.RUnlock() if ok && time.Now().Before(sess.expiresAt) { next.ServeHTTP(w, r) return } } // Check basic auth (for programmatic/CLI access) _, password, ok := r.BasicAuth() if ok && bcrypt.CompareHashAndPassword([]byte(s.passwordHash), []byte(password)) == nil { next.ServeHTTP(w, r) return } // Redirect browsers to login page; send 401 for API-like requests if r.Header.Get("Accept") == "application/json" || r.Header.Get("X-Requested-With") != "" { w.Header().Set("WWW-Authenticate", `Basic realm="Felhom Hub"`) http.Error(w, "Unauthorized", http.StatusUnauthorized) return } http.Redirect(w, r, "/login", http.StatusFound) }) } func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { password := r.FormValue("password") if s.passwordHash != "" && bcrypt.CompareHashAndPassword([]byte(s.passwordHash), []byte(password)) == nil { // Generate random session token b := make([]byte, 32) _, _ = rand.Read(b) sessionToken := hex.EncodeToString(b) // Generate CSRF token cb := make([]byte, 32) _, _ = rand.Read(cb) csrfToken := hex.EncodeToString(cb) s.sessionsMu.Lock() s.sessions[sessionToken] = &hubSession{ expiresAt: time.Now().Add(7 * 24 * time.Hour), csrfToken: csrfToken, } s.sessionsMu.Unlock() isSecure := r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" http.SetCookie(w, &http.Cookie{ Name: "hub_session", Value: sessionToken, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: isSecure, MaxAge: 86400 * 7, }) http.Redirect(w, r, "/", http.StatusSeeOther) return } // Render login with error w.WriteHeader(http.StatusUnauthorized) w.Write([]byte(`