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,11 @@
|
|||||||
|
{
|
||||||
|
"version": "0.0.1",
|
||||||
|
"configurations": [
|
||||||
|
{
|
||||||
|
"name": "stackwatch-demo",
|
||||||
|
"runtimeExecutable": "sh",
|
||||||
|
"runtimeArgs": ["dev/demo.sh", "8099"],
|
||||||
|
"port": 8099
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
**/node_modules
|
||||||
|
web/dist
|
||||||
|
data
|
||||||
|
demo
|
||||||
|
bin
|
||||||
|
.git
|
||||||
|
.claude
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
STACKWATCH_PORT=8080
|
||||||
|
# local, oidc, both ou none
|
||||||
|
AUTH_MODE=local
|
||||||
|
ADMIN_USER=
|
||||||
|
ADMIN_PASSWORD=
|
||||||
|
# closed, approval ou open
|
||||||
|
REGISTRATION=closed
|
||||||
|
OIDC_ISSUER=
|
||||||
|
OIDC_CLIENT_ID=
|
||||||
|
OIDC_CLIENT_SECRET=
|
||||||
|
OIDC_REDIRECT_URL=
|
||||||
|
OIDC_SCOPES=openid profile email groups
|
||||||
|
OIDC_GROUPS_CLAIM=groups
|
||||||
|
OIDC_LOGOUT=true
|
||||||
|
OIDC_NAME=SSO
|
||||||
|
OIDC_ALLOWED_GROUPS=
|
||||||
|
OIDC_ADMIN_GROUPS=
|
||||||
|
OIDC_ADMIN_EMAILS=
|
||||||
|
SESSION_SECRET=
|
||||||
|
PUBLIC_URL=
|
||||||
|
TITLE=Stackwatch
|
||||||
|
CHECK_INTERVAL=6h
|
||||||
|
MAX_PARALLEL=4
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
/data/
|
||||||
|
/bin/
|
||||||
|
/demo/.state/
|
||||||
|
web/dist/*
|
||||||
|
!web/dist/.gitkeep
|
||||||
|
frontend/node_modules/
|
||||||
|
.DS_Store
|
||||||
+34
@@ -0,0 +1,34 @@
|
|||||||
|
# syntax=docker/dockerfile:1
|
||||||
|
|
||||||
|
# --- 1. Frontend : React + Vite -> /src/web/dist
|
||||||
|
FROM node:22-alpine AS frontend
|
||||||
|
WORKDIR /src/frontend
|
||||||
|
COPY frontend/package.json frontend/package-lock.json ./
|
||||||
|
RUN --mount=type=cache,target=/root/.npm npm ci --no-audit --no-fund
|
||||||
|
COPY frontend/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# --- 2. Backend : binaire Go statique embarquant le frontend
|
||||||
|
FROM golang:1.24-alpine AS backend
|
||||||
|
ARG VERSION=dev
|
||||||
|
WORKDIR /src
|
||||||
|
COPY go.mod ./
|
||||||
|
COPY cmd ./cmd
|
||||||
|
COPY internal ./internal
|
||||||
|
COPY web/embed.go ./web/
|
||||||
|
COPY --from=frontend /src/web/dist ./web/dist
|
||||||
|
RUN --mount=type=cache,target=/root/.cache/go-build \
|
||||||
|
CGO_ENABLED=0 go test ./... && \
|
||||||
|
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w -X main.version=${VERSION}" -o /out/server ./cmd/server
|
||||||
|
|
||||||
|
# --- 3. Image finale : alpine + client ssh (les serveurs sont joints avec `ssh`), non-root (uid 65532)
|
||||||
|
FROM alpine:3.21
|
||||||
|
RUN apk add --no-cache openssh-client-default && \
|
||||||
|
adduser -D -u 65532 -h /data nonroot && mkdir -p /data && chown 65532:65532 /data
|
||||||
|
COPY --from=backend /out/server /server
|
||||||
|
ENV LISTEN_ADDR=:8080 DATA_DIR=/data HOME=/data
|
||||||
|
VOLUME ["/data"]
|
||||||
|
EXPOSE 8080
|
||||||
|
USER nonroot:nonroot
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 CMD ["/server", "healthcheck"]
|
||||||
|
ENTRYPOINT ["/server"]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 vLab-BZH
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# Licence MIT (traduction française)
|
||||||
|
|
||||||
|
> Traduction fournie à titre informatif. Seule la version anglaise du fichier [`LICENSE`](LICENSE) fait foi.
|
||||||
|
|
||||||
|
```text
|
||||||
|
Copyright (c) 2026 vLab-BZH
|
||||||
|
|
||||||
|
L'autorisation est accordée, gracieusement, à toute personne obtenant une copie
|
||||||
|
de ce logiciel et des fichiers de documentation associés (le « Logiciel »), de
|
||||||
|
commercialiser le Logiciel sans restriction, notamment les droits d'utiliser,
|
||||||
|
de copier, de modifier, de fusionner, de publier, de distribuer, de
|
||||||
|
sous-licencier et/ou de vendre des copies du Logiciel, ainsi que d'autoriser
|
||||||
|
les personnes auxquelles le Logiciel est fourni à le faire, sous réserve des
|
||||||
|
conditions suivantes :
|
||||||
|
|
||||||
|
La déclaration de copyright ci-dessus et la présente autorisation doivent être
|
||||||
|
incluses dans toutes copies ou parties substantielles du Logiciel.
|
||||||
|
|
||||||
|
LE LOGICIEL EST FOURNI « TEL QUEL », SANS GARANTIE D'AUCUNE SORTE, EXPLICITE OU
|
||||||
|
IMPLICITE, NOTAMMENT SANS GARANTIE DE QUALITÉ MARCHANDE, D'ADÉQUATION À UN
|
||||||
|
USAGE PARTICULIER ET D'ABSENCE DE CONTREFAÇON. EN AUCUN CAS LES AUTEURS OU
|
||||||
|
TITULAIRES DU DROIT D'AUTEUR NE SERONT RESPONSABLES DE TOUT DOMMAGE,
|
||||||
|
RÉCLAMATION OU AUTRE RESPONSABILITÉ, QUE CE SOIT DANS LE CADRE D'UN CONTRAT,
|
||||||
|
D'UN DÉLIT OU AUTRE, EN PROVENANCE DE, CONSÉCUTIF À OU EN RELATION AVEC LE
|
||||||
|
LOGICIEL OU SON UTILISATION, OU AVEC D'AUTRES ÉLÉMENTS DU LOGICIEL.
|
||||||
|
```
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Stackwatch
|
||||||
|
|
||||||
|
Suivi des mises à jour des stacks **docker compose** de plusieurs serveurs, joints en SSH.
|
||||||
|
Même interface et même authentification qu'[Up And Down](../upandown) (local, OIDC ou reverse proxy).
|
||||||
|
|
||||||
|
## Principe
|
||||||
|
|
||||||
|
- Une liste de **serveurs** (hôte, port). Chaque serveur a une ou plusieurs **connexions** :
|
||||||
|
un **utilisateur SSH** et des **racines** à parcourir (`/home`, ou `/home/alice` pour des
|
||||||
|
stacks qui n'ont que les droits d'alice), avec une profondeur (1 : `racine/<stack>`).
|
||||||
|
- Pour chaque stack trouvée (`compose.yaml`, `compose.yml`, `docker-compose.yaml|yml`) :
|
||||||
|
`docker compose pull` (les conteneurs ne sont pas touchés) puis comparaison de l'image en
|
||||||
|
cours et de l'image tirée, service par service. Même logique que `update-stacks.sh`.
|
||||||
|
- Statuts : **À jour**, **Mise à jour** (au moins une image plus récente), **Arrêtée**, **Erreur**
|
||||||
|
(fichier invalide, pull refusé...). Les répertoires cachés et `node_modules` sont ignorés.
|
||||||
|
- Bouton **Mettre à jour** (administrateurs, après confirmation) : `pull`, `down`, `up -d` de la stack.
|
||||||
|
- Analyse automatique toutes les `CHECK_INTERVAL` (6 h par défaut), ou à la demande
|
||||||
|
(par stack, connexion, serveur, ou **Tout vérifier**).
|
||||||
|
|
||||||
|
## Connexion SSH
|
||||||
|
|
||||||
|
Stackwatch utilise le client `ssh` du système avec une clé ed25519 dédiée, créée au premier
|
||||||
|
démarrage dans `DATA_DIR/ssh/` (ou `SSH_KEY_FILE`). La clé publique est affichée dans
|
||||||
|
l'interface (**Clé SSH**) : l'ajouter à `~/.ssh/authorized_keys` de chaque utilisateur déclaré.
|
||||||
|
Les clés d'hôte sont enregistrées à la première connexion (`known_hosts` dans `DATA_DIR/ssh/`)
|
||||||
|
puis vérifiées. Les utilisateurs doivent pouvoir utiliser docker (groupe `docker` ou rootless).
|
||||||
|
Le bouton **Tester la connexion** du dialogue serveur vérifie SSH, docker et docker compose v2.
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Voir `docker-compose.yml` et `.env.example`. Variables propres à Stackwatch :
|
||||||
|
`CHECK_INTERVAL` (`6h`, minimum `5m`, `0` : désactivée), `MAX_PARALLEL` (connexions analysées
|
||||||
|
en parallèle, 4), `SSH_KEY_FILE`, `SSH_KNOWN_HOSTS`, `SSH_CONNECT_TIMEOUT` (10 s), `TITLE`.
|
||||||
|
Authentification : `AUTH_MODE`, `ADMIN_USER`, `ADMIN_PASSWORD`, `OIDC_*` comme Up And Down.
|
||||||
|
Les utilisateurs simples consultent et lancent des analyses ; les administrateurs gèrent les
|
||||||
|
serveurs et les mises à jour.
|
||||||
|
|
||||||
|
## Données (`DATA_DIR`)
|
||||||
|
|
||||||
|
`fleet/servers.json` (serveurs), `fleet/state.json` (derniers résultats), `ssh/` (clé et
|
||||||
|
known_hosts), comptes et secrets de session.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd frontend && npm ci && npm run build # sortie dans web/dist (embarquée)
|
||||||
|
touch ../web/dist/.gitkeep
|
||||||
|
cd .. && go test ./... && go build -o bin/stackwatch ./cmd/server
|
||||||
|
# ou : docker compose build
|
||||||
|
```
|
||||||
|
|
||||||
|
## Démo locale
|
||||||
|
|
||||||
|
`sh demo/demo.sh 8099` lance le binaire avec un faux `ssh` (exécution locale) et un faux
|
||||||
|
`docker` (stacks à jour, en retard, arrêtée, en erreur) : aucun serveur réel nécessaire.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
Voir l'en-tête de `internal/api/api.go`. `GET /api/summary` donne les compteurs
|
||||||
|
(stacks, mises à jour, erreurs) pour une supervision.
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
// Commande server : suivi des mises à jour de stacks docker compose (SSH) + frontend embarqué.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"path"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/vblogio/stackwatch/internal/api"
|
||||||
|
"github.com/vblogio/stackwatch/internal/auth"
|
||||||
|
"github.com/vblogio/stackwatch/internal/fleet"
|
||||||
|
"github.com/vblogio/stackwatch/web"
|
||||||
|
)
|
||||||
|
|
||||||
|
// version est renseignée au build (-ldflags "-X main.version=...").
|
||||||
|
var version = "dev"
|
||||||
|
|
||||||
|
func env(key, def string) string {
|
||||||
|
if v := os.Getenv(key); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
// envBool lit un booléen ; une valeur illisible est une erreur de configuration.
|
||||||
|
func envBool(key string, def bool) bool {
|
||||||
|
v := os.Getenv(key)
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
b, err := strconv.ParseBool(v)
|
||||||
|
if err != nil {
|
||||||
|
fatal(key + " invalide (true ou false)")
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func envInt(key string, def int64) int64 {
|
||||||
|
v := os.Getenv(key)
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil || n < 0 {
|
||||||
|
fatal(key + " invalide (entier >= 0)")
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func fatal(msg string, args ...any) {
|
||||||
|
slog.Error(msg, args...)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// secretEnv lit un secret dans NAME, ou dans le fichier NAME_FILE (secrets Docker).
|
||||||
|
func secretEnv(name string) string {
|
||||||
|
if v := os.Getenv(name); v != "" {
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
if f := os.Getenv(name + "_FILE"); f != "" {
|
||||||
|
b, err := os.ReadFile(f)
|
||||||
|
if err != nil {
|
||||||
|
fatal(name+"_FILE illisible", "err", err)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(b))
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil)))
|
||||||
|
|
||||||
|
addr := env("LISTEN_ADDR", ":8080")
|
||||||
|
// `server healthcheck` : sonde pour le conteneur.
|
||||||
|
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
|
||||||
|
os.Exit(healthcheck(addr))
|
||||||
|
}
|
||||||
|
dataDir := env("DATA_DIR", "./data")
|
||||||
|
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
||||||
|
fatal("répertoire de données", "dir", dataDir, "err", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
|
defer stop()
|
||||||
|
|
||||||
|
// Clé SSH : SSH_KEY_FILE, ou une clé ed25519 créée dans DATA_DIR/ssh au premier démarrage.
|
||||||
|
keyFile, pub, err := fleet.EnsureKey(filepath.Join(dataDir, "ssh"), os.Getenv("SSH_KEY_FILE"))
|
||||||
|
if err != nil {
|
||||||
|
fatal("clé SSH", "err", err)
|
||||||
|
}
|
||||||
|
runner := fleet.SSH{KeyFile: keyFile, KnownHosts: env("SSH_KNOWN_HOSTS", filepath.Join(dataDir, "ssh", "known_hosts")),
|
||||||
|
Timeout: int(envInt("SSH_CONNECT_TIMEOUT", 10))}
|
||||||
|
manager, err := fleet.Open(ctx, filepath.Join(dataDir, "fleet"), runner, int(envInt("MAX_PARALLEL", 4)))
|
||||||
|
if err != nil {
|
||||||
|
fatal("serveurs", "err", err)
|
||||||
|
}
|
||||||
|
interval, err := time.ParseDuration(env("CHECK_INTERVAL", "6h"))
|
||||||
|
if err != nil || interval < 0 || (interval > 0 && interval < 5*time.Minute) {
|
||||||
|
fatal("CHECK_INTERVAL invalide (ex. 6h, minimum 5m, 0 : pas d'analyse automatique)")
|
||||||
|
}
|
||||||
|
manager.Interval = interval
|
||||||
|
go manager.Run(ctx)
|
||||||
|
|
||||||
|
mode := strings.ToLower(env("AUTH_MODE", "local"))
|
||||||
|
handler := (&api.Handler{Fleet: manager, Mode: mode, Version: version, Title: env("TITLE", "Stackwatch"),
|
||||||
|
PublicKey: pub, Interval: interval}).Init()
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
var root http.Handler = mux
|
||||||
|
|
||||||
|
switch mode {
|
||||||
|
case "none":
|
||||||
|
// Aucune authentification intégrée (reverse proxy avec SSO, usage local).
|
||||||
|
slog.Warn("aucune authentification intégrée (AUTH_MODE=none) : à réserver à un reverse proxy qui authentifie")
|
||||||
|
case "local", "oidc", "both":
|
||||||
|
accounts, err := auth.OpenAccounts(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
fatal("comptes", "err", err)
|
||||||
|
}
|
||||||
|
handler.Accounts = accounts
|
||||||
|
a, err := authentication(ctx, mode, dataDir, accounts, handler)
|
||||||
|
if err != nil {
|
||||||
|
fatal("authentification", "err", err)
|
||||||
|
}
|
||||||
|
a.Register(mux)
|
||||||
|
handler.Auth = a
|
||||||
|
root = a.Middleware(mux, public)
|
||||||
|
default:
|
||||||
|
fatal(fmt.Sprintf("AUTH_MODE %q inconnu (local, oidc, both ou none)", mode))
|
||||||
|
}
|
||||||
|
|
||||||
|
handler.Register(mux)
|
||||||
|
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })
|
||||||
|
mux.Handle("/", spa())
|
||||||
|
|
||||||
|
srv := &http.Server{
|
||||||
|
Addr: addr,
|
||||||
|
Handler: logRequests(securityHeaders(sameOrigin(root))),
|
||||||
|
ReadHeaderTimeout: 10 * time.Second,
|
||||||
|
IdleTimeout: 120 * time.Second,
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
slog.Info("démarrage", "addr", addr, "data", dataDir, "auth", mode, "version", version, "check_interval", interval.String())
|
||||||
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
|
fatal("serveur", "err", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
<-ctx.Done()
|
||||||
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
_ = srv.Shutdown(shutdownCtx)
|
||||||
|
slog.Info("arrêt")
|
||||||
|
}
|
||||||
|
|
||||||
|
// authentication prépare l'authentification locale (comptes, inscription) et/ou OIDC.
|
||||||
|
func authentication(ctx context.Context, mode, dataDir string, accounts *auth.Accounts, h *api.Handler) (*auth.Auth, error) {
|
||||||
|
secret, err := auth.LoadSecret(os.Getenv("SESSION_SECRET"), dataDir)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ttl, err := time.ParseDuration(env("SESSION_TTL", "24h"))
|
||||||
|
if err != nil || ttl < 5*time.Minute {
|
||||||
|
return nil, errors.New("SESSION_TTL invalide (ex. 24h, minimum 5m)")
|
||||||
|
}
|
||||||
|
registration := strings.ToLower(env("REGISTRATION", "closed"))
|
||||||
|
if registration != "closed" && registration != "approval" && registration != "open" {
|
||||||
|
return nil, errors.New("REGISTRATION invalide (closed, approval ou open)")
|
||||||
|
}
|
||||||
|
pub := publicURL()
|
||||||
|
secureCookies := strings.HasPrefix(pub, "https://") || strings.HasPrefix(os.Getenv("OIDC_REDIRECT_URL"), "https://")
|
||||||
|
sessions := auth.NewSessions(secret, ttl, secureCookies)
|
||||||
|
|
||||||
|
a := auth.New(&auth.Auth{
|
||||||
|
Accounts: accounts,
|
||||||
|
Sessions: sessions,
|
||||||
|
Local: mode == "local" || mode == "both",
|
||||||
|
Registration: func() string { return registration },
|
||||||
|
OIDCName: env("OIDC_NAME", "SSO"),
|
||||||
|
})
|
||||||
|
h.OIDCName = a.OIDCName
|
||||||
|
|
||||||
|
if a.Local {
|
||||||
|
if user := os.Getenv("ADMIN_USER"); user != "" {
|
||||||
|
pass := secretEnv("ADMIN_PASSWORD")
|
||||||
|
if pass == "" {
|
||||||
|
return nil, errors.New("ADMIN_USER défini sans ADMIN_PASSWORD")
|
||||||
|
}
|
||||||
|
if err := accounts.EnsureAdmin(user, pass); err != nil {
|
||||||
|
return nil, fmt.Errorf("administrateur initial : %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if accounts.NeedsSetup() {
|
||||||
|
slog.Warn("aucun administrateur : le premier compte créé (inscription) le deviendra ; définir ADMIN_USER et ADMIN_PASSWORD pour l'imposer")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if mode == "local" {
|
||||||
|
return a, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// OIDC
|
||||||
|
cfg, err := oidcConfig(secret, ttl)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg.Sessions = sessions
|
||||||
|
policy := auth.OIDCPolicy{AdminGroups: fields(os.Getenv("OIDC_ADMIN_GROUPS")), AdminEmails: fields(os.Getenv("OIDC_ADMIN_EMAILS"))}
|
||||||
|
cfg.Provision = func(u auth.User, groups []string) (auth.User, error) {
|
||||||
|
return accounts.UpsertOIDC(u, groups, policy)
|
||||||
|
}
|
||||||
|
o, err := auth.NewOIDC(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
a.OIDC = o
|
||||||
|
slog.Info("authentification OIDC activée", "issuer", cfg.Issuer, "client_id", cfg.ClientID,
|
||||||
|
"groups", cfg.AllowedGroups, "admin_groups", policy.AdminGroups, "session_ttl", ttl.String())
|
||||||
|
return a, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// publicURL est l'origine publique du service : PUBLIC_URL, sinon celle de
|
||||||
|
// OIDC_REDIRECT_URL ; vide, elle est déduite de chaque requête.
|
||||||
|
func publicURL() string {
|
||||||
|
if v := os.Getenv("PUBLIC_URL"); v != "" {
|
||||||
|
return strings.TrimRight(v, "/")
|
||||||
|
}
|
||||||
|
if u, err := url.Parse(os.Getenv("OIDC_REDIRECT_URL")); err == nil && u.Scheme != "" && u.Host != "" {
|
||||||
|
return u.Scheme + "://" + u.Host
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// oidcConfig lit les variables OIDC_*.
|
||||||
|
func oidcConfig(secret []byte, ttl time.Duration) (auth.Config, error) {
|
||||||
|
cfg := auth.Config{
|
||||||
|
Issuer: os.Getenv("OIDC_ISSUER"),
|
||||||
|
ClientID: os.Getenv("OIDC_CLIENT_ID"),
|
||||||
|
ClientSecret: secretEnv("OIDC_CLIENT_SECRET"),
|
||||||
|
RedirectURL: os.Getenv("OIDC_REDIRECT_URL"),
|
||||||
|
Scopes: fields(env("OIDC_SCOPES", "openid profile email groups")),
|
||||||
|
GroupsClaim: env("OIDC_GROUPS_CLAIM", "groups"),
|
||||||
|
SessionTTL: ttl,
|
||||||
|
Secret: secret,
|
||||||
|
}
|
||||||
|
cfg.AllowedGroups = fields(os.Getenv("OIDC_ALLOWED_GROUPS"))
|
||||||
|
var err error
|
||||||
|
if cfg.EndSession, err = strconv.ParseBool(env("OIDC_LOGOUT", "true")); err != nil {
|
||||||
|
return cfg, errors.New("OIDC_LOGOUT invalide (true ou false)")
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fields découpe une liste séparée par des espaces ou des virgules.
|
||||||
|
func fields(s string) []string {
|
||||||
|
return strings.FieldsFunc(s, func(r rune) bool { return r == ' ' || r == ',' })
|
||||||
|
}
|
||||||
|
|
||||||
|
func healthcheck(addr string) int {
|
||||||
|
host, port, err := net.SplitHostPort(addr)
|
||||||
|
if err != nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if host == "" || host == "0.0.0.0" || host == "::" {
|
||||||
|
host = "127.0.0.1"
|
||||||
|
}
|
||||||
|
c := http.Client{Timeout: 3 * time.Second}
|
||||||
|
res, err := c.Get("http://" + net.JoinHostPort(host, port) + "/healthz")
|
||||||
|
if err != nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
res.Body.Close()
|
||||||
|
if res.StatusCode != http.StatusOK {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// spa sert le build Vite embarqué ; toute route inconnue renvoie index.html.
|
||||||
|
func spa() http.Handler {
|
||||||
|
dist, _ := fs.Sub(web.Dist, "dist")
|
||||||
|
files := http.FileServerFS(dist)
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
p := path.Clean(r.URL.Path)
|
||||||
|
if p != "/" {
|
||||||
|
if fi, err := fs.Stat(dist, p[1:]); err == nil && !fi.IsDir() {
|
||||||
|
// Les assets Vite sont nommés par empreinte : cache long.
|
||||||
|
if path.Dir(p) == "/assets" {
|
||||||
|
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||||
|
}
|
||||||
|
files.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
index, err := fs.ReadFile(dist, "index.html")
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "frontend absent : lancer `npm run build` dans frontend/", http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
|
_, _ = w.Write(index)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// public indique les chemins servis sans session : sonde, état de la connexion
|
||||||
|
// (/api/me : page de connexion) et fichiers statiques du build (code de
|
||||||
|
// l'application, sans aucune donnée).
|
||||||
|
func public(p string) bool {
|
||||||
|
switch {
|
||||||
|
case p == "/healthz", p == "/api/me":
|
||||||
|
return true
|
||||||
|
case strings.HasPrefix(p, "/api/"), p == "/", p == "/index.html":
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
dist, _ := fs.Sub(web.Dist, "dist")
|
||||||
|
fi, err := fs.Stat(dist, strings.TrimPrefix(path.Clean(p), "/"))
|
||||||
|
return err == nil && !fi.IsDir()
|
||||||
|
}
|
||||||
|
|
||||||
|
// sameOrigin refuse les requêtes qui modifient des données et viennent d'un
|
||||||
|
// autre site (CSRF) : l'en-tête Origin d'une requête de navigateur doit
|
||||||
|
// désigner l'hôte du service. Les requêtes sans Origin (curl, jetons d'API)
|
||||||
|
// ne sont pas concernées.
|
||||||
|
func sameOrigin(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
switch r.Method {
|
||||||
|
case http.MethodGet, http.MethodHead, http.MethodOptions:
|
||||||
|
default:
|
||||||
|
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||||
|
http.Error(w, "origine refusée", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if o := r.Header.Get("Origin"); o != "" && o != "null" {
|
||||||
|
host := r.Host
|
||||||
|
if h := r.Header.Get("X-Forwarded-Host"); h != "" {
|
||||||
|
host, _, _ = strings.Cut(h, ",")
|
||||||
|
host = strings.TrimSpace(host)
|
||||||
|
}
|
||||||
|
if u, err := url.Parse(o); err != nil || !strings.EqualFold(u.Host, host) {
|
||||||
|
http.Error(w, "origine refusée", http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func securityHeaders(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := w.Header()
|
||||||
|
h.Set("X-Content-Type-Options", "nosniff")
|
||||||
|
h.Set("Referrer-Policy", "same-origin")
|
||||||
|
h.Set("X-Frame-Options", "SAMEORIGIN")
|
||||||
|
h.Set("X-Robots-Tag", "noindex, nofollow")
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type statusWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
status int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *statusWriter) WriteHeader(code int) {
|
||||||
|
s.status = code
|
||||||
|
s.ResponseWriter.WriteHeader(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unwrap permet à http.ResponseController (Flush, SetWriteDeadline) d'atteindre
|
||||||
|
// l'écrivain d'origine.
|
||||||
|
func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }
|
||||||
|
|
||||||
|
func (s *statusWriter) Flush() {
|
||||||
|
if f, ok := s.ResponseWriter.(http.Flusher); ok {
|
||||||
|
f.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func logRequests(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
start := time.Now()
|
||||||
|
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||||
|
next.ServeHTTP(sw, r)
|
||||||
|
if r.URL.Path != "/healthz" {
|
||||||
|
p := r.URL.Path
|
||||||
|
slog.Info("http", "method", r.Method, "path", p, "status", sw.status,
|
||||||
|
"dur_ms", time.Since(start).Milliseconds())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
Executable
+29
@@ -0,0 +1,29 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Démo locale sans serveur réel : un faux `ssh` exécute le script distant en local,
|
||||||
|
# un faux `docker` simule des stacks (à jour, en retard, arrêtée, en erreur...).
|
||||||
|
# Usage : demo/demo.sh [port] (binaire : bin/stackwatch, voir README)
|
||||||
|
set -e
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
PORT=${1:-8099}
|
||||||
|
DEMO=$PWD/demo/.state
|
||||||
|
mkdir -p "$DEMO/data"
|
||||||
|
if [ ! -d "$DEMO/home" ]; then
|
||||||
|
for d in nextcloud outdated traefik alice/blog stopped badpull broken; do
|
||||||
|
mkdir -p "$DEMO/home/$d"; echo "services: {}" > "$DEMO/home/$d/compose.yaml"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
export PATH="$PWD/demo/fake-bin:$PATH" AUTH_MODE=none DATA_DIR="$DEMO/data" LISTEN_ADDR=127.0.0.1:$PORT CHECK_INTERVAL=0
|
||||||
|
# Serveur de démonstration pré-enregistré au premier lancement.
|
||||||
|
mkdir -p "$DEMO/data/fleet"
|
||||||
|
if [ ! -f "$DEMO/data/fleet/servers.json" ]; then
|
||||||
|
cat > "$DEMO/data/fleet/servers.json" <<JSON
|
||||||
|
[
|
||||||
|
{"id":"demo1","name":"lancelot","host":"lancelot.example.org","port":22,"note":"stacks de production","enabled":true,
|
||||||
|
"targets":[{"id":"t1","user":"root","roots":["$DEMO/home"],"depth":1},
|
||||||
|
{"id":"t2","user":"alice","roots":["$DEMO/home/alice"],"depth":1}]},
|
||||||
|
{"id":"demo2","name":"arthur","host":"arthur.example.org","port":2222,"enabled":true,
|
||||||
|
"targets":[{"id":"t3","user":"deploy","roots":["$DEMO/home/alice"],"depth":1}]}
|
||||||
|
]
|
||||||
|
JSON
|
||||||
|
fi
|
||||||
|
exec ./bin/stackwatch
|
||||||
Executable
+24
@@ -0,0 +1,24 @@
|
|||||||
|
#!/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
|
||||||
Executable
+5
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# faux ssh : exécute la commande distante (dernier argument) en local
|
||||||
|
for a; do last=$a; done
|
||||||
|
sleep 0.6
|
||||||
|
exec sh -c "$last"
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Premier envoi vers Gitea (à lancer une fois depuis la racine du dépôt).
|
||||||
|
set -e
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
rm -rf .git
|
||||||
|
git init -q -b main
|
||||||
|
git add -A
|
||||||
|
git -c user.name="Cédric" -c user.email="claude@killy.net" commit -q -m "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>"
|
||||||
|
git remote add origin git@gitea.vlab.bzh:vLab-BZH/stackwatch.git
|
||||||
|
git push -u origin main
|
||||||
|
git log --oneline | head -3
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Stackwatch
|
||||||
|
services:
|
||||||
|
stackwatch:
|
||||||
|
build: .
|
||||||
|
image: stackwatch:local
|
||||||
|
restart: unless-stopped
|
||||||
|
# ports:
|
||||||
|
# - "${STACKWATCH_PORT:-8080}:8080"
|
||||||
|
environment:
|
||||||
|
# Authentification : local (comptes), oidc, both ou none (reverse proxy qui authentifie).
|
||||||
|
AUTH_MODE: ${AUTH_MODE:-local}
|
||||||
|
ADMIN_USER: ${ADMIN_USER:-}
|
||||||
|
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||||
|
# Inscription des comptes locaux : closed, approval ou open.
|
||||||
|
REGISTRATION: ${REGISTRATION:-closed}
|
||||||
|
OIDC_ISSUER: ${OIDC_ISSUER:-}
|
||||||
|
OIDC_CLIENT_ID: ${OIDC_CLIENT_ID:-}
|
||||||
|
OIDC_CLIENT_SECRET: ${OIDC_CLIENT_SECRET:-}
|
||||||
|
OIDC_REDIRECT_URL: ${OIDC_REDIRECT_URL:-}
|
||||||
|
OIDC_SCOPES: ${OIDC_SCOPES:-openid profile email groups}
|
||||||
|
OIDC_NAME: ${OIDC_NAME:-SSO}
|
||||||
|
OIDC_ALLOWED_GROUPS: ${OIDC_ALLOWED_GROUPS:-}
|
||||||
|
OIDC_GROUPS_CLAIM: ${OIDC_GROUPS_CLAIM:-groups}
|
||||||
|
OIDC_ADMIN_GROUPS: ${OIDC_ADMIN_GROUPS:-}
|
||||||
|
OIDC_ADMIN_EMAILS: ${OIDC_ADMIN_EMAILS:-}
|
||||||
|
OIDC_LOGOUT: ${OIDC_LOGOUT:-true}
|
||||||
|
SESSION_TTL: ${SESSION_TTL:-24h}
|
||||||
|
SESSION_SECRET: ${SESSION_SECRET:-}
|
||||||
|
PUBLIC_URL: ${PUBLIC_URL:-}
|
||||||
|
TITLE: ${TITLE:-Stackwatch}
|
||||||
|
# Analyse automatique (pull + comparaison des images) ; 0 : seulement à la demande.
|
||||||
|
CHECK_INTERVAL: ${CHECK_INTERVAL:-6h}
|
||||||
|
MAX_PARALLEL: ${MAX_PARALLEL:-4}
|
||||||
|
volumes:
|
||||||
|
# Serveurs, résultats, comptes et clé SSH : chown -R 65532:65532 ./data
|
||||||
|
- ./data:/data
|
||||||
|
read_only: true
|
||||||
|
cap_drop: [ALL]
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
networks:
|
||||||
|
- traefik-net
|
||||||
|
networks:
|
||||||
|
traefik-net:
|
||||||
|
external: true
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
node_modules/
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="fr">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||||
|
<meta name="theme-color" content="#6965db" />
|
||||||
|
<meta name="robots" content="noindex" />
|
||||||
|
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%236965db' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 3.2 3.2 8 12 12.8 20.8 8 12 3.2zM3.2 12 12 16.8 20.8 12M3.2 16 12 20.8 20.8 16'/%3E%3C/svg%3E" />
|
||||||
|
<title>Stackwatch</title>
|
||||||
|
<script>
|
||||||
|
// Thème appliqué avant le premier rendu (évite un flash clair).
|
||||||
|
try {
|
||||||
|
var t = localStorage.getItem("swTheme");
|
||||||
|
if (t === "dark" || t === "light") document.documentElement.dataset.theme = t;
|
||||||
|
else if (matchMedia("(prefers-color-scheme: dark)").matches) document.documentElement.dataset.theme = "dark";
|
||||||
|
} catch (e) {}
|
||||||
|
</script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script type="module" src="/src/main.tsx"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1877
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "stackwatch-frontend",
|
||||||
|
"private": true,
|
||||||
|
"version": "0.1.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "tsc --noEmit && vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"react": "^19.1.0",
|
||||||
|
"react-dom": "^19.1.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/react": "^19.1.0",
|
||||||
|
"@types/react-dom": "^19.1.0",
|
||||||
|
"@vitejs/plugin-react": "^5.0.0",
|
||||||
|
"typescript": "^5.8.0",
|
||||||
|
"vite": "^7.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
/** Bouton « … » qui a ouvert le menu : le menu s'aligne sur lui. */
|
||||||
|
anchor: HTMLElement;
|
||||||
|
onClose: () => void;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const MARGIN = 8; // écart minimal avec les bords de la fenêtre
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Menu déroulant des actions d'un élément, ouvert sous le bouton « … » et aligné
|
||||||
|
* sur son bord droit (au-dessus s'il manque de place en bas). Rendu dans <body>
|
||||||
|
* pour ne pas être rogné par le défilement de la liste ; refermé par un clic
|
||||||
|
* ailleurs, Échap, un défilement, un redimensionnement ou le choix d'une action.
|
||||||
|
*/
|
||||||
|
export function ActionMenu({ anchor, onClose, children }: Props) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const menu = ref.current;
|
||||||
|
if (!menu) return;
|
||||||
|
const a = anchor.getBoundingClientRect();
|
||||||
|
const { offsetWidth: w, offsetHeight: h } = menu;
|
||||||
|
let top = a.bottom + 4;
|
||||||
|
if (top + h > innerHeight - MARGIN) top = Math.max(MARGIN, a.top - 4 - h);
|
||||||
|
const left = Math.min(Math.max(MARGIN, a.right - w), innerWidth - w - MARGIN);
|
||||||
|
setPos({ top, left });
|
||||||
|
}, [anchor]);
|
||||||
|
|
||||||
|
// Focus sur la première action une fois le menu placé (masqué, il ne le prend pas).
|
||||||
|
useEffect(() => {
|
||||||
|
if (pos) ref.current?.querySelector<HTMLElement>("button, a")?.focus({ preventScroll: true });
|
||||||
|
}, [pos]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const inside = (t: EventTarget | null) => t instanceof Node && (ref.current?.contains(t) || anchor.contains(t));
|
||||||
|
const onDown = (ev: PointerEvent) => {
|
||||||
|
if (!inside(ev.target)) onClose();
|
||||||
|
};
|
||||||
|
const onKey = (ev: KeyboardEvent) => {
|
||||||
|
if (ev.key === "Escape") {
|
||||||
|
// Ni désélection, ni fermeture du panneau flottant : seulement le menu.
|
||||||
|
ev.preventDefault();
|
||||||
|
ev.stopPropagation();
|
||||||
|
onClose();
|
||||||
|
anchor.focus();
|
||||||
|
} else if (ev.key === "ArrowDown" || ev.key === "ArrowUp") {
|
||||||
|
const items = [...(ref.current?.querySelectorAll<HTMLElement>("button, a") ?? [])];
|
||||||
|
if (!items.length) return;
|
||||||
|
ev.preventDefault();
|
||||||
|
const i = items.indexOf(document.activeElement as HTMLElement);
|
||||||
|
const next = ev.key === "ArrowDown" ? (i + 1) % items.length : (i - 1 + items.length) % items.length;
|
||||||
|
items[next].focus();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const onScroll = (ev: Event) => {
|
||||||
|
if (!(ev.target instanceof Node && ref.current?.contains(ev.target))) onClose();
|
||||||
|
};
|
||||||
|
document.addEventListener("pointerdown", onDown, true);
|
||||||
|
document.addEventListener("keydown", onKey, true);
|
||||||
|
document.addEventListener("scroll", onScroll, true);
|
||||||
|
window.addEventListener("resize", onClose);
|
||||||
|
return () => {
|
||||||
|
document.removeEventListener("pointerdown", onDown, true);
|
||||||
|
document.removeEventListener("keydown", onKey, true);
|
||||||
|
document.removeEventListener("scroll", onScroll, true);
|
||||||
|
window.removeEventListener("resize", onClose);
|
||||||
|
};
|
||||||
|
}, [anchor, onClose]);
|
||||||
|
|
||||||
|
return createPortal(
|
||||||
|
<div
|
||||||
|
ref={ref}
|
||||||
|
className="actions menu-popup"
|
||||||
|
role="menu"
|
||||||
|
style={pos ?? { top: 0, left: 0, visibility: "hidden" }}
|
||||||
|
// Une action choisie referme le menu (après coup, pour laisser un lien de
|
||||||
|
// téléchargement aboutir).
|
||||||
|
onClick={(ev) => {
|
||||||
|
if ((ev.target as HTMLElement).closest("button, a")) setTimeout(onClose);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
|
import { api, type Fleet, type Me } from "./api";
|
||||||
|
import { ActionMenu } from "./ActionMenu";
|
||||||
|
import { FleetView } from "./FleetView";
|
||||||
|
import { KeyDialog, ServerDialog } from "./ServerDialog";
|
||||||
|
import { Login } from "./Login";
|
||||||
|
import { SettingsDialog } from "./SettingsDialog";
|
||||||
|
import { initials } from "./format";
|
||||||
|
import { LogoutIcon, MenuIcon, MoonIcon, PlusIcon, RefreshIcon, ServerIcon, SettingsIcon, ShieldIcon, StackIcon, SunIcon, UserIcon, UsersIcon, KeyIcon } from "./icons";
|
||||||
|
|
||||||
|
type Theme = "light" | "dark";
|
||||||
|
|
||||||
|
const initialTheme = (): Theme => (document.documentElement.dataset.theme === "dark" ? "dark" : "light");
|
||||||
|
|
||||||
|
const hashServer = () => decodeURIComponent(location.hash.replace(/^#\/?/, ""));
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
const [me, setMe] = useState<Me | null>(null);
|
||||||
|
const [loadError, setLoadError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const loadMe = useCallback(
|
||||||
|
() =>
|
||||||
|
api
|
||||||
|
.me()
|
||||||
|
.then((m) => {
|
||||||
|
setMe(m);
|
||||||
|
setLoadError(null);
|
||||||
|
document.title = m.title || "Stackwatch";
|
||||||
|
})
|
||||||
|
.catch((e) => setLoadError(e instanceof Error ? e.message : String(e))),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadMe();
|
||||||
|
}, [loadMe]);
|
||||||
|
|
||||||
|
// OIDC seul : pas de page de connexion locale, direction le fournisseur.
|
||||||
|
const redirecting = !!me && !me.user && me.oidc && !me.local;
|
||||||
|
useEffect(() => {
|
||||||
|
if (redirecting) location.replace(`/auth/login?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
|
||||||
|
}, [redirecting]);
|
||||||
|
|
||||||
|
if (loadError) {
|
||||||
|
return (
|
||||||
|
<main className="login">
|
||||||
|
<div className="login-card center">
|
||||||
|
<p className="error">{loadError}</p>
|
||||||
|
<button className="primary" onClick={loadMe}>
|
||||||
|
Réessayer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!me || redirecting) return <div className="splash muted">Chargement…</div>;
|
||||||
|
if (!me.user) return <Login me={me} onLoggedIn={loadMe} />;
|
||||||
|
return <Shell me={me} reloadMe={loadMe} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Shell({ me, reloadMe }: { me: Me; reloadMe: () => Promise<unknown> }) {
|
||||||
|
const [theme, setTheme] = useState<Theme>(initialTheme);
|
||||||
|
const [fleet, setFleet] = useState<Fleet | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [sel, setSel] = useState(hashServer());
|
||||||
|
const [drawer, setDrawer] = useState(false);
|
||||||
|
const [settings, setSettings] = useState<"account" | "users" | null>(null);
|
||||||
|
const [userMenu, setUserMenu] = useState<HTMLElement | null>(null);
|
||||||
|
const [serverDialog, setServerDialog] = useState<{ id?: string } | null>(null);
|
||||||
|
const [keyDialog, setKeyDialog] = useState(false);
|
||||||
|
const title = me.title || "Stackwatch";
|
||||||
|
const user = me.user!;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.documentElement.dataset.theme = theme;
|
||||||
|
try {
|
||||||
|
localStorage.setItem("swTheme", theme);
|
||||||
|
} catch {
|
||||||
|
/* stockage indisponible */
|
||||||
|
}
|
||||||
|
}, [theme]);
|
||||||
|
|
||||||
|
const load = useCallback(
|
||||||
|
() =>
|
||||||
|
api
|
||||||
|
.fleet()
|
||||||
|
.then((f) => {
|
||||||
|
setFleet(f);
|
||||||
|
setError(null);
|
||||||
|
return f;
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
setError(e instanceof Error ? e.message : String(e));
|
||||||
|
return null;
|
||||||
|
}),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Rafraîchissement : rapide pendant une analyse, lent sinon.
|
||||||
|
const busy = !!fleet && fleet.summary.scanning > 0;
|
||||||
|
const loadRef = useRef(load);
|
||||||
|
loadRef.current = load;
|
||||||
|
useEffect(() => {
|
||||||
|
loadRef.current();
|
||||||
|
const t = setInterval(() => loadRef.current(), busy ? 2000 : 30000);
|
||||||
|
return () => clearInterval(t);
|
||||||
|
}, [busy]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onHash = () => setSel(hashServer());
|
||||||
|
window.addEventListener("hashchange", onHash);
|
||||||
|
return () => window.removeEventListener("hashchange", onHash);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const go = (id: string) => {
|
||||||
|
setSel(id);
|
||||||
|
setDrawer(false);
|
||||||
|
if (id) location.hash = `#/${encodeURIComponent(id)}`;
|
||||||
|
else history.pushState(null, "", location.pathname + location.search);
|
||||||
|
};
|
||||||
|
|
||||||
|
const run = async (fn: () => Promise<unknown>) => {
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : String(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const servers = fleet?.servers ?? [];
|
||||||
|
const current = servers.find((s) => s.id === sel);
|
||||||
|
const sum = fleet?.summary;
|
||||||
|
|
||||||
|
const dot = (s: (typeof servers)[number]) => {
|
||||||
|
const scans = Object.values(s.scans);
|
||||||
|
if (!s.enabled) return "off";
|
||||||
|
if (scans.some((x) => x.error)) return "err";
|
||||||
|
if (scans.some((x) => x.stacks.some((st) => st.status === "error"))) return "err";
|
||||||
|
if (scans.some((x) => x.stacks.some((st) => st.status === "updates"))) return "upd";
|
||||||
|
if (scans.length === 0) return "off";
|
||||||
|
return "ok";
|
||||||
|
};
|
||||||
|
const updatesOf = (s: (typeof servers)[number]) => Object.values(s.scans).reduce((n, x) => n + x.stacks.filter((st) => st.status === "updates").length, 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="app">
|
||||||
|
<header className="topbar">
|
||||||
|
<button className="icon-btn menu-btn-inline" onClick={() => setDrawer(!drawer)} aria-label="Menu" title="Menu">
|
||||||
|
<MenuIcon />
|
||||||
|
</button>
|
||||||
|
<a className="brand" href="/" onClick={(e) => (e.preventDefault(), go(""))} title={title}>
|
||||||
|
<StackIcon size={26} />
|
||||||
|
<span>{title}</span>
|
||||||
|
</a>
|
||||||
|
<div className="topbar-tools">
|
||||||
|
<button className="ex-btn" onClick={() => run(api.checkAll)} disabled={!servers.length || busy} title="Analyser tous les serveurs">
|
||||||
|
<RefreshIcon className={busy ? "spin" : ""} />
|
||||||
|
<span className="hide-sm">{busy ? "Analyse…" : "Tout vérifier"}</span>
|
||||||
|
</button>
|
||||||
|
<button className="icon-btn" onClick={() => setTheme(theme === "dark" ? "light" : "dark")} aria-label={theme === "dark" ? "Thème clair" : "Thème sombre"} title={theme === "dark" ? "Thème clair" : "Thème sombre"}>
|
||||||
|
{theme === "dark" ? <SunIcon /> : <MoonIcon />}
|
||||||
|
</button>
|
||||||
|
<button className="user-btn" onClick={(e) => setUserMenu(userMenu ? null : e.currentTarget)} aria-haspopup="menu" aria-expanded={!!userMenu} title={`${user.name} (${user.id})`}>
|
||||||
|
<span className="avatar">{initials(user.name)}</span>
|
||||||
|
<span className="user-name">{user.name}</span>
|
||||||
|
{me.admin && me.mode !== "none" && <ShieldIcon size={14} />}
|
||||||
|
{!!me.pending && <small className="badge">{me.pending}</small>}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div className="layout">
|
||||||
|
{drawer && <div className="scrim" onClick={() => setDrawer(false)} />}
|
||||||
|
<aside className={`sidebar ${drawer ? "open" : ""}`}>
|
||||||
|
<nav>
|
||||||
|
<button className={`nav-item ${sel === "" ? "on" : ""}`} onClick={() => go("")} aria-current={sel === "" ? "page" : undefined}>
|
||||||
|
<ServerIcon />
|
||||||
|
<span>Tous les serveurs</span>
|
||||||
|
{!!sum?.updates && <small className="badge warn">{sum.updates}</small>}
|
||||||
|
</button>
|
||||||
|
{servers.map((s) => (
|
||||||
|
<button key={s.id} className={`nav-item ${sel === s.id ? "on" : ""}`} onClick={() => go(s.id)} aria-current={sel === s.id ? "page" : undefined} title={`${s.host}:${s.port}`}>
|
||||||
|
<i className={`dot ${dot(s)}`} aria-hidden />
|
||||||
|
<span>{s.name}</span>
|
||||||
|
{updatesOf(s) > 0 && <small className="badge warn">{updatesOf(s)}</small>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
<div className="sidebar-foot">
|
||||||
|
{me.admin && (
|
||||||
|
<>
|
||||||
|
<button onClick={() => (setServerDialog({}), setDrawer(false))}>
|
||||||
|
<PlusIcon />
|
||||||
|
Ajouter un serveur
|
||||||
|
</button>
|
||||||
|
<button onClick={() => (setKeyDialog(true), setDrawer(false))}>
|
||||||
|
<KeyIcon />
|
||||||
|
Clé SSH
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
{fleet && <small className="muted">{fleet.interval > 0 ? `Analyse automatique toutes les ${fmtInterval(fleet.interval)}` : "Analyse automatique désactivée"}</small>}
|
||||||
|
{me.version && me.version !== "dev" && <small className="muted">v{me.version}</small>}
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
<div className="splitter-line" />
|
||||||
|
<main className="main">
|
||||||
|
{error && (
|
||||||
|
<div className="error floating" onClick={() => setError(null)}>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<FleetView
|
||||||
|
me={me}
|
||||||
|
fleet={fleet}
|
||||||
|
current={current}
|
||||||
|
reload={load}
|
||||||
|
run={run}
|
||||||
|
onEdit={(id) => setServerDialog({ id })}
|
||||||
|
onAdd={() => setServerDialog({})}
|
||||||
|
onKey={() => setKeyDialog(true)}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{userMenu && (
|
||||||
|
<ActionMenu anchor={userMenu} onClose={() => setUserMenu(null)}>
|
||||||
|
<div className="menu-head">
|
||||||
|
<strong>{user.name}</strong>
|
||||||
|
<small className="muted">{user.email || user.id}</small>
|
||||||
|
<small className="muted">{me.admin && me.mode !== "none" ? "Administrateur" : ""}</small>
|
||||||
|
</div>
|
||||||
|
<hr />
|
||||||
|
{me.mode !== "none" && (
|
||||||
|
<button role="menuitem" onClick={() => setSettings("account")}>
|
||||||
|
<UserIcon />
|
||||||
|
Mon compte
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{me.admin && me.mode !== "none" && (
|
||||||
|
<button role="menuitem" onClick={() => setSettings("users")}>
|
||||||
|
<UsersIcon />
|
||||||
|
Utilisateurs{!!me.pending && ` (${me.pending} en attente)`}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{me.admin && (
|
||||||
|
<button role="menuitem" onClick={() => setKeyDialog(true)}>
|
||||||
|
<SettingsIcon />
|
||||||
|
Clé SSH
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{me.logout && (
|
||||||
|
<>
|
||||||
|
<hr />
|
||||||
|
<a role="menuitem" href={me.logout}>
|
||||||
|
<LogoutIcon />
|
||||||
|
Se déconnecter
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</ActionMenu>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{settings && <SettingsDialog me={me} initialTab={settings} onClose={() => setSettings(null)} onChanged={reloadMe} />}
|
||||||
|
{keyDialog && fleet && <KeyDialog publicKey={fleet.publicKey ?? ""} onClose={() => setKeyDialog(false)} />}
|
||||||
|
{serverDialog && (
|
||||||
|
<ServerDialog
|
||||||
|
server={servers.find((s) => s.id === serverDialog.id)}
|
||||||
|
publicKey={fleet?.publicKey ?? ""}
|
||||||
|
onClose={() => setServerDialog(null)}
|
||||||
|
onSaved={(id) => {
|
||||||
|
setServerDialog(null);
|
||||||
|
load();
|
||||||
|
if (id) go(id);
|
||||||
|
}}
|
||||||
|
onDeleted={() => {
|
||||||
|
setServerDialog(null);
|
||||||
|
go("");
|
||||||
|
load();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fmtInterval(seconds: number) {
|
||||||
|
if (seconds % 86400 === 0) return `${seconds / 86400} j`;
|
||||||
|
if (seconds % 3600 === 0) return `${seconds / 3600} h`;
|
||||||
|
return `${Math.round(seconds / 60)} min`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
function useEscape(onClose: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [onClose]);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PromptProps {
|
||||||
|
title: string;
|
||||||
|
label?: string;
|
||||||
|
initial?: string;
|
||||||
|
placeholder?: string;
|
||||||
|
submit?: string;
|
||||||
|
/** Sélectionne seulement le nom, sans l'extension (renommage d'un fichier). */
|
||||||
|
stem?: boolean;
|
||||||
|
onSubmit: (value: string) => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saisie d'un nom (nouveau dossier, renommage), à la place de prompt(). */
|
||||||
|
export function PromptDialog({ title, label, initial = "", placeholder, submit = "Valider", stem, onSubmit, onClose }: PromptProps) {
|
||||||
|
const [value, setValue] = useState(initial);
|
||||||
|
const ref = useRef<HTMLInputElement>(null);
|
||||||
|
useEscape(onClose);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const el = ref.current;
|
||||||
|
if (!el) return;
|
||||||
|
el.focus();
|
||||||
|
const dot = initial.lastIndexOf(".");
|
||||||
|
el.setSelectionRange(0, stem && dot > 0 ? dot : initial.length);
|
||||||
|
}, [initial, stem]);
|
||||||
|
|
||||||
|
const trimmed = value.trim();
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<form
|
||||||
|
className="modal small"
|
||||||
|
role="dialog"
|
||||||
|
aria-modal="true"
|
||||||
|
aria-label={title}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (trimmed) onSubmit(trimmed);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h3>{title}</h3>
|
||||||
|
<label className="field">
|
||||||
|
{label && <span>{label}</span>}
|
||||||
|
<input ref={ref} value={value} placeholder={placeholder} maxLength={255} onChange={(e) => setValue(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<div className="modal-actions">
|
||||||
|
<span className="spacer" />
|
||||||
|
<button type="button" onClick={onClose}>
|
||||||
|
Annuler
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="primary" disabled={!trimmed || trimmed === initial}>
|
||||||
|
{submit}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ConfirmProps {
|
||||||
|
title: string;
|
||||||
|
children: ReactNode;
|
||||||
|
confirm: string;
|
||||||
|
danger?: boolean;
|
||||||
|
onConfirm: () => void;
|
||||||
|
onClose: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Confirmation d'une action destructrice, à la place de confirm(). */
|
||||||
|
export function ConfirmDialog({ title, children, confirm, danger, onConfirm, onClose }: ConfirmProps) {
|
||||||
|
useEscape(onClose);
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal small" role="alertdialog" aria-modal="true" aria-label={title} onClick={(e) => e.stopPropagation()}>
|
||||||
|
<h3>{title}</h3>
|
||||||
|
<div className="modal-text">{children}</div>
|
||||||
|
<div className="modal-actions">
|
||||||
|
<span className="spacer" />
|
||||||
|
<button onClick={onClose}>Annuler</button>
|
||||||
|
<button autoFocus className={danger ? "primary danger-fill" : "primary"} onClick={onConfirm}>
|
||||||
|
{confirm}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import { api, type Me, type Fleet, type Scan, type Server, type Stack, type StackStatus, type Target } from "./api";
|
||||||
|
import { ConfirmDialog } from "./Dialogs";
|
||||||
|
import { fmtRelative, plural } from "./format";
|
||||||
|
import { ArrowUpIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon, ClockIcon, EditIcon, KeyIcon, PlusIcon, RefreshIcon, SearchIcon, ServerIcon, WarningIcon } from "./icons";
|
||||||
|
|
||||||
|
type Filter = "all" | "updates" | "problems";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
me: Me;
|
||||||
|
fleet: Fleet | null;
|
||||||
|
/** Serveur affiché ; absent : tous. */
|
||||||
|
current?: Server;
|
||||||
|
reload: () => Promise<unknown>;
|
||||||
|
run: (fn: () => Promise<unknown>) => Promise<void>;
|
||||||
|
onEdit: (id: string) => void;
|
||||||
|
onAdd: () => void;
|
||||||
|
onKey: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusLabel: Record<StackStatus, string> = {
|
||||||
|
uptodate: "À jour",
|
||||||
|
updates: "Mise à jour",
|
||||||
|
stopped: "Arrêtée",
|
||||||
|
error: "Erreur",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function FleetView({ me, fleet, current, run, onEdit, onAdd, onKey }: Props) {
|
||||||
|
const [filter, setFilter] = useState<Filter>("all");
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [applying, setApplying] = useState<{ server: Server; target: Target; stack: Stack } | null>(null);
|
||||||
|
|
||||||
|
const servers = useMemo(() => (current ? [current] : (fleet?.servers ?? [])), [current, fleet]);
|
||||||
|
|
||||||
|
if (!fleet) return <div className="splash muted">Chargement…</div>;
|
||||||
|
|
||||||
|
if (!fleet.servers.length) {
|
||||||
|
return (
|
||||||
|
<div className="empty-state">
|
||||||
|
<ServerIcon size={44} />
|
||||||
|
<h2>Aucun serveur</h2>
|
||||||
|
<p className="muted">
|
||||||
|
Ajoutez un serveur joignable en SSH : stackwatch y retrouve les stacks docker compose (dans <code>/home</code> par défaut) et vous dit lesquelles ont une nouvelle image.
|
||||||
|
</p>
|
||||||
|
{me.admin ? (
|
||||||
|
<div className="row-actions">
|
||||||
|
<button className="primary big" onClick={onAdd}>
|
||||||
|
<PlusIcon />
|
||||||
|
Ajouter un serveur
|
||||||
|
</button>
|
||||||
|
<button className="big" onClick={onKey}>
|
||||||
|
<KeyIcon />
|
||||||
|
Clé SSH à autoriser
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="muted">Un administrateur doit d'abord en déclarer.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!current && location.hash.replace(/^#\/?/, "")) {
|
||||||
|
return <div className="empty-state"><p className="muted">Serveur introuvable.</p></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compteurs du périmètre affiché.
|
||||||
|
const all = servers.flatMap((s) => Object.values(s.scans).flatMap((sc) => sc.stacks));
|
||||||
|
const count = (st: StackStatus) => all.filter((x) => x.status === st).length;
|
||||||
|
const unreachable = servers.reduce((n, s) => n + Object.values(s.scans).filter((sc) => sc.error).length, 0);
|
||||||
|
const scanning = servers.some((s) => Object.values(s.scans).some((sc) => sc.running));
|
||||||
|
const q = search.trim().toLowerCase();
|
||||||
|
|
||||||
|
const keep = (st: Stack) => {
|
||||||
|
if (filter === "updates" && st.status !== "updates") return false;
|
||||||
|
if (filter === "problems" && st.status !== "error") return false;
|
||||||
|
return !q || st.name.toLowerCase().includes(q) || st.dir.toLowerCase().includes(q) || (st.services ?? []).some((s) => s.image.toLowerCase().includes(q));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fleet">
|
||||||
|
<div className="head">
|
||||||
|
<div className="head-title">
|
||||||
|
<h2>{current ? current.name : "Tous les serveurs"}</h2>
|
||||||
|
{current && (
|
||||||
|
<span className="muted">
|
||||||
|
{current.host}
|
||||||
|
{current.port !== 22 ? `:${current.port}` : ""}
|
||||||
|
{current.note ? ` · ${current.note}` : ""}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="stats">
|
||||||
|
<span className="stat">{plural(all.length, "stack")}</span>
|
||||||
|
<span className={`stat ${count("updates") ? "warn" : ""}`}>{plural(count("updates"), "mise")} à jour à faire</span>
|
||||||
|
{count("error") > 0 && <span className="stat err">{plural(count("error"), "erreur")}</span>}
|
||||||
|
{unreachable > 0 && <span className="stat err">{plural(unreachable, "connexion")} en échec</span>}
|
||||||
|
{count("stopped") > 0 && <span className="stat">{plural(count("stopped"), "arrêtée")}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="toolbar">
|
||||||
|
<div className="segmented" role="group" aria-label="Filtre">
|
||||||
|
{(
|
||||||
|
[
|
||||||
|
["all", "Toutes"],
|
||||||
|
["updates", "Mises à jour"],
|
||||||
|
["problems", "Erreurs"],
|
||||||
|
] as [Filter, string][]
|
||||||
|
).map(([k, label]) => (
|
||||||
|
<button key={k} className={filter === k ? "on" : ""} onClick={() => setFilter(k)} aria-pressed={filter === k}>
|
||||||
|
{label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<label className="searchbox">
|
||||||
|
<SearchIcon />
|
||||||
|
<input type="search" placeholder="Stack, répertoire, image…" value={search} onChange={(e) => setSearch(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<span className="spacer" />
|
||||||
|
{current && (
|
||||||
|
<>
|
||||||
|
<button onClick={() => run(() => api.check(current.id))} disabled={scanning}>
|
||||||
|
<RefreshIcon className={scanning ? "spin" : ""} />
|
||||||
|
Vérifier
|
||||||
|
</button>
|
||||||
|
{me.admin && (
|
||||||
|
<button onClick={() => onEdit(current.id)}>
|
||||||
|
<EditIcon />
|
||||||
|
Modifier
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="scroll">
|
||||||
|
{servers.map((s) => (
|
||||||
|
<ServerBlock
|
||||||
|
key={s.id}
|
||||||
|
server={s}
|
||||||
|
single={!!current}
|
||||||
|
me={me}
|
||||||
|
keep={keep}
|
||||||
|
filtering={filter !== "all" || !!q}
|
||||||
|
onEdit={() => onEdit(s.id)}
|
||||||
|
onCheck={(t) => run(() => api.check(s.id, t))}
|
||||||
|
onApply={(target, stack) => setApplying({ server: s, target, stack })}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{applying && (
|
||||||
|
<ConfirmDialog
|
||||||
|
title="Mettre à jour la stack"
|
||||||
|
confirm="Mettre à jour"
|
||||||
|
onClose={() => setApplying(null)}
|
||||||
|
onConfirm={() => {
|
||||||
|
const a = applying;
|
||||||
|
setApplying(null);
|
||||||
|
run(() => api.applyStack(a.server.id, a.target.id, a.stack.dir));
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
Sur <strong>{applying.server.name}</strong>, <code>{applying.stack.dir}</code> : téléchargement des images, arrêt (<code>down</code>) puis redémarrage (<code>up -d</code>) de toute la stack, sous l'utilisateur{" "}
|
||||||
|
<code>{applying.target.user}</code>. Les services sont interrompus quelques instants.
|
||||||
|
</p>
|
||||||
|
</ConfirmDialog>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BlockProps {
|
||||||
|
server: Server;
|
||||||
|
single: boolean;
|
||||||
|
me: Me;
|
||||||
|
keep: (s: Stack) => boolean;
|
||||||
|
filtering: boolean;
|
||||||
|
onEdit: () => void;
|
||||||
|
onCheck: (targetId?: string) => void;
|
||||||
|
onApply: (t: Target, s: Stack) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ServerBlock({ server, single, me, keep, filtering, onEdit, onCheck, onApply }: BlockProps) {
|
||||||
|
const scans = Object.values(server.scans);
|
||||||
|
const running = scans.some((s) => s.running);
|
||||||
|
const last = scans.map((s) => s.finished).filter(Boolean).sort().pop();
|
||||||
|
const updates = scans.reduce((n, s) => n + s.stacks.filter((x) => x.status === "updates").length, 0);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="server-block">
|
||||||
|
{!single && (
|
||||||
|
<header className="server-head">
|
||||||
|
<ServerIcon size={18} />
|
||||||
|
<h3>{server.name}</h3>
|
||||||
|
<span className="muted">{server.host}</span>
|
||||||
|
{!server.enabled && <span className="pill">désactivé</span>}
|
||||||
|
{updates > 0 && <span className="pill warn">{plural(updates, "mise")} à jour</span>}
|
||||||
|
<span className="spacer" />
|
||||||
|
{last && (
|
||||||
|
<span className="muted small-text" title={new Date(last).toLocaleString()}>
|
||||||
|
<ClockIcon size={13} /> {fmtRelative(last)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<button className="icon-btn" onClick={() => onCheck()} disabled={running} aria-label={`Vérifier ${server.name}`} title="Vérifier ce serveur">
|
||||||
|
<RefreshIcon className={running ? "spin" : ""} />
|
||||||
|
</button>
|
||||||
|
{me.admin && (
|
||||||
|
<button className="icon-btn" onClick={onEdit} aria-label={`Modifier ${server.name}`} title="Modifier">
|
||||||
|
<EditIcon />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
)}
|
||||||
|
{server.targets.map((t) => (
|
||||||
|
<TargetBlock key={t.id} server={server} target={t} scan={server.scans[t.id]} me={me} keep={keep} filtering={filtering} onCheck={() => onCheck(t.id)} onApply={(s) => onApply(t, s)} />
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TargetBlock({ server, target, scan, me, keep, filtering, onCheck, onApply }: { server: Server; target: Target; scan?: Scan; me: Me; keep: (s: Stack) => boolean; filtering: boolean; onCheck: () => void; onApply: (s: Stack) => void }) {
|
||||||
|
const [open, setOpen] = useState<Record<string, boolean>>({});
|
||||||
|
const stacks = (scan?.stacks ?? []).filter(keep);
|
||||||
|
const hidden = (scan?.stacks.length ?? 0) - stacks.length;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="target">
|
||||||
|
<div className="target-head">
|
||||||
|
<code>
|
||||||
|
{target.user}@{server.host}
|
||||||
|
</code>
|
||||||
|
<span className="muted roots">{target.roots.join(" · ")}{target.depth > 1 ? ` (profondeur ${target.depth})` : ""}</span>
|
||||||
|
<span className="spacer" />
|
||||||
|
{scan?.running && (
|
||||||
|
<span className="muted small-text running">
|
||||||
|
<RefreshIcon size={13} className="spin" /> {scan.task === "apply" ? "Mise à jour" : "Analyse"}
|
||||||
|
{scan.current ? ` : ${scan.current.split("/").pop()}` : "…"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{!scan?.running && scan?.finished && (
|
||||||
|
<span className="muted small-text" title={new Date(scan.finished).toLocaleString()}>
|
||||||
|
vérifié {fmtRelative(scan.finished)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{scan?.compose && (
|
||||||
|
<span className="muted small-text" title={`docker ${scan.docker ?? "?"}, compose ${scan.compose}`}>
|
||||||
|
compose {scan.compose}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<button className="icon-btn" onClick={onCheck} disabled={scan?.running} aria-label={`Vérifier ${target.user}`} title="Vérifier cette connexion">
|
||||||
|
<RefreshIcon className={scan?.running ? "spin" : ""} />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{scan?.error && (
|
||||||
|
<div className="error static">
|
||||||
|
<WarningIcon /> {scan.error}
|
||||||
|
{scan.stacks.length > 0 && <span className="muted"> (dernier résultat conservé)</span>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{scan?.warnings?.map((w) => (
|
||||||
|
<div key={w} className="notice warn-notice">
|
||||||
|
<WarningIcon /> {w}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
|
{!scan && <p className="muted pad">Pas encore analysé.</p>}
|
||||||
|
{scan && !scan.error && !scan.running && scan.stacks.length === 0 && <p className="muted pad">Aucune stack compose trouvée sous ces racines.</p>}
|
||||||
|
{scan && scan.stacks.length > 0 && stacks.length === 0 && filtering && <p className="muted pad">Aucune stack ne correspond au filtre ({hidden} masquées).</p>}
|
||||||
|
|
||||||
|
{stacks.length > 0 && (
|
||||||
|
<ul className="stacks">
|
||||||
|
{stacks.map((st) => {
|
||||||
|
const isOpen = !!open[st.dir];
|
||||||
|
const [late, total] = [st.services?.filter((s) => s.state === "update").length ?? 0, st.services?.length ?? 0];
|
||||||
|
return (
|
||||||
|
<li key={st.dir} className={`stack st-${st.status} ${isOpen ? "open" : ""}`}>
|
||||||
|
<div className="stack-row" onClick={() => setOpen({ ...open, [st.dir]: !isOpen })}>
|
||||||
|
<button className="icon-btn" aria-expanded={isOpen} aria-label="Détails" onClick={(e) => (e.stopPropagation(), setOpen({ ...open, [st.dir]: !isOpen }))}>
|
||||||
|
{isOpen ? <ChevronDownIcon /> : <ChevronRightIcon />}
|
||||||
|
</button>
|
||||||
|
<span className={`status-pill st-${st.status}`}>
|
||||||
|
{st.status === "uptodate" && <CheckIcon size={13} />}
|
||||||
|
{st.status === "updates" && <ArrowUpIcon size={13} />}
|
||||||
|
{st.status === "error" && <WarningIcon size={13} />}
|
||||||
|
{statusLabel[st.status]}
|
||||||
|
</span>
|
||||||
|
<span className="stack-name">
|
||||||
|
<strong>{st.name}</strong>
|
||||||
|
<small className="muted">{st.dir}</small>
|
||||||
|
</span>
|
||||||
|
<span className="stack-meta muted">
|
||||||
|
{st.status === "error" ? <span className="error-text clip" title={st.error}>{st.error}</span> : total > 0 ? (late > 0 ? `${late}/${plural(total, "image")} à mettre à jour` : plural(total, "image")) : ""}
|
||||||
|
</span>
|
||||||
|
{me.admin && st.status === "updates" && (
|
||||||
|
<button className="primary" disabled={scan?.running} onClick={(e) => (e.stopPropagation(), onApply(st))} title="pull, down puis up -d">
|
||||||
|
<ArrowUpIcon />
|
||||||
|
Mettre à jour
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{isOpen && (
|
||||||
|
<div className="stack-detail">
|
||||||
|
<div className="muted small-text">
|
||||||
|
<code>{st.file}</code>
|
||||||
|
</div>
|
||||||
|
{st.error && <div className="error static">{st.error}</div>}
|
||||||
|
{total > 0 && (
|
||||||
|
<table className="services">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Service</th>
|
||||||
|
<th>Image</th>
|
||||||
|
<th>En cours</th>
|
||||||
|
<th>Disponible</th>
|
||||||
|
<th />
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{st.services!.map((s) => (
|
||||||
|
<tr key={s.name}>
|
||||||
|
<td>{s.name}</td>
|
||||||
|
<td>
|
||||||
|
<code>{s.image}</code>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<code>{s.running}</code>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<code>{s.latest || "?"}</code>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`svc ${s.state}`}>{s.state === "ok" ? "à jour" : s.state === "update" ? "nouvelle image" : "inconnu"}</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
{st.applied && (
|
||||||
|
<div className={`notice ${st.applied.ok ? "" : "warn-notice"}`}>
|
||||||
|
{st.applied.ok ? "Mise à jour effectuée" : "Mise à jour en échec"} le {new Date(st.applied.at).toLocaleString()} par {st.applied.by} : {st.applied.message}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { api, ApiError, type Me } from "./api";
|
||||||
|
import { StackIcon } from "./icons";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
me: Me;
|
||||||
|
/** Connexion ou inscription réussie (session ouverte) : recharge l'application. */
|
||||||
|
onLoggedIn: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Page de connexion : compte local, inscription (selon le mode choisi par l'administrateur) et bouton OIDC. */
|
||||||
|
export function Login({ me, onLoggedIn }: Props) {
|
||||||
|
const canRegister = me.local && (me.registration !== "closed" || !!me.setup);
|
||||||
|
const [mode, setMode] = useState<"login" | "register">(me.setup ? "register" : "login");
|
||||||
|
const [f, setF] = useState({ username: "", name: "", email: "", password: "", confirm: "" });
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [info, setInfo] = useState<string | null>(null);
|
||||||
|
const title = me.title || "Stackwatch";
|
||||||
|
const next = encodeURIComponent(location.pathname + location.search + location.hash);
|
||||||
|
|
||||||
|
const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement>) => setF({ ...f, [k]: e.target.value });
|
||||||
|
|
||||||
|
const submit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
setInfo(null);
|
||||||
|
if (mode === "register" && f.password !== f.confirm) {
|
||||||
|
setError("Les deux mots de passe sont différents.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
if (mode === "login") {
|
||||||
|
await api.login(f.username, f.password);
|
||||||
|
onLoggedIn();
|
||||||
|
} else {
|
||||||
|
const status = await api.register({ username: f.username, name: f.name, email: f.email, password: f.password });
|
||||||
|
if (status === "pending") {
|
||||||
|
setInfo("Compte créé. Un administrateur doit le valider avant votre première connexion.");
|
||||||
|
setMode("login");
|
||||||
|
setF({ ...f, password: "", confirm: "" });
|
||||||
|
} else onLoggedIn();
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof ApiError && err.code === "pending") setInfo("Votre compte est en attente de validation par un administrateur.");
|
||||||
|
else setError(err instanceof Error ? err.message : String(err));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="login">
|
||||||
|
<div className="login-card">
|
||||||
|
<div className="login-brand">
|
||||||
|
<StackIcon size={36} />
|
||||||
|
<h1>{title}</h1>
|
||||||
|
<p className="muted">Suivez les mises à jour de vos stacks docker compose.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{me.setup && (
|
||||||
|
<div className="notice">
|
||||||
|
<strong>Première utilisation.</strong> Le compte créé ici devient l'administrateur.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{info && <div className="notice">{info}</div>}
|
||||||
|
{error && <div className="error">{error}</div>}
|
||||||
|
|
||||||
|
{me.local && (
|
||||||
|
<form onSubmit={submit} className="form">
|
||||||
|
{canRegister && !me.setup && (
|
||||||
|
<div className="tabs" role="tablist">
|
||||||
|
<button type="button" role="tab" aria-selected={mode === "login"} className={mode === "login" ? "on" : ""} onClick={() => setMode("login")}>
|
||||||
|
Connexion
|
||||||
|
</button>
|
||||||
|
<button type="button" role="tab" aria-selected={mode === "register"} className={mode === "register" ? "on" : ""} onClick={() => setMode("register")}>
|
||||||
|
Créer un compte
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<label className="field">
|
||||||
|
<span>Identifiant</span>
|
||||||
|
<input autoFocus autoComplete="username" autoCapitalize="none" spellCheck={false} required value={f.username} onChange={set("username")} />
|
||||||
|
</label>
|
||||||
|
{mode === "register" && (
|
||||||
|
<>
|
||||||
|
<label className="field">
|
||||||
|
<span>Nom affiché (facultatif)</span>
|
||||||
|
<input autoComplete="name" maxLength={80} value={f.name} onChange={set("name")} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Adresse e-mail (facultatif)</span>
|
||||||
|
<input type="email" autoComplete="email" maxLength={120} value={f.email} onChange={set("email")} />
|
||||||
|
</label>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
<label className="field">
|
||||||
|
<span>{mode === "register" ? "Mot de passe (10 caractères minimum)" : "Mot de passe"}</span>
|
||||||
|
<input type="password" required minLength={mode === "register" ? 10 : undefined} autoComplete={mode === "login" ? "current-password" : "new-password"} value={f.password} onChange={set("password")} />
|
||||||
|
</label>
|
||||||
|
{mode === "register" && (
|
||||||
|
<label className="field">
|
||||||
|
<span>Confirmer le mot de passe</span>
|
||||||
|
<input type="password" required autoComplete="new-password" value={f.confirm} onChange={set("confirm")} />
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<button className="primary big" type="submit" disabled={busy}>
|
||||||
|
{mode === "login" ? "Se connecter" : me.setup ? "Créer l'administrateur" : "Créer mon compte"}
|
||||||
|
</button>
|
||||||
|
{mode === "register" && me.registration === "approval" && !me.setup && <p className="muted small-text">Votre compte devra être validé par un administrateur.</p>}
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{me.oidc && (
|
||||||
|
<>
|
||||||
|
{me.local && <div className="or">ou</div>}
|
||||||
|
<a className="ex-btn big" href={`/auth/login?next=${next}`}>
|
||||||
|
Se connecter avec {me.oidcName || "SSO"}
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,284 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { api, type PingResult, type Server, type ServerInput } from "./api";
|
||||||
|
import { ConfirmDialog } from "./Dialogs";
|
||||||
|
import { CheckIcon, CloseIcon, CopyIcon, PlusIcon, TrashIcon, WarningIcon } from "./icons";
|
||||||
|
|
||||||
|
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
||||||
|
|
||||||
|
function useEscape(onClose: () => void) {
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [onClose]);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copy(text: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TargetForm {
|
||||||
|
id?: string;
|
||||||
|
user: string;
|
||||||
|
roots: string;
|
||||||
|
depth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const emptyTarget = (): TargetForm => ({ user: "", roots: "/home", depth: 1 });
|
||||||
|
|
||||||
|
const toInput = (f: { name: string; host: string; port: string; note: string; enabled: boolean }, targets: TargetForm[]): ServerInput => ({
|
||||||
|
name: f.name,
|
||||||
|
host: f.host,
|
||||||
|
port: Number(f.port) || 22,
|
||||||
|
note: f.note,
|
||||||
|
enabled: f.enabled,
|
||||||
|
targets: targets.map((t) => ({ id: t.id, user: t.user.trim(), depth: t.depth, roots: t.roots.split(/[\n,]+/).map((r) => r.trim()).filter(Boolean) })),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Ajout ou modification d'un serveur : hôte SSH et connexions (utilisateur + racines à parcourir). */
|
||||||
|
export function ServerDialog({
|
||||||
|
server,
|
||||||
|
publicKey,
|
||||||
|
onClose,
|
||||||
|
onSaved,
|
||||||
|
onDeleted,
|
||||||
|
}: {
|
||||||
|
server?: Server;
|
||||||
|
publicKey: string;
|
||||||
|
onClose: () => void;
|
||||||
|
onSaved: (id?: string) => void;
|
||||||
|
onDeleted: () => void;
|
||||||
|
}) {
|
||||||
|
const [f, setF] = useState({
|
||||||
|
name: server?.name ?? "",
|
||||||
|
host: server?.host ?? "",
|
||||||
|
port: String(server?.port ?? 22),
|
||||||
|
note: server?.note ?? "",
|
||||||
|
enabled: server?.enabled ?? true,
|
||||||
|
});
|
||||||
|
const [targets, setTargets] = useState<TargetForm[]>(
|
||||||
|
server ? server.targets.map((t) => ({ id: t.id, user: t.user, roots: t.roots.join("\n"), depth: t.depth })) : [emptyTarget()],
|
||||||
|
);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [ping, setPing] = useState<PingResult[] | null>(null);
|
||||||
|
const [removing, setRemoving] = useState(false);
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
useEscape(onClose);
|
||||||
|
|
||||||
|
const set = (k: keyof typeof f) => (e: React.ChangeEvent<HTMLInputElement>) => setF({ ...f, [k]: k === "enabled" ? e.target.checked : e.target.value });
|
||||||
|
const setT = (i: number, v: Partial<TargetForm>) => setTargets(targets.map((t, j) => (j === i ? { ...t, ...v } : t)));
|
||||||
|
|
||||||
|
const test = async () => {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setPing(null);
|
||||||
|
try {
|
||||||
|
setPing(await api.testServer("-", toInput(f, targets)));
|
||||||
|
} catch (e) {
|
||||||
|
setError(msg(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const save = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = server ? await api.updateServer(server.id, toInput(f, targets)) : await api.addServer(toInput(f, targets));
|
||||||
|
onSaved(res.id);
|
||||||
|
} catch (e) {
|
||||||
|
setError(msg(e));
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const remove = async () => {
|
||||||
|
setRemoving(false);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await api.deleteServer(server!.id);
|
||||||
|
onDeleted();
|
||||||
|
} catch (e) {
|
||||||
|
setError(msg(e));
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<form className="modal wide" role="dialog" aria-modal="true" aria-label={server ? "Modifier le serveur" : "Ajouter un serveur"} onClick={(e) => e.stopPropagation()} onSubmit={save}>
|
||||||
|
<header className="settings-head flat">
|
||||||
|
<h3>{server ? `Serveur ${server.name}` : "Ajouter un serveur"}</h3>
|
||||||
|
<button type="button" className="icon-btn" onClick={onClose} aria-label="Fermer" title="Fermer (Échap)">
|
||||||
|
<CloseIcon />
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
{error && (
|
||||||
|
<div className="error" onClick={() => setError(null)}>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="form">
|
||||||
|
<div className="grid2">
|
||||||
|
<label className="field">
|
||||||
|
<span>Nom</span>
|
||||||
|
<input autoFocus required maxLength={80} value={f.name} onChange={set("name")} placeholder="lancelot" />
|
||||||
|
</label>
|
||||||
|
<div className="grid-host">
|
||||||
|
<label className="field">
|
||||||
|
<span>Hôte SSH</span>
|
||||||
|
<input required spellCheck={false} autoCapitalize="none" value={f.host} onChange={set("host")} placeholder="lancelot.home.naoned.net" />
|
||||||
|
</label>
|
||||||
|
<label className="field port">
|
||||||
|
<span>Port</span>
|
||||||
|
<input type="number" min={1} max={65535} value={f.port} onChange={set("port")} />
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label className="field">
|
||||||
|
<span>Note (facultative)</span>
|
||||||
|
<input maxLength={300} value={f.note} onChange={set("note")} placeholder="Hôte des stacks de prod" />
|
||||||
|
</label>
|
||||||
|
<label className="check-row">
|
||||||
|
<input type="checkbox" checked={f.enabled} onChange={set("enabled")} />
|
||||||
|
<span>Analyse automatique activée (désactivé : seulement à la demande)</span>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<h4>Connexions</h4>
|
||||||
|
<p className="muted small-text">
|
||||||
|
Une connexion = un utilisateur SSH et les répertoires où chercher des stacks (<code>compose.yaml</code>, <code>docker-compose.yml</code>…). Pour des stacks qui n'appartiennent qu'à un utilisateur, ajoutez une connexion sous cet utilisateur, avec son répertoire (ex. <code>/home/alice</code>) :
|
||||||
|
elles ne tournent alors qu'avec ses droits. L'utilisateur doit pouvoir utiliser docker.
|
||||||
|
</p>
|
||||||
|
{targets.map((t, i) => (
|
||||||
|
<div key={t.id ?? i} className="card target-form">
|
||||||
|
<div className="grid-target">
|
||||||
|
<label className="field">
|
||||||
|
<span>Utilisateur SSH</span>
|
||||||
|
<input required spellCheck={false} autoCapitalize="none" value={t.user} onChange={(e) => setT(i, { user: e.target.value })} placeholder="root" />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Profondeur</span>
|
||||||
|
<select value={t.depth} onChange={(e) => setT(i, { depth: Number(e.target.value) })} title="Niveaux de sous-répertoires parcourus sous chaque racine">
|
||||||
|
<option value={1}>1 : racine/stack</option>
|
||||||
|
<option value={2}>2 : racine/x/stack</option>
|
||||||
|
<option value={3}>3</option>
|
||||||
|
<option value={4}>4</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{targets.length > 1 && (
|
||||||
|
<button type="button" className="icon-btn danger" onClick={() => setTargets(targets.filter((_, j) => j !== i))} aria-label="Retirer cette connexion" title="Retirer cette connexion">
|
||||||
|
<TrashIcon />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<label className="field">
|
||||||
|
<span>Racines (une par ligne)</span>
|
||||||
|
<textarea rows={Math.min(5, Math.max(2, t.roots.split("\n").length))} spellCheck={false} value={t.roots} onChange={(e) => setT(i, { roots: e.target.value })} placeholder="/home" />
|
||||||
|
</label>
|
||||||
|
{ping && ping[i] && (
|
||||||
|
<div className={`ping ${ping[i].ok ? "ok" : "ko"}`}>
|
||||||
|
{ping[i].ok ? <CheckIcon size={14} /> : <WarningIcon size={14} />} {ping[i].message || (ping[i].ok ? "OK" : "échec")}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div>
|
||||||
|
<button type="button" onClick={() => setTargets([...targets, emptyTarget()])} disabled={targets.length >= 20}>
|
||||||
|
<PlusIcon />
|
||||||
|
Ajouter une connexion
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{publicKey && (
|
||||||
|
<details className="keyhelp">
|
||||||
|
<summary>Clé publique à autoriser sur le serveur</summary>
|
||||||
|
<p className="muted small-text">
|
||||||
|
À ajouter dans <code>~/.ssh/authorized_keys</code> de chaque utilisateur ci-dessus :
|
||||||
|
</p>
|
||||||
|
<pre className="example">{publicKey}</pre>
|
||||||
|
<button type="button" onClick={async () => setCopied(await copy(publicKey.trim()))}>
|
||||||
|
<CopyIcon />
|
||||||
|
{copied ? "Copiée" : "Copier"}
|
||||||
|
</button>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<div className="modal-actions">
|
||||||
|
{server && (
|
||||||
|
<button type="button" className="danger-outline" onClick={() => setRemoving(true)} disabled={busy}>
|
||||||
|
<TrashIcon />
|
||||||
|
Supprimer
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
<span className="spacer" />
|
||||||
|
<button type="button" onClick={test} disabled={busy || !f.host}>
|
||||||
|
Tester la connexion
|
||||||
|
</button>
|
||||||
|
<button type="button" onClick={onClose}>
|
||||||
|
Annuler
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="primary" disabled={busy}>
|
||||||
|
{server ? "Enregistrer" : "Ajouter"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
{removing && server && (
|
||||||
|
<ConfirmDialog title="Supprimer le serveur" confirm="Supprimer" danger onClose={() => setRemoving(false)} onConfirm={remove}>
|
||||||
|
<p>
|
||||||
|
Retirer <strong>{server.name}</strong> de stackwatch ? Rien n'est modifié sur le serveur.
|
||||||
|
</p>
|
||||||
|
</ConfirmDialog>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Clé publique SSH de stackwatch, à autoriser sur chaque serveur. */
|
||||||
|
export function KeyDialog({ publicKey, onClose }: { publicKey: string; onClose: () => void }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
useEscape(onClose);
|
||||||
|
const cmd = `echo '${publicKey.trim()}' >> ~/.ssh/authorized_keys`;
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal" role="dialog" aria-modal="true" aria-label="Clé SSH" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<header className="settings-head flat">
|
||||||
|
<h3>Clé SSH de stackwatch</h3>
|
||||||
|
<button className="icon-btn" onClick={onClose} aria-label="Fermer" title="Fermer (Échap)">
|
||||||
|
<CloseIcon />
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
{publicKey ? (
|
||||||
|
<>
|
||||||
|
<p>Stackwatch se connecte en SSH avec cette clé (créée au premier démarrage, stockée dans son volume de données). Ajoutez-la à chaque utilisateur déclaré sur vos serveurs :</p>
|
||||||
|
<pre className="example">{publicKey}</pre>
|
||||||
|
<p className="muted small-text">Sur le serveur, connecté en tant que cet utilisateur :</p>
|
||||||
|
<pre className="example">{cmd}</pre>
|
||||||
|
<p className="muted small-text">
|
||||||
|
L'utilisateur doit appartenir au groupe <code>docker</code> (ou faire tourner docker en mode rootless). Les clés d'hôte sont enregistrées à la première connexion puis vérifiées.
|
||||||
|
</p>
|
||||||
|
<div className="modal-actions">
|
||||||
|
<span className="spacer" />
|
||||||
|
<button onClick={async () => setCopied(await copy(publicKey.trim()))}>
|
||||||
|
<CopyIcon />
|
||||||
|
{copied ? "Copiée" : "Copier la clé"}
|
||||||
|
</button>
|
||||||
|
<button className="primary" onClick={onClose}>
|
||||||
|
Fermer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<p className="muted">Clé indisponible.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,367 @@
|
|||||||
|
import { useCallback, useEffect, useState } from "react";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import { api, type Account, type Me, type Role, type Status } from "./api";
|
||||||
|
import { CheckIcon, CloseIcon, KeyIcon, TrashIcon, UserIcon, UsersIcon } from "./icons";
|
||||||
|
import { ConfirmDialog } from "./Dialogs";
|
||||||
|
import { fmtDate, plural } from "./format";
|
||||||
|
|
||||||
|
type Tab = "account" | "users";
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
me: Me;
|
||||||
|
initialTab?: Tab;
|
||||||
|
onClose: () => void;
|
||||||
|
/** Comptes modifiés : le parent recharge /api/me. */
|
||||||
|
onChanged: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusLabel: Record<Status, string> = { active: "Actif", pending: "En attente", disabled: "Désactivé" };
|
||||||
|
|
||||||
|
const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));
|
||||||
|
|
||||||
|
/** Paramètres : compte ; pour les administrateurs, gestion des utilisateurs. */
|
||||||
|
export function SettingsDialog({ me, initialTab = "account", onClose, onChanged }: Props) {
|
||||||
|
const [tab, setTab] = useState<Tab>(initialTab);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
|
||||||
|
window.addEventListener("keydown", onKey);
|
||||||
|
return () => window.removeEventListener("keydown", onKey);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
const tabs: { id: Tab; label: string; icon: ReactNode; admin?: boolean; badge?: number }[] = [
|
||||||
|
{ id: "account", label: "Mon compte", icon: <UserIcon /> },
|
||||||
|
{ id: "users", label: "Utilisateurs", icon: <UsersIcon />, admin: true, badge: me.pending },
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="modal-backdrop" onClick={onClose}>
|
||||||
|
<div className="modal settings" role="dialog" aria-modal="true" aria-label="Paramètres" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<header className="settings-head">
|
||||||
|
<h3>Paramètres</h3>
|
||||||
|
<button className="icon-btn" onClick={onClose} aria-label="Fermer" title="Fermer (Échap)">
|
||||||
|
<CloseIcon />
|
||||||
|
</button>
|
||||||
|
</header>
|
||||||
|
<nav className="tabs" role="tablist">
|
||||||
|
{tabs
|
||||||
|
.filter((t) => !t.admin || me.admin)
|
||||||
|
.map((t) => (
|
||||||
|
<button
|
||||||
|
key={t.id}
|
||||||
|
role="tab"
|
||||||
|
aria-selected={tab === t.id}
|
||||||
|
className={tab === t.id ? "on" : ""}
|
||||||
|
onClick={() => {
|
||||||
|
setError(null);
|
||||||
|
setTab(t.id);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t.icon}
|
||||||
|
<span>{t.label}</span>
|
||||||
|
{!!t.badge && <small className="badge">{t.badge}</small>}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
|
{error && (
|
||||||
|
<div className="error" onClick={() => setError(null)}>
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="settings-body">
|
||||||
|
{tab === "account" && <AccountTab me={me} onError={setError} onChanged={onChanged} />}
|
||||||
|
{tab === "users" && me.admin && <UsersTab me={me} onError={setError} onChanged={onChanged} />}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// --- Mon compte ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
function AccountTab({ me, onError, onChanged }: { me: Me; onError: (m: string | null) => void; onChanged: () => void }) {
|
||||||
|
const u = me.user;
|
||||||
|
const [name, setName] = useState(u?.name ?? "");
|
||||||
|
const [email, setEmail] = useState(u?.email ?? "");
|
||||||
|
const [current, setCurrent] = useState("");
|
||||||
|
const [next, setNext] = useState("");
|
||||||
|
const [ok, setOk] = useState<string | null>(null);
|
||||||
|
const local = me.canChangePassword;
|
||||||
|
|
||||||
|
const run = async (fn: () => Promise<unknown>, done: string) => {
|
||||||
|
onError(null);
|
||||||
|
setOk(null);
|
||||||
|
try {
|
||||||
|
await fn();
|
||||||
|
setOk(done);
|
||||||
|
} catch (e) {
|
||||||
|
onError(msg(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="section">
|
||||||
|
<dl className="kv">
|
||||||
|
<dt>Identifiant</dt>
|
||||||
|
<dd>
|
||||||
|
<code>{u?.id}</code>
|
||||||
|
</dd>
|
||||||
|
<dt>Rôle</dt>
|
||||||
|
<dd>{u?.role === "admin" ? "Administrateur" : "Utilisateur"}</dd>
|
||||||
|
<dt>Connexion</dt>
|
||||||
|
<dd>{u?.provider === "oidc" ? "Fournisseur d'identité (OIDC)" : u?.provider === "local" ? "Compte local" : "Sans authentification intégrée"}</dd>
|
||||||
|
</dl>
|
||||||
|
{ok && <div className="notice">{ok}</div>}
|
||||||
|
{local ? (
|
||||||
|
<>
|
||||||
|
<form
|
||||||
|
className="form"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
run(async () => {
|
||||||
|
await api.patchAccount({ name, email });
|
||||||
|
onChanged();
|
||||||
|
}, "Profil enregistré.");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h4>Profil</h4>
|
||||||
|
<label className="field">
|
||||||
|
<span>Nom affiché</span>
|
||||||
|
<input value={name} maxLength={80} onChange={(e) => setName(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Adresse e-mail</span>
|
||||||
|
<input type="email" value={email} maxLength={120} onChange={(e) => setEmail(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<div>
|
||||||
|
<button className="primary" type="submit">
|
||||||
|
Enregistrer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<form
|
||||||
|
className="form"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
run(async () => {
|
||||||
|
await api.changePassword(current, next);
|
||||||
|
setCurrent("");
|
||||||
|
setNext("");
|
||||||
|
}, "Mot de passe modifié.");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h4>Mot de passe</h4>
|
||||||
|
<label className="field">
|
||||||
|
<span>Mot de passe actuel</span>
|
||||||
|
<input type="password" autoComplete="current-password" value={current} onChange={(e) => setCurrent(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Nouveau mot de passe (10 caractères minimum)</span>
|
||||||
|
<input type="password" autoComplete="new-password" minLength={10} value={next} onChange={(e) => setNext(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
<div>
|
||||||
|
<button className="primary" type="submit" disabled={!current || next.length < 10}>
|
||||||
|
Changer le mot de passe
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<p className="muted">Le nom, l'adresse et le mot de passe de ce compte sont gérés par votre fournisseur d'identité.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
function UsersTab({ me, onError, onChanged }: { me: Me; onError: (m: string | null) => void; onChanged: () => void }) {
|
||||||
|
const [users, setUsers] = useState<Account[] | null>(null);
|
||||||
|
const [form, setForm] = useState({ username: "", name: "", email: "", password: "", role: "user" as Role });
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
const [removing, setRemoving] = useState<Account | null>(null);
|
||||||
|
const [resetting, setResetting] = useState<Account | null>(null);
|
||||||
|
const [newPassword, setNewPassword] = useState("");
|
||||||
|
|
||||||
|
const load = useCallback(() => api.users().then(setUsers).catch((e) => onError(msg(e))), [onError]);
|
||||||
|
useEffect(() => {
|
||||||
|
load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const patch = async (u: Account, v: Parameters<typeof api.patchUser>[1]) => {
|
||||||
|
onError(null);
|
||||||
|
try {
|
||||||
|
await api.patchUser(u.id, v);
|
||||||
|
await load();
|
||||||
|
onChanged();
|
||||||
|
} catch (e) {
|
||||||
|
onError(msg(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const create = async () => {
|
||||||
|
onError(null);
|
||||||
|
try {
|
||||||
|
await api.createUser(form);
|
||||||
|
setForm({ username: "", name: "", email: "", password: "", role: "user" });
|
||||||
|
setCreating(false);
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
onError(msg(e));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="section">
|
||||||
|
<div className="row-between">
|
||||||
|
<span className="muted">{users ? plural(users.length, "compte") : ""}</span>
|
||||||
|
<button className="primary" onClick={() => setCreating(!creating)}>
|
||||||
|
{creating ? "Annuler" : "Créer un compte local"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{creating && (
|
||||||
|
<form
|
||||||
|
className="form card"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
create();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="grid2">
|
||||||
|
<label className="field">
|
||||||
|
<span>Identifiant</span>
|
||||||
|
<input value={form.username} autoComplete="off" onChange={(e) => setForm({ ...form, username: e.target.value })} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Nom affiché</span>
|
||||||
|
<input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Adresse e-mail</span>
|
||||||
|
<input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Mot de passe (10 caractères minimum)</span>
|
||||||
|
<input type="password" autoComplete="new-password" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
|
||||||
|
</label>
|
||||||
|
<label className="field">
|
||||||
|
<span>Rôle</span>
|
||||||
|
<select value={form.role} onChange={(e) => setForm({ ...form, role: e.target.value as Role })}>
|
||||||
|
<option value="user">Utilisateur</option>
|
||||||
|
<option value="admin">Administrateur</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<button className="primary" type="submit" disabled={form.username.length < 3 || form.password.length < 10}>
|
||||||
|
Créer
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
<div className="table-wrap">
|
||||||
|
<table className="users">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Compte</th>
|
||||||
|
<th>Origine</th>
|
||||||
|
<th>Rôle</th>
|
||||||
|
<th>État</th>
|
||||||
|
<th>Dernière connexion</th>
|
||||||
|
<th />
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{users?.map((u) => (
|
||||||
|
<tr key={u.id} className={u.status}>
|
||||||
|
<td>
|
||||||
|
<strong>{u.name}</strong>
|
||||||
|
<small className="muted"> {u.id}</small>
|
||||||
|
{u.email && u.email !== u.id && <small className="muted block">{u.email}</small>}
|
||||||
|
</td>
|
||||||
|
<td>{u.provider === "oidc" ? "OIDC" : "Local"}</td>
|
||||||
|
<td>
|
||||||
|
<select value={u.role} onChange={(e) => patch(u, { role: e.target.value as Role })} aria-label={`Rôle de ${u.id}`}>
|
||||||
|
<option value="user">Utilisateur</option>
|
||||||
|
<option value="admin">Administrateur</option>
|
||||||
|
</select>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
<span className={`status ${u.status}`}>{statusLabel[u.status]}</span>
|
||||||
|
</td>
|
||||||
|
<td className="muted">{u.lastLogin ? fmtDate(u.lastLogin) : "jamais"}</td>
|
||||||
|
<td className="actions-cell">
|
||||||
|
{u.status === "pending" && (
|
||||||
|
<button className="primary" onClick={() => patch(u, { status: "active" })}>
|
||||||
|
<CheckIcon />
|
||||||
|
<span>Valider</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{u.status === "active" && u.id !== me.user?.id && <button onClick={() => patch(u, { status: "disabled" })}>Désactiver</button>}
|
||||||
|
{u.status === "disabled" && <button onClick={() => patch(u, { status: "active" })}>Réactiver</button>}
|
||||||
|
{u.provider === "local" && (
|
||||||
|
<button className="icon-btn" onClick={() => setResetting(u)} title="Nouveau mot de passe" aria-label={`Nouveau mot de passe pour ${u.id}`}>
|
||||||
|
<KeyIcon />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{u.id !== me.user?.id && (
|
||||||
|
<button className="icon-btn danger" onClick={() => setRemoving(u)} title="Supprimer le compte" aria-label={`Supprimer ${u.id}`}>
|
||||||
|
<TrashIcon />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{resetting && (
|
||||||
|
<ConfirmDialog
|
||||||
|
title={`Nouveau mot de passe pour ${resetting.id}`}
|
||||||
|
confirm="Changer"
|
||||||
|
onClose={() => {
|
||||||
|
setResetting(null);
|
||||||
|
setNewPassword("");
|
||||||
|
}}
|
||||||
|
onConfirm={async () => {
|
||||||
|
const u = resetting;
|
||||||
|
setResetting(null);
|
||||||
|
await patch(u, { password: newPassword });
|
||||||
|
setNewPassword("");
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<label className="field">
|
||||||
|
<span>Mot de passe (10 caractères minimum)</span>
|
||||||
|
<input type="password" autoFocus autoComplete="new-password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} />
|
||||||
|
</label>
|
||||||
|
</ConfirmDialog>
|
||||||
|
)}
|
||||||
|
{removing && (
|
||||||
|
<ConfirmDialog
|
||||||
|
title="Supprimer le compte"
|
||||||
|
confirm="Supprimer"
|
||||||
|
danger
|
||||||
|
onClose={() => setRemoving(null)}
|
||||||
|
onConfirm={async () => {
|
||||||
|
const u = removing;
|
||||||
|
setRemoving(null);
|
||||||
|
onError(null);
|
||||||
|
try {
|
||||||
|
await api.deleteUser(u.id);
|
||||||
|
await load();
|
||||||
|
onChanged();
|
||||||
|
} catch (e) {
|
||||||
|
onError(msg(e));
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<p>
|
||||||
|
Supprimer le compte de <strong>{removing.name}</strong> ({removing.id}) ? Ses sessions sont révoquées.
|
||||||
|
</p>
|
||||||
|
</ConfirmDialog>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
// Client de l'API Go (voir internal/api/api.go).
|
||||||
|
|
||||||
|
export type Role = "admin" | "user";
|
||||||
|
export type Status = "active" | "pending" | "disabled";
|
||||||
|
export type Registration = "closed" | "approval" | "open";
|
||||||
|
|
||||||
|
/** Session courante et réglages publics (GET /api/me, accessible sans connexion). */
|
||||||
|
export interface Me {
|
||||||
|
mode: "none" | "local" | "oidc" | "both";
|
||||||
|
local: boolean;
|
||||||
|
oidc: boolean;
|
||||||
|
oidcName?: string;
|
||||||
|
registration: Registration;
|
||||||
|
/** Aucun administrateur : le premier compte créé le devient. */
|
||||||
|
setup?: boolean;
|
||||||
|
title: string;
|
||||||
|
version?: string;
|
||||||
|
user?: { id: string; name: string; email?: string; role: Role; provider?: "local" | "oidc" };
|
||||||
|
admin: boolean;
|
||||||
|
canChangePassword?: boolean;
|
||||||
|
logout?: string;
|
||||||
|
/** Administrateur : inscriptions à valider. */
|
||||||
|
pending?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Account {
|
||||||
|
id: string;
|
||||||
|
username?: string;
|
||||||
|
name: string;
|
||||||
|
email?: string;
|
||||||
|
provider: "local" | "oidc";
|
||||||
|
role: Role;
|
||||||
|
status: Status;
|
||||||
|
created: string;
|
||||||
|
lastLogin?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Suivi des stacks --------------------------------------------------------------
|
||||||
|
|
||||||
|
export type StackStatus = "uptodate" | "updates" | "stopped" | "error";
|
||||||
|
|
||||||
|
export interface Target {
|
||||||
|
id: string;
|
||||||
|
user: string;
|
||||||
|
roots: string[];
|
||||||
|
depth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Service {
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
running: string;
|
||||||
|
latest: string;
|
||||||
|
state: "ok" | "update" | "unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Applied {
|
||||||
|
at: string;
|
||||||
|
by: string;
|
||||||
|
ok: boolean;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Stack {
|
||||||
|
dir: string;
|
||||||
|
name: string;
|
||||||
|
file: string;
|
||||||
|
status: StackStatus;
|
||||||
|
error?: string;
|
||||||
|
services?: Service[];
|
||||||
|
applied?: Applied;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Scan {
|
||||||
|
running: boolean;
|
||||||
|
task?: "scan" | "apply";
|
||||||
|
current?: string;
|
||||||
|
started?: string;
|
||||||
|
finished?: string;
|
||||||
|
error?: string;
|
||||||
|
warnings?: string[];
|
||||||
|
stacks: Stack[];
|
||||||
|
docker?: string;
|
||||||
|
compose?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ServerInput {
|
||||||
|
id?: string;
|
||||||
|
name: string;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
note?: string;
|
||||||
|
enabled: boolean;
|
||||||
|
targets: { id?: string; user: string; roots: string[]; depth: number }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Server extends ServerInput {
|
||||||
|
id: string;
|
||||||
|
targets: Target[];
|
||||||
|
/** Résultat de chaque connexion, par identifiant de connexion. */
|
||||||
|
scans: Record<string, Scan>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Summary {
|
||||||
|
servers: number;
|
||||||
|
stacks: number;
|
||||||
|
updates: number;
|
||||||
|
errors: number;
|
||||||
|
stopped: number;
|
||||||
|
unreachable: number;
|
||||||
|
scanning: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Fleet {
|
||||||
|
servers: Server[];
|
||||||
|
summary: Summary;
|
||||||
|
/** Secondes entre deux analyses automatiques (0 : désactivées). */
|
||||||
|
interval: number;
|
||||||
|
/** Administrateur : clé publique SSH à autoriser sur les serveurs. */
|
||||||
|
publicKey?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PingResult {
|
||||||
|
target: string;
|
||||||
|
user: string;
|
||||||
|
ok: boolean;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
public status: number,
|
||||||
|
message: string,
|
||||||
|
public code?: string,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function request(url: string, init?: RequestInit): Promise<Response> {
|
||||||
|
const res = await fetch(url, init);
|
||||||
|
if (!res.ok) {
|
||||||
|
// Session OIDC expirée : reconnexion, puis retour sur la page courante.
|
||||||
|
const login = res.status === 401 ? res.headers.get("X-Auth-Login") : null;
|
||||||
|
if (login) location.assign(`${login}?next=${encodeURIComponent(location.pathname + location.search + location.hash)}`);
|
||||||
|
let msg = res.statusText;
|
||||||
|
let code: string | undefined;
|
||||||
|
try {
|
||||||
|
const j = await res.json();
|
||||||
|
msg = j.error ?? msg;
|
||||||
|
code = j.code;
|
||||||
|
} catch {
|
||||||
|
/* corps non JSON */
|
||||||
|
}
|
||||||
|
throw new ApiError(res.status, msg, code);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
const q = (p: string) => encodeURIComponent(p);
|
||||||
|
|
||||||
|
const json = (body: unknown, method = "POST"): RequestInit => ({
|
||||||
|
method,
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const api = {
|
||||||
|
me: async (): Promise<Me> => (await request("/api/me")).json(),
|
||||||
|
|
||||||
|
// --- Connexion ---------------------------------------------------------------
|
||||||
|
login: async (username: string, password: string): Promise<void> => {
|
||||||
|
await request("/auth/local/login", json({ username, password }));
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Renvoie « active » (connecté d'office) ou « pending » (à valider par un administrateur). */
|
||||||
|
register: async (v: { username: string; name: string; email: string; password: string }): Promise<"active" | "pending"> => {
|
||||||
|
const res = await request("/auth/local/register", json(v));
|
||||||
|
return (await res.json()).status;
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Serveurs et analyses ----------------------------------------------------
|
||||||
|
fleet: async (): Promise<Fleet> => (await request("/api/fleet")).json(),
|
||||||
|
|
||||||
|
checkAll: async (): Promise<void> => {
|
||||||
|
await request("/api/check", { method: "POST" });
|
||||||
|
},
|
||||||
|
|
||||||
|
check: async (serverId: string, targetId?: string): Promise<void> => {
|
||||||
|
await request(`/api/servers/${q(serverId)}/check${targetId ? `?target=${q(targetId)}` : ""}`, { method: "POST" });
|
||||||
|
},
|
||||||
|
|
||||||
|
addServer: async (v: ServerInput): Promise<{ id: string }> => (await request("/api/servers", json(v))).json(),
|
||||||
|
|
||||||
|
updateServer: async (id: string, v: ServerInput): Promise<{ id: string }> => (await request(`/api/servers/${q(id)}`, json(v, "PUT"))).json(),
|
||||||
|
|
||||||
|
deleteServer: async (id: string): Promise<void> => {
|
||||||
|
await request(`/api/servers/${q(id)}`, { method: "DELETE" });
|
||||||
|
},
|
||||||
|
|
||||||
|
/** Teste la connexion SSH, docker et docker compose (id « - » : serveur pas encore enregistré, décrit par v). */
|
||||||
|
testServer: async (id: string, v?: ServerInput): Promise<PingResult[]> =>
|
||||||
|
(await request(`/api/servers/${q(id)}/test`, v ? json(v) : { method: "POST" })).json(),
|
||||||
|
|
||||||
|
applyStack: async (serverId: string, targetId: string, dir: string): Promise<void> => {
|
||||||
|
await request(`/api/servers/${q(serverId)}/targets/${q(targetId)}/apply`, json({ dir }));
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Compte ------------------------------------------------------------------
|
||||||
|
changePassword: async (current: string, next: string): Promise<void> => {
|
||||||
|
await request("/api/account/password", json({ current, new: next }));
|
||||||
|
},
|
||||||
|
|
||||||
|
patchAccount: async (v: { name?: string; email?: string }): Promise<void> => {
|
||||||
|
await request("/api/account", json(v, "PATCH"));
|
||||||
|
},
|
||||||
|
|
||||||
|
// --- Administration ----------------------------------------------------------
|
||||||
|
users: async (): Promise<Account[]> => (await request("/api/admin/users")).json(),
|
||||||
|
|
||||||
|
createUser: async (v: { username: string; name: string; email: string; password: string; role: Role }): Promise<Account> =>
|
||||||
|
(await request("/api/admin/users", json(v))).json(),
|
||||||
|
|
||||||
|
patchUser: async (id: string, v: Partial<{ name: string; email: string; role: Role; status: Status; password: string }>): Promise<Account> =>
|
||||||
|
(await request(`/api/admin/users/${q(id)}`, json(v, "PATCH"))).json(),
|
||||||
|
|
||||||
|
deleteUser: async (id: string): Promise<void> => {
|
||||||
|
await request(`/api/admin/users/${q(id)}`, { method: "DELETE" });
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
// Mise en forme des dates, tailles et auteurs (explorateur, panneau Détails).
|
||||||
|
|
||||||
|
export const fmtDate = (iso: string) => new Date(iso).toLocaleString(undefined, { dateStyle: "short", timeStyle: "short" });
|
||||||
|
|
||||||
|
export const fmtSize = (n: number) => {
|
||||||
|
if (n < 1024) return `${n} o`;
|
||||||
|
const units = ["Ko", "Mo", "Go", "To"];
|
||||||
|
let v = n / 1024;
|
||||||
|
let i = 0;
|
||||||
|
while (v >= 1024 && i < units.length - 1) {
|
||||||
|
v /= 1024;
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
return `${v >= 100 ? v.toFixed(0) : v.toFixed(1)} ${units[i]}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const fmtRate = (bytesPerSecond: number) => `${fmtSize(bytesPerSecond)}/s`;
|
||||||
|
|
||||||
|
export const plural = (n: number, word: string) => `${n} ${word}${n > 1 ? "s" : ""}`;
|
||||||
|
|
||||||
|
const relative = new Intl.RelativeTimeFormat("fr", { numeric: "auto" });
|
||||||
|
|
||||||
|
/** « à l'instant », « il y a 5 minutes », « hier »… puis la date au-delà d'un mois. */
|
||||||
|
export const fmtRelative = (iso: string) => {
|
||||||
|
const s = (Date.now() - new Date(iso).getTime()) / 1000;
|
||||||
|
if (s < 60) return "à l'instant";
|
||||||
|
if (s < 3600) return relative.format(-Math.round(s / 60), "minute");
|
||||||
|
if (s < 86400) return relative.format(-Math.round(s / 3600), "hour");
|
||||||
|
if (s < 30 * 86400) return relative.format(-Math.round(s / 86400), "day");
|
||||||
|
return new Date(iso).toLocaleDateString(undefined, { dateStyle: "medium" });
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Auteur affichable : rien pour l'utilisateur unique sans authentification. */
|
||||||
|
export const who = (id?: string) => (id && id !== "local" ? id : "");
|
||||||
|
|
||||||
|
/** Initiales d'un nom pour l'avatar. */
|
||||||
|
export const initials = (name: string) =>
|
||||||
|
name
|
||||||
|
.split(/[\s._@-]+/)
|
||||||
|
.filter(Boolean)
|
||||||
|
.slice(0, 2)
|
||||||
|
.map((p) => p[0].toUpperCase())
|
||||||
|
.join("") || "?";
|
||||||
@@ -0,0 +1,414 @@
|
|||||||
|
// Icônes de l'interface : jeu Papicons (formes pleines, couleur héritée via currentColor),
|
||||||
|
// identique à celui d'Excalicloud (frontend/src/icons.tsx) pour que les deux outils se ressemblent.
|
||||||
|
// Les tracés Papicons sont dans papicons.ts ; les quelques icônes absentes du jeu sont
|
||||||
|
// dessinées ici dans le même esprit (formes pleines arrondies, ou trait épais à bouts ronds).
|
||||||
|
import { useId, type ReactNode } from "react";
|
||||||
|
import * as P from "./papicons";
|
||||||
|
import type { PapPath } from "./papicons";
|
||||||
|
|
||||||
|
type IconProps = { size?: number; className?: string };
|
||||||
|
|
||||||
|
/** Identifiant de masque SVG unique et sûr dans url(#…). */
|
||||||
|
function useMaskId() {
|
||||||
|
return "m" + useId().replace(/[^a-zA-Z0-9_-]/g, "");
|
||||||
|
}
|
||||||
|
|
||||||
|
function Svg({ size = 16, className, children }: IconProps & { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className} aria-hidden>
|
||||||
|
{children}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const paths = (p: PapPath[]) =>
|
||||||
|
p.map((x, i) => <path key={i} d={x.d} fillRule={x.evenodd ? "evenodd" : undefined} clipRule={x.evenodd ? "evenodd" : undefined} />);
|
||||||
|
|
||||||
|
/** Icône Papicons telle quelle. */
|
||||||
|
export const pap = (p: PapPath[], transform?: string) =>
|
||||||
|
function Icon({ size, className }: IconProps) {
|
||||||
|
return (
|
||||||
|
<Svg size={size} className={className}>
|
||||||
|
<g transform={transform}>{paths(p)}</g>
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Icône au trait, pour les icônes de dossiers sans équivalent Papicons (trait 2, plus appuyé que Tabler). */
|
||||||
|
export const icon = (children: ReactNode) =>
|
||||||
|
function Icon({ size = 16, className }: IconProps) {
|
||||||
|
return (
|
||||||
|
<svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round" className={className} aria-hidden>
|
||||||
|
{children}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Icône pleine dessinée ici. */
|
||||||
|
const solid = (children: ReactNode) =>
|
||||||
|
function Icon({ size, className }: IconProps) {
|
||||||
|
return <Svg size={size} className={className}>{children}</Svg>;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Icône au trait épais (graisse des flèches Papicons), pour les symboles absents du jeu. */
|
||||||
|
const line = (children: ReactNode) =>
|
||||||
|
function Icon({ size = 16, className }: IconProps) {
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
className={className}
|
||||||
|
width={size}
|
||||||
|
height={size}
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={2.5}
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
aria-hidden
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Icône Papicons avec une pastille en bas à droite (le fond est évidé autour de la pastille). */
|
||||||
|
const badged = (base: PapPath[], badge: PapPath[]) =>
|
||||||
|
function Icon({ size }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<circle cx="18" cy="18" r="7" fill="#000" />
|
||||||
|
</mask>
|
||||||
|
<g mask={`url(#${id})`}>{paths(base)}</g>
|
||||||
|
<g transform="translate(18 18) scale(0.5) translate(-12 -12)">{paths(badge)}</g>
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Thème, barre du haut, panneaux.
|
||||||
|
/** Soleil dessiné ici : celui de Papicons ressemble trop à la roue dentée des Paramètres. */
|
||||||
|
export const SunIcon = solid(
|
||||||
|
<>
|
||||||
|
<circle cx="12" cy="12" r="4.5" />
|
||||||
|
<path
|
||||||
|
d="M12 2.5v1.5M12 20v1.5M2.5 12H4M20 12h1.5M5.3 5.3l1.05 1.05M17.65 17.65l1.05 1.05M5.3 18.7l1.05-1.05M17.65 6.35l1.05-1.05"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={2.5}
|
||||||
|
strokeLinecap="round"
|
||||||
|
/>
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
export const MoonIcon = pap(P.Moon);
|
||||||
|
export const SettingsIcon = pap(P.Gears);
|
||||||
|
export const MenuIcon = pap(P.Menu);
|
||||||
|
export const CloseIcon = pap(P.Cross);
|
||||||
|
export const UpdateIcon = pap(P.Sparkles);
|
||||||
|
export const UserIcon = pap(P.User);
|
||||||
|
export const LogoutIcon = pap(P.Logout);
|
||||||
|
export const InfoIcon = pap(P.Info);
|
||||||
|
export const LinkIcon = pap(P.Link);
|
||||||
|
export const SearchIcon = pap(P.Search);
|
||||||
|
|
||||||
|
// Fichiers et dossiers.
|
||||||
|
export const FolderIcon = pap(P.Folder);
|
||||||
|
export const FileIcon = pap(P.Paper);
|
||||||
|
export const FilePlusIcon = badged(P.Paper, P.Add);
|
||||||
|
export const FolderPlusIcon = badged(P.Folder, P.Add);
|
||||||
|
export const FolderUploadIcon = badged(P.Folder, P.ArrowUpBox);
|
||||||
|
export const MoveIcon = badged(P.Folder, P.ArrowRightBox);
|
||||||
|
export const UploadIcon = pap(P.ArrowUpBox);
|
||||||
|
export const DownloadIcon = pap(P.ArrowDownBox);
|
||||||
|
/** Dossier parent (« .. »). */
|
||||||
|
export const UpIcon = pap(P.ArrowLeftUp);
|
||||||
|
export const EditIcon = pap(P.PenAlt);
|
||||||
|
export const SelectAllIcon = pap(P.Tasks);
|
||||||
|
export const DeselectIcon = pap(P.Placeholder);
|
||||||
|
/** Menu d'actions « … » : points à l'horizontale. */
|
||||||
|
export const DotsIcon = pap(P.Dots, "rotate(90 12 12)");
|
||||||
|
|
||||||
|
// Vues de l'explorateur.
|
||||||
|
export const ListIcon = pap(P.List);
|
||||||
|
export const GridIcon = pap(P.Grid);
|
||||||
|
export const GalleryIcon = pap(P.Gallery);
|
||||||
|
|
||||||
|
// Poubelle.
|
||||||
|
export const TrashIcon = pap(P.Trash);
|
||||||
|
/** Poubelle qui contient des éléments : pastille pleine sur le couvercle. */
|
||||||
|
export function TrashFullIcon({ size }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<circle cx="19.5" cy="4.5" r="4.5" fill="#000" />
|
||||||
|
</mask>
|
||||||
|
<g mask={`url(#${id})`}>{paths(P.Trash)}</g>
|
||||||
|
<circle cx="19.5" cy="4.5" r="3" />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Favoris : étoile pleine (favori) ou évidée (pas favori), même silhouette.
|
||||||
|
export const StarFilledIcon = pap(P.Star);
|
||||||
|
export function StarIcon({ size }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<g fill="#000" transform="translate(12 13) scale(0.45) translate(-12 -13)">
|
||||||
|
{paths(P.Star)}
|
||||||
|
</g>
|
||||||
|
</mask>
|
||||||
|
<g mask={`url(#${id})`}>{paths(P.Star)}</g>
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Actions sans équivalent dans Papicons.
|
||||||
|
export const RefreshIcon = line(
|
||||||
|
<>
|
||||||
|
<path d="M19.5 10.5A7.8 7.8 0 0 0 5 8.5M4.5 4.5v4h4" />
|
||||||
|
<path d="M4.5 13.5A7.8 7.8 0 0 0 19 15.5m.5 4v-4h-4" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const RestoreIcon = line(<path d="M9 14.5 4.5 10 9 5.5M4.5 10h11a4.5 4.5 0 1 1 0 9H14" />);
|
||||||
|
|
||||||
|
export const HistoryIcon = line(
|
||||||
|
<>
|
||||||
|
<path d="M12 8v4l2.5 2" />
|
||||||
|
<path d="M3.5 11a8.6 8.6 0 1 1 .6 4M3.5 20v-5h5" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const SortIcon = line(<path d="M4 6h9M4 12h7M4 18h5M17.5 4.5v15M14.5 16.5l3 3 3-3" />);
|
||||||
|
|
||||||
|
export const CopyIcon = function CopyIcon({ size }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<rect x="7" y="7" width="16" height="16" rx="5" fill="#000" />
|
||||||
|
</mask>
|
||||||
|
<rect x="3" y="3" width="12.5" height="12.5" rx="3.5" mask={`url(#${id})`} />
|
||||||
|
<rect x="9" y="9" width="12" height="12" rx="3.5" />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const SaveIcon = function SaveIcon({ size }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<rect x="7.5" y="1" width="7.5" height="6.5" rx="1.5" fill="#000" />
|
||||||
|
<circle cx="12" cy="15" r="2.75" fill="#000" />
|
||||||
|
</mask>
|
||||||
|
<path mask={`url(#${id})`} d="M7 3h8.2c.8 0 1.56.32 2.12.88l2.8 2.8c.56.56.88 1.32.88 2.12V17a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V7a4 4 0 0 1 4-4z" />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const TagIcon = solid(
|
||||||
|
<path
|
||||||
|
fillRule="evenodd"
|
||||||
|
clipRule="evenodd"
|
||||||
|
d="M3 6a3 3 0 0 1 3-3h4.76a3 3 0 0 1 2.12.88l7.9 7.9a3 3 0 0 1 0 4.24l-4.76 4.76a3 3 0 0 1-4.24 0l-7.9-7.9A3 3 0 0 1 3 10.76zm5 .25a1.75 1.75 0 1 0 0 3.5 1.75 1.75 0 0 0 0-3.5z"
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const ShareIcon = solid(
|
||||||
|
<>
|
||||||
|
<path d="M6 12 17.5 5.5M6 12l11.5 6.5" fill="none" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" />
|
||||||
|
<circle cx="6" cy="12" r="3.25" />
|
||||||
|
<circle cx="17.5" cy="5.5" r="3.25" />
|
||||||
|
<circle cx="17.5" cy="18.5" r="3.25" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const EyeIcon = solid(
|
||||||
|
<path
|
||||||
|
fillRule="evenodd"
|
||||||
|
clipRule="evenodd"
|
||||||
|
d="M12 5c4.3 0 7.6 2.7 9.5 6.1.3.56.3 1.24 0 1.8C19.6 16.3 16.3 19 12 19s-7.6-2.7-9.5-6.1a1.9 1.9 0 0 1 0-1.8C4.4 7.7 7.7 5 12 5m0 3.5a3.5 3.5 0 1 0 0 7 3.5 3.5 0 0 0 0-7m0 2a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3"
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
/** Punaise : panneau épinglé ou flottant. */
|
||||||
|
export const PinIcon = solid(
|
||||||
|
<g transform="rotate(35 12 12)">
|
||||||
|
<path d="M8.5 3h7a1.5 1.5 0 0 1 0 3H15v4l2.6 2.4c.95.88.33 2.6-1 2.6H7.4c-1.33 0-1.95-1.72-1-2.6L9 10V6h-.5a1.5 1.5 0 0 1 0-3z" />
|
||||||
|
<path d="M12 15v6" stroke="currentColor" strokeWidth={2.5} strokeLinecap="round" />
|
||||||
|
</g>,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Métadonnées des schémas (vue Galerie, panneau Détails).
|
||||||
|
export const ClockIcon = pap(P.Clock);
|
||||||
|
export const TextIcon = pap(P.Font);
|
||||||
|
export const PhotoIcon = pap(P.Camera);
|
||||||
|
export const ArrowIcon = pap(P.ArrowRightUp);
|
||||||
|
/** Taille du fichier. */
|
||||||
|
export const SizeIcon = pap(P.Archive);
|
||||||
|
|
||||||
|
export const ShapesIcon = solid(
|
||||||
|
<>
|
||||||
|
<rect x="3" y="3" width="8.5" height="8.5" rx="2.5" />
|
||||||
|
<circle cx="17" cy="17" r="4.25" />
|
||||||
|
<path d="M15.7 3.75a1.5 1.5 0 0 1 2.6 0l3.2 5.5A1.5 1.5 0 0 1 20.2 11.5h-6.4a1.5 1.5 0 0 1-1.3-2.25z" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const FrameIcon = line(<path d="M4 7.5h16M4 16.5h16M7.5 4v16M16.5 4v16" />);
|
||||||
|
|
||||||
|
// --- Propres à Up And Down : types de fichiers, aperçu, comptes ----------------------
|
||||||
|
// Même esprit : Papicons quand l'équivalent existe, sinon formes pleines ou trait épais.
|
||||||
|
|
||||||
|
/** Feuille Papicons dont un motif est évidé (types de fichiers). */
|
||||||
|
const page = (glyph: ReactNode) =>
|
||||||
|
function Icon({ size, className }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size} className={className}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<g fill="none" stroke="#000" strokeWidth={1.6} strokeLinecap="round" strokeLinejoin="round">
|
||||||
|
{glyph}
|
||||||
|
</g>
|
||||||
|
</mask>
|
||||||
|
<g mask={`url(#${id})`}>{paths(P.Paper)}</g>
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const FileTextIcon = page(<path d="M8.5 14.5h7M8.5 17.5h5" />);
|
||||||
|
export const FileCodeIcon = page(<path d="M10.5 13.5l-2 2.25 2 2.25M13.5 13.5l2 2.25-2 2.25" />);
|
||||||
|
export const FileZipIcon = page(
|
||||||
|
<>
|
||||||
|
<path d="M8.5 7h1.5M8.5 9.5h1.5M8.5 12h1.5" />
|
||||||
|
<rect x="8" y="14.5" width="3.5" height="4" rx="1" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
export const FileMusicIcon = page(
|
||||||
|
<>
|
||||||
|
<circle cx="10.5" cy="17.5" r="1.4" />
|
||||||
|
<path d="M11.9 17.5V13.5l2.6 1" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
export const FileVideoIcon = page(<path d="M10.5 13.5v5l4-2.5z" fill="#000" />);
|
||||||
|
export const FilePdfIcon = page(
|
||||||
|
<path d="M8.5 18.5v-4.5h1.3a1.3 1.3 0 0 1 0 2.6H8.5M12.7 14v4.5M12.7 14h.8a1.6 1.6 0 0 1 1.6 1.6v1.3a1.6 1.6 0 0 1-1.6 1.6h-.8" />,
|
||||||
|
);
|
||||||
|
export const FileSheetIcon = page(<path d="M8.5 14h7M8.5 17h7M12 13v6" />);
|
||||||
|
export const FileSlidesIcon = page(<path d="M9 18.5v-2M12 18.5v-4.5M15 18.5v-3" />);
|
||||||
|
export const FileImageIcon = page(
|
||||||
|
<>
|
||||||
|
<circle cx="9.75" cy="14" r="1" fill="#000" />
|
||||||
|
<path d="M8.5 18.5l2.75-2.5 1.75 1.5 2.5-2.5" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const PlayIcon = solid(<path d="M7 5.1v13.8a1.3 1.3 0 0 0 2 1.1l11-6.9a1.3 1.3 0 0 0 0-2.2L9 4a1.3 1.3 0 0 0-2 1.1z" />);
|
||||||
|
|
||||||
|
export const ChevronLeftIcon = line(<path d="M15 5.5 8.5 12l6.5 6.5" />);
|
||||||
|
export const ChevronRightIcon = line(<path d="M9 5.5 15.5 12 9 18.5" />);
|
||||||
|
export const ChevronDownIcon = line(<path d="M5.5 9 12 15.5 18.5 9" />);
|
||||||
|
|
||||||
|
export const LockIcon = pap(P.Lock);
|
||||||
|
|
||||||
|
export const KeyIcon = line(
|
||||||
|
<>
|
||||||
|
<circle cx="8" cy="15.5" r="3.75" />
|
||||||
|
<path d="M10.75 12.75 19 4.5M16.5 7l2.5 2.5M14 9.5l2 2" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const UsersIcon = solid(
|
||||||
|
<>
|
||||||
|
<circle cx="9" cy="7.75" r="3.75" />
|
||||||
|
<path d="M2.5 19a5.5 5.5 0 0 1 5.5-5.5h2a5.5 5.5 0 0 1 5.5 5.5v.5a1.5 1.5 0 0 1-1.5 1.5H4a1.5 1.5 0 0 1-1.5-1.5z" />
|
||||||
|
<circle cx="16.5" cy="7.25" r="3" />
|
||||||
|
<path d="M17 13.5h.5A4.5 4.5 0 0 1 22 18v1a1.5 1.5 0 0 1-1.5 1.5h-3.2c.13-.33.2-.69.2-1.07V19c0-2.1-.9-4-2.3-5.3.6-.13 1.2-.2 1.8-.2z" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const ShieldIcon = solid(
|
||||||
|
<path d="M11.3 2.7a2 2 0 0 1 1.4 0l6.5 2.4c.8.3 1.3 1 1.3 1.9V12c0 4.6-3.3 8.4-8 9.4a2.4 2.4 0 0 1-1 0c-4.7-1-8-4.8-8-9.4V7c0-.9.5-1.6 1.3-1.9z" />,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const CheckIcon = line(<path d="M5 12.5l4.5 4.5L19 7.5" />);
|
||||||
|
|
||||||
|
export const PlusIcon = pap(P.Add);
|
||||||
|
|
||||||
|
export const HomeIcon = solid(
|
||||||
|
<path d="M10.6 3.6a2 2 0 0 1 2.8 0l7 6.6c.4.38.6.9.6 1.45V18a3 3 0 0 1-3 3h-3v-5a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v5H6a3 3 0 0 1-3-3v-6.35c0-.55.22-1.07.6-1.45z" />,
|
||||||
|
);
|
||||||
|
|
||||||
|
export const TableIcon = line(
|
||||||
|
<>
|
||||||
|
<rect x="3.5" y="4.5" width="17" height="15" rx="3" />
|
||||||
|
<path d="M3.5 10h17M10 10v9.5" />
|
||||||
|
</>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const cloud = "M7 19.5a5 5 0 0 1-.6-9.96 6.5 6.5 0 0 1 12.4 1.56A4.25 4.25 0 0 1 17.5 19.5z";
|
||||||
|
export const CloudIcon = solid(<path d={cloud} />);
|
||||||
|
/** Nuage avec une flèche vers le haut évidée : logo par défaut. */
|
||||||
|
export function CloudUpIcon({ size, className }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size} className={className}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<path d="M12 17v-5.5M9.25 14 12 11.25 14.75 14" fill="none" stroke="#000" strokeWidth={2.25} strokeLinecap="round" strokeLinejoin="round" />
|
||||||
|
</mask>
|
||||||
|
<path d={cloud} mask={`url(#${id})`} />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ExpandIcon = line(<path d="M4.5 9.5v-5h5M19.5 9.5v-5h-5M4.5 14.5v5h5M19.5 14.5v5h-5" />);
|
||||||
|
|
||||||
|
export const CopyLinkIcon = CopyIcon;
|
||||||
|
|
||||||
|
export function WarningIcon({ size, className }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size} className={className}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<path d="M12 9.5v4" stroke="#000" strokeWidth={2.25} strokeLinecap="round" />
|
||||||
|
<circle cx="12" cy="17" r="1.25" fill="#000" />
|
||||||
|
</mask>
|
||||||
|
<path mask={`url(#${id})`} d="M10.27 3.98a2 2 0 0 1 3.46 0l8.02 13.9A2 2 0 0 1 20.02 21H3.98a2 2 0 0 1-1.73-3.12z" />
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Serveur : deux boîtiers empilés, voyants évidés. */
|
||||||
|
export function ServerIcon({ size, className }: IconProps) {
|
||||||
|
const id = useMaskId();
|
||||||
|
return (
|
||||||
|
<Svg size={size} className={className}>
|
||||||
|
<mask id={id}>
|
||||||
|
<rect width="24" height="24" fill="#fff" />
|
||||||
|
<circle cx="7" cy="7.5" r="1.2" fill="#000" />
|
||||||
|
<circle cx="7" cy="16.5" r="1.2" fill="#000" />
|
||||||
|
</mask>
|
||||||
|
<g mask={`url(#${id})`}>
|
||||||
|
<rect x="2.5" y="3.5" width="19" height="8" rx="2.4" />
|
||||||
|
<rect x="2.5" y="12.5" width="19" height="8" rx="2.4" />
|
||||||
|
</g>
|
||||||
|
</Svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Couches empilées : logo (stacks docker compose). */
|
||||||
|
export const StackIcon = line(<path d="M12 3.2 3.2 8 12 12.8 20.8 8 12 3.2zM3.2 12 12 16.8 20.8 12M3.2 16 12 20.8 20.8 16" />);
|
||||||
|
|
||||||
|
/** Flèche vers le haut dans un cercle : mise à jour disponible. */
|
||||||
|
export const ArrowUpIcon = line(<path d="M12 19V5.5M6 11.5l6-6 6 6" />);
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { StrictMode } from "react";
|
||||||
|
import { createRoot } from "react-dom/client";
|
||||||
|
import "./styles.css";
|
||||||
|
import App from "./App";
|
||||||
|
|
||||||
|
createRoot(document.getElementById("root")!).render(
|
||||||
|
<StrictMode>
|
||||||
|
<App />
|
||||||
|
</StrictMode>,
|
||||||
|
);
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// Tracés extraits de Papicons 0.2.3 (@getpapillon/papicons, https://github.com/PapillonApp/papicons),
|
||||||
|
// icônes de Tom Things pour Papillon. Licence MIT, (c) 2025 Association Papillon : voir THIRD_PARTY_NOTICES.md.
|
||||||
|
// Grille 24 x 24, formes pleines. Seules les icônes utilisées par Excalicloud sont reprises.
|
||||||
|
|
||||||
|
export type PapPath = { d: string; evenodd?: boolean };
|
||||||
|
|
||||||
|
export const Add: PapPath[] = [
|
||||||
|
{ d: "M20.414 10.515c.375.374.586.916.586 1.485s-.21 1.112-.585 1.486a1.8 1.8 0 0 1-1.415.515l-.35-.025-5.035-.36.36 5.035.026.349c.038.53-.14 1.04-.515 1.415-.374.375-.917.585-1.486.585s-1.111-.211-1.485-.586A1.79 1.79 0 0 1 10 19.001l.026-.35.36-5.036-5.037.36L5 14a1.79 1.79 0 0 1-1.413-.515C3.21 13.111 3 12.57 3 12s.21-1.112.585-1.486A1.8 1.8 0 0 1 5 10l.35.024 5.034.36L10 5c-.039-.53.138-1.04.514-1.415C10.888 3.21 11.431 3 12 3s1.111.211 1.485.586c.376.375.553.883.515 1.413l-.026.35-.359 5.036 5.036-.36L19 10a1.79 1.79 0 0 1 1.413.515" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Archive: PapPath[] = [
|
||||||
|
{ d: "M12.935 9.076c3.192-.1 4.79-.15 5.381.368.066.057.089.08.148.144.536.576.536 1.92.536 4.605 0 2.641 0 3.962-.774 4.819a3 3 0 0 1-.214.214c-.857.774-2.178.774-4.819.774h-2.386c-2.641 0-3.962 0-4.819-.774a3 3 0 0 1-.214-.214C5 18.155 5 16.834 5 14.193c0-2.686 0-4.03.536-4.605.06-.064.082-.087.148-.144.592-.517 2.189-.468 5.381-.368a30 30 0 0 0 1.87 0M12 12c-.713 0-1.275.017-1.695.037C9.668 12.068 9 12.363 9 13s.668.932 1.305.963c.42.02.982.037 1.695.037s1.275-.017 1.695-.037C14.332 13.932 15 13.637 15 13s-.668-.932-1.305-.963A35 35 0 0 0 12 12m6.65-8c.745 0 1.35.605 1.35 1.35 0 .663-.48 1.224-1.138 1.297C17.547 6.795 15.151 7 12 7c-3.15 0-5.546-.205-6.862-.353A1.29 1.29 0 0 1 4 5.351C4 4.605 4.605 4 5.35 4z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ArrowDownBox: PapPath[] = [
|
||||||
|
{ d: "M21 12c0 1.483-.072 2.748-.178 3.805-.274 2.723-2.293 4.743-5.016 5.016a38 38 0 0 1-3.806.18c-1.483 0-2.748-.073-3.805-.18-2.723-.273-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.294-4.741 5.016-5.015A38 38 0 0 1 12 3c1.483 0 2.75.073 3.806.179 2.723.274 4.742 2.293 5.016 5.015C20.928 9.251 21 10.517 21 12m-4.122.828a1 1 0 1 0-1.414-1.414l-2.366 2.367.268-5.228.017-.322a1.23 1.23 0 0 0-.355-.944c-.25-.25-.606-.39-.978-.39s-.728.14-.978.39-.373.59-.355.944l.017.322.26 5.046-2.185-2.185a1 1 0 0 0-1.414 1.414l4.034 4.035c.39.39 1.024.39 1.415 0z", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ArrowLeftUp: PapPath[] = [
|
||||||
|
{ d: "M4.5 15a1.5 1.5 0 0 0 3 0V9.621l9.44 9.44a1.5 1.5 0 1 0 2.12-2.122L9.622 7.5h5.38a1.5 1.5 0 0 0 0-3H6A1.5 1.5 0 0 0 4.5 6z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ArrowRightBox: PapPath[] = [
|
||||||
|
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.274 4.743 2.293 5.017 5.015C20.928 9.251 21 10.517 21 12s-.072 2.748-.178 3.805c-.274 2.723-2.294 4.743-5.017 5.016a38 38 0 0 1-3.805.18c-1.483 0-2.749-.073-3.805-.18-2.723-.274-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.293-4.741 5.016-5.015A38 38 0 0 1 12 3m.828 4.122a1 1 0 1 0-1.414 1.414l2.367 2.367-5.228-.27-.322-.016a1.23 1.23 0 0 0-.944.356c-.25.25-.39.606-.39.977 0 .372.14.728.39.978s.59.374.944.355l.322-.016 5.046-.261-2.185 2.185a1 1 0 0 0 1.414 1.415l4.035-4.035c.391-.39.391-1.024 0-1.415z", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ArrowRightUp: PapPath[] = [
|
||||||
|
{ d: "M19.5 15a1.5 1.5 0 0 1-3 0V9.621l-9.44 9.44a1.5 1.5 0 1 1-2.12-2.122L14.378 7.5H9a1.5 1.5 0 1 1 0-3h9A1.5 1.5 0 0 1 19.5 6z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const ArrowUpBox: PapPath[] = [
|
||||||
|
{ d: "M21 12c0-1.483-.072-2.748-.178-3.805-.274-2.722-2.293-4.742-5.016-5.016A38 38 0 0 0 12 3c-1.483 0-2.748.073-3.805.179-2.723.274-4.742 2.293-5.016 5.016A38 38 0 0 0 3 12c0 1.483.073 2.75.179 3.806.274 2.723 2.294 4.742 5.016 5.015 1.057.107 2.322.18 3.805.18a38 38 0 0 0 3.806-.18c2.723-.274 4.742-2.292 5.016-5.015.106-1.057.178-2.323.178-3.806m-4.122-.828a1 1 0 0 1-1.414 1.414l-2.366-2.367.268 5.228.017.323c.018.353-.105.693-.355.943s-.606.39-.978.39-.728-.14-.978-.39-.373-.59-.355-.943l.017-.323.26-5.045-2.185 2.184a1 1 0 0 1-1.414-1.414l4.034-4.035c.39-.39 1.024-.39 1.415 0z", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Calendar: PapPath[] = [
|
||||||
|
{ d: "M3 6.125C3 4.399 4.4 3 6.125 3h11.75C19.601 3 21 4.4 21 6.125 21 7.161 20.16 8 19.125 8H4.875A1.875 1.875 0 0 1 3 6.125M18.174 10.005a3 3 0 0 1 2.821 2.821c.003.048.002.101.002.174H17a4 4 0 0 0-4 4v3.99c-.373.009-.804.01-1.313.01h-2.4c-2.133 0-3.2 0-4.022-.396a4 4 0 0 1-1.869-1.869C3 17.913 3 16.846 3 14.714c0-1.6 0-2.399.297-3.016a3 3 0 0 1 1.401-1.401C5.315 10 6.115 10 7.714 10h10.065c.205 0 .308 0 .395.005" },
|
||||||
|
{ d: "M17 15h3.64c-.181.397-.426.766-.73 1.089-.04.042-.083.084-.168.169l-2.4 2.4c-1.087 1.087-1.665 1.66-2.342 1.978V17a2 2 0 0 1 1.796-1.99z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Camera: PapPath[] = [
|
||||||
|
{ d: "M12 11a2 2 0 1 1 0 4 2 2 0 0 1 0-4" },
|
||||||
|
{ d: "M12 4c1.73 0 3.103.853 3.963 2.153l-.102-.01c2.674.213 4.812 2.038 5.048 4.71A24 24 0 0 1 21 13a24 24 0 0 1-.09 2.148c-.237 2.671-2.375 4.496-5.049 4.708A49 49 0 0 1 12 20c-1.51 0-2.793-.058-3.861-.144-2.674-.213-4.812-2.037-5.048-4.709A24 24 0 0 1 3 13c0-.796.035-1.51.09-2.148.237-2.671 2.375-4.496 5.049-4.708q-.052.003-.103.01C8.896 4.851 10.27 4 12 4m0 5a4 4 0 1 0 0 8 4 4 0 0 0 0-8", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Clock: PapPath[] = [
|
||||||
|
{ d: "M12 3a9 9 0 1 1 0 18 9 9 0 0 1 0-18m0 3a1 1 0 0 0-1 1v3.93c0 .334-.167.647-.445.832l-2.11 1.406a1 1 0 0 0 1.11 1.665l2.11-1.407A3 3 0 0 0 13 10.93V7a1 1 0 0 0-1-1", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Code: PapPath[] = [
|
||||||
|
{ d: "M7.898 4.009c.52-.104 1.088.021 1.56.336s.806.79.91 1.31-.03 1.043-.355 1.463l-.221.286-3.553 4.605 3.553 4.604.22.287c.326.42.46.942.355 1.462-.103.52-.437.996-.909 1.31-.472.316-1.04.441-1.56.337a1.8 1.8 0 0 1-1.213-.89l-.18-.314q-1.612-2.826-3.226-5.65l-.178-.314a1.44 1.44 0 0 1-.182-.615v-.436a1.44 1.44 0 0 1 .182-.613l.178-.314 3.226-5.65.18-.313a1.8 1.8 0 0 1 1.213-.891M13.94 4.345c.472-.315 1.04-.44 1.559-.336.52.104.95.429 1.214.89l.18.314 3.225 5.65.179.314c.141.248.2.54.181.83.02.293-.04.585-.181.834l-.179.313-3.225 5.65-.18.314a1.8 1.8 0 0 1-1.214.89c-.52.105-1.087-.02-1.56-.335-.472-.315-.805-.791-.909-1.31-.104-.52.03-1.043.355-1.463l.22-.287 3.553-4.604-3.553-4.605-.22-.286a1.8 1.8 0 0 1-.355-1.463c.104-.52.437-.995.91-1.31" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Cross: PapPath[] = [
|
||||||
|
{ d: "M17.958 3.958c.53 0 1.059.23 1.456.628.397.397.628.926.628 1.456s-.23 1.02-.628 1.372l-.317.282L14.253 12l4.844 4.304.317.282c.397.353.628.841.628 1.372 0 .53-.23 1.059-.628 1.456-.397.397-.926.628-1.456.628s-1.02-.23-1.372-.628l-.282-.317L12 14.253l-4.304 4.844-.282.317a1.82 1.82 0 0 1-1.372.628c-.53 0-1.059-.23-1.456-.628-.398-.397-.628-.926-.628-1.456s.23-1.02.628-1.372l.317-.282L9.746 12 4.903 7.696l-.317-.282a1.82 1.82 0 0 1-.628-1.372c0-.53.23-1.059.628-1.456.397-.398.926-.628 1.456-.628s1.02.23 1.372.628l.282.317L12 9.746l4.304-4.843.282-.317a1.82 1.82 0 0 1 1.372-.628" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Dots: PapPath[] = [
|
||||||
|
{ d: "M10 12a2 2 0 1 1 4 0 2 2 0 0 1-4 0M10 6a2 2 0 1 1 4 0 2 2 0 0 1-4 0M10 18a2 2 0 1 1 4 0 2 2 0 0 1-4 0" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Folder: PapPath[] = [
|
||||||
|
{ d: "M18.295 12c1.462 0 2.194 0 2.618.373.19.166.334.378.42.614.193.531-.073 1.213-.603 2.575-.71 1.822-1.066 2.733-1.725 3.353a4 4 0 0 1-1.018.695c-.816.39-1.795.39-3.75.39H9.831c-1.945 0-2.917 0-3.727-.382a4 4 0 0 1-1.12-.787c-.634-.633-.964-1.548-1.624-3.378-.468-1.3-.702-1.952-.521-2.459a1.5 1.5 0 0 1 .458-.651C3.714 12 4.405 12 5.788 12zM8.7 4c.484 0 .726 0 .947.05a2 2 0 0 1 1.063.638c.148.171.262.385.49.812s.341.64.49.812a2 2 0 0 0 1.063.637c.22.05.463.051.947.051H17a3 3 0 0 1 3 3H4V8.571c0-1.464 0-2.197.25-2.77A3 3 0 0 1 5.8 4.25C6.374 4 7.106 4 8.57 4z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Font: PapPath[] = [
|
||||||
|
{ d: "M8.303 5.71c1.362-3.297 6.032-3.297 7.394 0l2.29 5.542 2.817 5.885a2 2 0 1 1-3.608 1.726l-.878-1.834H7.682l-.878 1.834a2 2 0 1 1-3.608-1.726l2.816-5.885zm1.39 7.112-.022.051-.024.049-.051.107h4.808l-.052-.107-.023-.049-.021-.05L12 7.236z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Gallery: PapPath[] = [
|
||||||
|
{ d: "M12 3c1.483 0 2.748.072 3.805.179 2.723.273 4.743 2.293 5.016 5.016C20.927 9.252 21 10.517 21 12s-.073 2.748-.179 3.805c-.274 2.723-2.293 4.743-5.016 5.016A38 38 0 0 1 12 21c-1.483 0-2.748-.073-3.805-.179-2.723-.274-4.743-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.072-2.748.179-3.805.273-2.723 2.293-4.743 5.016-5.016A38 38 0 0 1 12 3M9.842 13.212a2 2 0 0 0-2.683 0l-1.628 1.47a1.1 1.1 0 0 0-.362.923c.179 1.777 1.45 3.047 3.226 3.226.988.1 2.187.169 3.605.169s2.617-.07 3.605-.169c1.217-.122 2.195-.758 2.747-1.717.357-.617.082-1.366-.447-1.844l-.063-.058a2 2 0 0 0-2.683 0l-.212.191a2 2 0 0 1-2.681 0zM15 7a2 2 0 1 0 0 4 2 2 0 0 0 0-4" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Gears: PapPath[] = [
|
||||||
|
{ d: "M12 3c.593 0 1.309.202 1.892.412.66.238.99.948.822 1.63l-.183.746c-.098.4.114.809.47 1.016.357.207.814.184 1.112-.102l.555-.531c.508-.486 1.287-.557 1.824-.104.473.4 1.006.92 1.302 1.433.297.514.48 1.235.59 1.845.124.69-.328 1.33-1.002 1.527l-.739.215c-.396.115-.643.5-.643.913 0 .412.246.797.642.913l.741.216c.674.197 1.125.835 1 1.526-.11.61-.292 1.331-.589 1.845-.296.514-.829 1.032-1.302 1.433-.537.453-1.316.383-1.824-.103l-.555-.532c-.298-.286-.754-.31-1.112-.103-.356.207-.569.616-.47 1.016l.183.747c.167.682-.161 1.393-.822 1.63-.583.21-1.3.412-1.892.412-.594 0-1.309-.201-1.892-.411-.66-.238-.99-.949-.822-1.631l.182-.748c.098-.4-.114-.809-.47-1.015-.358-.206-.814-.183-1.112.103l-.554.532c-.508.486-1.288.556-1.824.103-.473-.4-1.006-.92-1.302-1.433-.297-.514-.48-1.235-.59-1.845-.125-.69.327-1.33 1-1.526l.74-.216c.396-.115.644-.5.644-.913 0-.412-.248-.798-.644-.913l-.74-.215c-.673-.196-1.124-.836-1-1.527.11-.61.293-1.331.59-1.845.296-.514.829-1.032 1.302-1.433.537-.453 1.316-.382 1.824.104l.554.531c.298.285.754.309 1.112.102.356-.207.568-.615.47-1.016l-.182-.746c-.167-.682.161-1.392.822-1.63.583-.21 1.298-.412 1.891-.412m0 6a3 3 0 1 0 0 6 3 3 0 0 0 0-6", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Globe: PapPath[] = [
|
||||||
|
{ d: "M12 2c5.523 0 10 4.477 10 10s-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2M4.74 9a.24.24 0 0 0-.22.16A8 8 0 0 0 12 20c.509 0 1-.328 1-.837a1.837 1.837 0 0 0-1.837-1.836H8.826a1.044 1.044 0 0 1 0-2.087h.043c.6 0 1.087-.486 1.087-1.087v-.51c0-.881-.714-1.596-1.596-1.596h-.358a1.523 1.523 0 0 1-1.523-1.524C6.479 9.683 5.796 9 4.955 9zm7.778-1.774a1.703 1.703 0 0 0 1.185 2.925h1.873A2.425 2.425 0 0 1 18 12.576v.924c0 .294.084.567.23.798.457.723 1.428.168 1.602-.669q.166-.79.168-1.629a7.99 7.99 0 0 0-3.654-6.717c-.679-.44-1.556-.262-2.136.3z", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Grid: PapPath[] = [
|
||||||
|
{ d: "M7 13c.552 0 1.036.023 1.454.058 1.364.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.363-1.124 2.374-2.488 2.488C8.036 20.977 7.552 21 7 21s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.125-2.488-2.488A17 17 0 0 1 3 17c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488C5.964 13.023 6.448 13 7 13M17 13c.552 0 1.036.023 1.454.058 1.363.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.363-1.125 2.374-2.488 2.488-.418.035-.902.058-1.454.058s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.125-2.488-2.488A18 18 0 0 1 13 17c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488.418-.035.902-.058 1.454-.058M7 3c.552 0 1.036.023 1.454.058 1.364.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.364-1.124 2.374-2.488 2.488C8.036 10.977 7.552 11 7 11s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.124-2.488-2.488A17 17 0 0 1 3 7c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488C5.964 3.023 6.448 3 7 3M17 3c.552 0 1.036.023 1.454.058 1.363.114 2.374 1.124 2.488 2.488.035.418.058.902.058 1.454s-.023 1.036-.058 1.454c-.114 1.364-1.125 2.374-2.488 2.488-.418.035-.902.058-1.454.058s-1.036-.023-1.454-.058c-1.364-.114-2.374-1.124-2.488-2.488A18 18 0 0 1 13 7c0-.552.023-1.036.058-1.454.114-1.364 1.124-2.374 2.488-2.488C15.964 3.023 16.448 3 17 3" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Info: PapPath[] = [
|
||||||
|
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.274 4.743 2.293 5.017 5.015C20.928 9.251 21 10.517 21 12s-.072 2.748-.178 3.805c-.274 2.723-2.294 4.743-5.017 5.016a38 38 0 0 1-3.805.18c-1.483 0-2.749-.073-3.805-.18-2.723-.274-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.293-4.741 5.016-5.015A38 38 0 0 1 12 3m0 8a1 1 0 0 0-1 1v5a1 1 0 1 0 2 0v-5a1 1 0 0 0-1-1m0-4a1 1 0 1 0 0 2 1 1 0 0 0 0-2", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Link: PapPath[] = [
|
||||||
|
{ d: "M9.415 10.429a1.5 1.5 0 0 1 2.12 2.12 10 10 0 0 0-.223.231c-.56.6-.606 1.602.24 2.546q.528.593 1.276 1.344.476.475.888.86c1.203 1.123 2.568 1.096 3.232.432.606-.606.867-1.051.975-1.33.1-.258.075-.384.067-.42a.3.3 0 0 0-.092-.155l-.007-.008.012.01.017.011.012.01q.003.001.006.004l.005.002a1.5 1.5 0 0 1 1.653-2.503l-.58.882c.553-.84.58-.88.582-.881l.002.002.005.003.01.006q.008.007.02.014l.05.037q.057.041.134.105a3.32 3.32 0 0 1 1.09 1.775c.327 1.389-.222 2.94-1.839 4.557-2.274 2.274-5.565 1.352-7.4-.36a39 39 0 0 1-2.354-2.396c-1.571-1.755-2.108-4.55-.194-6.597q.139-.149.293-.301" },
|
||||||
|
{ d: "M5.981 4.112c2.274-2.274 5.566-1.35 7.4.362a39 39 0 0 1 2.353 2.395c1.572 1.755 2.11 4.55.196 6.596q-.14.15-.293.303a1.5 1.5 0 0 1-2.122-2.122q.119-.117.224-.23c.561-.6.606-1.602-.24-2.546a35.758 35.758 0 0 0-2.165-2.203c-1.203-1.123-2.566-1.097-3.23-.433-.606.606-.867 1.051-.975 1.33-.1.257-.076.383-.068.42a.3.3 0 0 0 .092.156l.007.008q0-.001-.012-.01l-.016-.013-.013-.008-.006-.005-.005-.002a1.5 1.5 0 0 1-1.653 2.502l.58-.881c-.552.837-.58.88-.582.881l-.002-.002-.005-.002-.009-.007-.02-.014-.051-.036a3.263 3.263 0 0 1-.496-.462A3.3 3.3 0 0 1 4.14 8.67c-.325-1.389.223-2.94 1.84-4.558" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const List: PapPath[] = [
|
||||||
|
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.273 4.742 2.293 5.016 5.015C20.927 9.251 21 10.517 21 12s-.073 2.748-.179 3.805c-.274 2.723-2.293 4.743-5.016 5.016A38 38 0 0 1 12 21c-1.483 0-2.749-.073-3.806-.179-2.722-.274-4.742-2.293-5.015-5.016A38 38 0 0 1 3 12c0-1.483.072-2.749.179-3.806.274-2.722 2.293-4.741 5.015-5.015A38 38 0 0 1 12 3m-.5 12c-1.31 0-2.281.025-2.937.052C7.86 15.08 7 15.298 7 16s.86.92 1.563.948c.656.027 1.626.052 2.937.052s2.281-.025 2.938-.052C15.139 16.92 16 16.702 16 16s-.86-.92-1.562-.948A74 74 0 0 0 11.5 15m-1-4c-.91 0-1.609.02-2.111.043-.657.03-1.389.3-1.389.957 0 .658.732.927 1.389.957C8.89 12.98 9.59 13 10.5 13s1.609-.02 2.111-.043c.657-.03 1.389-.3 1.389-.957 0-.658-.732-.927-1.389-.957A46 46 0 0 0 10.5 11M12 7a90 90 0 0 0-3.347.055C7.927 7.082 7 7.274 7 8s.927.918 1.653.945C9.383 8.973 10.487 9 12 9s2.617-.027 3.347-.055C16.073 8.918 17 8.726 17 8s-.927-.918-1.653-.945A90 90 0 0 0 12 7" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Lock: PapPath[] = [
|
||||||
|
{ d: "M12.324 3.866c3.316.171 5.504 2.964 5.636 6.349q.029.78.035 1.68c.656.043 1.117.14 1.505.364a3 3 0 0 1 1.098 1.098c.402.696.402 1.63.402 3.5s0 2.804-.402 3.5a3 3 0 0 1-1.098 1.098c-.696.402-1.63.402-3.5.402H8c-1.87 0-2.804 0-3.5-.402a3 3 0 0 1-1.098-1.098C3 19.661 3 18.727 3 16.857s0-2.804.402-3.5A3 3 0 0 1 4.5 12.26c.387-.223.849-.32 1.504-.365q.002-.336.007-.655l.029-1.024C6.176 6.72 8.503 3.857 12 3.857zM12 6.857c-1.497 0-2.872 1.172-2.962 3.474q-.026.707-.033 1.526h5.99a51 51 0 0 0-.033-1.526c-.09-2.302-1.465-3.474-2.962-3.474", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Logout: PapPath[] = [
|
||||||
|
{ d: "M7.5 3c1.272 0 2.281.143 3.045.321 1.234.288 2.004 1.367 2.15 2.626q.069.582.131 1.346c.065.811-.634 1.47-1.443 1.38L11 8.634c-.884-.098-1.732.167-2.357.794-.626.623-.976 1.557-.976 2.539s.35 1.916.976 2.539c.625.626 1.473.891 2.357.794l.382-.041c.81-.089 1.512.568 1.448 1.382a38 38 0 0 1-.136 1.413c-.146 1.259-.916 2.338-2.15 2.626C9.78 20.857 8.772 21 7.5 21s-2.282-.143-3.045-.321c-1.234-.288-2.004-1.367-2.15-2.626C2.152 16.74 2 14.743 2 12s.152-4.74.305-6.053c.146-1.259.916-2.338 2.15-2.626C5.218 3.143 6.228 3 7.5 3m8.396 4.384a1 1 0 0 1 1.414 0l3.773 3.773a1 1 0 0 1 0 1.414l-3.773 3.773a1 1 0 0 1-1.414-1.414L17.824 13l-6.442.281L11 13.3a1.25 1.25 0 0 1-.943-.361c-.25-.25-.39-.603-.39-.972 0-.37.14-.722.39-.972s.59-.377.943-.361l.382.016 6.655.29-2.141-2.141a1 1 0 0 1 0-1.414" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Menu: PapPath[] = [
|
||||||
|
{ d: "M12 17c2.472 0 3.263.043 4.429.085 1.114.04 2.571.3 2.571 1.415s-1.457 1.375-2.571 1.415C15.263 19.957 14.472 20 12 20s-3.263-.043-4.429-.085C6.457 19.875 5 19.615 5 18.5s1.457-1.375 2.571-1.415C8.737 17.043 9.528 17 12 17M12 11c2.472 0 2.263.043 3.429.085 1.114.04 2.571.3 2.571 1.415s-1.457 1.375-2.571 1.415c-1.166.042-.957.085-3.429.085s-2.263-.043-3.429-.085C7.457 13.875 6 13.615 6 12.5s1.457-1.375 2.571-1.415C9.737 11.043 9.528 11 12 11M12 5c2.472 0 4.263.043 5.429.085 1.114.04 2.571.3 2.571 1.415s-1.457 1.375-2.571 1.415A152 152 0 0 1 12 8c-2.472 0-4.263-.043-5.429-.085C5.457 7.875 4 7.615 4 6.5s1.457-1.375 2.571-1.415C7.737 5.043 9.528 5 12 5" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Moon: PapPath[] = [
|
||||||
|
{ d: "M11 3.857c.79 0 1 1.185.464 1.764a5.5 5.5 0 0 0 7.77 7.772c.58-.536 1.766-.325 1.766.464.003 4.97-4.03 8-9 8a9 9 0 0 1-9-9c0-4.97 3.03-9 8-9" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Paper: PapPath[] = [
|
||||||
|
{ d: "M12 7.828a4 4 0 0 0 4 4c.932 0 1.398 0 1.765.152a2 2 0 0 1 1.083 1.082c.152.368.152.834.152 1.766V15c0 2.828 0 4.243-.879 5.122S15.828 21 13 21h-2c-2.828 0-4.242 0-5.121-.878C5 19.242 5 17.828 5 14.999v-4c0-2.808 0-4.212.674-5.221a4 4 0 0 1 1.103-1.104c.39-.26.837-.42 1.402-.518 1.538-.267 2.307-.401 2.99.09.073.053.165.13.23.193C12 5.028 12 5.961 12 7.828" },
|
||||||
|
{ d: "M14 6.365c0-1.004 0-1.506.304-1.636s.666.219 1.39.915l2.792 2.688c.316.304.501.701.507 1.14.003.186-.147.356-.334.356H16l-.204-.011A2 2 0 0 1 14 7.827z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const PenAlt: PapPath[] = [
|
||||||
|
{ d: "M19.145 14.688a.4.4 0 0 1 .157.054c.229.125.343 1.145.573 3.184l.029.26c.122 1.088.184 1.633-.128 1.966q-.027.029-.057.055c-.337.308-.887.247-1.988.127l-.263-.029c-2.065-.226-3.097-.34-3.223-.566a.4.4 0 0 1-.055-.154c-.044-.254.746-1.036 2.327-2.598s2.371-2.343 2.628-2.299M12.326 8.006a1.19 1.19 0 0 1 1.676-.012c1.7 1.68 2.692 2.933 3.205 3.65.307.43.366.974.111 1.437-.332.602-.958 1.53-2.082 2.64s-2.062 1.729-2.672 2.057c-.468.252-1.018.194-1.454-.11-.725-.507-1.994-1.487-3.694-3.166a1.163 1.163 0 0 1 .012-1.656zM8.494 4.923c.681-.413 1.51-.325 2.151.147.552.406.585 1.207.098 1.688l-4.58 4.526c-.49.484-1.292.451-1.706-.099-.478-.634-.567-1.452-.149-2.126.365-.586.951-1.374 1.873-2.285s1.72-1.49 2.313-1.85" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Pie: PapPath[] = [
|
||||||
|
{ d: "M11 12a1 1 0 0 0 1 1h4.477c2.117 0 3.175 0 3.736 1.074s.1 1.738-.824 3.065A9 9 0 1 1 6.862 4.612c1.326-.924 1.99-1.386 3.064-.825S11 5.407 11 7.523z" },
|
||||||
|
{ d: "M13 7.247c0-1.777 0-2.665.823-3.264.112-.082.336-.203.466-.252.95-.362 1.507 0 2.62.726a9.05 9.05 0 0 1 2.634 2.634c.726 1.113 1.088 1.67.726 2.62-.049.13-.17.354-.252.466-.599.823-1.487.823-3.264.823-1.647 0-2.47 0-3.024-.455a2 2 0 0 1-.274-.274C13 9.717 13 8.894 13 7.247" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Placeholder: PapPath[] = [
|
||||||
|
{ d: "M4 17.357a1.5 1.5 0 0 1 1.5 1.5v.5H6a1.5 1.5 0 0 1 0 3H5a2.5 2.5 0 0 1-2.5-2.5v-1a1.5 1.5 0 0 1 1.5-1.5M13 19.357a1.5 1.5 0 0 1 0 3h-2a1.5 1.5 0 0 1 0-3zM20 17.357a1.5 1.5 0 0 1 1.5 1.5v1a2.5 2.5 0 0 1-2.5 2.5h-1a1.5 1.5 0 0 1 0-3h.5v-.5a1.5 1.5 0 0 1 1.5-1.5M4 10.357a1.5 1.5 0 0 1 1.5 1.5v2a1.5 1.5 0 0 1-3 0v-2a1.5 1.5 0 0 1 1.5-1.5M20 10.357a1.5 1.5 0 0 1 1.5 1.5v2a1.5 1.5 0 0 1-3 0v-2a1.5 1.5 0 0 1 1.5-1.5M6 3.357a1.5 1.5 0 1 1 0 3h-.5v.5a1.5 1.5 0 0 1-3 0v-1a2.5 2.5 0 0 1 2.5-2.5zM19 3.357a2.5 2.5 0 0 1 2.5 2.5v1a1.5 1.5 0 0 1-3 0v-.5H18a1.5 1.5 0 0 1 0-3zM13 3.357a1.5 1.5 0 0 1 0 3h-2a1.5 1.5 0 0 1 0-3z" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Search: PapPath[] = [
|
||||||
|
{ d: "M10 3a7 7 0 0 1 5.573 11.232l4.078 3.548c1.28 1.114.492 3.22-1.205 3.22a1.84 1.84 0 0 1-1.43-.685l-3.453-4.29A7 7 0 1 1 10 3m0 3a4 4 0 1 0 0 8 4 4 0 0 0 0-8", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Sparkles: PapPath[] = [
|
||||||
|
{ d: "M12.647 16.859c-1.087 2.185-1.63 3.278-2.412 3.543a2 2 0 0 1-1.284 0c-.782-.265-1.325-1.358-2.412-3.543-1.156-.202-1.735-.302-1.876-.35-1.888-.626-1.801-3.326.123-3.831.144-.038.68-.097 1.753-.213 1.064-2.252 1.596-3.378 2.365-3.66a2 2 0 0 1 1.378 0c.77.282 1.301 1.408 2.365 3.66 1.176.114 1.765.172 1.91.208 1.958.49 2.038 3.246.11 3.849-.142.044-.768.142-2.02.337M14.294 9.114l-.25-.14c-.944-.531-1.416-.796-1.549-1.114a1 1 0 0 1 .081-.925c.186-.29.697-.47 1.718-.827.768-1.43 1.152-2.146 1.682-2.343a1.5 1.5 0 0 1 1.047 0c.53.197.915.912 1.683 2.343 1.021.358 1.532.537 1.718.827a1 1 0 0 1 .08.925c-.132.318-.604.583-1.547 1.113l-.251.141c-.79 1.39-1.184 2.085-1.726 2.269a1.5 1.5 0 0 1-.96 0c-.542-.183-.937-.879-1.726-2.269" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Star: PapPath[] = [
|
||||||
|
{ d: "m7.82 8.84-1.563 5.203L12 17.68l5.744-3.637L16.18 8.84z" },
|
||||||
|
{ d: "M12 17.68c2.723 2.55 4.084 3.826 5.08 3.639a2 2 0 0 0 1.091-.6c.693-.74.347-2.573-.345-6.239l-.082-.437z" },
|
||||||
|
{ d: "m16.18 8.84 1.564 5.203c2.305-1.066 3.459-1.599 3.76-2a2 2 0 0 0-.651-2.965c-.443-.238-1.713-.238-4.254-.238zM7.82 8.84h8.36l-.564-1.192C14.05 4.335 13.266 2.68 12 2.68s-2.05 1.656-3.616 4.97zM6.174 14.48c-.692 3.666-1.038 5.499-.345 6.24a2 2 0 0 0 1.09.599c.997.187 2.359-1.088 5.081-3.639l-5.743-3.637zM6.257 14.043 7.82 8.84h-.419c-2.54 0-3.81 0-4.254.238a2 2 0 0 0-.652 2.965c.302.401 1.455.934 3.762 2" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Tasks: PapPath[] = [
|
||||||
|
{ d: "M12 3c1.483 0 2.748.073 3.805.179 2.723.274 4.743 2.293 5.017 5.015C20.928 9.251 21 10.517 21 12s-.072 2.748-.178 3.805c-.274 2.723-2.294 4.743-5.017 5.016a38 38 0 0 1-3.805.18c-1.483 0-2.749-.073-3.805-.18-2.723-.274-4.742-2.293-5.016-5.016A38 38 0 0 1 3 12c0-1.483.073-2.749.179-3.806.274-2.722 2.293-4.741 5.016-5.015A38 38 0 0 1 12 3m5.63 4.223a1 1 0 0 0-1.407.148l-5.773 7.136-2.213-2.214-.077-.068a1 1 0 0 0-1.338 1.482l2.214 2.214a2 2 0 0 0 2.97-.156l5.772-7.136a1 1 0 0 0-.149-1.406", evenodd: true },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const Trash: PapPath[] = [
|
||||||
|
{ d: "M14.876 10.29c2.406-.085 3.608-.127 4.233.586.626.713.433 1.87.047 4.187l-.321 1.923c-.4 2.395-.598 3.592-1.437 4.303S15.344 22 12.917 22h-1.835c-2.427 0-3.641 0-4.48-.71-.84-.712-1.039-1.91-1.438-4.304l-.32-1.924c-.386-2.315-.58-3.473.046-4.186.625-.713 1.828-.67 4.234-.587.934.033 1.917.054 2.876.054s1.942-.021 2.876-.054M8.5 12a1 1 0 0 0-1 1v6a1 1 0 0 0 2 0v-6a1 1 0 0 0-1-1m3.5 0a1 1 0 0 0-1 1v6a1 1 0 1 0 2 0v-6a1 1 0 0 0-1-1m3.5 0a1 1 0 0 0-1 1v6a1 1 0 1 0 2 0v-6a1 1 0 0 0-1-1M12 2c1.275 0 2.271.276 2.97.854.722.597.978 1.388 1.022 2.083.024.376-.013.74-.073 1.063h2.73C19.395 6 20 6.605 20 7.35c0 .663-.48 1.224-1.138 1.297C17.547 8.795 15.151 9 12 9c-3.15 0-5.546-.205-6.862-.353A1.29 1.29 0 0 1 4 7.351C4 6.605 4.605 6 5.35 6h2.731a4.3 4.3 0 0 1-.073-1.063c.044-.695.3-1.486 1.021-2.083C9.73 2.276 10.725 2 12 2m0 2c-1.018 0-1.488.224-1.696.396-.186.153-.28.362-.3.667-.02.302.043.638.133.937h3.726c.09-.3.152-.635.133-.937-.02-.305-.114-.514-.3-.667C13.488 4.224 13.018 4 12 4" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export const User: PapPath[] = [
|
||||||
|
{ d: "M17 8A5 5 0 1 1 7 8a5 5 0 0 1 10 0M4.345 18.582c.052-.358.077-.537.094-.628.41-2.155 2.06-3.414 4.247-3.24.091.008.35.04.868.105.85.107 1.705.181 2.446.181s1.595-.073 2.446-.18c.518-.066.777-.098.868-.106 2.187-.174 3.837 1.085 4.247 3.24.017.09.042.27.094.628.017.124.026.185.03.236a2 2 0 0 1-1.89 2.18c-.05.002-.113.002-.238.002H6.444c-.125 0-.188 0-.238-.003a2 2 0 0 1-1.89-2.18c.004-.05.013-.111.03-.235" },
|
||||||
|
];
|
||||||
File diff suppressed because it is too large.
Load diff
Vendored
+1
@@ -0,0 +1 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2022",
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Bundler",
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"allowImportingTsExtensions": false,
|
||||||
|
"noUnusedLocals": true,
|
||||||
|
"noUnusedParameters": true
|
||||||
|
},
|
||||||
|
"include": ["src"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { defineConfig } from "vite";
|
||||||
|
import react from "@vitejs/plugin-react";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [react()],
|
||||||
|
// Le build est embarqué dans le binaire Go (web/dist).
|
||||||
|
build: { outDir: "../web/dist", emptyOutDir: true },
|
||||||
|
// `npm run dev` : l'API Go tourne sur :8080 (les routes /auth et /api passent par le proxy).
|
||||||
|
server: { proxy: { "/api": "http://localhost:8080", "/auth": "http://localhost:8080" } },
|
||||||
|
});
|
||||||
@@ -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
|
||||||
|
}
|
||||||
Vendored
Whitespace-only changes.
@@ -0,0 +1,10 @@
|
|||||||
|
// Package web embarque le frontend compilé (frontend/ -> web/dist) dans le binaire.
|
||||||
|
package web
|
||||||
|
|
||||||
|
import "embed"
|
||||||
|
|
||||||
|
// Dist contient le build Vite. En développement, dist/ peut ne contenir que
|
||||||
|
// .gitkeep : le serveur affiche alors un message invitant à lancer le build.
|
||||||
|
//
|
||||||
|
//go:embed all:dist
|
||||||
|
var Dist embed.FS
|
||||||
Reference in new issue
Block a user