Stackwatch : suivi des mises à jour de stacks docker compose via SSH
Base Up And Down (auth, thème, dialogues) + moteur fleet (script distant POSIX, analyse pull + comparaison d'images, mise à jour d'une stack), interface de suivi. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
56e1bbe842
54 files changed
+10954
No files matched your search
@@ -0,0 +1,82 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/vblogio/stackwatch/internal/auth"
|
||||
)
|
||||
|
||||
func (h *Handler) adminUsers(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, h.Accounts.List())
|
||||
}
|
||||
|
||||
func (h *Handler) adminCreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Role string `json:"role"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
acc, err := h.Accounts.CreateLocal(auth.NewAccount{Username: req.Username, Name: req.Name, Email: req.Email,
|
||||
Password: req.Password, Role: req.Role, Status: auth.StatusActive})
|
||||
if err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
slog.Info("compte créé", "user", acc.ID, "by", UserID(r))
|
||||
writeJSON(w, http.StatusCreated, acc.Info())
|
||||
}
|
||||
|
||||
func (h *Handler) adminPatchUser(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
Email *string `json:"email"`
|
||||
Role *string `json:"role"`
|
||||
Status *string `json:"status"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
acc, err := h.Accounts.Update(id, auth.Patch{Name: req.Name, Email: req.Email, Role: req.Role,
|
||||
Status: req.Status, Password: req.Password})
|
||||
if err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
slog.Info("compte modifié", "user", id, "by", UserID(r))
|
||||
writeJSON(w, http.StatusOK, acc.Info())
|
||||
}
|
||||
|
||||
func (h *Handler) adminDeleteUser(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.admin(w, r) {
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == UserID(r) {
|
||||
writeErr(w, http.StatusBadRequest, "vous ne pouvez pas supprimer votre propre compte")
|
||||
return
|
||||
}
|
||||
if err := h.Accounts.Delete(id); err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
slog.Info("compte supprimé", "user", id, "by", UserID(r))
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
// 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)
|
||||
// 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)
|
||||
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):
|
||||
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()),
|
||||
}
|
||||
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"})
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/vblogio/stackwatch/internal/auth"
|
||||
)
|
||||
|
||||
type meUser struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Role string `json:"role"`
|
||||
Provider string `json:"provider,omitempty"`
|
||||
}
|
||||
|
||||
// meResponse est lu avant la connexion (page de connexion) puis après (utilisateur, droits).
|
||||
type meResponse struct {
|
||||
Mode string `json:"mode"` // none, local, oidc ou both
|
||||
Local bool `json:"local"`
|
||||
OIDC bool `json:"oidc"`
|
||||
OIDCName string `json:"oidcName,omitempty"`
|
||||
Registration string `json:"registration"`
|
||||
Setup bool `json:"setup,omitempty"`
|
||||
Title string `json:"title"`
|
||||
Version string `json:"version,omitempty"`
|
||||
|
||||
User *meUser `json:"user,omitempty"`
|
||||
Admin bool `json:"admin"`
|
||||
CanChangePW bool `json:"canChangePassword,omitempty"`
|
||||
Logout string `json:"logout,omitempty"`
|
||||
Pending int `json:"pending,omitempty"` // administrateur : inscriptions à valider
|
||||
}
|
||||
|
||||
func (h *Handler) me(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
m := meResponse{Mode: h.Mode, Local: h.Mode == "local" || h.Mode == "both", OIDC: h.Mode == "oidc" || h.Mode == "both",
|
||||
OIDCName: h.OIDCName, Registration: "closed", Title: h.Title, Version: h.Version}
|
||||
if m.Local && h.Auth != nil && h.Auth.Registration != nil {
|
||||
m.Registration = h.Auth.Registration()
|
||||
}
|
||||
if h.Accounts != nil {
|
||||
m.Setup = m.Local && h.Accounts.NeedsSetup()
|
||||
}
|
||||
u := auth.UserFrom(r.Context())
|
||||
switch {
|
||||
case u != nil:
|
||||
m.User = &meUser{ID: u.ID, Name: u.Name, Email: u.Email, Role: u.Role, Provider: u.Provider}
|
||||
m.Logout = "/auth/logout"
|
||||
m.CanChangePW = u.Provider == auth.ProviderLocal
|
||||
case h.Mode == "none":
|
||||
m.User = &meUser{ID: LocalUser, Name: "Utilisateur", Role: auth.RoleAdmin}
|
||||
}
|
||||
if m.User != nil {
|
||||
m.Admin = h.isAdmin(r)
|
||||
if m.Admin && h.Accounts != nil {
|
||||
m.Pending = h.Accounts.PendingCount()
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
}
|
||||
|
||||
// --- Comptes ----------------------------------------------------------------------
|
||||
|
||||
func accountErr(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, auth.ErrNoAccount):
|
||||
writeErr(w, http.StatusNotFound, err.Error())
|
||||
case errors.Is(err, auth.ErrBadCredentials):
|
||||
writeErr(w, http.StatusForbidden, "mot de passe actuel incorrect")
|
||||
case errors.Is(err, auth.ErrInvalidAccount), errors.Is(err, auth.ErrLastAdmin), errors.Is(err, auth.ErrAccountExists):
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
default:
|
||||
slog.Error("compte", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Current string `json:"current"`
|
||||
New string `json:"new"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if err := h.Accounts.ChangePassword(UserID(r), req.Current, req.New); err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) patchAccount(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name *string `json:"name"`
|
||||
Email *string `json:"email"`
|
||||
}
|
||||
if !h.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
acc, ok := h.Accounts.Get(UserID(r))
|
||||
if !ok || acc.Provider != auth.ProviderLocal {
|
||||
writeErr(w, http.StatusBadRequest, "profil géré par le fournisseur d'identité")
|
||||
return
|
||||
}
|
||||
if _, err := h.Accounts.Update(acc.ID, auth.Patch{Name: req.Name, Email: req.Email}); err != nil {
|
||||
accountErr(w, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
Reference in new issue
Block a user