// Commande server : suivi des mises à jour de stacks docker compose (SSH) + frontend embarqué. package main import ( "context" "errors" "fmt" "io/fs" "log/slog" "net" "net/http" "net/url" "os" "os/signal" "path" "path/filepath" "strconv" "strings" "syscall" "time" "github.com/vblogio/stackwatch/internal/api" "github.com/vblogio/stackwatch/internal/auth" "github.com/vblogio/stackwatch/internal/fleet" "github.com/vblogio/stackwatch/web" ) // version est renseignée au build (-ldflags "-X main.version=..."). var version = "dev" func env(key, def string) string { if v := os.Getenv(key); v != "" { return v } return def } // envBool lit un booléen ; une valeur illisible est une erreur de configuration. func envBool(key string, def bool) bool { v := os.Getenv(key) if v == "" { return def } b, err := strconv.ParseBool(v) if err != nil { fatal(key + " invalide (true ou false)") } return b } func envInt(key string, def int64) int64 { v := os.Getenv(key) if v == "" { return def } n, err := strconv.ParseInt(v, 10, 64) if err != nil || n < 0 { fatal(key + " invalide (entier >= 0)") } return n } func fatal(msg string, args ...any) { slog.Error(msg, args...) os.Exit(1) } // secretEnv lit un secret dans NAME, ou dans le fichier NAME_FILE (secrets Docker). func secretEnv(name string) string { if v := os.Getenv(name); v != "" { return v } if f := os.Getenv(name + "_FILE"); f != "" { b, err := os.ReadFile(f) if err != nil { fatal(name+"_FILE illisible", "err", err) } return strings.TrimSpace(string(b)) } return "" } func main() { slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil))) addr := env("LISTEN_ADDR", ":8080") // `server healthcheck` : sonde pour le conteneur. if len(os.Args) > 1 && os.Args[1] == "healthcheck" { os.Exit(healthcheck(addr)) } dataDir := env("DATA_DIR", "./data") if err := os.MkdirAll(dataDir, 0o700); err != nil { fatal("répertoire de données", "dir", dataDir, "err", err) } ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() // Clé SSH : SSH_KEY_FILE, ou une clé ed25519 créée dans DATA_DIR/ssh au premier démarrage. keyFile, pub, err := fleet.EnsureKey(filepath.Join(dataDir, "ssh"), os.Getenv("SSH_KEY_FILE")) if err != nil { fatal("clé SSH", "err", err) } runner := fleet.SSH{KeyFile: keyFile, KnownHosts: env("SSH_KNOWN_HOSTS", filepath.Join(dataDir, "ssh", "known_hosts")), Timeout: int(envInt("SSH_CONNECT_TIMEOUT", 10))} manager, err := fleet.Open(ctx, filepath.Join(dataDir, "fleet"), runner, int(envInt("MAX_PARALLEL", 4))) if err != nil { fatal("serveurs", "err", err) } interval, err := time.ParseDuration(env("CHECK_INTERVAL", "6h")) if err != nil || interval < 0 || (interval > 0 && interval < 5*time.Minute) { fatal("CHECK_INTERVAL invalide (ex. 6h, minimum 5m, 0 : pas d'analyse automatique)") } manager.Interval = interval go manager.Run(ctx) mode := strings.ToLower(env("AUTH_MODE", "local")) handler := (&api.Handler{Fleet: manager, Mode: mode, Version: version, Title: env("TITLE", "Stackwatch"), PublicKey: pub, Interval: interval}).Init() mux := http.NewServeMux() var root http.Handler = mux switch mode { case "none": // Aucune authentification intégrée (reverse proxy avec SSO, usage local). slog.Warn("aucune authentification intégrée (AUTH_MODE=none) : à réserver à un reverse proxy qui authentifie") case "local", "oidc", "both": accounts, err := auth.OpenAccounts(dataDir) if err != nil { fatal("comptes", "err", err) } handler.Accounts = accounts a, err := authentication(ctx, mode, dataDir, accounts, handler) if err != nil { fatal("authentification", "err", err) } a.Register(mux) handler.Auth = a root = a.Middleware(mux, public) default: fatal(fmt.Sprintf("AUTH_MODE %q inconnu (local, oidc, both ou none)", mode)) } handler.Register(mux) mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }) mux.Handle("/", spa()) srv := &http.Server{ Addr: addr, Handler: logRequests(securityHeaders(sameOrigin(root))), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, } go func() { slog.Info("démarrage", "addr", addr, "data", dataDir, "auth", mode, "version", version, "check_interval", interval.String()) if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { fatal("serveur", "err", err) } }() <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() _ = srv.Shutdown(shutdownCtx) slog.Info("arrêt") } // authentication prépare l'authentification locale (comptes, inscription) et/ou OIDC. func authentication(ctx context.Context, mode, dataDir string, accounts *auth.Accounts, h *api.Handler) (*auth.Auth, error) { secret, err := auth.LoadSecret(os.Getenv("SESSION_SECRET"), dataDir) if err != nil { return nil, err } ttl, err := time.ParseDuration(env("SESSION_TTL", "24h")) if err != nil || ttl < 5*time.Minute { return nil, errors.New("SESSION_TTL invalide (ex. 24h, minimum 5m)") } registration := strings.ToLower(env("REGISTRATION", "closed")) if registration != "closed" && registration != "approval" && registration != "open" { return nil, errors.New("REGISTRATION invalide (closed, approval ou open)") } pub := publicURL() secureCookies := strings.HasPrefix(pub, "https://") || strings.HasPrefix(os.Getenv("OIDC_REDIRECT_URL"), "https://") sessions := auth.NewSessions(secret, ttl, secureCookies) a := auth.New(&auth.Auth{ Accounts: accounts, Sessions: sessions, Local: mode == "local" || mode == "both", Registration: func() string { return registration }, OIDCName: env("OIDC_NAME", "SSO"), }) h.OIDCName = a.OIDCName if a.Local { if user := os.Getenv("ADMIN_USER"); user != "" { pass := secretEnv("ADMIN_PASSWORD") if pass == "" { return nil, errors.New("ADMIN_USER défini sans ADMIN_PASSWORD") } if err := accounts.EnsureAdmin(user, pass); err != nil { return nil, fmt.Errorf("administrateur initial : %w", err) } } if accounts.NeedsSetup() { slog.Warn("aucun administrateur : le premier compte créé (inscription) le deviendra ; définir ADMIN_USER et ADMIN_PASSWORD pour l'imposer") } } if mode == "local" { return a, nil } // OIDC cfg, err := oidcConfig(secret, ttl) if err != nil { return nil, err } cfg.Sessions = sessions policy := auth.OIDCPolicy{AdminGroups: fields(os.Getenv("OIDC_ADMIN_GROUPS")), AdminEmails: fields(os.Getenv("OIDC_ADMIN_EMAILS"))} cfg.Provision = func(u auth.User, groups []string) (auth.User, error) { return accounts.UpsertOIDC(u, groups, policy) } o, err := auth.NewOIDC(ctx, cfg) if err != nil { return nil, err } a.OIDC = o slog.Info("authentification OIDC activée", "issuer", cfg.Issuer, "client_id", cfg.ClientID, "groups", cfg.AllowedGroups, "admin_groups", policy.AdminGroups, "session_ttl", ttl.String()) return a, nil } // publicURL est l'origine publique du service : PUBLIC_URL, sinon celle de // OIDC_REDIRECT_URL ; vide, elle est déduite de chaque requête. func publicURL() string { if v := os.Getenv("PUBLIC_URL"); v != "" { return strings.TrimRight(v, "/") } if u, err := url.Parse(os.Getenv("OIDC_REDIRECT_URL")); err == nil && u.Scheme != "" && u.Host != "" { return u.Scheme + "://" + u.Host } return "" } // oidcConfig lit les variables OIDC_*. func oidcConfig(secret []byte, ttl time.Duration) (auth.Config, error) { cfg := auth.Config{ Issuer: os.Getenv("OIDC_ISSUER"), ClientID: os.Getenv("OIDC_CLIENT_ID"), ClientSecret: secretEnv("OIDC_CLIENT_SECRET"), RedirectURL: os.Getenv("OIDC_REDIRECT_URL"), Scopes: fields(env("OIDC_SCOPES", "openid profile email groups")), GroupsClaim: env("OIDC_GROUPS_CLAIM", "groups"), SessionTTL: ttl, Secret: secret, } cfg.AllowedGroups = fields(os.Getenv("OIDC_ALLOWED_GROUPS")) var err error if cfg.EndSession, err = strconv.ParseBool(env("OIDC_LOGOUT", "true")); err != nil { return cfg, errors.New("OIDC_LOGOUT invalide (true ou false)") } return cfg, nil } // fields découpe une liste séparée par des espaces ou des virgules. func fields(s string) []string { return strings.FieldsFunc(s, func(r rune) bool { return r == ' ' || r == ',' }) } func healthcheck(addr string) int { host, port, err := net.SplitHostPort(addr) if err != nil { return 1 } if host == "" || host == "0.0.0.0" || host == "::" { host = "127.0.0.1" } c := http.Client{Timeout: 3 * time.Second} res, err := c.Get("http://" + net.JoinHostPort(host, port) + "/healthz") if err != nil { return 1 } res.Body.Close() if res.StatusCode != http.StatusOK { return 1 } return 0 } // spa sert le build Vite embarqué ; toute route inconnue renvoie index.html. func spa() http.Handler { dist, _ := fs.Sub(web.Dist, "dist") files := http.FileServerFS(dist) return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { p := path.Clean(r.URL.Path) if p != "/" { if fi, err := fs.Stat(dist, p[1:]); err == nil && !fi.IsDir() { // Les assets Vite sont nommés par empreinte : cache long. if path.Dir(p) == "/assets" { w.Header().Set("Cache-Control", "public, max-age=31536000, immutable") } files.ServeHTTP(w, r) return } } index, err := fs.ReadFile(dist, "index.html") if err != nil { http.Error(w, "frontend absent : lancer `npm run build` dans frontend/", http.StatusNotFound) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache") _, _ = w.Write(index) }) } // public indique les chemins servis sans session : sonde, état de la connexion // (/api/me : page de connexion) et fichiers statiques du build (code de // l'application, sans aucune donnée). func public(p string) bool { switch { case p == "/healthz", p == "/api/me": return true case strings.HasPrefix(p, "/api/"), p == "/", p == "/index.html": return false } dist, _ := fs.Sub(web.Dist, "dist") fi, err := fs.Stat(dist, strings.TrimPrefix(path.Clean(p), "/")) return err == nil && !fi.IsDir() } // sameOrigin refuse les requêtes qui modifient des données et viennent d'un // autre site (CSRF) : l'en-tête Origin d'une requête de navigateur doit // désigner l'hôte du service. Les requêtes sans Origin (curl, jetons d'API) // ne sont pas concernées. func sameOrigin(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet, http.MethodHead, http.MethodOptions: default: if r.Header.Get("Sec-Fetch-Site") == "cross-site" { http.Error(w, "origine refusée", http.StatusForbidden) return } if o := r.Header.Get("Origin"); o != "" && o != "null" { host := r.Host if h := r.Header.Get("X-Forwarded-Host"); h != "" { host, _, _ = strings.Cut(h, ",") host = strings.TrimSpace(host) } if u, err := url.Parse(o); err != nil || !strings.EqualFold(u.Host, host) { http.Error(w, "origine refusée", http.StatusForbidden) return } } } next.ServeHTTP(w, r) }) } func securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Set("X-Content-Type-Options", "nosniff") h.Set("Referrer-Policy", "same-origin") h.Set("X-Frame-Options", "SAMEORIGIN") h.Set("X-Robots-Tag", "noindex, nofollow") next.ServeHTTP(w, r) }) } type statusWriter struct { http.ResponseWriter status int } func (s *statusWriter) WriteHeader(code int) { s.status = code s.ResponseWriter.WriteHeader(code) } // Unwrap permet à http.ResponseController (Flush, SetWriteDeadline) d'atteindre // l'écrivain d'origine. func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter } func (s *statusWriter) Flush() { if f, ok := s.ResponseWriter.(http.Flusher); ok { f.Flush() } } func logRequests(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() sw := &statusWriter{ResponseWriter: w, status: http.StatusOK} next.ServeHTTP(sw, r) if r.URL.Path != "/healthz" { p := r.URL.Path slog.Info("http", "method", r.Method, "path", p, "status", sw.status, "dur_ms", time.Since(start).Milliseconds()) } }) }