- planification crontab par stack (autoupdate.json), incompatible avec l'exclusion
- scheduler a la minute ; pull puis down + up -d seulement si une image a change (mode autoapply)
- API PUT .../targets/{t}/auto et GET /api/cron (apercu des prochaines executions)
- interface : option dans le detail, badge sarcelle, vue de suivi "Mises a jour auto"
- TZ dans docker-compose / .env.example (tzdata embarque)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LNfwm6UCYFyvNQNSF5i9Gy
302 lines
9.3 KiB
Go
302 lines
9.3 KiB
Go
// Package api expose le suivi des stacks en REST/JSON.
|
|
//
|
|
// GET /api/me session, fournisseurs d'identité (sans authentification)
|
|
// GET /api/fleet serveurs, connexions, stacks, résumé ; clé publique SSH (administrateur)
|
|
// GET /api/summary compteurs (stacks, mises à jour, erreurs...)
|
|
// POST /api/check analyse de tous les serveurs actifs
|
|
// POST /api/servers/{id}/check[?target=t] analyse d'un serveur (ou d'une de ses connexions)
|
|
// POST /api/servers (administrateur) ajout d'un serveur
|
|
// PUT /api/servers/{id} (administrateur) modification
|
|
// DELETE /api/servers/{id} (administrateur) suppression
|
|
// POST /api/servers/{id}/test (administrateur) test de la connexion SSH, de docker et de docker compose
|
|
// POST /api/servers/{id}/targets/{t}/apply {"dir"} mise à jour d'une stack : pull, down, up -d (administrateur)
|
|
// PUT /api/servers/{id}/targets/{t}/exclude {"dir","excluded"} exclut une stack des mises à jour ou la réactive (administrateur)
|
|
// PUT /api/servers/{id}/targets/{t}/auto {"dir","schedule"} programme (crontab) ou desactive ("") la mise a jour auto d'une stack (administrateur)
|
|
// GET /api/cron?expr=... validation d'une planification et prochaines executions
|
|
// POST /api/account/password, PATCH /api/account compte local
|
|
// GET|POST /api/admin/users, PATCH|DELETE /api/admin/users/{id} comptes (administrateur)
|
|
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/vblogio/stackwatch/internal/auth"
|
|
"github.com/vblogio/stackwatch/internal/fleet"
|
|
)
|
|
|
|
// LocalUser identifie l'utilisateur sans authentification intégrée.
|
|
const LocalUser = "local"
|
|
|
|
// Handler regroupe les routes de l'API.
|
|
type Handler struct {
|
|
Fleet *fleet.Manager
|
|
|
|
Auth *auth.Auth // nil : pas d'authentification intégrée
|
|
Accounts *auth.Accounts // nil : pas de comptes (AUTH_MODE=none)
|
|
|
|
Mode string // none, local, oidc ou both
|
|
OIDCName string
|
|
Title string
|
|
Version string
|
|
PublicKey string // clé publique SSH à autoriser sur les serveurs
|
|
Interval time.Duration // analyse périodique (0 : désactivée)
|
|
|
|
MaxJSON int64
|
|
}
|
|
|
|
// Init prépare les valeurs par défaut.
|
|
func (h *Handler) Init() *Handler {
|
|
if h.MaxJSON == 0 {
|
|
h.MaxJSON = 1 << 20
|
|
}
|
|
if h.Title == "" {
|
|
h.Title = "Stackwatch"
|
|
}
|
|
return h
|
|
}
|
|
|
|
// UserID identifie l'utilisateur d'une requête.
|
|
func UserID(r *http.Request) string {
|
|
if u := auth.UserFrom(r.Context()); u != nil && u.ID != "" {
|
|
return u.ID
|
|
}
|
|
return LocalUser
|
|
}
|
|
|
|
// isAdmin : sans authentification intégrée (AUTH_MODE=none), tout le monde
|
|
// administre, le contrôle d'accès étant celui du reverse proxy.
|
|
func (h *Handler) isAdmin(r *http.Request) bool {
|
|
if h.Mode == "none" {
|
|
return true
|
|
}
|
|
u := auth.UserFrom(r.Context())
|
|
return u != nil && u.Role == auth.RoleAdmin
|
|
}
|
|
|
|
func (h *Handler) admin(w http.ResponseWriter, r *http.Request) bool {
|
|
if !h.isAdmin(r) {
|
|
writeErr(w, http.StatusForbidden, "réservé aux administrateurs")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// Register enregistre les routes sur mux.
|
|
func (h *Handler) Register(mux *http.ServeMux) {
|
|
mux.HandleFunc("GET /api/me", h.me)
|
|
mux.HandleFunc("GET /api/fleet", h.getFleet)
|
|
mux.HandleFunc("GET /api/summary", h.summary)
|
|
mux.HandleFunc("POST /api/check", h.checkAll)
|
|
mux.HandleFunc("POST /api/servers", h.addServer)
|
|
mux.HandleFunc("PUT /api/servers/{id}", h.updateServer)
|
|
mux.HandleFunc("DELETE /api/servers/{id}", h.deleteServer)
|
|
mux.HandleFunc("POST /api/servers/{id}/check", h.checkServer)
|
|
mux.HandleFunc("POST /api/servers/{id}/test", h.testServer)
|
|
mux.HandleFunc("POST /api/servers/{id}/targets/{target}/apply", h.apply)
|
|
mux.HandleFunc("PUT /api/servers/{id}/targets/{target}/exclude", h.exclude)
|
|
mux.HandleFunc("PUT /api/servers/{id}/targets/{target}/auto", h.autoUpdate)
|
|
mux.HandleFunc("GET /api/cron", h.cronPreview)
|
|
if h.Accounts != nil {
|
|
mux.HandleFunc("POST /api/account/password", h.changePassword)
|
|
mux.HandleFunc("PATCH /api/account", h.patchAccount)
|
|
mux.HandleFunc("GET /api/admin/users", h.adminUsers)
|
|
mux.HandleFunc("POST /api/admin/users", h.adminCreateUser)
|
|
mux.HandleFunc("PATCH /api/admin/users/{id}", h.adminPatchUser)
|
|
mux.HandleFunc("DELETE /api/admin/users/{id}", h.adminDeleteUser)
|
|
}
|
|
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
|
|
writeErr(w, http.StatusNotFound, "route inconnue")
|
|
})
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
func writeErr(w http.ResponseWriter, status int, msg string) {
|
|
writeJSON(w, status, map[string]string{"error": msg})
|
|
}
|
|
|
|
func fail(w http.ResponseWriter, err error) {
|
|
switch {
|
|
case errors.Is(err, fleet.ErrNotFound):
|
|
writeErr(w, http.StatusNotFound, err.Error())
|
|
case errors.Is(err, fleet.ErrInvalid):
|
|
writeErr(w, http.StatusBadRequest, err.Error())
|
|
case errors.Is(err, fleet.ErrBusy), errors.Is(err, fleet.ErrExcluded):
|
|
writeErr(w, http.StatusConflict, err.Error())
|
|
default:
|
|
slog.Error("erreur interne", "err", err)
|
|
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
|
}
|
|
}
|
|
|
|
func (h *Handler) decode(w http.ResponseWriter, r *http.Request, v any) bool {
|
|
b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, h.MaxJSON))
|
|
if err == nil {
|
|
err = json.Unmarshal(b, v)
|
|
}
|
|
if err != nil {
|
|
writeErr(w, http.StatusBadRequest, "requête JSON invalide")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// --- Serveurs et analyses ---------------------------------------------------------
|
|
|
|
func (h *Handler) getFleet(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
resp := map[string]any{
|
|
"servers": h.Fleet.Snapshot(),
|
|
"summary": h.Fleet.Summary(),
|
|
"interval": int(h.Interval.Seconds()),
|
|
"tz": tzName(),
|
|
}
|
|
if h.isAdmin(r) {
|
|
resp["publicKey"] = h.PublicKey
|
|
}
|
|
writeJSON(w, http.StatusOK, resp)
|
|
}
|
|
|
|
func (h *Handler) summary(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
writeJSON(w, http.StatusOK, h.Fleet.Summary())
|
|
}
|
|
|
|
func (h *Handler) checkAll(w http.ResponseWriter, r *http.Request) {
|
|
n := h.Fleet.CheckAll()
|
|
writeJSON(w, http.StatusAccepted, map[string]int{"started": n})
|
|
}
|
|
|
|
func (h *Handler) checkServer(w http.ResponseWriter, r *http.Request) {
|
|
n, err := h.Fleet.Check(r.PathValue("id"), r.URL.Query().Get("target"))
|
|
if err != nil {
|
|
fail(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusAccepted, map[string]int{"started": n})
|
|
}
|
|
|
|
func (h *Handler) addServer(w http.ResponseWriter, r *http.Request) {
|
|
if !h.admin(w, r) {
|
|
return
|
|
}
|
|
var s fleet.Server
|
|
if !h.decode(w, r, &s) {
|
|
return
|
|
}
|
|
s, err := h.Fleet.Add(s)
|
|
if err != nil {
|
|
fail(w, err)
|
|
return
|
|
}
|
|
slog.Info("serveur ajouté", "server", s.Name, "by", UserID(r))
|
|
if s.Enabled {
|
|
_, _ = h.Fleet.Check(s.ID, "")
|
|
}
|
|
writeJSON(w, http.StatusCreated, s)
|
|
}
|
|
|
|
func (h *Handler) updateServer(w http.ResponseWriter, r *http.Request) {
|
|
if !h.admin(w, r) {
|
|
return
|
|
}
|
|
var s fleet.Server
|
|
if !h.decode(w, r, &s) {
|
|
return
|
|
}
|
|
s, err := h.Fleet.Update(r.PathValue("id"), s)
|
|
if err != nil {
|
|
fail(w, err)
|
|
return
|
|
}
|
|
slog.Info("serveur modifié", "server", s.Name, "by", UserID(r))
|
|
if s.Enabled {
|
|
_, _ = h.Fleet.Check(s.ID, "") // les connexions nouvelles ou modifiées sont analysées
|
|
}
|
|
writeJSON(w, http.StatusOK, s)
|
|
}
|
|
|
|
func (h *Handler) deleteServer(w http.ResponseWriter, r *http.Request) {
|
|
if !h.admin(w, r) {
|
|
return
|
|
}
|
|
if err := h.Fleet.Delete(r.PathValue("id")); err != nil {
|
|
fail(w, err)
|
|
return
|
|
}
|
|
slog.Info("serveur supprimé", "id", r.PathValue("id"), "by", UserID(r))
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
func (h *Handler) testServer(w http.ResponseWriter, r *http.Request) {
|
|
if !h.admin(w, r) {
|
|
return
|
|
}
|
|
// Le serveur peut ne pas être enregistré encore : le corps éventuel le décrit.
|
|
var s fleet.Server
|
|
if id := r.PathValue("id"); id != "-" {
|
|
var ok bool
|
|
if s, ok = h.Fleet.Server(id); !ok {
|
|
fail(w, fleet.ErrNotFound)
|
|
return
|
|
}
|
|
} else {
|
|
if !h.decode(w, r, &s) {
|
|
return
|
|
}
|
|
if err := s.Validate(); err != nil {
|
|
fail(w, err)
|
|
return
|
|
}
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 60*time.Second)
|
|
defer cancel()
|
|
writeJSON(w, http.StatusOK, h.Fleet.Test(ctx, s))
|
|
}
|
|
|
|
func (h *Handler) apply(w http.ResponseWriter, r *http.Request) {
|
|
if !h.admin(w, r) {
|
|
return
|
|
}
|
|
var req struct {
|
|
Dir string `json:"dir"`
|
|
}
|
|
if !h.decode(w, r, &req) {
|
|
return
|
|
}
|
|
if err := h.Fleet.Apply(r.PathValue("id"), r.PathValue("target"), req.Dir, UserID(r)); err != nil {
|
|
fail(w, err)
|
|
return
|
|
}
|
|
writeJSON(w, http.StatusAccepted, map[string]string{"status": "started"})
|
|
}
|
|
|
|
func (h *Handler) exclude(w http.ResponseWriter, r *http.Request) {
|
|
if !h.admin(w, r) {
|
|
return
|
|
}
|
|
var req struct {
|
|
Dir string `json:"dir"`
|
|
Excluded bool `json:"excluded"`
|
|
}
|
|
if !h.decode(w, r, &req) {
|
|
return
|
|
}
|
|
if err := h.Fleet.SetExcluded(r.PathValue("id"), r.PathValue("target"), req.Dir, req.Excluded); err != nil {
|
|
fail(w, err)
|
|
return
|
|
}
|
|
slog.Info("exclusion de stack", "server", r.PathValue("id"), "target", r.PathValue("target"), "dir", req.Dir, "excluded", req.Excluded, "by", UserID(r))
|
|
writeJSON(w, http.StatusOK, map[string]bool{"excluded": req.Excluded})
|
|
}
|