Scaffold und Core-Infrastruktur 1:1 nach enconf-Pattern (netcell- webpanel/management-ui), reduziert auf EdgeGuard-Scope (kein reseller/ customer-Roles, keine codemirror/extensions). Stack: React 19 + AntD 6 + TS strict + Vite + TanStack-Query + zustand + react-i18next. Layout: AppLayout (Sider+Header+Content), Sidebar (Dashboard/Domains), Header (User-Dropdown + Logout). i18n mit de/en common.json. Pages: Login (POST /auth/login), Setup-Wizard (POST /setup/complete), Dashboard (Health-Polling + Statistics), Domains (volles CRUD via TanStack-Query gegen /domains-API). UpdateBanner-Komponente (/system/package-versions, alle 5 min poll, /system/upgrade trigger) ist von Tag 1 wie vom User gefordert eingebaut. API-Wiring: cmd/edgeguard-api/main.go mountUI() — gin StaticFS für /usr/share/edgeguard/ui/ (overridebar via EDGEGUARD_UI_DIR), echte Files werden direkt geserved, alle nicht-API-Pfade fallen via NoRoute auf index.html für React-Router-SPA. Wenn dist/ fehlt: HTML-Placeholder mit Build-Hinweis. Verifiziert: bun install + npx tsc -b strict (0 errors) + bun run build (12 chunks). End-to-end gegen /tmp/eg-api: / serviert echte React-index.html, /domains SPA-Fallback, /api/v1/* JSON, /assets/* direkt, /api/v1/nonexistent korrekt 404. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
233 lines
7.6 KiB
Go
233 lines
7.6 KiB
Go
// Command edgeguard-api serves the management REST API on
|
|
// 127.0.0.1:9443. HAProxy (or a dev curl) terminates TLS in front of
|
|
// it; this process is plain HTTP behind that.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"log"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/database"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/handlers"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/handlers/response"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/audit"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/backends"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/domains"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/routingrules"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/session"
|
|
"git.netcell-it.de/projekte/edgeguard-native/internal/services/setup"
|
|
)
|
|
|
|
var version = "0.0.1-dev"
|
|
|
|
func main() {
|
|
addr := os.Getenv("EDGEGUARD_API_ADDR")
|
|
if addr == "" {
|
|
addr = "127.0.0.1:9443"
|
|
}
|
|
|
|
dataDir := os.Getenv("EDGEGUARD_DATA_DIR")
|
|
if dataDir == "" {
|
|
dataDir = setup.DefaultDir
|
|
}
|
|
setupStore := setup.NewStore(dataDir)
|
|
|
|
signer, err := session.NewSignerFromPath("")
|
|
if err != nil {
|
|
// /var/lib/edgeguard not writable in dev → fall back to a
|
|
// process-local secret so `go run` works without sudo. Tokens
|
|
// won't survive a restart, which is fine for an unprivileged
|
|
// developer machine.
|
|
slog.Warn("session signer: persisted secret unavailable, using ephemeral",
|
|
"error", err)
|
|
signer = session.NewSigner(randomEphemeralSecret(), nil, 0)
|
|
}
|
|
|
|
gin.SetMode(gin.ReleaseMode)
|
|
r := gin.New()
|
|
r.Use(handlers.Recover())
|
|
|
|
// Health endpoints are mounted *before* SetupGate so they answer
|
|
// 200 even on a virgin box. UI uses /api/v1/system/health for the
|
|
// post-upgrade version-flip poll.
|
|
r.GET("/healthz", func(c *gin.Context) {
|
|
response.OK(c, gin.H{"status": "ok", "version": version})
|
|
})
|
|
r.GET("/api/health", func(c *gin.Context) {
|
|
response.OK(c, gin.H{"status": "ok", "version": version})
|
|
})
|
|
|
|
v1 := r.Group("/api/v1")
|
|
v1.Use(handlers.SetupGate(setupStore))
|
|
|
|
requireAuth := handlers.RequireAuth(signer)
|
|
|
|
handlers.NewSetupHandler(setupStore).Register(v1)
|
|
handlers.NewSystemHandler(version).Register(v1)
|
|
handlers.NewAuthHandler(setupStore, signer).Register(v1, requireAuth)
|
|
|
|
// Open the DB pool best-effort. Without a reachable PG, CRUD
|
|
// handlers stay unregistered and only Auth/Setup/System answer —
|
|
// good enough for `go run` on a developer machine that has no
|
|
// postgres-16 yet.
|
|
pool, err := openDBBestEffort()
|
|
if err != nil {
|
|
slog.Warn("DB pool unavailable, CRUD endpoints disabled",
|
|
"error", err)
|
|
} else {
|
|
slog.Info("DB pool open, registering CRUD handlers")
|
|
nodeID := nodeIDOrHostname()
|
|
|
|
auditRepo := audit.New(pool)
|
|
domainsRepo := domains.New(pool)
|
|
backendsRepo := backends.New(pool)
|
|
routingRepo := routingrules.New(pool)
|
|
|
|
authed := v1.Group("")
|
|
authed.Use(requireAuth)
|
|
handlers.NewDomainsHandler(domainsRepo, routingRepo, auditRepo, nodeID).Register(authed)
|
|
handlers.NewBackendsHandler(backendsRepo, auditRepo, nodeID).Register(authed)
|
|
handlers.NewRoutingRulesHandler(routingRepo, auditRepo, nodeID).Register(authed)
|
|
}
|
|
|
|
mountUI(r)
|
|
|
|
log.Printf("edgeguard-api %s listening on %s", version, addr)
|
|
srv := &http.Server{Addr: addr, Handler: r}
|
|
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
log.Fatalf("edgeguard-api: %v", err)
|
|
}
|
|
}
|
|
|
|
// mountUI serves the management UI — Vite-built static assets under
|
|
// /usr/share/edgeguard/ui/ — with SPA fallback (any path that isn't
|
|
// /api/* or /healthz and isn't a real file → index.html). When the
|
|
// dist directory is missing (dev box without `bun run build`), a
|
|
// placeholder HTML page is served at /.
|
|
func mountUI(r *gin.Engine) {
|
|
uiDir := os.Getenv("EDGEGUARD_UI_DIR")
|
|
if uiDir == "" {
|
|
uiDir = "/usr/share/edgeguard/ui"
|
|
}
|
|
indexPath := filepath.Join(uiDir, "index.html")
|
|
|
|
if _, err := os.Stat(indexPath); err != nil {
|
|
slog.Warn("UI dist not found, serving placeholder",
|
|
"ui_dir", uiDir, "error", err)
|
|
r.NoRoute(func(c *gin.Context) {
|
|
path := c.Request.URL.Path
|
|
if isAPIPath(path) {
|
|
c.Status(http.StatusNotFound)
|
|
return
|
|
}
|
|
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(uiPlaceholder))
|
|
})
|
|
return
|
|
}
|
|
|
|
r.NoRoute(func(c *gin.Context) {
|
|
path := c.Request.URL.Path
|
|
if isAPIPath(path) {
|
|
c.Status(http.StatusNotFound)
|
|
return
|
|
}
|
|
// Serve real file when one exists for the requested path.
|
|
// filepath.Clean blocks `..` traversal; the join still pins
|
|
// the result inside uiDir even with shenanigans.
|
|
clean := filepath.Clean(path)
|
|
if !strings.HasPrefix(clean, "/") {
|
|
clean = "/" + clean
|
|
}
|
|
full := filepath.Join(uiDir, clean)
|
|
if !strings.HasPrefix(full, uiDir) {
|
|
c.Status(http.StatusForbidden)
|
|
return
|
|
}
|
|
if info, err := os.Stat(full); err == nil && !info.IsDir() {
|
|
c.File(full)
|
|
return
|
|
}
|
|
// SPA fallback — React Router renders the right page.
|
|
c.File(indexPath)
|
|
})
|
|
}
|
|
|
|
// isAPIPath returns true for paths the API owns; UI serves
|
|
// everything else. /healthz and /api/health are technically API
|
|
// surfaces but don't need to fall through to index.html either.
|
|
func isAPIPath(p string) bool {
|
|
return strings.HasPrefix(p, "/api/") || p == "/healthz" || p == "/api/health"
|
|
}
|
|
|
|
const uiPlaceholder = `<!doctype html>
|
|
<html lang="en"><head><meta charset="utf-8"><title>EdgeGuard</title></head>
|
|
<body style="font-family: -apple-system, sans-serif; max-width: 640px; margin: 4em auto; line-height: 1.5;">
|
|
<h1>EdgeGuard</h1>
|
|
<p>The management UI has not been built yet. From the project root, run:</p>
|
|
<pre style="background:#f4f4f4;padding:12px;border-radius:4px;">cd management-ui && bun install && bun run build</pre>
|
|
<p>Then the same URL will serve the React SPA. The REST API is fully functional at
|
|
<code>/api/v1/*</code> regardless.</p>
|
|
</body></html>`
|
|
|
|
// openDBBestEffort opens the pool with a 3s timeout. Returns the
|
|
// non-nil error so callers can decide whether to register CRUD or
|
|
// degrade gracefully.
|
|
func openDBBestEffort() (*pgxpoolPool, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer cancel()
|
|
dsn := database.ConnStringFromEnv()
|
|
return database.Open(ctx, dsn)
|
|
}
|
|
|
|
// pgxpoolPool aliases the concrete pool type so we don't import it in
|
|
// main.go on every platform — keeps the import block lean.
|
|
type pgxpoolPool = pgxpool.Pool
|
|
|
|
// nodeIDOrHostname returns the node identifier audit_log entries are
|
|
// stamped with. v1 just uses /etc/machine-id (or the hostname on dev
|
|
// machines without one). Phase 3's cluster store will replace this.
|
|
func nodeIDOrHostname() string {
|
|
if b, err := os.ReadFile("/etc/machine-id"); err == nil {
|
|
s := string(b)
|
|
s = stripTrailingNewline(s)
|
|
if s != "" {
|
|
return s
|
|
}
|
|
}
|
|
if h, err := os.Hostname(); err == nil {
|
|
return h
|
|
}
|
|
return "unknown"
|
|
}
|
|
|
|
func stripTrailingNewline(s string) string {
|
|
for len(s) > 0 && (s[len(s)-1] == '\n' || s[len(s)-1] == '\r') {
|
|
s = s[:len(s)-1]
|
|
}
|
|
return s
|
|
}
|
|
|
|
// randomEphemeralSecret is the fallback for dev environments where
|
|
// /var/lib/edgeguard isn't writable. Tokens issued with this secret
|
|
// die on restart — production reads/writes the persistent file via
|
|
// session.NewSignerFromPath.
|
|
func randomEphemeralSecret() []byte {
|
|
b := make([]byte, 32)
|
|
if _, err := rand.Read(b); err != nil {
|
|
// Should never happen on a sane Linux box; fall back to a
|
|
// time-based filler so the process can at least start.
|
|
log.Printf("WARN: crypto/rand read failed: %v", err)
|
|
}
|
|
return b
|
|
}
|