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)
|
||||
}
|
||||
@@ -0,0 +1,677 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/pbkdf2"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Comptes utilisateurs : comptes locaux (identifiant + mot de passe) et comptes
|
||||
// créés à la première connexion OIDC, conservés dans DATA_DIR/.accounts.json
|
||||
// (0600). Les mots de passe ne sont gardés que sous forme d'empreinte
|
||||
// PBKDF2-SHA256 salée.
|
||||
|
||||
const accountsFile = ".accounts.json"
|
||||
|
||||
// Rôles et états d'un compte.
|
||||
const (
|
||||
RoleAdmin = "admin"
|
||||
RoleUser = "user"
|
||||
|
||||
StatusActive = "active"
|
||||
StatusPending = "pending" // inscription à valider par un administrateur
|
||||
StatusDisabled = "disabled" // connexion refusée
|
||||
)
|
||||
|
||||
// Fournisseurs d'identité.
|
||||
const (
|
||||
ProviderLocal = "local"
|
||||
ProviderOIDC = "oidc"
|
||||
)
|
||||
|
||||
const (
|
||||
minPasswordLen = 10
|
||||
maxPasswordLen = 200
|
||||
maxNameLen = 80
|
||||
)
|
||||
|
||||
// pbkdf2Iter : itérations PBKDF2-SHA256 (variable pour accélérer les tests).
|
||||
var pbkdf2Iter = 600_000
|
||||
|
||||
var (
|
||||
ErrInvalidAccount = errors.New("compte invalide")
|
||||
ErrAccountExists = errors.New("identifiant déjà utilisé")
|
||||
ErrNoAccount = errors.New("compte introuvable")
|
||||
ErrLastAdmin = errors.New("il doit rester au moins un administrateur actif")
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{2,31}$`)
|
||||
|
||||
// Account est un compte enregistré.
|
||||
type Account struct {
|
||||
ID string `json:"id"` // nom de l'espace personnel
|
||||
Username string `json:"username,omitempty"` // compte local : identifiant de connexion
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider"`
|
||||
Sub string `json:"sub,omitempty"` // compte OIDC : sujet du jeton
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Hash string `json:"hash,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
LastLogin time.Time `json:"lastLogin,omitzero"`
|
||||
}
|
||||
|
||||
// AccountInfo est la vue d'un compte renvoyée à l'interface d'administration.
|
||||
type AccountInfo struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider"`
|
||||
Role string `json:"role"`
|
||||
Status string `json:"status"`
|
||||
Created time.Time `json:"created"`
|
||||
LastLogin time.Time `json:"lastLogin,omitzero"`
|
||||
}
|
||||
|
||||
// Info renvoie la vue publique du compte (sans empreinte).
|
||||
func (a Account) Info() AccountInfo {
|
||||
return AccountInfo{ID: a.ID, Username: a.Username, Name: a.Name, Email: a.Email, Provider: a.Provider,
|
||||
Role: a.Role, Status: a.Status, Created: a.Created, LastLogin: a.LastLogin}
|
||||
}
|
||||
|
||||
// User renvoie l'utilisateur de session correspondant au compte.
|
||||
func (a Account) User() User {
|
||||
return User{ID: a.ID, Sub: a.Sub, Name: a.Name, Email: a.Email, Provider: a.Provider, Role: a.Role}
|
||||
}
|
||||
|
||||
// Accounts conserve les comptes dans dir/.accounts.json.
|
||||
type Accounts struct {
|
||||
mu sync.Mutex
|
||||
file string
|
||||
byID map[string]*Account
|
||||
dummy string // empreinte factice : égalise le temps de réponse d'un identifiant inconnu
|
||||
}
|
||||
|
||||
// OpenAccounts charge (ou crée) le fichier des comptes de dir.
|
||||
func OpenAccounts(dir string) (*Accounts, error) {
|
||||
a := &Accounts{file: filepath.Join(dir, accountsFile), byID: map[string]*Account{}}
|
||||
b, err := os.ReadFile(a.file)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
case err != nil:
|
||||
return nil, err
|
||||
default:
|
||||
var d struct {
|
||||
Accounts []*Account `json:"accounts"`
|
||||
}
|
||||
if err := json.Unmarshal(b, &d); err != nil {
|
||||
return nil, errors.New(a.file + " invalide : " + err.Error())
|
||||
}
|
||||
for _, acc := range d.Accounts {
|
||||
a.byID[acc.ID] = acc
|
||||
}
|
||||
}
|
||||
a.dummy = hashPassword("mot de passe factice")
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// save écrit le fichier ; appelé sous mu.
|
||||
func (a *Accounts) save() error {
|
||||
list := make([]*Account, 0, len(a.byID))
|
||||
for _, acc := range a.byID {
|
||||
list = append(list, acc)
|
||||
}
|
||||
sort.Slice(list, func(i, j int) bool { return list[i].Created.Before(list[j].Created) })
|
||||
b, err := json.MarshalIndent(map[string]any{"accounts": list}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(a.file), ".tmp-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp.Name())
|
||||
if err := tmp.Chmod(0o600); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := tmp.Write(b); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
tmp.Close()
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), a.file)
|
||||
}
|
||||
|
||||
// --- Mots de passe ------------------------------------------------------------------
|
||||
|
||||
func hashPassword(pw string) string {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
return deriveHash(pw, salt, pbkdf2Iter)
|
||||
}
|
||||
|
||||
func deriveHash(pw string, salt []byte, iter int) string {
|
||||
h, err := pbkdf2.Key(sha256.New, pw, salt, iter, 32)
|
||||
if err != nil {
|
||||
panic(err) // paramètres constants valides
|
||||
}
|
||||
return fmt.Sprintf("pbkdf2-sha256$%d$%s$%s", iter, b64.EncodeToString(salt), b64.EncodeToString(h))
|
||||
}
|
||||
|
||||
func checkPassword(hash, pw string) bool {
|
||||
parts := strings.Split(hash, "$")
|
||||
if len(parts) != 4 || parts[0] != "pbkdf2-sha256" {
|
||||
return false
|
||||
}
|
||||
iter, err := strconv.Atoi(parts[1])
|
||||
if err != nil || iter < 1 || iter > 10_000_000 {
|
||||
return false
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[2])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return subtle.ConstantTimeCompare([]byte(deriveHash(pw, salt, iter)), []byte(hash)) == 1
|
||||
}
|
||||
|
||||
// ValidatePassword vérifie la longueur d'un nouveau mot de passe.
|
||||
func ValidatePassword(pw string) error {
|
||||
if n := utf8.RuneCountInString(pw); n < minPasswordLen || len(pw) > maxPasswordLen {
|
||||
return fmt.Errorf("%w : mot de passe de %d à %d caractères", ErrInvalidAccount, minPasswordLen, maxPasswordLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Lecture ---------------------------------------------------------------------------
|
||||
|
||||
// Get renvoie le compte d'identifiant id.
|
||||
func (a *Accounts) Get(id string) (Account, bool) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if acc, ok := a.byID[id]; ok {
|
||||
return *acc, true
|
||||
}
|
||||
return Account{}, false
|
||||
}
|
||||
|
||||
// List renvoie tous les comptes, du plus ancien au plus récent.
|
||||
func (a *Accounts) List() []AccountInfo {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
out := make([]AccountInfo, 0, len(a.byID))
|
||||
for _, acc := range a.byID {
|
||||
out = append(out, acc.Info())
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if !out[i].Created.Equal(out[j].Created) {
|
||||
return out[i].Created.Before(out[j].Created)
|
||||
}
|
||||
return out[i].ID < out[j].ID
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// Count renvoie le nombre de comptes.
|
||||
func (a *Accounts) Count() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return len(a.byID)
|
||||
}
|
||||
|
||||
// hasAdmin indique si un administrateur actif existe ; appelé sous mu.
|
||||
func (a *Accounts) hasAdmin() bool {
|
||||
for _, acc := range a.byID {
|
||||
if acc.Role == RoleAdmin && acc.Status == StatusActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// NeedsSetup indique qu'aucun administrateur n'existe encore : le premier
|
||||
// compte créé le deviendra.
|
||||
func (a *Accounts) NeedsSetup() bool {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
return !a.hasAdmin()
|
||||
}
|
||||
|
||||
// PendingCount renvoie le nombre d'inscriptions en attente de validation.
|
||||
func (a *Accounts) PendingCount() int {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
n := 0
|
||||
for _, acc := range a.byID {
|
||||
if acc.Status == StatusPending {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (a *Accounts) byUsername(name string) *Account {
|
||||
for _, acc := range a.byID {
|
||||
if acc.Provider == ProviderLocal && acc.Username == name {
|
||||
return acc
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Création ---------------------------------------------------------------------------
|
||||
|
||||
// NewAccount décrit un compte local à créer.
|
||||
type NewAccount struct {
|
||||
Username string
|
||||
Name string
|
||||
Email string
|
||||
Password string
|
||||
Role string // vide : user (admin si aucun administrateur n'existe)
|
||||
Status string // vide : active
|
||||
}
|
||||
|
||||
func cleanText(s string, max int) (string, bool) {
|
||||
s = strings.Join(strings.Fields(s), " ")
|
||||
return s, utf8.ValidString(s) && utf8.RuneCountInString(s) <= max && !strings.ContainsAny(s, "\x00")
|
||||
}
|
||||
|
||||
// CreateLocal crée un compte local. Tant qu'aucun administrateur n'existe, le
|
||||
// compte créé l'est (et est actif).
|
||||
func (a *Accounts) CreateLocal(n NewAccount) (Account, error) {
|
||||
username := strings.ToLower(strings.TrimSpace(n.Username))
|
||||
if !usernameRe.MatchString(username) || strings.HasPrefix(username, "oidc.") {
|
||||
return Account{}, fmt.Errorf("%w : identifiant de 3 à 32 caractères (a-z, 0-9, point, tiret, tiret bas)", ErrInvalidAccount)
|
||||
}
|
||||
if err := ValidatePassword(n.Password); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
name, ok := cleanText(n.Name, maxNameLen)
|
||||
if !ok {
|
||||
return Account{}, fmt.Errorf("%w : nom", ErrInvalidAccount)
|
||||
}
|
||||
if name == "" {
|
||||
name = username
|
||||
}
|
||||
email, ok := cleanText(n.Email, 120)
|
||||
if !ok || (email != "" && (!strings.Contains(email, "@") || strings.ContainsAny(email, " <>\"'"))) {
|
||||
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
|
||||
}
|
||||
hash := hashPassword(n.Password) // hors verrou : calcul lent
|
||||
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if _, exists := a.byID[username]; exists {
|
||||
return Account{}, ErrAccountExists
|
||||
}
|
||||
acc := &Account{ID: username, Username: username, Name: name, Email: email, Provider: ProviderLocal,
|
||||
Role: n.Role, Status: n.Status, Hash: hash, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if !a.hasAdmin() {
|
||||
acc.Role, acc.Status = RoleAdmin, StatusActive
|
||||
}
|
||||
if acc.Role != RoleAdmin {
|
||||
acc.Role = RoleUser
|
||||
}
|
||||
if acc.Status != StatusPending && acc.Status != StatusDisabled {
|
||||
acc.Status = StatusActive
|
||||
}
|
||||
a.byID[acc.ID] = acc
|
||||
if err := a.save(); err != nil {
|
||||
delete(a.byID, acc.ID)
|
||||
return Account{}, err
|
||||
}
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// EnsureAdmin crée l'administrateur local initial (ADMIN_USER / ADMIN_PASSWORD)
|
||||
// s'il n'existe pas ; un compte existant n'est pas modifié.
|
||||
func (a *Accounts) EnsureAdmin(username, password string) error {
|
||||
_, err := a.CreateLocal(NewAccount{Username: username, Name: username, Password: password, Role: RoleAdmin})
|
||||
if errors.Is(err, ErrAccountExists) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// --- Connexion ----------------------------------------------------------------------------
|
||||
|
||||
// Authenticate vérifie un identifiant et un mot de passe locaux.
|
||||
func (a *Accounts) Authenticate(username, password string) (Account, error) {
|
||||
username = strings.ToLower(strings.TrimSpace(username))
|
||||
a.mu.Lock()
|
||||
acc := a.byUsername(username)
|
||||
var hash string
|
||||
if acc != nil {
|
||||
hash = acc.Hash
|
||||
} else {
|
||||
hash = a.dummy
|
||||
}
|
||||
a.mu.Unlock()
|
||||
ok := checkPassword(hash, password) && acc != nil
|
||||
if !ok {
|
||||
return Account{}, ErrBadCredentials
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc = a.byID[acc.ID]
|
||||
if acc == nil {
|
||||
return Account{}, ErrBadCredentials
|
||||
}
|
||||
switch acc.Status {
|
||||
case StatusPending:
|
||||
return *acc, ErrPending
|
||||
case StatusDisabled:
|
||||
return *acc, ErrDisabled
|
||||
}
|
||||
acc.LastLogin = time.Now().UTC().Truncate(time.Second)
|
||||
_ = a.save()
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// oidcID construit l'identifiant d'un compte OIDC : l'e-mail s'il existe (il
|
||||
// contient « @ », donc ne peut pas entrer en conflit avec un identifiant local),
|
||||
// sinon « oidc. » suivi du sujet.
|
||||
func oidcID(email, sub string) string {
|
||||
if e := strings.ToLower(strings.TrimSpace(email)); e != "" {
|
||||
return sanitizeID(e)
|
||||
}
|
||||
return "oidc." + sanitizeID(sub)
|
||||
}
|
||||
|
||||
func sanitizeID(raw string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range strings.ToLower(raw) {
|
||||
if r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune("._@+-", r) {
|
||||
b.WriteRune(r)
|
||||
} else {
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
id := strings.TrimLeft(b.String(), ".")
|
||||
if len(id) > 80 {
|
||||
h := sha256.Sum256([]byte(raw))
|
||||
id = id[:60] + "-" + b64.EncodeToString(h[:6])
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// OIDCPolicy règle la création et la mise à jour des comptes OIDC.
|
||||
type OIDCPolicy struct {
|
||||
AdminGroups []string // groupes dont les membres sont administrateurs
|
||||
AdminEmails []string // adresses dont les titulaires sont administrateurs
|
||||
}
|
||||
|
||||
func (p OIDCPolicy) configured() bool { return len(p.AdminGroups) > 0 || len(p.AdminEmails) > 0 }
|
||||
|
||||
func (p OIDCPolicy) isAdmin(email string, groups []string) bool {
|
||||
for _, e := range p.AdminEmails {
|
||||
if email != "" && strings.EqualFold(strings.TrimSpace(e), email) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, g := range groups {
|
||||
for _, ag := range p.AdminGroups {
|
||||
if g == strings.TrimPrefix(ag, "/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// UpsertOIDC crée ou met à jour le compte d'une connexion OIDC et renvoie
|
||||
// l'utilisateur de la session. Le compte est créé actif ; il devient
|
||||
// administrateur s'il appartient à OIDC_ADMIN_GROUPS / OIDC_ADMIN_EMAILS, ou
|
||||
// s'il est le premier compte alors qu'aucun administrateur n'existe. Un compte
|
||||
// désactivé ou en attente est refusé (ErrDisabled, ErrPending).
|
||||
func (a *Accounts) UpsertOIDC(u User, groups []string, pol OIDCPolicy) (User, error) {
|
||||
if u.Sub == "" {
|
||||
return User{}, fmt.Errorf("%w : sujet OIDC absent", ErrInvalidAccount)
|
||||
}
|
||||
name, ok := cleanText(u.Name, maxNameLen)
|
||||
if !ok || name == "" {
|
||||
name = u.Sub
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
var acc *Account
|
||||
for _, c := range a.byID {
|
||||
if c.Provider == ProviderOIDC && c.Sub == u.Sub {
|
||||
acc = c
|
||||
break
|
||||
}
|
||||
}
|
||||
wantAdmin := pol.isAdmin(u.Email, groups)
|
||||
if acc == nil {
|
||||
id := oidcID(u.Email, u.Sub)
|
||||
if _, taken := a.byID[id]; taken { // même e-mail, autre sujet : identifiant distinct
|
||||
id = "oidc." + sanitizeID(u.Sub)
|
||||
}
|
||||
acc = &Account{ID: id, Name: name, Email: u.Email, Provider: ProviderOIDC, Sub: u.Sub,
|
||||
Role: RoleUser, Status: StatusActive, Created: time.Now().UTC().Truncate(time.Second)}
|
||||
if wantAdmin || !a.hasAdmin() {
|
||||
acc.Role = RoleAdmin
|
||||
}
|
||||
a.byID[acc.ID] = acc
|
||||
} else {
|
||||
acc.Name, acc.Email = name, u.Email
|
||||
if pol.configured() {
|
||||
switch {
|
||||
case wantAdmin:
|
||||
acc.Role = RoleAdmin
|
||||
case acc.Role == RoleAdmin && a.otherAdmin(acc.ID):
|
||||
acc.Role = RoleUser
|
||||
}
|
||||
}
|
||||
}
|
||||
switch acc.Status {
|
||||
case StatusPending:
|
||||
return acc.User(), ErrPending
|
||||
case StatusDisabled:
|
||||
return acc.User(), ErrDisabled
|
||||
}
|
||||
acc.LastLogin = time.Now().UTC().Truncate(time.Second)
|
||||
if err := a.save(); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
return acc.User(), nil
|
||||
}
|
||||
|
||||
// otherAdmin indique si un administrateur actif autre que id existe ; appelé sous mu.
|
||||
func (a *Accounts) otherAdmin(id string) bool {
|
||||
for _, acc := range a.byID {
|
||||
if acc.ID != id && acc.Role == RoleAdmin && acc.Status == StatusActive {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- Modification (administration) -------------------------------------------------------
|
||||
|
||||
// Patch décrit les modifications d'un compte (champs nil : inchangés).
|
||||
type Patch struct {
|
||||
Name *string
|
||||
Email *string
|
||||
Role *string
|
||||
Status *string
|
||||
Password *string // comptes locaux seulement
|
||||
}
|
||||
|
||||
// Update modifie un compte. Le dernier administrateur actif ne peut être ni
|
||||
// rétrogradé ni désactivé.
|
||||
func (a *Accounts) Update(id string, p Patch) (Account, error) {
|
||||
var hash string
|
||||
if p.Password != nil {
|
||||
if err := ValidatePassword(*p.Password); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
hash = hashPassword(*p.Password)
|
||||
}
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc := a.byID[id]
|
||||
if acc == nil {
|
||||
return Account{}, ErrNoAccount
|
||||
}
|
||||
next := *acc
|
||||
if p.Name != nil {
|
||||
n, ok := cleanText(*p.Name, maxNameLen)
|
||||
if !ok || n == "" {
|
||||
return Account{}, fmt.Errorf("%w : nom", ErrInvalidAccount)
|
||||
}
|
||||
next.Name = n
|
||||
}
|
||||
if p.Email != nil && next.Provider == ProviderLocal {
|
||||
e, ok := cleanText(*p.Email, 120)
|
||||
if !ok || (e != "" && (!strings.Contains(e, "@") || strings.ContainsAny(e, " <>\"'"))) {
|
||||
return Account{}, fmt.Errorf("%w : adresse e-mail", ErrInvalidAccount)
|
||||
}
|
||||
next.Email = e
|
||||
}
|
||||
if p.Role != nil {
|
||||
if *p.Role != RoleAdmin && *p.Role != RoleUser {
|
||||
return Account{}, fmt.Errorf("%w : rôle", ErrInvalidAccount)
|
||||
}
|
||||
next.Role = *p.Role
|
||||
}
|
||||
if p.Status != nil {
|
||||
if *p.Status != StatusActive && *p.Status != StatusPending && *p.Status != StatusDisabled {
|
||||
return Account{}, fmt.Errorf("%w : état", ErrInvalidAccount)
|
||||
}
|
||||
next.Status = *p.Status
|
||||
}
|
||||
if p.Password != nil {
|
||||
if next.Provider != ProviderLocal {
|
||||
return Account{}, fmt.Errorf("%w : mot de passe géré par le fournisseur d'identité", ErrInvalidAccount)
|
||||
}
|
||||
next.Hash = hash
|
||||
}
|
||||
wasAdmin := acc.Role == RoleAdmin && acc.Status == StatusActive
|
||||
isAdmin := next.Role == RoleAdmin && next.Status == StatusActive
|
||||
if wasAdmin && !isAdmin && !a.otherAdmin(id) {
|
||||
return Account{}, ErrLastAdmin
|
||||
}
|
||||
*acc = next
|
||||
if err := a.save(); err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
return *acc, nil
|
||||
}
|
||||
|
||||
// ChangePassword remplace le mot de passe d'un compte local après vérification
|
||||
// de l'ancien.
|
||||
func (a *Accounts) ChangePassword(id, current, next string) error {
|
||||
if err := ValidatePassword(next); err != nil {
|
||||
return err
|
||||
}
|
||||
acc, ok := a.Get(id)
|
||||
if !ok || acc.Provider != ProviderLocal {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if !checkPassword(acc.Hash, current) {
|
||||
return ErrBadCredentials
|
||||
}
|
||||
_, err := a.Update(id, Patch{Password: &next})
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete supprime un compte. Le dernier administrateur actif ne peut l'être.
|
||||
func (a *Accounts) Delete(id string) error {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
acc := a.byID[id]
|
||||
if acc == nil {
|
||||
return ErrNoAccount
|
||||
}
|
||||
if acc.Role == RoleAdmin && acc.Status == StatusActive && !a.otherAdmin(id) {
|
||||
return ErrLastAdmin
|
||||
}
|
||||
delete(a.byID, id)
|
||||
if err := a.save(); err != nil {
|
||||
a.byID[id] = acc
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// --- Limitation des tentatives ------------------------------------------------------------
|
||||
|
||||
// Limiter limite les échecs de connexion : max échecs par clé et par fenêtre.
|
||||
type Limiter struct {
|
||||
mu sync.Mutex
|
||||
max int
|
||||
window time.Duration
|
||||
fails map[string][]time.Time
|
||||
}
|
||||
|
||||
// NewLimiter crée un limiteur.
|
||||
func NewLimiter(max int, window time.Duration) *Limiter {
|
||||
return &Limiter{max: max, window: window, fails: map[string][]time.Time{}}
|
||||
}
|
||||
|
||||
func (l *Limiter) prune(key string, now time.Time) []time.Time {
|
||||
kept := l.fails[key][:0]
|
||||
for _, t := range l.fails[key] {
|
||||
if now.Sub(t) < l.window {
|
||||
kept = append(kept, t)
|
||||
}
|
||||
}
|
||||
if len(kept) == 0 {
|
||||
delete(l.fails, key)
|
||||
} else {
|
||||
l.fails[key] = kept
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
// Allowed indique si key peut encore tenter une connexion.
|
||||
func (l *Limiter) Allowed(key string) bool {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return len(l.prune(key, time.Now())) < l.max
|
||||
}
|
||||
|
||||
// Fail enregistre un échec.
|
||||
func (l *Limiter) Fail(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
now := time.Now()
|
||||
l.prune(key, now)
|
||||
l.fails[key] = append(l.fails[key], now)
|
||||
if len(l.fails) > 10000 { // borne la mémoire
|
||||
for k := range l.fails {
|
||||
if len(l.prune(k, now)) == 0 {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset efface les échecs de key (connexion réussie).
|
||||
func (l *Limiter) Reset(key string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
delete(l.fails, key)
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func init() { pbkdf2Iter = 1000 } // tests rapides
|
||||
|
||||
func newAccounts(t *testing.T) *Accounts {
|
||||
t.Helper()
|
||||
a, err := OpenAccounts(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func TestFirstAccountIsAdmin(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
if !a.NeedsSetup() {
|
||||
t.Fatal("NeedsSetup")
|
||||
}
|
||||
first, err := a.CreateLocal(NewAccount{Username: "Alice", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first.Role != RoleAdmin || first.Status != StatusActive || first.ID != "alice" {
|
||||
t.Errorf("premier compte = %+v", first)
|
||||
}
|
||||
second, _ := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe", Status: StatusPending})
|
||||
if second.Role != RoleUser || second.Status != StatusPending {
|
||||
t.Errorf("second compte = %+v", second)
|
||||
}
|
||||
if a.NeedsSetup() || a.PendingCount() != 1 {
|
||||
t.Error("état après création")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateLocalValidation(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
for _, n := range []NewAccount{
|
||||
{Username: "ab", Password: "un-mot-de-passe"}, // trop court
|
||||
{Username: "Bob Dupont", Password: "un-mot-de-passe"}, // espace
|
||||
{Username: "oidc.x", Password: "un-mot-de-passe"}, // préfixe réservé
|
||||
{Username: "bob@example.org", Password: "un-mot-de-passe"}, // @ réservé aux comptes OIDC
|
||||
{Username: "bob", Password: "court"}, // mot de passe trop court
|
||||
{Username: "bob", Password: "un-mot-de-passe", Email: "x"}, // e-mail invalide
|
||||
{Username: "bob", Password: strings.Repeat("x", 300)}, // mot de passe trop long
|
||||
{Username: ".hidden", Password: "un-mot-de-passe"}, // caché
|
||||
{Username: "bob", Password: "un-mot-de-passe", Name: "a\x00"}, // nom invalide
|
||||
} {
|
||||
if _, err := a.CreateLocal(n); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("CreateLocal(%+v) = %v", n, err)
|
||||
}
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "bob", Password: "un-mot-de-passe"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: "BOB", Password: "un-mot-de-passe"}); !errors.Is(err, ErrAccountExists) {
|
||||
t.Errorf("doublon : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticate(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2", Status: StatusPending})
|
||||
if _, err := a.Authenticate("Alice", "mot-de-passe-1"); err != nil {
|
||||
t.Errorf("connexion : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("mauvais mot de passe : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("inconnu", "mot-de-passe-1"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("inconnu : %v", err)
|
||||
}
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrPending) {
|
||||
t.Errorf("en attente : %v", err)
|
||||
}
|
||||
// Mauvais mot de passe d'un compte en attente : pas de fuite d'état.
|
||||
if _, err := a.Authenticate("bob", "faux"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("fuite d'état : %v", err)
|
||||
}
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update("bob", Patch{Status: &disabled})
|
||||
if _, err := a.Authenticate("bob", "mot-de-passe-2"); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistenceAndFileMode(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, _ := OpenAccounts(dir)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b, err := OpenAccounts(dir)
|
||||
if err != nil || b.Count() != 1 {
|
||||
t.Fatalf("rechargement : %v %d", err, b.Count())
|
||||
}
|
||||
if _, err := b.Authenticate("alice", "mot-de-passe-1"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastAdminProtected(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"}) // admin
|
||||
user, disabled := RoleUser, StatusDisabled
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("rétrogradation : %v", err)
|
||||
}
|
||||
if _, err := a.Update("alice", Patch{Status: &disabled}); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("désactivation : %v", err)
|
||||
}
|
||||
if err := a.Delete("alice"); !errors.Is(err, ErrLastAdmin) {
|
||||
t.Errorf("suppression : %v", err)
|
||||
}
|
||||
admin := RoleAdmin
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
_, _ = a.Update("bob", Patch{Role: &admin})
|
||||
if _, err := a.Update("alice", Patch{Role: &user}); err != nil {
|
||||
t.Errorf("rétrogradation avec un autre admin : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChangePassword(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
_, _ = a.CreateLocal(NewAccount{Username: "alice", Password: "ancien-mot-de-passe"})
|
||||
if err := a.ChangePassword("alice", "faux", "nouveau-mot-de-passe"); !errors.Is(err, ErrBadCredentials) {
|
||||
t.Errorf("ancien faux : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "court"); !errors.Is(err, ErrInvalidAccount) {
|
||||
t.Errorf("nouveau trop court : %v", err)
|
||||
}
|
||||
if err := a.ChangePassword("alice", "ancien-mot-de-passe", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "nouveau-mot-de-passe"); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if _, err := a.Authenticate("alice", "ancien-mot-de-passe"); err == nil {
|
||||
t.Error("ancien mot de passe encore valable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpsertOIDC(t *testing.T) {
|
||||
a := newAccounts(t)
|
||||
pol := OIDCPolicy{AdminGroups: []string{"admins"}}
|
||||
u1, err := a.UpsertOIDC(User{Sub: "s1", Name: "Zoé", Email: "Zoe@Example.org"}, []string{"users"}, pol)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Premier compte : administrateur même hors du groupe (aucun admin n'existait).
|
||||
if u1.ID != "zoe@example.org" || u1.Role != RoleAdmin || u1.Provider != ProviderOIDC {
|
||||
t.Errorf("premier = %+v", u1)
|
||||
}
|
||||
u2, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"users"}, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("second = %+v", u2)
|
||||
}
|
||||
// Promotion par groupe, puis rétrogradation quand il en sort.
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, []string{"admins"}, pol)
|
||||
if u2.Role != RoleAdmin {
|
||||
t.Errorf("promotion = %+v", u2)
|
||||
}
|
||||
u2, _ = a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@example.org"}, nil, pol)
|
||||
if u2.Role != RoleUser {
|
||||
t.Errorf("rétrogradation = %+v", u2)
|
||||
}
|
||||
// Même sujet, nouvel e-mail : même compte.
|
||||
u3, _ := a.UpsertOIDC(User{Sub: "s2", Name: "Max B", Email: "max@autre.org"}, nil, pol)
|
||||
if u3.ID != u2.ID || u3.Name != "Max B" {
|
||||
t.Errorf("identité : %+v", u3)
|
||||
}
|
||||
// Sans e-mail : identifiant « oidc.<sub> », qui ne peut pas être un identifiant local.
|
||||
u4, _ := a.UpsertOIDC(User{Sub: "S/4", Name: "Sans mail"}, nil, pol)
|
||||
if !strings.HasPrefix(u4.ID, "oidc.") {
|
||||
t.Errorf("sans e-mail = %+v", u4)
|
||||
}
|
||||
if _, err := a.CreateLocal(NewAccount{Username: u4.ID, Password: "mot-de-passe-1"}); err == nil {
|
||||
t.Error("identifiant local en collision avec un compte OIDC")
|
||||
}
|
||||
// Même e-mail, autre sujet : pas de fusion (prise de contrôle).
|
||||
u5, _ := a.UpsertOIDC(User{Sub: "autre", Name: "Usurpateur", Email: "zoe@example.org"}, nil, pol)
|
||||
if u5.ID == u1.ID {
|
||||
t.Error("deux sujets OIDC partagent un compte")
|
||||
}
|
||||
// Désactivation.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Update(u2.ID, Patch{Status: &disabled})
|
||||
if _, err := a.UpsertOIDC(User{Sub: "s2", Name: "Max", Email: "max@autre.org"}, nil, pol); !errors.Is(err, ErrDisabled) {
|
||||
t.Errorf("désactivé : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiter(t *testing.T) {
|
||||
l := NewLimiter(3, 50*time.Millisecond)
|
||||
for i := 0; i < 3; i++ {
|
||||
if !l.Allowed("k") {
|
||||
t.Fatal("bloqué trop tôt")
|
||||
}
|
||||
l.Fail("k")
|
||||
}
|
||||
if l.Allowed("k") {
|
||||
t.Error("pas bloqué")
|
||||
}
|
||||
if !l.Allowed("autre") {
|
||||
t.Error("autre clé bloquée")
|
||||
}
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
if !l.Allowed("k") {
|
||||
t.Error("fenêtre non expirée")
|
||||
}
|
||||
l.Fail("k")
|
||||
l.Reset("k")
|
||||
if !l.Allowed("k") {
|
||||
t.Error("Reset")
|
||||
}
|
||||
}
|
||||
|
||||
// --- Flux HTTP (sans ouvrir de port) -------------------------------------------------
|
||||
|
||||
type browser struct {
|
||||
t *testing.T
|
||||
h http.Handler
|
||||
cookies map[string]*http.Cookie
|
||||
}
|
||||
|
||||
func newBrowser(t *testing.T, h http.Handler) *browser {
|
||||
return &browser{t: t, h: h, cookies: map[string]*http.Cookie{}}
|
||||
}
|
||||
|
||||
func (b *browser) do(method, path, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for _, c := range b.cookies {
|
||||
r.AddCookie(c)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
b.h.ServeHTTP(w, r)
|
||||
for _, c := range w.Result().Cookies() {
|
||||
if c.MaxAge < 0 {
|
||||
delete(b.cookies, c.Name)
|
||||
} else {
|
||||
b.cookies[c.Name] = c
|
||||
}
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func testAuth(t *testing.T, reg string) (*Auth, http.Handler) {
|
||||
t.Helper()
|
||||
acc := newAccounts(t)
|
||||
a := New(&Auth{
|
||||
Accounts: acc,
|
||||
Sessions: NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false),
|
||||
Local: true,
|
||||
Registration: func() string { return reg },
|
||||
})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role))
|
||||
})
|
||||
mux.HandleFunc("GET /api/open", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ouvert")) })
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("<html>spa</html>")) })
|
||||
return a, a.Middleware(mux, func(p string) bool { return p == "/api/open" })
|
||||
}
|
||||
|
||||
func TestRegistrationClosedAllowsOnlySetup(t *testing.T) {
|
||||
_, h := testAuth(t, "closed")
|
||||
b := newBrowser(t, h)
|
||||
// Premier compte : accepté malgré « closed » (installation), connecté d'office.
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"admin","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("installation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "admin:admin" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
// Ensuite, fermé.
|
||||
b2 := newBrowser(t, h)
|
||||
if w := b2.do("POST", "/auth/local/register", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 403 {
|
||||
t.Errorf("inscription fermée : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationApprovalFlow(t *testing.T) {
|
||||
a, h := testAuth(t, "approval")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"bob","name":"Bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 202 || len(b.cookies) != 0 {
|
||||
t.Fatalf("inscription : %d %s %v", w.Code, w.Body, b.cookies)
|
||||
}
|
||||
w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`)
|
||||
if w.Code != 403 || !strings.Contains(w.Body.String(), `"pending"`) {
|
||||
t.Errorf("connexion en attente : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if b.do("GET", "/api/whoami", "").Code != 401 {
|
||||
t.Error("accès sans session")
|
||||
}
|
||||
active := StatusActive
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &active})
|
||||
if w = b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-1"}`); w.Code != 200 {
|
||||
t.Fatalf("connexion : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationOpenAutoLogin(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
b := newBrowser(t, h)
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 201 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "carl:user" {
|
||||
t.Errorf("whoami = %q", got)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"carl","password":"mot-de-passe-1"}`); w.Code != 409 {
|
||||
t.Errorf("doublon : %d", w.Code)
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/register", `{"username":"x","password":"mot-de-passe-1"}`); w.Code != 400 {
|
||||
t.Errorf("identifiant invalide : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationThrottle(t *testing.T) {
|
||||
a, h := testAuth(t, "open")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "root", Password: "mot-de-passe-0"})
|
||||
last := 0
|
||||
for i := 0; i < 8; i++ {
|
||||
b := newBrowser(t, h)
|
||||
w := b.do("POST", "/auth/local/register", `{"username":"user`+string(rune('a'+i))+`x","password":"mot-de-passe-1"}`)
|
||||
last = w.Code
|
||||
}
|
||||
if last != 429 {
|
||||
t.Errorf("après 8 inscriptions depuis la même adresse : %d", last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginThrottleAndSessionRules(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
for i := 0; i < 10; i++ {
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"faux"}`); w.Code != 401 {
|
||||
t.Fatalf("essai %d : %d", i, w.Code)
|
||||
}
|
||||
}
|
||||
if w := b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`); w.Code != 429 {
|
||||
t.Errorf("après 10 échecs : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMiddlewareRoutesAndSessionRevocation(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "bob", Password: "mot-de-passe-2"})
|
||||
b := newBrowser(t, h)
|
||||
// Sans session : API refusée, route publique ouverte, navigation = application.
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 || w.Header().Get(LoginHeader) != "" {
|
||||
t.Errorf("API : %d %v", w.Code, w.Header())
|
||||
}
|
||||
if w := b.do("GET", "/api/open", ""); w.Code != 200 {
|
||||
t.Errorf("public : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "spa") {
|
||||
t.Errorf("navigation : %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := b.do("POST", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("POST sans session : %d", w.Code)
|
||||
}
|
||||
b.do("POST", "/auth/local/login", `{"username":"bob","password":"mot-de-passe-2"}`)
|
||||
if got := b.do("GET", "/api/whoami", "").Body.String(); got != "bob:user" {
|
||||
t.Fatalf("whoami = %q", got)
|
||||
}
|
||||
// Un compte désactivé perd sa session tout de suite.
|
||||
disabled := StatusDisabled
|
||||
_, _ = a.Accounts.Update("bob", Patch{Status: &disabled})
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", w.Code)
|
||||
}
|
||||
// Un compte supprimé aussi.
|
||||
b2 := newBrowser(t, h)
|
||||
b2.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "carl", Password: "mot-de-passe-3", Role: RoleAdmin})
|
||||
_ = a.Accounts.Delete("alice")
|
||||
if w := b2.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("session d'un compte supprimé : %d", w.Code)
|
||||
}
|
||||
// Un cookie falsifié est refusé.
|
||||
b3 := newBrowser(t, h)
|
||||
b3.cookies["stackwatch_session"] = &http.Cookie{Name: "stackwatch_session", Value: "eyJpZCI6ImFkbWluIn0.AAAA"}
|
||||
if w := b3.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("cookie falsifié : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutClearsSession(t *testing.T) {
|
||||
a, h := testAuth(t, "closed")
|
||||
_, _ = a.Accounts.CreateLocal(NewAccount{Username: "alice", Password: "mot-de-passe-1"})
|
||||
b := newBrowser(t, h)
|
||||
b.do("POST", "/auth/local/login", `{"username":"alice","password":"mot-de-passe-1"}`)
|
||||
if w := b.do("GET", "/auth/logout", ""); w.Code != 303 {
|
||||
t.Errorf("logout : %d", w.Code)
|
||||
}
|
||||
if w := b.do("GET", "/api/whoami", ""); w.Code != 401 {
|
||||
t.Errorf("après logout : %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOIDCLoginCreatesAccountAndHonoursStatus(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
acc := newAccounts(t)
|
||||
sessions := NewSessions([]byte("0123456789abcdef0123456789abcdef"), time.Hour, false)
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
Secret: []byte("0123456789abcdef0123456789abcdef"), Client: testNet.client(), Sessions: sessions,
|
||||
Provision: func(u User, g []string) (User, error) { return acc.UpsertOIDC(u, g, OIDCPolicy{}) },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
a := New(&Auth{Accounts: acc, Sessions: sessions, OIDC: o})
|
||||
mux := http.NewServeMux()
|
||||
a.Register(mux)
|
||||
mux.HandleFunc("GET /api/whoami", func(w http.ResponseWriter, r *http.Request) {
|
||||
u := UserFrom(r.Context())
|
||||
_, _ = w.Write([]byte(u.ID + ":" + u.Role + ":" + u.Provider))
|
||||
})
|
||||
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv := testNet.serve("app", a.Middleware(mux, func(string) bool { return false }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
c := &http.Client{Jar: jar, Transport: testNet}
|
||||
|
||||
if res, body := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("OIDC seul, sans session : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("connexion : %d %q", res.StatusCode, body)
|
||||
}
|
||||
if _, body := get(t, c, srv.URL+"/api/whoami"); body != "cedric@example.org:admin:oidc" {
|
||||
t.Errorf("whoami = %q", body)
|
||||
}
|
||||
if got, ok := acc.Get("cedric@example.org"); !ok || got.Sub != "u-42" {
|
||||
t.Errorf("compte non créé : %+v", got)
|
||||
}
|
||||
// Désactivation : la session tombe, la reconnexion est refusée avec un message clair.
|
||||
id := "cedric@example.org"
|
||||
admin, disabled := RoleAdmin, StatusDisabled
|
||||
_, _ = acc.CreateLocal(NewAccount{Username: "backup", Password: "mot-de-passe-1", Role: admin})
|
||||
_, _ = acc.Update(id, Patch{Status: &disabled})
|
||||
if res, _ := get(t, c, srv.URL+"/api/whoami"); res.StatusCode != 401 {
|
||||
t.Errorf("session d'un compte désactivé : %d", res.StatusCode)
|
||||
}
|
||||
res, body := get(t, c, srv.URL+"/auth/login")
|
||||
if res.StatusCode != 403 || !strings.Contains(body, "désactivé") {
|
||||
t.Errorf("reconnexion refusée : %d %.80s", res.StatusCode, body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Auth réunit l'authentification locale (comptes, inscription) et OIDC derrière
|
||||
// une même session : cookie signé, vérifié à chaque requête contre l'état du
|
||||
// compte (désactivé, supprimé, rôle modifié : effet immédiat).
|
||||
//
|
||||
// POST /auth/local/login {"username","password"}
|
||||
// POST /auth/local/register {"username","name","email","password"}
|
||||
// GET /auth/login connexion OIDC (si activée)
|
||||
// GET /auth/logout déconnexion (propagée au fournisseur OIDC)
|
||||
type Auth struct {
|
||||
Accounts *Accounts
|
||||
Sessions *Sessions
|
||||
OIDC *OIDC // nil : OIDC désactivé
|
||||
Local bool // comptes locaux activés
|
||||
// Registration renvoie le mode d'inscription courant : closed, approval ou open.
|
||||
Registration func() string
|
||||
// OIDCName : libellé du bouton de connexion OIDC.
|
||||
OIDCName string
|
||||
|
||||
logins *Limiter
|
||||
regs *Limiter
|
||||
}
|
||||
|
||||
// New prépare l'authentification ; Accounts et Sessions sont obligatoires.
|
||||
func New(a *Auth) *Auth {
|
||||
a.logins = NewLimiter(10, 15*time.Minute)
|
||||
a.regs = NewLimiter(5, time.Hour)
|
||||
if a.Registration == nil {
|
||||
a.Registration = func() string { return "closed" }
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// OnlyOIDC indique que la connexion passe uniquement par le fournisseur OIDC.
|
||||
func (a *Auth) OnlyOIDC() bool { return a.OIDC != nil && !a.Local }
|
||||
|
||||
// Register ajoute les routes /auth/*.
|
||||
func (a *Auth) Register(mux *http.ServeMux) {
|
||||
if a.OIDC != nil {
|
||||
a.OIDC.RegisterLogin(mux)
|
||||
}
|
||||
if a.Local {
|
||||
mux.HandleFunc("POST /auth/local/login", a.localLogin)
|
||||
mux.HandleFunc("POST /auth/local/register", a.localRegister)
|
||||
}
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
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})
|
||||
}
|
||||
|
||||
// clientIP : adresse du client. Derrière un reverse proxy, l'entrée la plus à
|
||||
// droite de X-Forwarded-For est celle qu'il a ajoutée.
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
if ip := strings.TrimSpace(parts[len(parts)-1]); ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
type credentials struct {
|
||||
Username string `json:"username"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeJSON(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(v); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "requête JSON invalide")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *Auth) localLogin(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
userKey, ipKey := "u:"+strings.ToLower(strings.TrimSpace(c.Username)), "ip:"+clientIP(r)
|
||||
if !a.logins.Allowed(userKey) || !a.logins.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "900")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop de tentatives : réessayer dans quelques minutes")
|
||||
return
|
||||
}
|
||||
acc, err := a.Accounts.Authenticate(c.Username, c.Password)
|
||||
switch err {
|
||||
case nil:
|
||||
case ErrBadCredentials:
|
||||
a.logins.Fail(userKey)
|
||||
a.logins.Fail(ipKey)
|
||||
writeErr(w, http.StatusUnauthorized, err.Error())
|
||||
return
|
||||
case ErrPending, ErrDisabled:
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": err.Error(), "code": codeOf(err)})
|
||||
return
|
||||
default:
|
||||
slog.Error("connexion locale", "err", err)
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
a.logins.Reset(userKey)
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
slog.Info("connexion locale", "user", acc.ID)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func codeOf(err error) string {
|
||||
if err == ErrPending {
|
||||
return "pending"
|
||||
}
|
||||
return "disabled"
|
||||
}
|
||||
|
||||
func (a *Auth) localRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var c credentials
|
||||
if !decodeJSON(w, r, &c) {
|
||||
return
|
||||
}
|
||||
setup := a.Accounts.NeedsSetup() // premier compte : administrateur, même si les inscriptions sont fermées
|
||||
mode := a.Registration()
|
||||
if mode == "closed" && !setup {
|
||||
writeErr(w, http.StatusForbidden, "les inscriptions sont fermées")
|
||||
return
|
||||
}
|
||||
ipKey := "reg:" + clientIP(r)
|
||||
if !setup && !a.regs.Allowed(ipKey) {
|
||||
w.Header().Set("Retry-After", "3600")
|
||||
writeErr(w, http.StatusTooManyRequests, "trop d'inscriptions depuis cette adresse")
|
||||
return
|
||||
}
|
||||
status := StatusActive
|
||||
if mode == "approval" {
|
||||
status = StatusPending
|
||||
}
|
||||
acc, err := a.Accounts.CreateLocal(NewAccount{Username: c.Username, Name: c.Name, Email: c.Email,
|
||||
Password: c.Password, Status: status})
|
||||
if err != nil {
|
||||
code := http.StatusBadRequest
|
||||
if err == ErrAccountExists {
|
||||
code = http.StatusConflict
|
||||
}
|
||||
writeErr(w, code, err.Error())
|
||||
return
|
||||
}
|
||||
if !setup {
|
||||
a.regs.Fail(ipKey)
|
||||
}
|
||||
slog.Info("inscription", "user", acc.ID, "status", acc.Status, "role", acc.Role)
|
||||
if acc.Status == StatusPending {
|
||||
writeJSON(w, http.StatusAccepted, map[string]string{"status": StatusPending})
|
||||
return
|
||||
}
|
||||
if err := a.Sessions.Start(w, r, acc.User()); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "erreur interne")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"status": StatusActive})
|
||||
}
|
||||
|
||||
func (a *Auth) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if s, ok := a.Sessions.Get(r); ok && s.Provider == ProviderOIDC && a.OIDC != nil {
|
||||
a.OIDC.logout(w, r)
|
||||
return
|
||||
}
|
||||
a.Sessions.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// current renvoie l'utilisateur de la session : le compte doit exister et être
|
||||
// actif ; son rôle est celui du compte. La session est prolongée passée la
|
||||
// moitié de sa durée.
|
||||
func (a *Auth) current(w http.ResponseWriter, r *http.Request) (*User, bool) {
|
||||
s, ok := a.Sessions.Get(r)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
acc, ok := a.Accounts.Get(s.ID)
|
||||
if !ok || acc.Status != StatusActive {
|
||||
a.Sessions.Clear(w, r)
|
||||
return nil, false
|
||||
}
|
||||
u := acc.User()
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.Sessions.TTL/2 {
|
||||
_ = a.Sessions.Start(w, r, u)
|
||||
}
|
||||
return &u, true
|
||||
}
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics. Sans
|
||||
// session : l'API répond 401 ; une navigation reçoit l'application, qui affiche
|
||||
// la page de connexion (ou, avec OIDC seul, est renvoyée vers le fournisseur).
|
||||
func (a *Auth) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
if u, ok := a.current(w, r); ok { // identité disponible sur les routes publiques (ex. /api/me)
|
||||
r = r.WithContext(WithUser(r.Context(), u))
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
u, ok := a.current(w, r)
|
||||
if ok {
|
||||
next.ServeHTTP(w, r.WithContext(WithUser(r.Context(), u)))
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
if a.OnlyOIDC() {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
}
|
||||
writeErr(w, http.StatusUnauthorized, "connexion nécessaire")
|
||||
return
|
||||
}
|
||||
if a.OnlyOIDC() {
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// UserContext renvoie ctx portant l'utilisateur u (jetons d'API).
|
||||
func UserContext(ctx context.Context, u *User) context.Context { return WithUser(ctx, u) }
|
||||
@@ -0,0 +1,379 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// memNet est un « réseau » en mémoire : chaque hôte https est servi par un
|
||||
// http.Handler, sans ouvrir de port (les tests tournent aussi sous un bac à
|
||||
// sable qui interdit l'écoute locale).
|
||||
type memNet struct {
|
||||
hosts map[string]http.Handler
|
||||
n int
|
||||
}
|
||||
|
||||
var testNet = &memNet{hosts: map[string]http.Handler{}}
|
||||
|
||||
type memServer struct{ URL string }
|
||||
|
||||
// serve enregistre h sous un nouveau nom d'hôte et renvoie son URL.
|
||||
func (m *memNet) serve(prefix string, h http.Handler) *memServer {
|
||||
m.n++
|
||||
host := fmt.Sprintf("%s%d.test", prefix, m.n)
|
||||
m.hosts[host] = h
|
||||
return &memServer{URL: "https://" + host}
|
||||
}
|
||||
|
||||
func (m *memNet) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
h := m.hosts[req.URL.Host]
|
||||
if h == nil {
|
||||
return nil, fmt.Errorf("hôte inconnu : %s", req.URL.Host)
|
||||
}
|
||||
r := req.Clone(req.Context())
|
||||
r.RequestURI = req.URL.RequestURI()
|
||||
if r.Host == "" {
|
||||
r.Host = req.URL.Host
|
||||
}
|
||||
r.RemoteAddr = "192.0.2.1:4242"
|
||||
if req.URL.Scheme == "https" {
|
||||
r.TLS = &tls.ConnectionState{}
|
||||
}
|
||||
if r.Body == nil {
|
||||
r.Body = http.NoBody
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
res := rec.Result()
|
||||
res.Request = req
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (m *memNet) client() *http.Client { return &http.Client{Transport: m} }
|
||||
|
||||
// fakeIdP est un fournisseur OIDC minimal : découverte, autorisation (connexion
|
||||
// immédiate), jetons, JWKS et déconnexion.
|
||||
type fakeIdP struct {
|
||||
t *testing.T
|
||||
srv *memServer
|
||||
rsaKey *rsa.PrivateKey
|
||||
ecKey *ecdsa.PrivateKey
|
||||
alg string // RS256, ES256 ou HS256
|
||||
secret string
|
||||
groups []string
|
||||
|
||||
codes map[string]url.Values // code -> paramètres de la demande d'autorisation
|
||||
}
|
||||
|
||||
func newIdP(t *testing.T, alg string) *fakeIdP {
|
||||
rk, _ := rsa.GenerateKey(rand.Reader, 2048)
|
||||
ek, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
p := &fakeIdP{t: t, rsaKey: rk, ecKey: ek, alg: alg, secret: "secret-client-assez-long", codes: map[string]url.Values{}}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"issuer": p.srv.URL,
|
||||
"authorization_endpoint": p.srv.URL + "/authorize",
|
||||
"token_endpoint": p.srv.URL + "/token",
|
||||
"jwks_uri": p.srv.URL + "/jwks",
|
||||
"end_session_endpoint": p.srv.URL + "/logout",
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/jwks", func(w http.ResponseWriter, r *http.Request) {
|
||||
e := big.NewInt(int64(rk.E)).Bytes()
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []map[string]string{
|
||||
{"kty": "RSA", "kid": "r1", "use": "sig", "n": b64.EncodeToString(rk.N.Bytes()), "e": b64.EncodeToString(e)},
|
||||
{"kty": "EC", "kid": "e1", "crv": "P-256", "x": b64.EncodeToString(ek.X.FillBytes(make([]byte, 32))), "y": b64.EncodeToString(ek.Y.FillBytes(make([]byte, 32)))},
|
||||
}})
|
||||
})
|
||||
mux.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
code := randomString(8)
|
||||
p.codes[code] = q
|
||||
http.Redirect(w, r, q.Get("redirect_uri")+"?code="+code+"&state="+url.QueryEscape(q.Get("state")), http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = r.ParseForm()
|
||||
q, ok := p.codes[r.Form.Get("code")]
|
||||
delete(p.codes, r.Form.Get("code"))
|
||||
id, sec, _ := r.BasicAuth()
|
||||
ch := sha256.Sum256([]byte(r.Form.Get("code_verifier")))
|
||||
switch {
|
||||
case !ok, id != "excalicloud", sec != p.secret,
|
||||
r.Form.Get("redirect_uri") != q.Get("redirect_uri"),
|
||||
q.Get("code_challenge_method") != "S256", b64.EncodeToString(ch[:]) != q.Get("code_challenge"):
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"id_token": p.idToken(q.Get("nonce")), "token_type": "Bearer"})
|
||||
})
|
||||
p.srv = testNet.serve("idp", mux)
|
||||
return p
|
||||
}
|
||||
|
||||
func (p *fakeIdP) idToken(nonce string) string {
|
||||
claims := map[string]any{
|
||||
"iss": p.srv.URL, "sub": "u-42", "aud": "excalicloud", "nonce": nonce,
|
||||
"exp": time.Now().Add(5 * time.Minute).Unix(), "iat": time.Now().Unix(),
|
||||
"preferred_username": "cedric", "email": "cedric@example.org",
|
||||
}
|
||||
if p.groups != nil {
|
||||
claims["groups"] = p.groups
|
||||
}
|
||||
return p.sign(claims)
|
||||
}
|
||||
|
||||
func (p *fakeIdP) sign(claims map[string]any) string {
|
||||
hdr := map[string]string{"alg": p.alg, "typ": "JWT"}
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
hdr["kid"] = "r1"
|
||||
case "ES256":
|
||||
hdr["kid"] = "e1"
|
||||
}
|
||||
hb, _ := json.Marshal(hdr)
|
||||
cb, _ := json.Marshal(claims)
|
||||
signed := b64.EncodeToString(hb) + "." + b64.EncodeToString(cb)
|
||||
d := sha256.Sum256([]byte(signed))
|
||||
var sig []byte
|
||||
switch p.alg {
|
||||
case "RS256":
|
||||
sig, _ = rsa.SignPKCS1v15(rand.Reader, p.rsaKey, crypto.SHA256, d[:])
|
||||
case "ES256":
|
||||
r, s, _ := ecdsa.Sign(rand.Reader, p.ecKey, d[:])
|
||||
sig = append(r.FillBytes(make([]byte, 32)), s.FillBytes(make([]byte, 32))...)
|
||||
case "HS256":
|
||||
m := hmac.New(sha256.New, []byte(p.secret))
|
||||
m.Write([]byte(signed))
|
||||
sig = m.Sum(nil)
|
||||
}
|
||||
return signed + "." + b64.EncodeToString(sig)
|
||||
}
|
||||
|
||||
// app démarre excalicloud (routes /auth/*, une API et une page protégées, un
|
||||
// chemin public) avec l'authentification OIDC.
|
||||
func app(t *testing.T, idp *fakeIdP, groups []string) (*memServer, *http.Client) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
var srv *memServer
|
||||
o, err := NewOIDC(context.Background(), Config{
|
||||
Issuer: idp.srv.URL, ClientID: "excalicloud", ClientSecret: idp.secret,
|
||||
AllowedGroups: groups, EndSession: true, Secret: []byte("0123456789abcdef0123456789abcdef"),
|
||||
Client: testNet.client(),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
o.Register(mux)
|
||||
mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(UserFrom(r.Context()))
|
||||
})
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("app")) })
|
||||
srv = testNet.serve("app", o.Middleware(mux, func(p string) bool { return strings.HasPrefix(p, "/s/") }))
|
||||
jar, _ := cookiejar.New(nil)
|
||||
return srv, &http.Client{Jar: jar, Transport: testNet}
|
||||
}
|
||||
|
||||
func get(t *testing.T, c *http.Client, u string) (*http.Response, string) {
|
||||
t.Helper()
|
||||
res, err := c.Get(u)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(res.Body)
|
||||
return res, string(b)
|
||||
}
|
||||
|
||||
func TestLoginFlow(t *testing.T) {
|
||||
for _, alg := range []string{"RS256", "ES256", "HS256"} {
|
||||
t.Run(alg, func(t *testing.T) {
|
||||
idp := newIdP(t, alg)
|
||||
srv, c := app(t, idp, nil)
|
||||
|
||||
// Sans session : 401 avec l'adresse de connexion pour l'API...
|
||||
res, _ := get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 401 || res.Header.Get(LoginHeader) != "/auth/login" {
|
||||
t.Fatalf("API sans session : %d %q", res.StatusCode, res.Header.Get(LoginHeader))
|
||||
}
|
||||
// ... page de redirection (fragment conservé) pour la navigation.
|
||||
res, body := get(t, c, srv.URL+"/")
|
||||
if res.StatusCode != 401 || !strings.Contains(body, "location.hash") {
|
||||
t.Fatalf("navigation sans session : %d", res.StatusCode)
|
||||
}
|
||||
// Chemin public accessible.
|
||||
if res, _ := get(t, c, srv.URL+"/s/x.y"); res.StatusCode != 200 {
|
||||
t.Fatalf("chemin public : %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// Connexion complète : login -> fournisseur -> callback -> next.
|
||||
res, body = get(t, c, srv.URL+"/auth/login?next="+url.QueryEscape("/dossier?x=1"))
|
||||
if res.StatusCode != 200 || body != "app" || res.Request.URL.RequestURI() != "/dossier?x=1" {
|
||||
t.Fatalf("après connexion : %d %q %s", res.StatusCode, body, res.Request.URL)
|
||||
}
|
||||
res, body = get(t, c, srv.URL+"/api/me")
|
||||
if res.StatusCode != 200 || !strings.Contains(body, `"name":"cedric"`) || !strings.Contains(body, `"sub":"u-42"`) {
|
||||
t.Fatalf("/api/me : %d %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
// Déconnexion : cookie effacé, renvoi vers end_session_endpoint.
|
||||
nc := &http.Client{Jar: c.Jar, Transport: testNet, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
res, _ = get(t, nc, srv.URL+"/auth/logout")
|
||||
loc, _ := url.Parse(res.Header.Get("Location"))
|
||||
if res.StatusCode != 302 || loc.Path != "/logout" || loc.Query().Get("client_id") != "excalicloud" ||
|
||||
loc.Query().Get("post_logout_redirect_uri") != srv.URL+"/auth/logged-out" {
|
||||
t.Fatalf("logout : %d %s", res.StatusCode, loc)
|
||||
}
|
||||
if res, _ := get(t, c, srv.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("après déconnexion : %d", res.StatusCode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedGroups(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
idp.groups = []string{"/excalicloud-users"} // chemin complet Keycloak
|
||||
srv, c := app(t, idp, []string{"excalicloud-users"})
|
||||
if res, body := get(t, c, srv.URL+"/auth/login"); res.StatusCode != 200 || body != "app" {
|
||||
t.Fatalf("membre du groupe : %d %q", res.StatusCode, body)
|
||||
}
|
||||
|
||||
idp2 := newIdP(t, "RS256")
|
||||
idp2.groups = []string{"autres"}
|
||||
srv2, c2 := app(t, idp2, []string{"excalicloud-users"})
|
||||
if res, _ := get(t, c2, srv2.URL+"/auth/login"); res.StatusCode != 403 {
|
||||
t.Fatalf("hors groupe : %d", res.StatusCode)
|
||||
}
|
||||
if res, _ := get(t, c2, srv2.URL+"/api/me"); res.StatusCode != 401 {
|
||||
t.Fatalf("hors groupe, pas de session attendue : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallbackRejectsForgedState(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
srv, c := app(t, idp, nil)
|
||||
// Callback sans cookie d'état (CSRF de connexion) : refusé.
|
||||
if res, _ := get(t, c, srv.URL+"/auth/callback?code=x&state=y"); res.StatusCode != 400 {
|
||||
t.Fatalf("callback forgé : %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyIDToken(t *testing.T) {
|
||||
idp := newIdP(t, "RS256")
|
||||
o, err := NewOIDC(context.Background(), Config{Issuer: idp.srv.URL, ClientID: "excalicloud", Secret: []byte("0123456789abcdef"), Client: testNet.client()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
d, err := o.provider(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := func() map[string]any {
|
||||
return map[string]any{"iss": idp.srv.URL, "sub": "s", "aud": []string{"excalicloud"}, "nonce": "n",
|
||||
"exp": time.Now().Add(time.Minute).Unix(), "iat": time.Now().Unix()}
|
||||
}
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err != nil {
|
||||
t.Fatalf("jeton valide refusé : %v", err)
|
||||
}
|
||||
bad := map[string]func(map[string]any){
|
||||
"émetteur": func(c map[string]any) { c["iss"] = "https://ailleurs" },
|
||||
"audience": func(c map[string]any) { c["aud"] = "autre" },
|
||||
"expiré": func(c map[string]any) { c["exp"] = time.Now().Add(-time.Hour).Unix() },
|
||||
"nonce": func(c map[string]any) { c["nonce"] = "x" },
|
||||
}
|
||||
for name, mutate := range bad {
|
||||
c := base()
|
||||
mutate(c)
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(c), "n"); err == nil {
|
||||
t.Errorf("%s : jeton accepté", name)
|
||||
}
|
||||
}
|
||||
// Signature altérée, alg none et HS256 sans secret client.
|
||||
tok := idp.sign(base())
|
||||
if _, err := o.verifyIDToken(context.Background(), d, tok[:len(tok)-4]+"AAAA", "n"); err == nil {
|
||||
t.Error("signature altérée acceptée")
|
||||
}
|
||||
parts := strings.Split(tok, ".")
|
||||
none := b64.EncodeToString([]byte(`{"alg":"none"}`)) + "." + parts[1] + "."
|
||||
if _, err := o.verifyIDToken(context.Background(), d, none, "n"); err == nil {
|
||||
t.Error("alg none accepté")
|
||||
}
|
||||
idp.alg = "HS256"
|
||||
if _, err := o.verifyIDToken(context.Background(), d, idp.sign(base()), "n"); err == nil {
|
||||
t.Error("HS256 accepté sans secret client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeNext(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"/a/b?c=1": "/a/b?c=1",
|
||||
"//evil.example": "/",
|
||||
"/\\evil.example": "/",
|
||||
"https://evil": "/",
|
||||
"/auth/logout": "/",
|
||||
"": "/",
|
||||
"/x\r\nSet-Cookie:a": "/",
|
||||
} {
|
||||
if got := safeNext(in); got != want {
|
||||
t.Errorf("safeNext(%q) = %q, attendu %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionCookieTampering(t *testing.T) {
|
||||
s := signer{[]byte("0123456789abcdef")}
|
||||
v, _ := s.encode(session{User: User{Sub: "a"}, Exp: time.Now().Add(time.Hour).Unix()})
|
||||
var out session
|
||||
if err := s.decode(v, &out); err != nil || out.Sub != "a" {
|
||||
t.Fatalf("décodage : %v", err)
|
||||
}
|
||||
p, sig, _ := strings.Cut(v, ".")
|
||||
forged := b64.EncodeToString([]byte(`{"sub":"admin","exp":9999999999}`)) + "." + sig
|
||||
if s.decode(forged, &out) == nil || s.decode(p+".x", &out) == nil {
|
||||
t.Fatal("cookie altéré accepté")
|
||||
}
|
||||
if (signer{[]byte("autre-cle-0123456")}).decode(v, &out) == nil {
|
||||
t.Fatal("cookie signé par une autre clé accepté")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadSecret(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if _, err := LoadSecret("court", dir); err == nil {
|
||||
t.Fatal("secret trop court accepté")
|
||||
}
|
||||
k1, err := LoadSecret("", dir)
|
||||
if err != nil || len(k1) != 32 {
|
||||
t.Fatalf("génération : %v", err)
|
||||
}
|
||||
fi, _ := os.Stat(filepath.Join(dir, ".session-secret"))
|
||||
if fi.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("droits %v", fi.Mode().Perm())
|
||||
}
|
||||
k2, _ := LoadSecret("", dir)
|
||||
if string(k1) != string(k2) {
|
||||
t.Fatal("clé non conservée entre deux démarrages")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/hmac"
|
||||
"crypto/rsa"
|
||||
_ "crypto/sha256" // enregistre SHA-256 pour crypto.Hash
|
||||
_ "crypto/sha512" // enregistre SHA-384 et SHA-512
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// jwk est une clé publique d'un JWKS (RFC 7517), RSA ou EC.
|
||||
type jwk struct {
|
||||
Kty string `json:"kty"`
|
||||
Kid string `json:"kid"`
|
||||
Use string `json:"use"`
|
||||
Alg string `json:"alg"`
|
||||
N string `json:"n"`
|
||||
E string `json:"e"`
|
||||
Crv string `json:"crv"`
|
||||
X string `json:"x"`
|
||||
Y string `json:"y"`
|
||||
}
|
||||
|
||||
func (k jwk) publicKey() (crypto.PublicKey, error) {
|
||||
switch k.Kty {
|
||||
case "RSA":
|
||||
n, err1 := b64.DecodeString(k.N)
|
||||
e, err2 := b64.DecodeString(k.E)
|
||||
if err1 != nil || err2 != nil || len(n) == 0 || len(e) == 0 || len(e) > 4 {
|
||||
return nil, errors.New("clé RSA invalide")
|
||||
}
|
||||
return &rsa.PublicKey{N: new(big.Int).SetBytes(n), E: int(new(big.Int).SetBytes(e).Int64())}, nil
|
||||
case "EC":
|
||||
var c elliptic.Curve
|
||||
switch k.Crv {
|
||||
case "P-256":
|
||||
c = elliptic.P256()
|
||||
case "P-384":
|
||||
c = elliptic.P384()
|
||||
case "P-521":
|
||||
c = elliptic.P521()
|
||||
default:
|
||||
return nil, fmt.Errorf("courbe %q non prise en charge", k.Crv)
|
||||
}
|
||||
x, err1 := b64.DecodeString(k.X)
|
||||
y, err2 := b64.DecodeString(k.Y)
|
||||
if err1 != nil || err2 != nil {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
pub := &ecdsa.PublicKey{Curve: c, X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y)}
|
||||
if !c.IsOnCurve(pub.X, pub.Y) {
|
||||
return nil, errors.New("clé EC invalide")
|
||||
}
|
||||
return pub, nil
|
||||
}
|
||||
return nil, fmt.Errorf("type de clé %q non pris en charge", k.Kty)
|
||||
}
|
||||
|
||||
var algHash = map[string]crypto.Hash{
|
||||
"RS256": crypto.SHA256, "RS384": crypto.SHA384, "RS512": crypto.SHA512,
|
||||
"PS256": crypto.SHA256, "PS384": crypto.SHA384, "PS512": crypto.SHA512,
|
||||
"ES256": crypto.SHA256, "ES384": crypto.SHA384, "ES512": crypto.SHA512,
|
||||
"HS256": crypto.SHA256, "HS384": crypto.SHA384, "HS512": crypto.SHA512,
|
||||
}
|
||||
|
||||
type jwtHeader struct {
|
||||
Alg string `json:"alg"`
|
||||
Kid string `json:"kid"`
|
||||
}
|
||||
|
||||
// parseJWT découpe un JWS compact et renvoie l'en-tête, les claims bruts, le
|
||||
// contenu signé et la signature.
|
||||
func parseJWT(token string) (h jwtHeader, claims []byte, signed string, sig []byte, err error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 3 {
|
||||
return h, nil, "", nil, errors.New("jeton mal formé")
|
||||
}
|
||||
hb, err := b64.DecodeString(parts[0])
|
||||
if err != nil || json.Unmarshal(hb, &h) != nil {
|
||||
return h, nil, "", nil, errors.New("en-tête de jeton invalide")
|
||||
}
|
||||
if claims, err = b64.DecodeString(parts[1]); err != nil {
|
||||
return h, nil, "", nil, errors.New("contenu de jeton invalide")
|
||||
}
|
||||
if sig, err = b64.DecodeString(parts[2]); err != nil {
|
||||
return h, nil, "", nil, errors.New("signature de jeton invalide")
|
||||
}
|
||||
return h, claims, parts[0] + "." + parts[1], sig, nil
|
||||
}
|
||||
|
||||
// verifySignature vérifie la signature avec une clé publique (RS, PS, ES) ou
|
||||
// le secret client (HS, clé symétrique utilisée par exemple par Authentik
|
||||
// quand aucun certificat de signature n'est choisi).
|
||||
func verifySignature(alg string, key crypto.PublicKey, secret []byte, signed string, sig []byte) error {
|
||||
hash, ok := algHash[alg]
|
||||
if !ok {
|
||||
return fmt.Errorf("algorithme %q refusé", alg)
|
||||
}
|
||||
if strings.HasPrefix(alg, "HS") {
|
||||
if len(secret) == 0 {
|
||||
return fmt.Errorf("jeton %s sans OIDC_CLIENT_SECRET", alg)
|
||||
}
|
||||
m := hmac.New(hash.New, secret)
|
||||
m.Write([]byte(signed))
|
||||
if !hmac.Equal(m.Sum(nil), sig) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
d := hash.New()
|
||||
d.Write([]byte(signed))
|
||||
digest := d.Sum(nil)
|
||||
switch k := key.(type) {
|
||||
case *rsa.PublicKey:
|
||||
var err error
|
||||
switch alg[:2] {
|
||||
case "RS":
|
||||
err = rsa.VerifyPKCS1v15(k, hash, digest, sig)
|
||||
case "PS":
|
||||
err = rsa.VerifyPSS(k, hash, digest, sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
|
||||
default:
|
||||
err = errors.New("algorithme incompatible avec une clé RSA")
|
||||
}
|
||||
if err != nil {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
case *ecdsa.PublicKey:
|
||||
size := (k.Curve.Params().BitSize + 7) / 8
|
||||
if alg[:2] != "ES" || len(sig) != 2*size {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
r, s := new(big.Int).SetBytes(sig[:size]), new(big.Int).SetBytes(sig[size:])
|
||||
if !ecdsa.Verify(k, digest, r, s) {
|
||||
return errors.New("signature invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("clé de vérification inadaptée")
|
||||
}
|
||||
|
||||
// idClaims regroupe les claims utiles d'un ID Token.
|
||||
type idClaims struct {
|
||||
Iss string `json:"iss"`
|
||||
Sub string `json:"sub"`
|
||||
Aud json.RawMessage `json:"aud"`
|
||||
Azp string `json:"azp"`
|
||||
Exp json.Number `json:"exp"`
|
||||
Iat json.Number `json:"iat"`
|
||||
Nonce string `json:"nonce"`
|
||||
Name string `json:"name"`
|
||||
PreferredUsername string `json:"preferred_username"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
func (c idClaims) audiences() []string {
|
||||
var one string
|
||||
if json.Unmarshal(c.Aud, &one) == nil {
|
||||
return []string{one}
|
||||
}
|
||||
var many []string
|
||||
_ = json.Unmarshal(c.Aud, &many)
|
||||
return many
|
||||
}
|
||||
|
||||
const clockSkew = 2 * time.Minute
|
||||
|
||||
// validate contrôle émetteur, audience, dates et nonce (OIDC Core 3.1.3.7).
|
||||
func (c idClaims) validate(issuer, clientID, nonce string, t time.Time) error {
|
||||
if c.Iss != issuer {
|
||||
return fmt.Errorf("émetteur %q inattendu", c.Iss)
|
||||
}
|
||||
if c.Sub == "" {
|
||||
return errors.New("claim sub absent")
|
||||
}
|
||||
aud := c.audiences()
|
||||
found := false
|
||||
for _, a := range aud {
|
||||
found = found || a == clientID
|
||||
}
|
||||
if !found {
|
||||
return errors.New("jeton destiné à un autre client")
|
||||
}
|
||||
if len(aud) > 1 && c.Azp != "" && c.Azp != clientID {
|
||||
return errors.New("azp inattendu")
|
||||
}
|
||||
exp, err := c.Exp.Int64()
|
||||
if err != nil {
|
||||
f, ferr := c.Exp.Float64()
|
||||
if ferr != nil {
|
||||
return errors.New("claim exp invalide")
|
||||
}
|
||||
exp = int64(f)
|
||||
}
|
||||
if t.After(time.Unix(exp, 0).Add(clockSkew)) {
|
||||
return errors.New("jeton expiré")
|
||||
}
|
||||
if iat, err := c.Iat.Float64(); err == nil && time.Unix(int64(iat), 0).After(t.Add(clockSkew)) {
|
||||
return errors.New("jeton émis dans le futur (horloge ?)")
|
||||
}
|
||||
if !hmac.Equal([]byte(c.Nonce), []byte(nonce)) {
|
||||
return errors.New("nonce invalide")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stringList lit un claim chaîne ou tableau de chaînes (groupes, rôles).
|
||||
func stringList(v any) []string {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
return []string{x}
|
||||
case []any:
|
||||
out := make([]string, 0, len(x))
|
||||
for _, e := range x {
|
||||
if s, ok := e.(string); ok {
|
||||
out = append(out, s)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// claimPath lit un claim éventuellement imbriqué (« realm_access.roles »).
|
||||
func claimPath(all map[string]any, p string) any {
|
||||
var cur any = all
|
||||
for _, part := range strings.Split(p, ".") {
|
||||
m, ok := cur.(map[string]any)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
cur = m[part]
|
||||
}
|
||||
return cur
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"html"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
sessionCookie = "stackwatch_session"
|
||||
stateCookie = "stackwatch_oidc"
|
||||
stateTTL = 10 * time.Minute
|
||||
|
||||
// LoginHeader accompagne les réponses 401 de l'API : le frontend y lit
|
||||
// l'adresse de connexion.
|
||||
LoginHeader = "X-Auth-Login"
|
||||
)
|
||||
|
||||
// Config regroupe les réglages OIDC (variables OIDC_* et SESSION_*).
|
||||
type Config struct {
|
||||
Issuer string // OIDC_ISSUER
|
||||
ClientID string // OIDC_CLIENT_ID
|
||||
ClientSecret string // OIDC_CLIENT_SECRET (vide : client public, PKCE seul)
|
||||
RedirectURL string // OIDC_REDIRECT_URL (vide : https://<hôte>/auth/callback)
|
||||
Scopes []string // OIDC_SCOPES
|
||||
// AllowedGroups restreint l'accès aux membres d'au moins un de ces groupes
|
||||
// (claim GroupsClaim) ; vide : tout utilisateur authentifié.
|
||||
AllowedGroups []string
|
||||
GroupsClaim string // OIDC_GROUPS_CLAIM, « groups » par défaut
|
||||
EndSession bool // OIDC_LOGOUT : déconnexion aussi chez le fournisseur
|
||||
SessionTTL time.Duration
|
||||
Secret []byte // clé HMAC des cookies
|
||||
Client *http.Client
|
||||
// Sessions : gestionnaire de sessions partagé avec l'authentification locale
|
||||
// (nil : créé à partir de Secret et SessionTTL).
|
||||
Sessions *Sessions
|
||||
// Provision est appelé après une connexion réussie, avant l'ouverture de la
|
||||
// session : il crée ou met à jour le compte et peut refuser la connexion
|
||||
// (ErrPending, ErrDisabled). Il renvoie l'utilisateur de la session.
|
||||
Provision func(u User, groups []string) (User, error)
|
||||
}
|
||||
|
||||
// discovery est la partie utile de /.well-known/openid-configuration.
|
||||
type discovery struct {
|
||||
Issuer string `json:"issuer"`
|
||||
AuthorizationEndpoint string `json:"authorization_endpoint"`
|
||||
TokenEndpoint string `json:"token_endpoint"`
|
||||
JWKSURI string `json:"jwks_uri"`
|
||||
EndSessionEndpoint string `json:"end_session_endpoint"`
|
||||
}
|
||||
|
||||
// OIDC authentifie les utilisateurs auprès d'un fournisseur OpenID Connect
|
||||
// (Authentik, Keycloak, Entra ID, Google, Dex...).
|
||||
type OIDC struct {
|
||||
cfg Config
|
||||
signer signer
|
||||
sess *Sessions
|
||||
|
||||
mu sync.Mutex
|
||||
disc *discovery // nil : pas encore découvert
|
||||
keys map[string]crypto.PublicKey
|
||||
keysAt time.Time
|
||||
discErr time.Time // dernier échec de découverte (limite les tentatives)
|
||||
}
|
||||
|
||||
// NewOIDC prépare l'authentification ; la découverte du fournisseur est
|
||||
// tentée tout de suite puis, en cas d'échec, à la première connexion.
|
||||
func NewOIDC(ctx context.Context, cfg Config) (*OIDC, error) {
|
||||
if cfg.Issuer == "" || cfg.ClientID == "" {
|
||||
return nil, errors.New("OIDC_ISSUER et OIDC_CLIENT_ID sont requis en mode oidc")
|
||||
}
|
||||
if len(cfg.Secret) < 16 {
|
||||
return nil, errors.New("clé de session trop courte")
|
||||
}
|
||||
if cfg.RedirectURL != "" {
|
||||
u, err := url.Parse(cfg.RedirectURL)
|
||||
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" {
|
||||
return nil, errors.New("OIDC_REDIRECT_URL invalide (URL absolue attendue)")
|
||||
}
|
||||
}
|
||||
if len(cfg.Scopes) == 0 {
|
||||
cfg.Scopes = []string{"openid", "profile", "email"}
|
||||
}
|
||||
if !slices.Contains(cfg.Scopes, "openid") {
|
||||
cfg.Scopes = append([]string{"openid"}, cfg.Scopes...)
|
||||
}
|
||||
if cfg.GroupsClaim == "" {
|
||||
cfg.GroupsClaim = "groups"
|
||||
}
|
||||
if cfg.SessionTTL <= 0 {
|
||||
cfg.SessionTTL = 24 * time.Hour
|
||||
}
|
||||
if cfg.Client == nil {
|
||||
cfg.Client = &http.Client{Timeout: 15 * time.Second}
|
||||
}
|
||||
if cfg.Sessions == nil {
|
||||
cfg.Sessions = NewSessions(cfg.Secret, cfg.SessionTTL, strings.HasPrefix(cfg.RedirectURL, "https://"))
|
||||
}
|
||||
a := &OIDC{cfg: cfg, signer: signer{cfg.Secret}, sess: cfg.Sessions}
|
||||
if _, err := a.provider(ctx); err != nil {
|
||||
slog.Warn("fournisseur OIDC injoignable, nouvel essai à la première connexion", "issuer", cfg.Issuer, "err", err)
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) getJSON(ctx context.Context, u string, v any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("%s : HTTP %d", u, res.StatusCode)
|
||||
}
|
||||
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(v)
|
||||
}
|
||||
|
||||
// provider renvoie la configuration découverte (mise en cache).
|
||||
func (a *OIDC) provider(ctx context.Context) (*discovery, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
if a.disc != nil {
|
||||
return a.disc, nil
|
||||
}
|
||||
if time.Since(a.discErr) < 5*time.Second {
|
||||
return nil, errors.New("fournisseur OIDC injoignable")
|
||||
}
|
||||
var d discovery
|
||||
u := strings.TrimRight(a.cfg.Issuer, "/") + "/.well-known/openid-configuration"
|
||||
if err := a.getJSON(ctx, u, &d); err != nil {
|
||||
a.discErr = time.Now()
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimRight(d.Issuer, "/") != strings.TrimRight(a.cfg.Issuer, "/") {
|
||||
a.discErr = time.Now()
|
||||
return nil, fmt.Errorf("l'émetteur annoncé (%s) ne correspond pas à OIDC_ISSUER", d.Issuer)
|
||||
}
|
||||
if d.AuthorizationEndpoint == "" || d.TokenEndpoint == "" || d.JWKSURI == "" {
|
||||
a.discErr = time.Now()
|
||||
return nil, errors.New("configuration OIDC incomplète (authorization, token ou jwks absent)")
|
||||
}
|
||||
a.disc = &d
|
||||
slog.Info("fournisseur OIDC découvert", "issuer", d.Issuer)
|
||||
return a.disc, nil
|
||||
}
|
||||
|
||||
// key renvoie la clé publique kid, en rechargeant le JWKS si elle est
|
||||
// inconnue (rotation de clés), au plus une fois par minute.
|
||||
func (a *OIDC) key(ctx context.Context, d *discovery, kid, alg string) (crypto.PublicKey, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
find := func() crypto.PublicKey {
|
||||
if k, ok := a.keys[kid]; ok {
|
||||
return k
|
||||
}
|
||||
if kid == "" && len(a.keys) == 1 {
|
||||
for _, k := range a.keys {
|
||||
return k
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
if time.Since(a.keysAt) < time.Minute && a.keys != nil {
|
||||
return nil, fmt.Errorf("clé %q inconnue", kid)
|
||||
}
|
||||
var set struct {
|
||||
Keys []jwk `json:"keys"`
|
||||
}
|
||||
if err := a.getJSON(ctx, d.JWKSURI, &set); err != nil {
|
||||
return nil, fmt.Errorf("JWKS : %w", err)
|
||||
}
|
||||
a.keys = map[string]crypto.PublicKey{}
|
||||
a.keysAt = time.Now()
|
||||
for _, j := range set.Keys {
|
||||
if j.Use != "" && j.Use != "sig" {
|
||||
continue
|
||||
}
|
||||
if pk, err := j.publicKey(); err == nil {
|
||||
a.keys[j.Kid] = pk
|
||||
}
|
||||
}
|
||||
if k := find(); k != nil {
|
||||
return k, nil
|
||||
}
|
||||
return nil, fmt.Errorf("clé %q absente du JWKS (alg %s)", kid, alg)
|
||||
}
|
||||
|
||||
// --- Routes /auth/* -----------------------------------------------------------
|
||||
|
||||
// Register ajoute /auth/login, /auth/callback, /auth/logout et /auth/logged-out.
|
||||
func (a *OIDC) Register(mux *http.ServeMux) {
|
||||
a.RegisterLogin(mux)
|
||||
mux.HandleFunc("GET /auth/logout", a.logout)
|
||||
mux.HandleFunc("POST /auth/logout", a.logout)
|
||||
}
|
||||
|
||||
// RegisterLogin ajoute /auth/login, /auth/callback et /auth/logged-out (la
|
||||
// déconnexion est alors portée par l'appelant, voir Auth).
|
||||
func (a *OIDC) RegisterLogin(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /auth/login", a.login)
|
||||
mux.HandleFunc("GET /auth/callback", a.callback)
|
||||
mux.HandleFunc("GET /auth/logged-out", func(w http.ResponseWriter, r *http.Request) {
|
||||
page(w, http.StatusOK, "Déconnecté", "Vous êtes déconnecté.", "/", "Se reconnecter")
|
||||
})
|
||||
}
|
||||
|
||||
func secure(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||
}
|
||||
|
||||
// baseURL est l'origine publique du service : celle de OIDC_REDIRECT_URL si
|
||||
// elle est fixée, sinon celle de la requête (en-têtes X-Forwarded-* compris).
|
||||
func (a *OIDC) baseURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
u, _ := url.Parse(a.cfg.RedirectURL)
|
||||
return u.Scheme + "://" + u.Host
|
||||
}
|
||||
scheme := "http"
|
||||
if secure(r) {
|
||||
scheme = "https"
|
||||
}
|
||||
host := r.Host
|
||||
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
|
||||
host, _, _ = strings.Cut(h, ",")
|
||||
host = strings.TrimSpace(host)
|
||||
}
|
||||
return scheme + "://" + host
|
||||
}
|
||||
|
||||
func (a *OIDC) redirectURL(r *http.Request) string {
|
||||
if a.cfg.RedirectURL != "" {
|
||||
return a.cfg.RedirectURL
|
||||
}
|
||||
return a.baseURL(r) + "/auth/callback"
|
||||
}
|
||||
|
||||
func (a *OIDC) setCookie(w http.ResponseWriter, r *http.Request, name, value, path string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: name,
|
||||
Value: value,
|
||||
Path: path,
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || strings.HasPrefix(a.cfg.RedirectURL, "https://"),
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// safeNext n'accepte que les chemins locaux (pas de redirection ouverte).
|
||||
func safeNext(next string) string {
|
||||
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") ||
|
||||
strings.HasPrefix(next, "/auth/") || strings.ContainsAny(next, "\r\n") {
|
||||
return "/"
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (a *OIDC) login(w http.ResponseWriter, r *http.Request) {
|
||||
d, err := a.provider(r.Context())
|
||||
if err != nil {
|
||||
slog.Error("OIDC : découverte", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible",
|
||||
"Le fournisseur d'identité est injoignable pour l'instant.", r.URL.RequestURI(), "Réessayer")
|
||||
return
|
||||
}
|
||||
st := loginState{
|
||||
State: randomString(24),
|
||||
Nonce: randomString(24),
|
||||
Verifier: randomString(48), // 64 caractères (RFC 7636 : 43 à 128)
|
||||
Next: safeNext(r.URL.Query().Get("next")),
|
||||
Exp: now().Add(stateTTL).Unix(),
|
||||
}
|
||||
v, err := a.signer.encode(st)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, v, "/auth/", stateTTL)
|
||||
|
||||
challenge := sha256.Sum256([]byte(st.Verifier))
|
||||
q := url.Values{
|
||||
"response_type": {"code"},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"scope": {strings.Join(a.cfg.Scopes, " ")},
|
||||
"state": {st.State},
|
||||
"nonce": {st.Nonce},
|
||||
"code_challenge": {b64.EncodeToString(challenge[:])},
|
||||
"code_challenge_method": {"S256"},
|
||||
}
|
||||
sep := "?"
|
||||
if strings.Contains(d.AuthorizationEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
http.Redirect(w, r, d.AuthorizationEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
}
|
||||
|
||||
func (a *OIDC) callback(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
q := r.URL.Query()
|
||||
retry := "/auth/login"
|
||||
var st loginState
|
||||
c, err := r.Cookie(stateCookie)
|
||||
if err == nil {
|
||||
err = a.signer.decode(c.Value, &st)
|
||||
}
|
||||
if err == nil && st.Next != "/" {
|
||||
retry += "?next=" + url.QueryEscape(st.Next)
|
||||
}
|
||||
a.setCookie(w, r, stateCookie, "", "/auth/", -1) // usage unique
|
||||
if e := q.Get("error"); e != "" {
|
||||
slog.Warn("OIDC : refus du fournisseur", "error", e, "description", q.Get("error_description"))
|
||||
page(w, http.StatusForbidden, "Connexion refusée", "Le fournisseur d'identité a refusé la connexion ("+e+").", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err != nil || st.Exp < now().Unix() || st.State == "" || q.Get("state") != st.State {
|
||||
page(w, http.StatusBadRequest, "Connexion expirée",
|
||||
"La demande de connexion est expirée ou invalide (cookies bloqués ?).", retry, "Recommencer")
|
||||
return
|
||||
}
|
||||
user, err := a.exchange(r, q.Get("code"), st)
|
||||
if errors.Is(err, errForbidden) {
|
||||
slog.Warn("OIDC : accès refusé (groupes du jeton, à comparer à OIDC_ALLOWED_GROUPS)", "sub", user.Sub, "name", user.Name, "groups", user.Groups, "claim", a.cfg.GroupsClaim, "allowed", a.cfg.AllowedGroups)
|
||||
page(w, http.StatusForbidden, "Accès refusé",
|
||||
"Votre compte ("+user.Name+") n'appartient à aucun groupe autorisé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrPending) {
|
||||
page(w, http.StatusForbidden, "Compte en attente", "Votre compte ("+user.Name+") doit être validé par un administrateur.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ErrDisabled) {
|
||||
page(w, http.StatusForbidden, "Compte désactivé", "Votre compte ("+user.Name+") a été désactivé.", "/auth/logout", "Changer de compte")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Error("OIDC : échange du code", "err", err)
|
||||
page(w, http.StatusBadGateway, "Connexion impossible", "La vérification de l'identité a échoué.", retry, "Réessayer")
|
||||
return
|
||||
}
|
||||
if err := a.startSession(w, r, user); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
slog.Info("connexion OIDC", "sub", user.Sub, "name", user.Name)
|
||||
http.Redirect(w, r, st.Next, http.StatusFound)
|
||||
}
|
||||
|
||||
var errForbidden = errors.New("utilisateur hors des groupes autorisés")
|
||||
|
||||
// exchange échange le code contre les jetons, vérifie l'ID Token et en tire
|
||||
// l'utilisateur.
|
||||
func (a *OIDC) exchange(r *http.Request, code string, st loginState) (User, error) {
|
||||
ctx := r.Context()
|
||||
d, err := a.provider(ctx)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
form := url.Values{
|
||||
"grant_type": {"authorization_code"},
|
||||
"code": {code},
|
||||
"redirect_uri": {a.redirectURL(r)},
|
||||
"code_verifier": {st.Verifier},
|
||||
"client_id": {a.cfg.ClientID},
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, d.TokenEndpoint, strings.NewReader(form.Encode()))
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if a.cfg.ClientSecret != "" { // client_secret_basic (RFC 6749 2.3.1)
|
||||
req.SetBasicAuth(url.QueryEscape(a.cfg.ClientID), url.QueryEscape(a.cfg.ClientSecret))
|
||||
}
|
||||
res, err := a.cfg.Client.Do(req)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var tok struct {
|
||||
IDToken string `json:"id_token"`
|
||||
Error string `json:"error"`
|
||||
Desc string `json:"error_description"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&tok); err != nil {
|
||||
return User{}, fmt.Errorf("réponse du token endpoint (HTTP %d) : %w", res.StatusCode, err)
|
||||
}
|
||||
if res.StatusCode != http.StatusOK || tok.IDToken == "" {
|
||||
return User{}, fmt.Errorf("token endpoint : HTTP %d %s %s", res.StatusCode, tok.Error, tok.Desc)
|
||||
}
|
||||
u, err := a.verifyIDToken(ctx, d, tok.IDToken, st.Nonce)
|
||||
if err != nil {
|
||||
return u, err
|
||||
}
|
||||
if a.cfg.Provision != nil {
|
||||
return a.cfg.Provision(u, u.Groups)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) verifyIDToken(ctx context.Context, d *discovery, raw, nonce string) (User, error) {
|
||||
h, body, signed, sig, err := parseJWT(raw)
|
||||
if err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var key crypto.PublicKey
|
||||
if !strings.HasPrefix(h.Alg, "HS") {
|
||||
if key, err = a.key(ctx, d, h.Kid, h.Alg); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
}
|
||||
if err := verifySignature(h.Alg, key, []byte(a.cfg.ClientSecret), signed, sig); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
var c idClaims
|
||||
if err := json.Unmarshal(body, &c); err != nil {
|
||||
return User{}, errors.New("claims illisibles")
|
||||
}
|
||||
if err := c.validate(d.Issuer, a.cfg.ClientID, nonce, now()); err != nil {
|
||||
return User{}, err
|
||||
}
|
||||
u := User{Sub: c.Sub, Email: c.Email, Name: c.PreferredUsername}
|
||||
for _, n := range []string{c.Name, c.Email, c.Sub} {
|
||||
if u.Name == "" {
|
||||
u.Name = n
|
||||
}
|
||||
}
|
||||
var all map[string]any
|
||||
_ = json.Unmarshal(body, &all)
|
||||
groups := stringList(claimPath(all, a.cfg.GroupsClaim))
|
||||
for i, g := range groups {
|
||||
groups[i] = strings.TrimPrefix(g, "/") // Keycloak : chemin complet du groupe
|
||||
}
|
||||
u.Groups = groups
|
||||
if len(a.cfg.AllowedGroups) > 0 {
|
||||
ok := slices.ContainsFunc(groups, func(g string) bool {
|
||||
// Keycloak préfixe les groupes par « / » quand le chemin complet est inclus.
|
||||
return slices.Contains(a.cfg.AllowedGroups, g) || slices.Contains(a.cfg.AllowedGroups, strings.TrimPrefix(g, "/"))
|
||||
})
|
||||
if !ok {
|
||||
return u, errForbidden
|
||||
}
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (a *OIDC) startSession(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
return a.sess.Start(w, r, u)
|
||||
}
|
||||
|
||||
func (a *OIDC) logout(w http.ResponseWriter, r *http.Request) {
|
||||
a.sess.Clear(w, r)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
back := a.baseURL(r) + "/auth/logged-out"
|
||||
if a.cfg.EndSession {
|
||||
if d, err := a.provider(r.Context()); err == nil && d.EndSessionEndpoint != "" {
|
||||
// RP-Initiated Logout 1.0 : client_id identifie le client sans id_token_hint.
|
||||
q := url.Values{"client_id": {a.cfg.ClientID}, "post_logout_redirect_uri": {back}}
|
||||
sep := "?"
|
||||
if strings.Contains(d.EndSessionEndpoint, "?") {
|
||||
sep = "&"
|
||||
}
|
||||
http.Redirect(w, r, d.EndSessionEndpoint+sep+q.Encode(), http.StatusFound)
|
||||
return
|
||||
}
|
||||
}
|
||||
http.Redirect(w, r, back, http.StatusFound)
|
||||
}
|
||||
|
||||
// --- Protection des routes -------------------------------------------------------
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
// UserFrom renvoie l'utilisateur de la requête (nil hors session OIDC).
|
||||
func UserFrom(ctx context.Context) *User {
|
||||
u, _ := ctx.Value(ctxKey{}).(*User)
|
||||
return u
|
||||
}
|
||||
|
||||
// WithUser renvoie ctx portant l'utilisateur u (authentification par jeton d'API).
|
||||
func WithUser(ctx context.Context, u *User) context.Context {
|
||||
return context.WithValue(ctx, ctxKey{}, u)
|
||||
}
|
||||
|
||||
// Session renvoie l'utilisateur du cookie de session s'il est valide.
|
||||
func (a *OIDC) session(r *http.Request) (session, bool) { return a.sess.Get(r) }
|
||||
|
||||
// Middleware exige une session sauf pour /auth/* et les chemins publics.
|
||||
// Navigation sans session : page qui renvoie vers /auth/login en conservant
|
||||
// l'URL complète (fragment #/dossier/schéma compris). API : 401 + LoginHeader.
|
||||
// La session est prolongée à chaque requête passée la moitié de sa durée.
|
||||
func (a *OIDC) Middleware(next http.Handler, public func(string) bool) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
p := r.URL.Path
|
||||
if strings.HasPrefix(p, "/auth/") || public(p) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
s, ok := a.session(r)
|
||||
if !ok {
|
||||
if strings.HasPrefix(p, "/api/") || r.Method != http.MethodGet {
|
||||
w.Header().Set(LoginHeader, "/auth/login")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"session expirée : reconnexion nécessaire"}`))
|
||||
return
|
||||
}
|
||||
loginRedirect(w)
|
||||
return
|
||||
}
|
||||
if time.Until(time.Unix(s.Exp, 0)) < a.cfg.SessionTTL/2 {
|
||||
_ = a.startSession(w, r, s.User)
|
||||
}
|
||||
u := s.User
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, &u)))
|
||||
})
|
||||
}
|
||||
|
||||
// loginRedirect renvoie vers /auth/login par script pour conserver le
|
||||
// fragment de l'URL, que le navigateur n'envoie pas au serveur.
|
||||
func loginRedirect(w http.ResponseWriter) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = io.WriteString(w, `<!doctype html><meta charset="utf-8"><title>Connexion</title>
|
||||
<script>location.replace("/auth/login?next="+encodeURIComponent(location.pathname+location.search+location.hash))</script>
|
||||
<noscript><a href="/auth/login">Se connecter</a></noscript>`)
|
||||
}
|
||||
|
||||
// page affiche un message simple (erreur de connexion, déconnexion).
|
||||
func page(w http.ResponseWriter, status int, title, msg, link, label string) {
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/html; charset=utf-8")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(status)
|
||||
e := html.EscapeString
|
||||
_, _ = fmt.Fprintf(w, `<!doctype html><html lang="fr"><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"><title>%s</title>
|
||||
<style>body{font:16px system-ui,sans-serif;display:grid;place-items:center;min-height:90vh;margin:0;color:#1b1b1f;background:#fff}
|
||||
@media(prefers-color-scheme:dark){body{color:#e3e3e8;background:#121212}}main{max-width:28rem;padding:1rem;text-align:center}
|
||||
a{display:inline-block;margin-top:1rem;padding:.6rem 1.2rem;border-radius:8px;background:#6965db;color:#fff;text-decoration:none}</style>
|
||||
<main><h1>%s</h1><p>%s</p><a href="%s">%s</a></main></html>`, e(title), e(title), e(msg), e(link), e(label))
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Package auth fournit l'authentification OpenID Connect (flux Authorization
|
||||
// Code + PKCE) et les sessions signées associées, sans dépendance externe.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// User est l'utilisateur authentifié. Sub est l'identifiant du fournisseur
|
||||
// OIDC (vide pour un compte local) ; ID est celui du compte (nom de son
|
||||
// espace personnel) ; Role n'est jamais lu du cookie : il vient du compte.
|
||||
type User struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
Sub string `json:"sub,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email,omitempty"`
|
||||
Provider string `json:"provider,omitempty"` // "local" ou "oidc"
|
||||
Role string `json:"role,omitempty"` // "admin" ou "user" (rempli par le middleware)
|
||||
Groups []string `json:"-"` // groupes OIDC de la connexion en cours
|
||||
}
|
||||
|
||||
// session est le contenu du cookie de session (signé, non chiffré : il ne
|
||||
// contient que l'identité, pas de jeton).
|
||||
type session struct {
|
||||
User
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
// loginState accompagne l'aller-retour vers le fournisseur (cookie de 10 min).
|
||||
type loginState struct {
|
||||
State string `json:"state"`
|
||||
Nonce string `json:"nonce"`
|
||||
Verifier string `json:"verifier"`
|
||||
Next string `json:"next"`
|
||||
Exp int64 `json:"exp"`
|
||||
}
|
||||
|
||||
var errBadCookie = errors.New("cookie invalide")
|
||||
|
||||
// Erreurs de connexion.
|
||||
var (
|
||||
ErrBadCredentials = errors.New("identifiant ou mot de passe incorrect")
|
||||
ErrPending = errors.New("compte en attente de validation par un administrateur")
|
||||
ErrDisabled = errors.New("compte désactivé")
|
||||
)
|
||||
|
||||
// signer signe et vérifie des valeurs JSON (HMAC-SHA256).
|
||||
type signer struct{ key []byte }
|
||||
|
||||
var b64 = base64.RawURLEncoding
|
||||
|
||||
func (s signer) mac(payload string) string {
|
||||
m := hmac.New(sha256.New, s.key)
|
||||
m.Write([]byte(payload))
|
||||
return b64.EncodeToString(m.Sum(nil))
|
||||
}
|
||||
|
||||
func (s signer) encode(v any) (string, error) {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
p := b64.EncodeToString(raw)
|
||||
return p + "." + s.mac(p), nil
|
||||
}
|
||||
|
||||
// decode vérifie la signature puis décode ; le contrôle d'expiration revient
|
||||
// à l'appelant (champ Exp).
|
||||
func (s signer) decode(value string, v any) error {
|
||||
p, sig, ok := strings.Cut(value, ".")
|
||||
if !ok || !hmac.Equal([]byte(sig), []byte(s.mac(p))) {
|
||||
return errBadCookie
|
||||
}
|
||||
raw, err := b64.DecodeString(p)
|
||||
if err != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
if json.Unmarshal(raw, v) != nil {
|
||||
return errBadCookie
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func randomString(n int) string {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err) // crypto/rand ne échoue pas sur les systèmes supportés
|
||||
}
|
||||
return b64.EncodeToString(b)
|
||||
}
|
||||
|
||||
// LoadSecret renvoie la clé de signature des sessions : secret si fourni
|
||||
// (16 caractères minimum), sinon le contenu de dir/.session-secret, créé
|
||||
// aléatoirement au premier démarrage (0600).
|
||||
func LoadSecret(secret, dir string) ([]byte, error) {
|
||||
if secret != "" {
|
||||
if len(secret) < 16 {
|
||||
return nil, errors.New("SESSION_SECRET trop court (16 caractères minimum)")
|
||||
}
|
||||
return []byte(secret), nil
|
||||
}
|
||||
file := filepath.Join(dir, ".session-secret")
|
||||
if b, err := os.ReadFile(file); err == nil {
|
||||
if k, err := hex.DecodeString(strings.TrimSpace(string(b))); err == nil && len(k) >= 32 {
|
||||
return k, nil
|
||||
}
|
||||
return nil, errors.New(file + " invalide (supprimer le fichier pour en générer un nouveau)")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
k := make([]byte, 32)
|
||||
if _, err := rand.Read(k); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.WriteFile(file, []byte(hex.EncodeToString(k)+"\n"), 0o600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
func now() time.Time { return time.Now() }
|
||||
|
||||
// Sessions gère le cookie de session signé, commun aux comptes locaux et OIDC.
|
||||
type Sessions struct {
|
||||
signer signer
|
||||
TTL time.Duration
|
||||
secure bool // cookie Secure même si la requête n'arrive pas en HTTPS (URL publique en https)
|
||||
}
|
||||
|
||||
// NewSessions crée un gestionnaire de sessions : secret signe les cookies, ttl
|
||||
// est la durée d'inactivité maximale.
|
||||
func NewSessions(secret []byte, ttl time.Duration, forceSecure bool) *Sessions {
|
||||
if ttl <= 0 {
|
||||
ttl = 24 * time.Hour
|
||||
}
|
||||
return &Sessions{signer: signer{secret}, TTL: ttl, secure: forceSecure}
|
||||
}
|
||||
|
||||
func (s *Sessions) cookie(w http.ResponseWriter, r *http.Request, value string, ttl time.Duration) {
|
||||
c := &http.Cookie{
|
||||
Name: sessionCookie,
|
||||
Value: value,
|
||||
Path: "/",
|
||||
HttpOnly: true,
|
||||
Secure: secure(r) || s.secure,
|
||||
SameSite: http.SameSiteLaxMode, // envoyé au retour du fournisseur (navigation GET)
|
||||
}
|
||||
if ttl < 0 {
|
||||
c.MaxAge = -1
|
||||
} else {
|
||||
c.Expires = now().Add(ttl)
|
||||
c.MaxAge = int(ttl / time.Second)
|
||||
}
|
||||
http.SetCookie(w, c)
|
||||
}
|
||||
|
||||
// Start ouvre (ou prolonge) la session de u.
|
||||
func (s *Sessions) Start(w http.ResponseWriter, r *http.Request, u User) error {
|
||||
v, err := s.signer.encode(session{User: u, Exp: now().Add(s.TTL).Unix()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.cookie(w, r, v, s.TTL)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Clear supprime le cookie de session.
|
||||
func (s *Sessions) Clear(w http.ResponseWriter, r *http.Request) { s.cookie(w, r, "", -1) }
|
||||
|
||||
// Get renvoie la session du cookie s'il est valide.
|
||||
func (s *Sessions) Get(r *http.Request) (session, bool) {
|
||||
var v session
|
||||
c, err := r.Cookie(sessionCookie)
|
||||
if err != nil || s.signer.decode(c.Value, &v) != nil || v.Exp < now().Unix() || (v.Sub == "" && v.ID == "") {
|
||||
return v, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
package fleet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// localRunner exécute le script distant en local, avec un faux `docker` en tête du PATH.
|
||||
type localRunner struct{ bin string }
|
||||
|
||||
func (l localRunner) Run(ctx context.Context, host string, port int, user string, args []string, onLine func(string)) error {
|
||||
cmd := exec.CommandContext(ctx, shell(), append([]string{"-c", remoteScript, "stackwatch"}, args...)...)
|
||||
cmd.Env = append(os.Environ(), "PATH="+l.bin+":"+os.Getenv("PATH"))
|
||||
out, err := cmd.Output()
|
||||
for _, ln := range strings.Split(strings.TrimRight(string(out), "\n"), "\n") {
|
||||
if ln != "" {
|
||||
onLine(ln)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Faux docker : le comportement dépend du nom du répertoire courant.
|
||||
//
|
||||
// uptodate : une image à jour ; outdated : une à jour et une en retard ;
|
||||
// stopped : aucun conteneur ; badpull : pull en échec ; empty : fichier vide ; broken : fichier invalide.
|
||||
const fakeDocker = `#!/bin/sh
|
||||
d=$(basename "$PWD")
|
||||
case "$1 $2" in
|
||||
"version -f") echo 27.0.0; exit 0 ;;
|
||||
"compose version") if [ "$3" = "--short" ]; then echo 2.29.0; else echo "Docker Compose version v2.29.0"; fi; exit 0 ;;
|
||||
"compose config")
|
||||
[ "$d" = empty ] && { echo "empty compose file" >&2; exit 1; }
|
||||
[ "$d" = broken ] && { echo "yaml: line 3: mapping values are not allowed" >&2; exit 1; }
|
||||
exit 0 ;;
|
||||
"compose ps") [ "$d" = stopped ] && exit 0; echo c1; [ "$d" = outdated ] && echo c2; exit 0 ;;
|
||||
"compose pull") [ "$d" = badpull ] && { echo "pull access denied" >&2; exit 1; }; exit 0 ;;
|
||||
"compose down"|"compose up") exit 0 ;;
|
||||
"inspect -f")
|
||||
case "$4" in
|
||||
c1) echo "sha256:aaaaaaaaaaaaaaaaaaaa|nginx:latest|web" ;;
|
||||
c2) echo "sha256:bbbbbbbbbbbbbbbbbbbb|redis:7|cache" ;;
|
||||
esac; exit 0 ;;
|
||||
"image inspect")
|
||||
case "$5" in
|
||||
nginx:latest) [ "$d" = outdated ] && echo sha256:aaaaaaaaaaaaaaaaaaaa || echo sha256:aaaaaaaaaaaaaaaaaaaa ;;
|
||||
redis:7) echo sha256:cccccccccccccccccccc ;;
|
||||
esac; exit 0 ;;
|
||||
esac
|
||||
exit 1
|
||||
`
|
||||
|
||||
func setup(t *testing.T) (root string, r localRunner) {
|
||||
t.Helper()
|
||||
tmp := t.TempDir()
|
||||
bin := filepath.Join(tmp, "bin")
|
||||
os.MkdirAll(bin, 0o755)
|
||||
os.WriteFile(filepath.Join(bin, "docker"), []byte(fakeDocker), 0o755)
|
||||
root = filepath.Join(tmp, "home")
|
||||
for _, d := range []string{"uptodate", "outdated", "stopped", "badpull", "empty", "broken", "alice/deep", ".hidden", "nocompose"} {
|
||||
os.MkdirAll(filepath.Join(root, d), 0o755)
|
||||
}
|
||||
for d, f := range map[string]string{"uptodate": "compose.yaml", "outdated": "docker-compose.yml", "stopped": "compose.yml",
|
||||
"badpull": "compose.yaml", "empty": "compose.yaml", "broken": "compose.yaml", "alice/deep": "compose.yaml", ".hidden": "compose.yaml"} {
|
||||
os.WriteFile(filepath.Join(root, d, f), []byte("services: {}\n"), 0o644)
|
||||
}
|
||||
return root, localRunner{bin}
|
||||
}
|
||||
|
||||
func scanOnce(t *testing.T, r Runner, depth string, roots ...string) *Scan {
|
||||
t.Helper()
|
||||
sc := &Scan{}
|
||||
p := newScanParser(sc)
|
||||
if err := r.Run(context.Background(), "h", 22, "u", append([]string{"scan", depth}, roots...), p.Line); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.Finish()
|
||||
return sc
|
||||
}
|
||||
|
||||
func TestScanScript(t *testing.T) {
|
||||
root, r := setup(t)
|
||||
sc := scanOnce(t, r, "1", root, root+"/missing")
|
||||
got := map[string]Stack{}
|
||||
for _, s := range sc.Stacks {
|
||||
got[s.Name] = s
|
||||
}
|
||||
want := map[string]string{"uptodate": StatusUpToDate, "outdated": StatusUpdates, "stopped": StatusStopped, "badpull": StatusError, "broken": StatusError}
|
||||
for n, st := range want {
|
||||
if got[n].Status != st {
|
||||
t.Errorf("%s : statut %q, attendu %q (%+v)", n, got[n].Status, st, got[n])
|
||||
}
|
||||
}
|
||||
for _, n := range []string{"empty", ".hidden", "nocompose", "deep"} {
|
||||
if _, ok := got[n]; ok {
|
||||
t.Errorf("%s ne devrait pas être listée", n)
|
||||
}
|
||||
}
|
||||
if o, n := got["outdated"].Counts(); o != 1 || n != 2 {
|
||||
t.Errorf("outdated : %d/%d services en retard", o, n)
|
||||
}
|
||||
if !strings.Contains(got["badpull"].Error, "pull access denied") || !strings.Contains(got["broken"].Error, "invalide") {
|
||||
t.Errorf("messages d'erreur : %q / %q", got["badpull"].Error, got["broken"].Error)
|
||||
}
|
||||
if len(sc.Warnings) != 1 || !strings.Contains(sc.Warnings[0], "missing") {
|
||||
t.Errorf("avertissements : %v", sc.Warnings)
|
||||
}
|
||||
if sc.Docker != "27.0.0" || sc.Compose != "2.29.0" {
|
||||
t.Errorf("versions : %q %q", sc.Docker, sc.Compose)
|
||||
}
|
||||
// Profondeur 2 : alice/deep apparaît.
|
||||
sc = scanOnce(t, r, "2", root)
|
||||
found := false
|
||||
for _, s := range sc.Stacks {
|
||||
found = found || s.Dir == root+"/alice/deep"
|
||||
}
|
||||
if !found {
|
||||
t.Error("profondeur 2 : alice/deep absente")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManagerFlow(t *testing.T) {
|
||||
root, r := setup(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
m, err := Open(ctx, t.TempDir(), r, 2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv, err := m.Add(Server{Name: "lab", Host: "10.0.0.1", Enabled: true, Targets: []Target{{User: "root", Roots: []string{root}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := m.Check(srv.ID, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wait := func() View {
|
||||
for i := 0; i < 200; i++ {
|
||||
v := m.Snapshot()[0]
|
||||
if sc, ok := v.Scans[srv.Targets[0].ID]; ok && !sc.Running {
|
||||
return v
|
||||
}
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("analyse trop longue")
|
||||
return View{}
|
||||
}
|
||||
sc := wait().Scans[srv.Targets[0].ID]
|
||||
if sc.Error != "" || len(sc.Stacks) != 5 {
|
||||
t.Fatalf("analyse : erreur %q, %d stacks", sc.Error, len(sc.Stacks))
|
||||
}
|
||||
if sum := m.Summary(); sum.Updates != 1 || sum.Errors != 2 || sum.Stopped != 1 {
|
||||
t.Errorf("résumé : %+v", sum)
|
||||
}
|
||||
// Mise à jour : seulement une stack connue.
|
||||
if err := m.Apply(srv.ID, srv.Targets[0].ID, "/etc", "me"); err == nil {
|
||||
t.Error("stack inconnue acceptée")
|
||||
}
|
||||
if err := m.Apply(srv.ID, srv.Targets[0].ID, root+"/outdated", "me"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc = wait().Scans[srv.Targets[0].ID]
|
||||
var out Stack
|
||||
for _, s := range sc.Stacks {
|
||||
if s.Name == "outdated" {
|
||||
out = s
|
||||
}
|
||||
}
|
||||
if out.Status != StatusUpToDate || out.Applied == nil || !out.Applied.OK {
|
||||
t.Errorf("après mise à jour : %+v", out)
|
||||
}
|
||||
// Rechargement depuis le disque.
|
||||
m2, err := Open(ctx, m.dir, r, 2)
|
||||
if err != nil || len(m2.Snapshot()) != 1 || len(m2.Snapshot()[0].Scans) != 1 {
|
||||
t.Fatalf("persistance : %v", err)
|
||||
}
|
||||
if err := m.Delete(srv.ID); err != nil || len(m.Snapshot()) != 0 {
|
||||
t.Errorf("suppression : %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
bad := []Server{
|
||||
{Name: "", Host: "h", Targets: []Target{{User: "u"}}},
|
||||
{Name: "a", Host: "-oProxyCommand=x", Targets: []Target{{User: "u"}}},
|
||||
{Name: "a", Host: "h", Targets: []Target{{User: "u; id"}}},
|
||||
{Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"/home/../etc"}}}},
|
||||
{Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"/home/a b"}}}},
|
||||
{Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"/home/'x"}}}},
|
||||
{Name: "a", Host: "h", Targets: []Target{{User: "u", Roots: []string{"relatif"}}}},
|
||||
{Name: "a", Host: "h"},
|
||||
}
|
||||
for i, s := range bad {
|
||||
if err := s.Validate(); err == nil {
|
||||
t.Errorf("cas %d accepté", i)
|
||||
}
|
||||
}
|
||||
ok := Server{Name: "a", Host: "srv.example.org", Targets: []Target{{User: "alice", Roots: []string{"/home/alice/", "/srv/stacks"}}}}
|
||||
if err := ok.Validate(); err != nil || ok.Port != 22 || ok.Targets[0].Roots[0] != "/home/alice" || ok.Targets[0].ID == "" {
|
||||
t.Errorf("serveur valide refusé ou mal normalisé : %v %+v", err, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuote(t *testing.T) {
|
||||
if got := quote("a'b"); got != `'a'\''b'` {
|
||||
t.Errorf("quote : %s", got)
|
||||
}
|
||||
cmd := remoteCommand([]string{"scan", "1", "/home"})
|
||||
if !strings.HasPrefix(cmd, "sh -c '") || !strings.HasSuffix(cmd, "stackwatch 'scan' '1' '/home'") {
|
||||
t.Errorf("commande distante : ...%s", cmd[max(0, len(cmd)-60):])
|
||||
}
|
||||
}
|
||||
|
||||
// shell : interpréteur du script distant (TEST_SH=dash pour vérifier la portabilité POSIX).
|
||||
func shell() string {
|
||||
if s := os.Getenv("TEST_SH"); s != "" {
|
||||
return s
|
||||
}
|
||||
return "sh"
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package fleet
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
)
|
||||
|
||||
func newID() string {
|
||||
b := make([]byte, 6)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
package fleet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Manager tient la liste des serveurs et le dernier résultat de chaque cible,
|
||||
// lance les analyses (à la demande ou périodiquement) et les mises à jour.
|
||||
type Manager struct {
|
||||
Runner Runner
|
||||
Interval time.Duration // 0 : pas d'analyse périodique
|
||||
|
||||
dir string
|
||||
base context.Context
|
||||
sem chan struct{}
|
||||
mu sync.Mutex
|
||||
servers []Server
|
||||
scans map[string]*Scan
|
||||
watchers sync.WaitGroup
|
||||
}
|
||||
|
||||
// Open charge serveurs et résultats depuis dir.
|
||||
func Open(ctx context.Context, dir string, r Runner, parallel int) (*Manager, error) {
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if parallel < 1 {
|
||||
parallel = 4
|
||||
}
|
||||
m := &Manager{Runner: r, dir: dir, base: ctx, sem: make(chan struct{}, parallel), scans: map[string]*Scan{}}
|
||||
if err := readJSON(filepath.Join(dir, "servers.json"), &m.servers); err != nil {
|
||||
return nil, fmt.Errorf("servers.json : %w", err)
|
||||
}
|
||||
if err := readJSON(filepath.Join(dir, "state.json"), &m.scans); err != nil {
|
||||
slog.Warn("state.json illisible, résultats ignorés", "err", err)
|
||||
m.scans = map[string]*Scan{}
|
||||
}
|
||||
if m.scans == nil {
|
||||
m.scans = map[string]*Scan{}
|
||||
}
|
||||
for _, s := range m.scans {
|
||||
s.Running, s.Task, s.Current = false, "", ""
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func readJSON(path string, v any) error {
|
||||
b, err := os.ReadFile(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(b, v)
|
||||
}
|
||||
|
||||
func writeJSON(path string, v any) error {
|
||||
b, err := json.MarshalIndent(v, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, b, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
func (m *Manager) saveServersLocked() error {
|
||||
return writeJSON(filepath.Join(m.dir, "servers.json"), m.servers)
|
||||
}
|
||||
func (m *Manager) saveStateLocked() {
|
||||
if err := writeJSON(filepath.Join(m.dir, "state.json"), m.scans); err != nil {
|
||||
slog.Error("état non enregistré", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Serveurs ------------------------------------------------------------------
|
||||
|
||||
// View : un serveur et le résultat de chacune de ses cibles.
|
||||
type View struct {
|
||||
Server
|
||||
Scans map[string]Scan `json:"scans"`
|
||||
}
|
||||
|
||||
func copyScan(s *Scan) Scan {
|
||||
c := *s
|
||||
c.Stacks = append([]Stack{}, s.Stacks...)
|
||||
c.Warnings = append([]string(nil), s.Warnings...)
|
||||
return c
|
||||
}
|
||||
|
||||
// Snapshot renvoie les serveurs avec leurs résultats (copie).
|
||||
func (m *Manager) Snapshot() []View {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
out := make([]View, 0, len(m.servers))
|
||||
for _, s := range m.servers {
|
||||
v := View{Server: s, Scans: map[string]Scan{}}
|
||||
v.Targets = append([]Target(nil), s.Targets...)
|
||||
for _, t := range s.Targets {
|
||||
if sc, ok := m.scans[Key(s.ID, t.ID)]; ok {
|
||||
v.Scans[t.ID] = copyScan(sc)
|
||||
}
|
||||
}
|
||||
out = append(out, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Manager) Summary() Summary {
|
||||
var sum Summary
|
||||
for _, v := range m.Snapshot() {
|
||||
sum.Servers++
|
||||
for _, t := range v.Targets {
|
||||
sc, ok := v.Scans[t.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if sc.Running {
|
||||
sum.Scanning++
|
||||
}
|
||||
if sc.Error != "" {
|
||||
sum.Unreachable++
|
||||
}
|
||||
for _, st := range sc.Stacks {
|
||||
sum.Stacks++
|
||||
switch st.Status {
|
||||
case StatusUpdates:
|
||||
sum.Updates++
|
||||
case StatusError:
|
||||
sum.Errors++
|
||||
case StatusStopped:
|
||||
sum.Stopped++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
func (m *Manager) indexLocked(id string) int {
|
||||
for i, s := range m.servers {
|
||||
if s.ID == id {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Add enregistre un nouveau serveur.
|
||||
func (m *Manager) Add(s Server) (Server, error) {
|
||||
s.ID = newID()
|
||||
if err := s.Validate(); err != nil {
|
||||
return s, err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.servers = append(m.servers, s)
|
||||
if err := m.saveServersLocked(); err != nil {
|
||||
m.servers = m.servers[:len(m.servers)-1]
|
||||
return s, err
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Update remplace un serveur ; les résultats des connexions supprimées sont oubliés.
|
||||
func (m *Manager) Update(id string, s Server) (Server, error) {
|
||||
s.ID = id
|
||||
if err := s.Validate(); err != nil {
|
||||
return s, err
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
i := m.indexLocked(id)
|
||||
if i < 0 {
|
||||
return s, ErrNotFound
|
||||
}
|
||||
old := m.servers[i]
|
||||
for _, t := range old.Targets {
|
||||
if sc := m.scans[Key(id, t.ID)]; sc != nil && sc.Running {
|
||||
return s, ErrBusy
|
||||
}
|
||||
}
|
||||
keep := map[string]bool{}
|
||||
for _, t := range s.Targets {
|
||||
keep[t.ID] = true
|
||||
}
|
||||
// Une connexion dont l'utilisateur ou les racines changent repart d'un état vierge.
|
||||
changed := map[string]bool{}
|
||||
for _, o := range old.Targets {
|
||||
for _, n := range s.Targets {
|
||||
if n.ID == o.ID && (n.User != o.User || n.Depth != o.Depth || strings.Join(n.Roots, "\n") != strings.Join(o.Roots, "\n") || s.Host != old.Host || s.Port != old.Port) {
|
||||
changed[o.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
m.servers[i] = s
|
||||
if err := m.saveServersLocked(); err != nil {
|
||||
m.servers[i] = old
|
||||
return s, err
|
||||
}
|
||||
for _, o := range old.Targets {
|
||||
if !keep[o.ID] || changed[o.ID] {
|
||||
delete(m.scans, Key(id, o.ID))
|
||||
}
|
||||
}
|
||||
m.saveStateLocked()
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// Delete supprime un serveur et ses résultats.
|
||||
func (m *Manager) Delete(id string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
i := m.indexLocked(id)
|
||||
if i < 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
old := m.servers[i]
|
||||
for _, t := range old.Targets {
|
||||
if sc := m.scans[Key(id, t.ID)]; sc != nil && sc.Running {
|
||||
return ErrBusy
|
||||
}
|
||||
}
|
||||
m.servers = append(m.servers[:i:i], m.servers[i+1:]...)
|
||||
if err := m.saveServersLocked(); err != nil {
|
||||
m.servers = append(m.servers[:i], append([]Server{old}, m.servers[i:]...)...)
|
||||
return err
|
||||
}
|
||||
for _, t := range old.Targets {
|
||||
delete(m.scans, Key(id, t.ID))
|
||||
}
|
||||
m.saveStateLocked()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) find(serverID, targetID string) (Server, Target, error) {
|
||||
for _, s := range m.servers {
|
||||
if s.ID != serverID {
|
||||
continue
|
||||
}
|
||||
for _, t := range s.Targets {
|
||||
if t.ID == targetID {
|
||||
return s, t, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return Server{}, Target{}, ErrNotFound
|
||||
}
|
||||
|
||||
// --- Analyses --------------------------------------------------------------------
|
||||
|
||||
// begin réserve une cible (une seule tâche à la fois).
|
||||
func (m *Manager) begin(srv Server, t Target, task string) (*Scan, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
key := Key(srv.ID, t.ID)
|
||||
sc := m.scans[key]
|
||||
if sc == nil {
|
||||
sc = &Scan{Stacks: []Stack{}}
|
||||
m.scans[key] = sc
|
||||
}
|
||||
if sc.Running {
|
||||
return nil, ErrBusy
|
||||
}
|
||||
sc.Running, sc.Task, sc.Current, sc.Started = true, task, "", time.Now()
|
||||
return sc, nil
|
||||
}
|
||||
|
||||
// Check lance l'analyse des cibles d'un serveur (targetID vide : toutes) ;
|
||||
// elle se poursuit en arrière-plan. Renvoie le nombre d'analyses démarrées.
|
||||
func (m *Manager) Check(serverID, targetID string) (int, error) {
|
||||
m.mu.Lock()
|
||||
var srv Server
|
||||
i := m.indexLocked(serverID)
|
||||
if i >= 0 {
|
||||
srv = m.servers[i]
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if i < 0 {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
started := 0
|
||||
for _, t := range srv.Targets {
|
||||
if targetID != "" && t.ID != targetID {
|
||||
continue
|
||||
}
|
||||
if _, err := m.begin(srv, t, "scan"); err != nil {
|
||||
continue
|
||||
}
|
||||
started++
|
||||
go m.runScan(srv, t)
|
||||
}
|
||||
if started == 0 {
|
||||
return 0, ErrBusy
|
||||
}
|
||||
return started, nil
|
||||
}
|
||||
|
||||
// CheckAll analyse tous les serveurs actifs.
|
||||
func (m *Manager) CheckAll() int {
|
||||
n := 0
|
||||
for _, v := range m.Snapshot() {
|
||||
if !v.Enabled {
|
||||
continue
|
||||
}
|
||||
c, _ := m.Check(v.ID, "")
|
||||
n += c
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (m *Manager) runScan(srv Server, t Target) {
|
||||
m.sem <- struct{}{}
|
||||
defer func() { <-m.sem }()
|
||||
key := Key(srv.ID, t.ID)
|
||||
ctx, cancel := context.WithTimeout(m.base, 45*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
m.mu.Lock()
|
||||
sc := m.scans[key]
|
||||
sc.Error, sc.Warnings = "", nil
|
||||
p := newScanParser(sc)
|
||||
m.mu.Unlock()
|
||||
|
||||
args := append([]string{"scan", fmt.Sprint(t.Depth)}, t.Roots...)
|
||||
err := m.Runner.Run(ctx, srv.Host, srv.Port, t.User, args, func(line string) {
|
||||
m.mu.Lock()
|
||||
p.Line(line)
|
||||
sc.Current = p.Current()
|
||||
m.mu.Unlock()
|
||||
})
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err != nil {
|
||||
sc.Error = "connexion impossible : " + err.Error()
|
||||
}
|
||||
p.Finish()
|
||||
sc.Running, sc.Task, sc.Current, sc.Finished = false, "", "", time.Now()
|
||||
m.saveStateLocked()
|
||||
slog.Info("analyse terminée", "server", srv.Name, "user", t.User, "stacks", len(sc.Stacks), "err", sc.Error)
|
||||
}
|
||||
|
||||
// PingResult : résultat du test de connexion d'une cible.
|
||||
type PingResult struct {
|
||||
Target string `json:"target"`
|
||||
User string `json:"user"`
|
||||
OK bool `json:"ok"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Test vérifie, pour chaque cible, la connexion SSH, docker et docker compose.
|
||||
func (m *Manager) Test(ctx context.Context, srv Server) []PingResult {
|
||||
res := make([]PingResult, len(srv.Targets))
|
||||
var wg sync.WaitGroup
|
||||
for i, t := range srv.Targets {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
r := PingResult{Target: t.ID, User: t.User}
|
||||
ctx, cancel := context.WithTimeout(ctx, 40*time.Second)
|
||||
defer cancel()
|
||||
var msg string
|
||||
err := m.Runner.Run(ctx, srv.Host, srv.Port, t.User, []string{"ping"}, func(line string) {
|
||||
f := strings.Split(line, "\t")
|
||||
switch f[0] {
|
||||
case "P":
|
||||
if len(f) >= 4 {
|
||||
r.OK, msg = true, fmt.Sprintf("docker %s, compose %s", f[2], f[3])
|
||||
}
|
||||
case "E":
|
||||
if len(f) >= 3 {
|
||||
msg = f[2]
|
||||
}
|
||||
}
|
||||
})
|
||||
switch {
|
||||
case err != nil:
|
||||
r.Message = err.Error()
|
||||
default:
|
||||
r.Message = msg
|
||||
}
|
||||
res[i] = r
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return res
|
||||
}
|
||||
|
||||
// Server renvoie une copie d'un serveur.
|
||||
func (m *Manager) Server(id string) (Server, bool) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if i := m.indexLocked(id); i >= 0 {
|
||||
s := m.servers[i]
|
||||
s.Targets = append([]Target(nil), s.Targets...)
|
||||
return s, true
|
||||
}
|
||||
return Server{}, false
|
||||
}
|
||||
|
||||
// --- Mise à jour d'une stack ------------------------------------------------------
|
||||
|
||||
// Apply lance pull + down + up -d sur une stack déjà connue de l'analyse.
|
||||
func (m *Manager) Apply(serverID, targetID, dir, by string) error {
|
||||
m.mu.Lock()
|
||||
srv, t, err := m.find(serverID, targetID)
|
||||
if err != nil {
|
||||
m.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
known := false
|
||||
if sc := m.scans[Key(serverID, targetID)]; sc != nil {
|
||||
for _, s := range sc.Stacks {
|
||||
if s.Dir == dir {
|
||||
known = true
|
||||
}
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
if !known {
|
||||
return fmt.Errorf("%w : stack inconnue (lancer une analyse)", ErrNotFound)
|
||||
}
|
||||
if _, err := m.begin(srv, t, "apply"); err != nil {
|
||||
return err
|
||||
}
|
||||
go m.runApply(srv, t, dir, by)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) runApply(srv Server, t Target, dir, by string) {
|
||||
m.sem <- struct{}{}
|
||||
defer func() { <-m.sem }()
|
||||
key := Key(srv.ID, t.ID)
|
||||
m.mu.Lock()
|
||||
m.scans[key].Current = dir
|
||||
m.mu.Unlock()
|
||||
|
||||
ctx, cancel := context.WithTimeout(m.base, 30*time.Minute)
|
||||
defer cancel()
|
||||
res := Applied{At: time.Now(), By: by}
|
||||
err := m.Runner.Run(ctx, srv.Host, srv.Port, t.User, []string{"apply", dir}, func(line string) {
|
||||
f := strings.Split(line, "\t")
|
||||
if f[0] == "A" && len(f) >= 3 {
|
||||
res.OK, res.Message = f[1] == "ok", f[2]
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
res.OK, res.Message = false, "connexion impossible : "+err.Error()
|
||||
} else if res.Message == "" {
|
||||
res.Message = "aucune réponse du serveur"
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
sc := m.scans[key]
|
||||
for i := range sc.Stacks {
|
||||
st := &sc.Stacks[i]
|
||||
if st.Dir != dir {
|
||||
continue
|
||||
}
|
||||
r := res
|
||||
st.Applied = &r
|
||||
if res.OK {
|
||||
st.Status, st.Error = StatusUpToDate, ""
|
||||
for j := range st.Services {
|
||||
st.Services[j].Running = st.Services[j].Latest
|
||||
st.Services[j].State = "ok"
|
||||
}
|
||||
}
|
||||
}
|
||||
sc.Running, sc.Task, sc.Current = false, "", ""
|
||||
m.saveStateLocked()
|
||||
slog.Info("mise à jour de stack", "server", srv.Name, "user", t.User, "dir", dir, "by", by, "ok", res.OK, "msg", res.Message)
|
||||
}
|
||||
|
||||
// --- Planification ----------------------------------------------------------------
|
||||
|
||||
// Run analyse périodiquement les cibles dont le dernier résultat date de plus
|
||||
// de Interval (les nouvelles cibles sont analysées dès la minute suivante).
|
||||
func (m *Manager) Run(ctx context.Context) {
|
||||
if m.Interval <= 0 {
|
||||
return
|
||||
}
|
||||
t := time.NewTicker(time.Minute)
|
||||
defer t.Stop()
|
||||
for {
|
||||
m.checkStale()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) checkStale() {
|
||||
type job struct {
|
||||
srv Server
|
||||
t Target
|
||||
}
|
||||
var jobs []job
|
||||
m.mu.Lock()
|
||||
for _, s := range m.servers {
|
||||
if !s.Enabled {
|
||||
continue
|
||||
}
|
||||
for _, t := range s.Targets {
|
||||
if sc := m.scans[Key(s.ID, t.ID)]; sc != nil && (sc.Running || time.Since(sc.Finished) < m.Interval) {
|
||||
continue
|
||||
}
|
||||
jobs = append(jobs, job{s, t})
|
||||
}
|
||||
}
|
||||
m.mu.Unlock()
|
||||
sort.SliceStable(jobs, func(i, j int) bool { return jobs[i].srv.Name < jobs[j].srv.Name })
|
||||
for _, j := range jobs {
|
||||
if _, err := m.begin(j.srv, j.t, "scan"); err == nil {
|
||||
go m.runScan(j.srv, j.t)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
// Package fleet suit les mises à jour des stacks docker compose de plusieurs
|
||||
// serveurs, joints en SSH : liste de serveurs, analyses (pull + comparaison des
|
||||
// images), mise à jour d'une stack.
|
||||
package fleet
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Statuts d'une stack.
|
||||
const (
|
||||
StatusUpToDate = "uptodate" // toutes les images sont à jour
|
||||
StatusUpdates = "updates" // au moins une image a une nouvelle version
|
||||
StatusStopped = "stopped" // aucun conteneur en cours
|
||||
StatusError = "error" // fichier invalide, pull en échec...
|
||||
)
|
||||
|
||||
// Server est un serveur joint en SSH. Chaque Target est une connexion SSH sous
|
||||
// un utilisateur donné, avec les racines à parcourir : /home pour un compte qui
|
||||
// lit tout, ou /home/alice pour des stacks qui n'ont que les droits d'alice.
|
||||
type Server struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Note string `json:"note,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Targets []Target `json:"targets"`
|
||||
}
|
||||
|
||||
// Target : utilisateur SSH et racines (profondeur : niveaux de sous-répertoires
|
||||
// explorés sous chaque racine, 1 = /home/<stack>).
|
||||
type Target struct {
|
||||
ID string `json:"id"`
|
||||
User string `json:"user"`
|
||||
Roots []string `json:"roots"`
|
||||
Depth int `json:"depth"`
|
||||
}
|
||||
|
||||
// Service : un conteneur d'une stack.
|
||||
type Service struct {
|
||||
Name string `json:"name"`
|
||||
Image string `json:"image"`
|
||||
Running string `json:"running"` // identifiant (12 caractères) de l'image en cours
|
||||
Latest string `json:"latest"` // identifiant de l'image tirée
|
||||
State string `json:"state"` // ok, update ou unknown
|
||||
}
|
||||
|
||||
// Stack : une stack trouvée sous une racine.
|
||||
type Stack struct {
|
||||
Dir string `json:"dir"`
|
||||
Name string `json:"name"`
|
||||
File string `json:"file"`
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Services []Service `json:"services,omitempty"`
|
||||
// Applied : dernière mise à jour lancée depuis stackwatch.
|
||||
Applied *Applied `json:"applied,omitempty"`
|
||||
}
|
||||
|
||||
// Applied : résultat d'une mise à jour déclenchée depuis l'interface.
|
||||
type Applied struct {
|
||||
At time.Time `json:"at"`
|
||||
By string `json:"by"`
|
||||
OK bool `json:"ok"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// Scan : dernier résultat (ou analyse en cours) d'une cible.
|
||||
type Scan struct {
|
||||
Running bool `json:"running"`
|
||||
Task string `json:"task,omitempty"` // scan ou apply, pendant Running
|
||||
Current string `json:"current,omitempty"` // stack en cours de traitement
|
||||
Started time.Time `json:"started,omitzero"`
|
||||
Finished time.Time `json:"finished,omitzero"`
|
||||
Error string `json:"error,omitempty"`
|
||||
// Warnings : racines illisibles ou introuvables.
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
Stacks []Stack `json:"stacks"`
|
||||
Docker string `json:"docker,omitempty"`
|
||||
Compose string `json:"compose,omitempty"`
|
||||
}
|
||||
|
||||
// Summary compte les stacks de toutes les cibles.
|
||||
type Summary struct {
|
||||
Servers int `json:"servers"`
|
||||
Stacks int `json:"stacks"`
|
||||
Updates int `json:"updates"`
|
||||
Errors int `json:"errors"`
|
||||
Stopped int `json:"stopped"`
|
||||
Unreachable int `json:"unreachable"`
|
||||
Scanning int `json:"scanning"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("introuvable")
|
||||
ErrInvalid = errors.New("valeur invalide")
|
||||
ErrBusy = errors.New("analyse ou mise à jour déjà en cours")
|
||||
|
||||
hostRe = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._:-]*[A-Za-z0-9])?$`)
|
||||
userRe = regexp.MustCompile(`^[a-z_][a-z0-9_.-]{0,31}$`)
|
||||
// Chemins absolus simples : pas de guillemets, d'espaces ni de caractères de shell.
|
||||
pathRe = regexp.MustCompile(`^/[A-Za-z0-9._@+/-]*$`)
|
||||
)
|
||||
|
||||
// Validate normalise et contrôle un serveur ; les cibles sans identifiant en reçoivent un.
|
||||
func (s *Server) Validate() error {
|
||||
s.Name = strings.TrimSpace(s.Name)
|
||||
s.Host = strings.TrimSpace(s.Host)
|
||||
s.Note = strings.TrimSpace(s.Note)
|
||||
if s.Name == "" || len(s.Name) > 80 {
|
||||
return fmt.Errorf("%w : nom (1 à 80 caractères)", ErrInvalid)
|
||||
}
|
||||
if len(s.Host) > 253 || !hostRe.MatchString(s.Host) {
|
||||
return fmt.Errorf("%w : hôte (nom DNS ou adresse IP)", ErrInvalid)
|
||||
}
|
||||
if s.Port == 0 {
|
||||
s.Port = 22
|
||||
}
|
||||
if s.Port < 1 || s.Port > 65535 {
|
||||
return fmt.Errorf("%w : port", ErrInvalid)
|
||||
}
|
||||
if len(s.Note) > 300 {
|
||||
return fmt.Errorf("%w : note trop longue", ErrInvalid)
|
||||
}
|
||||
if len(s.Targets) == 0 {
|
||||
return fmt.Errorf("%w : au moins une connexion (utilisateur et racines)", ErrInvalid)
|
||||
}
|
||||
if len(s.Targets) > 20 {
|
||||
return fmt.Errorf("%w : 20 connexions au maximum", ErrInvalid)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i := range s.Targets {
|
||||
t := &s.Targets[i]
|
||||
if err := t.validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
if t.ID == "" {
|
||||
t.ID = newID()
|
||||
}
|
||||
if seen[t.ID] {
|
||||
return fmt.Errorf("%w : connexion en double", ErrInvalid)
|
||||
}
|
||||
seen[t.ID] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Target) validate() error {
|
||||
t.User = strings.TrimSpace(t.User)
|
||||
if !userRe.MatchString(t.User) {
|
||||
return fmt.Errorf("%w : utilisateur SSH %q", ErrInvalid, t.User)
|
||||
}
|
||||
if t.Depth == 0 {
|
||||
t.Depth = 1
|
||||
}
|
||||
if t.Depth < 0 || t.Depth > 4 {
|
||||
return fmt.Errorf("%w : profondeur (1 à 4)", ErrInvalid)
|
||||
}
|
||||
if len(t.Roots) > 20 {
|
||||
return fmt.Errorf("%w : 20 racines au maximum par connexion", ErrInvalid)
|
||||
}
|
||||
roots := make([]string, 0, len(t.Roots))
|
||||
for _, r := range t.Roots {
|
||||
r = strings.TrimSpace(r)
|
||||
if r == "" {
|
||||
continue
|
||||
}
|
||||
if !pathRe.MatchString(r) || strings.Contains(r, "..") {
|
||||
return fmt.Errorf("%w : racine %q (chemin absolu, sans espace ni caractère spécial)", ErrInvalid, r)
|
||||
}
|
||||
if r != "/" {
|
||||
r = path.Clean(r)
|
||||
}
|
||||
roots = append(roots, r)
|
||||
}
|
||||
if len(roots) == 0 {
|
||||
roots = []string{"/home"}
|
||||
}
|
||||
t.Roots = roots
|
||||
return nil
|
||||
}
|
||||
|
||||
// Key identifie une cible dans les résultats.
|
||||
func Key(serverID, targetID string) string { return serverID + "/" + targetID }
|
||||
|
||||
// Counts renvoie le nombre de services en retard sur le total.
|
||||
func (st Stack) Counts() (outdated, total int) {
|
||||
for _, s := range st.Services {
|
||||
total++
|
||||
if s.State == "update" {
|
||||
outdated++
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package fleet
|
||||
|
||||
import (
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// scanParser transforme les lignes du script distant en stacks.
|
||||
type scanParser struct {
|
||||
scan *Scan
|
||||
prev map[string]Stack // résultat précédent, par répertoire
|
||||
cur *Stack
|
||||
seen map[string]bool
|
||||
order []string
|
||||
}
|
||||
|
||||
func newScanParser(scan *Scan) *scanParser {
|
||||
p := &scanParser{scan: scan, prev: map[string]Stack{}, seen: map[string]bool{}}
|
||||
for _, s := range scan.Stacks {
|
||||
p.prev[s.Dir] = s
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// Line traite une ligne ; elle renvoie le répertoire en cours d'analyse.
|
||||
func (p *scanParser) Line(line string) {
|
||||
f := strings.Split(line, "\t")
|
||||
get := func(i int) string {
|
||||
if i < len(f) {
|
||||
return f[i]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
switch f[0] {
|
||||
case "P":
|
||||
p.scan.Docker, p.scan.Compose = get(2), get(3)
|
||||
case "S":
|
||||
p.cur = &Stack{Dir: get(1), Name: path.Base(get(1)), File: get(2), Status: StatusUpToDate}
|
||||
case "V":
|
||||
if p.cur != nil && p.cur.Dir == get(1) {
|
||||
p.cur.Services = append(p.cur.Services, Service{Name: get(2), Image: get(3), Running: get(4), Latest: get(5), State: get(6)})
|
||||
}
|
||||
case "T":
|
||||
if p.cur != nil {
|
||||
p.cur.Status = StatusStopped
|
||||
}
|
||||
case "E":
|
||||
if get(1) == "-" || p.cur == nil {
|
||||
p.scan.Error = get(2)
|
||||
return
|
||||
}
|
||||
p.cur.Status, p.cur.Error = StatusError, get(2)
|
||||
case "R":
|
||||
p.scan.Warnings = append(p.scan.Warnings, get(1)+" : "+get(2))
|
||||
case "D":
|
||||
if p.cur == nil {
|
||||
return
|
||||
}
|
||||
st := *p.cur
|
||||
p.cur = nil
|
||||
if st.Status == StatusUpToDate {
|
||||
if out, _ := st.Counts(); out > 0 {
|
||||
st.Status = StatusUpdates
|
||||
}
|
||||
}
|
||||
if old, ok := p.prev[st.Dir]; ok {
|
||||
st.Applied = old.Applied
|
||||
}
|
||||
p.seen[st.Dir] = true
|
||||
p.merge(st)
|
||||
}
|
||||
}
|
||||
|
||||
// Current : répertoire de la stack en cours d'analyse.
|
||||
func (p *scanParser) Current() string {
|
||||
if p.cur != nil {
|
||||
return p.cur.Dir
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (p *scanParser) merge(st Stack) {
|
||||
for i := range p.scan.Stacks {
|
||||
if p.scan.Stacks[i].Dir == st.Dir {
|
||||
p.scan.Stacks[i] = st
|
||||
return
|
||||
}
|
||||
}
|
||||
p.scan.Stacks = append(p.scan.Stacks, st)
|
||||
sort.Slice(p.scan.Stacks, func(i, j int) bool { return p.scan.Stacks[i].Dir < p.scan.Stacks[j].Dir })
|
||||
}
|
||||
|
||||
// Finish retire les stacks qui n'existent plus (absentes de cette analyse).
|
||||
func (p *scanParser) Finish() {
|
||||
if p.scan.Error != "" && len(p.seen) == 0 {
|
||||
return // échec complet : on garde l'ancien résultat
|
||||
}
|
||||
kept := p.scan.Stacks[:0]
|
||||
for _, s := range p.scan.Stacks {
|
||||
if p.seen[s.Dir] {
|
||||
kept = append(kept, s)
|
||||
}
|
||||
}
|
||||
p.scan.Stacks = kept
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
#!/bin/sh
|
||||
# Exécuté sur le serveur distant : sh -c "<script>" stackwatch MODE ARGS...
|
||||
#
|
||||
# ping vérifie docker et docker compose, affiche l'utilisateur
|
||||
# scan PROFONDEUR RACINE... cherche les stacks, télécharge les images (pull) sans toucher
|
||||
# aux conteneurs, compare l'image en cours à l'image tirée
|
||||
# apply RÉPERTOIRE pull, down puis up -d d'une stack
|
||||
#
|
||||
# Sortie : lignes séparées par des tabulations, lues par stackwatch.
|
||||
# P user docker compose
|
||||
# S dir fichier début d'une stack
|
||||
# V dir service image courant dernier etat (etat : ok | update | unknown)
|
||||
# T dir stack arrêtée
|
||||
# E dir message erreur sur la stack
|
||||
# D dir fin de la stack
|
||||
# A statut message résultat de apply (ok | fail)
|
||||
# R racine message racine inaccessible
|
||||
export LC_ALL=C
|
||||
TAB=$(printf '\t')
|
||||
mode=$1; shift
|
||||
|
||||
# Texte sur une seule ligne, sans tabulation, tronqué.
|
||||
flat() { tr '\n\t\r' ' ' | cut -c1-600; }
|
||||
|
||||
compose_file() {
|
||||
for f in compose.yaml compose.yml docker-compose.yaml docker-compose.yml; do
|
||||
[ -f "$1/$f" ] && { printf '%s' "$f"; return 0; }
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
with_timeout() {
|
||||
if command -v timeout >/dev/null 2>&1; then timeout "$@"; else shift; "$@"; fi
|
||||
}
|
||||
|
||||
case "$mode" in
|
||||
ping)
|
||||
d=$(docker version -f '{{.Server.Version}}' 2>&1) || { printf 'E\t-\tdocker inaccessible : %s\n' "$(printf '%s' "$d" | flat)"; exit 0; }
|
||||
c=$(docker compose version --short 2>&1) || { printf 'E\t-\tdocker compose (v2) introuvable : %s\n' "$(printf '%s' "$c" | flat)"; exit 0; }
|
||||
printf 'P\t%s\t%s\t%s\n' "$(id -un)" "$d" "$c"
|
||||
;;
|
||||
|
||||
scan)
|
||||
depth=$1; shift
|
||||
docker compose version >/dev/null 2>&1 || { printf 'E\t-\tdocker compose (v2) introuvable ou docker inaccessible pour %s\n' "$(id -un)"; exit 0; }
|
||||
printf 'P\t%s\t%s\t%s\n' "$(id -un)" "$(docker version -f '{{.Server.Version}}' 2>/dev/null </dev/null)" "$(docker compose version --short 2>/dev/null </dev/null)"
|
||||
for root in "$@"; do
|
||||
root=${root%/}
|
||||
[ -d "$root" ] || { printf 'R\t%s\t%s\n' "$root" "répertoire introuvable"; continue; }
|
||||
[ -r "$root" ] || { printf 'R\t%s\t%s\n' "$root" "répertoire illisible"; continue; }
|
||||
maxd=$((depth + 1))
|
||||
find "$root" -mindepth 1 -maxdepth "$maxd" \
|
||||
\( -type d \( -name '.*' -o -name node_modules \) -prune \) -o \
|
||||
\( -type f \( -name compose.yaml -o -name compose.yml -o -name docker-compose.yaml -o -name docker-compose.yml \) -print \) \
|
||||
2>/dev/null | while IFS= read -r f; do dirname "$f"; done | sort -u | while IFS= read -r dir; do
|
||||
file=$(compose_file "$dir") || continue
|
||||
cd "$dir" 2>/dev/null || continue
|
||||
out=$(docker compose config -q 2>&1 </dev/null) || {
|
||||
case "$out" in *"empty compose file"*) continue ;; esac
|
||||
printf 'S\t%s\t%s\n' "$dir" "$file"
|
||||
printf 'E\t%s\t%s\n' "$dir" "fichier compose invalide : $(printf '%s' "$out" | flat)"
|
||||
printf 'D\t%s\n' "$dir"
|
||||
continue
|
||||
}
|
||||
printf 'S\t%s\t%s\n' "$dir" "$file"
|
||||
ids=$(docker compose ps -q 2>/dev/null </dev/null)
|
||||
if [ -z "$ids" ]; then
|
||||
printf 'T\t%s\n' "$dir"; printf 'D\t%s\n' "$dir"; continue
|
||||
fi
|
||||
out=$(with_timeout 900 docker compose pull --ignore-buildable 2>&1 </dev/null) || {
|
||||
printf 'E\t%s\t%s\n' "$dir" "pull : $(printf '%s' "$out" | flat)"
|
||||
printf 'D\t%s\n' "$dir"; continue
|
||||
}
|
||||
for cid in $ids; do
|
||||
info=$(docker inspect -f '{{.Image}}|{{.Config.Image}}|{{index .Config.Labels "com.docker.compose.service"}}' "$cid" 2>/dev/null </dev/null) || continue
|
||||
running=${info%%|*}; rest=${info#*|}; image=${rest%%|*}; service=${rest#*|}
|
||||
if latest=$(docker image inspect -f '{{.Id}}' "$image" 2>/dev/null </dev/null); then
|
||||
if [ "$running" = "$latest" ]; then state=ok; else state=update; fi
|
||||
else
|
||||
latest=""; state=unknown
|
||||
fi
|
||||
r=${running#sha256:}; l=${latest#sha256:}
|
||||
printf 'V\t%s\t%s\t%s\t%s\t%s\t%s\n' "$dir" "$service" "$image" "$(printf '%s' "$r" | cut -c1-12)" "$(printf '%s' "$l" | cut -c1-12)" "$state"
|
||||
done
|
||||
printf 'D\t%s\n' "$dir"
|
||||
done
|
||||
done
|
||||
;;
|
||||
|
||||
apply)
|
||||
dir=$1
|
||||
[ -d "$dir" ] && compose_file "$dir" >/dev/null || { printf 'A\tfail\t%s\n' "aucune stack dans $dir"; exit 0; }
|
||||
cd "$dir" || { printf 'A\tfail\t%s\n' "répertoire inaccessible"; exit 0; }
|
||||
out=$(with_timeout 900 docker compose pull --ignore-buildable 2>&1 </dev/null) || { printf 'A\tfail\tpull : %s\n' "$(printf '%s' "$out" | flat)"; exit 0; }
|
||||
out=$(docker compose down 2>&1 </dev/null) || { printf 'A\tfail\tdown : %s\n' "$(printf '%s' "$out" | flat)"; exit 0; }
|
||||
out=$(docker compose up -d 2>&1 </dev/null) || { printf 'A\tfail\tup -d : %s\n' "$(printf '%s' "$out" | flat)"; exit 0; }
|
||||
printf 'A\tok\tstack relancée (down + up -d)\n'
|
||||
;;
|
||||
|
||||
*)
|
||||
printf 'E\t-\tmode inconnu\n'
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,138 @@
|
||||
package fleet
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
//go:embed remote.sh
|
||||
var remoteScript string
|
||||
|
||||
// Runner exécute le script distant pour une cible et transmet chaque ligne de
|
||||
// sortie à onLine. Une erreur signale un échec de connexion ou d'exécution ;
|
||||
// les erreurs « métier » (docker absent...) passent par des lignes E.
|
||||
type Runner interface {
|
||||
Run(ctx context.Context, host string, port int, user string, args []string, onLine func(string)) error
|
||||
}
|
||||
|
||||
// SSH joint les serveurs avec le client `ssh` du système : clé dédiée, hôtes
|
||||
// inconnus acceptés à la première connexion puis épinglés (known_hosts).
|
||||
type SSH struct {
|
||||
KeyFile string
|
||||
KnownHosts string
|
||||
Timeout int // secondes pour établir la connexion
|
||||
}
|
||||
|
||||
// quote protège un argument pour le shell distant.
|
||||
func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
|
||||
|
||||
// Command renvoie la commande distante : le script est passé en argument de
|
||||
// `sh -c` pour laisser l'entrée standard libre (docker ne doit pas la lire).
|
||||
func remoteCommand(args []string) string {
|
||||
parts := []string{"sh", "-c", quote(remoteScript), "stackwatch"}
|
||||
for _, a := range args {
|
||||
parts = append(parts, quote(a))
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
func (s SSH) sshArgs(host string, port int, user string) []string {
|
||||
to := s.Timeout
|
||||
if to <= 0 {
|
||||
to = 10
|
||||
}
|
||||
return []string{
|
||||
"-i", s.KeyFile,
|
||||
"-o", "IdentitiesOnly=yes",
|
||||
"-o", "BatchMode=yes",
|
||||
"-o", "StrictHostKeyChecking=accept-new",
|
||||
"-o", "UserKnownHostsFile=" + s.KnownHosts,
|
||||
"-o", "ConnectTimeout=" + strconv.Itoa(to),
|
||||
"-o", "ServerAliveInterval=15",
|
||||
"-o", "ServerAliveCountMax=4",
|
||||
"-o", "LogLevel=ERROR",
|
||||
"-p", strconv.Itoa(port),
|
||||
"-l", user,
|
||||
}
|
||||
}
|
||||
|
||||
func (s SSH) Run(ctx context.Context, host string, port int, user string, args []string, onLine func(string)) error {
|
||||
argv := append(s.sshArgs(host, port, user), "--", host, remoteCommand(args))
|
||||
cmd := exec.CommandContext(ctx, "ssh", argv...)
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &limitWriter{w: &stderr, max: 4096}
|
||||
out, err := cmd.StdoutPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
sc := bufio.NewScanner(out)
|
||||
sc.Buffer(make([]byte, 64<<10), 4<<20)
|
||||
lines := 0
|
||||
for sc.Scan() {
|
||||
lines++
|
||||
onLine(sc.Text())
|
||||
}
|
||||
werr := cmd.Wait()
|
||||
if ctx.Err() != nil {
|
||||
return fmt.Errorf("interrompu : %w", ctx.Err())
|
||||
}
|
||||
if werr != nil && lines == 0 {
|
||||
msg := strings.TrimSpace(stderr.String())
|
||||
if msg == "" {
|
||||
msg = werr.Error()
|
||||
}
|
||||
return errors.New(msg)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type limitWriter struct {
|
||||
w *bytes.Buffer
|
||||
max int
|
||||
}
|
||||
|
||||
func (l *limitWriter) Write(p []byte) (int, error) {
|
||||
if room := l.max - l.w.Len(); room > 0 {
|
||||
if len(p) > room {
|
||||
l.w.Write(p[:room])
|
||||
} else {
|
||||
l.w.Write(p)
|
||||
}
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// EnsureKey crée la clé SSH de stackwatch (ed25519, sans phrase de passe) si
|
||||
// elle n'existe pas, et renvoie le chemin de la clé privée et la clé publique.
|
||||
func EnsureKey(dir, override string) (keyFile, pub string, err error) {
|
||||
keyFile = override
|
||||
if keyFile == "" {
|
||||
if err = os.MkdirAll(dir, 0o700); err != nil {
|
||||
return
|
||||
}
|
||||
keyFile = filepath.Join(dir, "id_ed25519")
|
||||
if _, serr := os.Stat(keyFile); errors.Is(serr, os.ErrNotExist) {
|
||||
out, kerr := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "stackwatch", "-f", keyFile).CombinedOutput()
|
||||
if kerr != nil {
|
||||
return "", "", fmt.Errorf("ssh-keygen : %v : %s", kerr, strings.TrimSpace(string(out)))
|
||||
}
|
||||
}
|
||||
}
|
||||
out, kerr := exec.Command("ssh-keygen", "-y", "-f", keyFile).Output()
|
||||
if kerr != nil {
|
||||
return "", "", fmt.Errorf("clé publique illisible (%s) : %v", keyFile, kerr)
|
||||
}
|
||||
return keyFile, strings.TrimSpace(string(out)) + "\n", nil
|
||||
}
|
||||
Reference in new issue
Block a user