Files
garage-ui/cmd/server/main.go
T

405 lines
12 KiB
Go

// Garage UI : interface web d'administration d'un cluster Garage (S3).
//
// Le serveur ne contient pas de logique métier : il authentifie l'utilisateur, relaie
// l'API d'administration v2 de Garage en y ajoutant le jeton (qui ne va jamais au
// navigateur) et exécute, si on l'y autorise, quelques sous-commandes de la CLI garage.
package main
import (
"bytes"
"context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"os/exec"
"path"
"strconv"
"strings"
"time"
"github.com/vLab-BZH/garage-ui/web"
)
var version = "dev"
const (
cookieName = "garage_ui"
csrfHeader = "X-Requested-With"
)
type config struct {
listen string
adminURL *url.URL
adminToken string
user string
password string
secret []byte
title string
s3Endpoint string
s3Region string
cliBin string
cliConfig string
publicURL string
sessionTTL time.Duration
cliTimeout time.Duration
transport http.RoundTripper // nil : transport par défaut (les tests y mettent un faux Garage)
}
func env(k, def string) string {
if v := strings.TrimSpace(os.Getenv(k)); v != "" {
return v
}
return def
}
func loadConfig() (*config, error) {
c := &config{
listen: env("LISTEN_ADDR", ":8080"),
adminToken: env("GARAGE_ADMIN_TOKEN", ""),
user: env("UI_USER", "admin"),
password: os.Getenv("UI_PASSWORD"),
title: env("TITLE", "Garage UI"),
s3Endpoint: env("GARAGE_S3_ENDPOINT", ""),
s3Region: env("GARAGE_S3_REGION", "garage"),
cliBin: env("GARAGE_BIN", ""),
cliConfig: env("GARAGE_CONFIG", ""),
publicURL: env("PUBLIC_URL", ""),
sessionTTL: 24 * time.Hour,
cliTimeout: 120 * time.Second,
}
u, err := url.Parse(env("GARAGE_ADMIN_URL", "http://garage:3903"))
if err != nil || u.Host == "" {
return nil, fmt.Errorf("GARAGE_ADMIN_URL invalide")
}
c.adminURL = u
if d, err := time.ParseDuration(env("SESSION_TTL", "24h")); err == nil && d > 0 {
c.sessionTTL = d
}
if s := env("SESSION_SECRET", ""); s != "" {
c.secret = []byte(s)
} else {
c.secret = make([]byte, 32)
if _, err := rand.Read(c.secret); err != nil {
return nil, err
}
}
if c.cliBin == "" {
if st, err := os.Stat("/garage"); err == nil && !st.IsDir() {
c.cliBin = "/garage"
}
}
return c, nil
}
// --- Session -------------------------------------------------------------------
func (c *config) authEnabled() bool { return c.password != "" }
func (c *config) sign(msg string) string {
m := hmac.New(sha256.New, c.secret)
m.Write([]byte(msg))
return hex.EncodeToString(m.Sum(nil))
}
func (c *config) newSession(user string) string {
exp := strconv.FormatInt(time.Now().Add(c.sessionTTL).Unix(), 10)
msg := base64.RawURLEncoding.EncodeToString([]byte(user)) + "." + exp
return msg + "." + c.sign(msg)
}
// sessionUser renvoie l'utilisateur de la session, ou "" si elle est absente ou invalide.
func (c *config) sessionUser(r *http.Request) string {
if !c.authEnabled() {
return "admin"
}
ck, err := r.Cookie(cookieName)
if err != nil {
return ""
}
parts := strings.Split(ck.Value, ".")
if len(parts) != 3 {
return ""
}
msg := parts[0] + "." + parts[1]
if subtle.ConstantTimeCompare([]byte(parts[2]), []byte(c.sign(msg))) != 1 {
return ""
}
exp, err := strconv.ParseInt(parts[1], 10, 64)
if err != nil || time.Now().Unix() > exp {
return ""
}
u, err := base64.RawURLEncoding.DecodeString(parts[0])
if err != nil {
return ""
}
return string(u)
}
func (c *config) setCookie(w http.ResponseWriter, value string, maxAge int) {
http.SetCookie(w, &http.Cookie{
Name: cookieName, Value: value, Path: "/", MaxAge: maxAge, HttpOnly: true,
SameSite: http.SameSiteStrictMode, Secure: strings.HasPrefix(c.publicURL, "https://"),
})
}
// --- Utilitaires HTTP ----------------------------------------------------------
func writeJSON(w http.ResponseWriter, code int, v any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(code)
_ = json.NewEncoder(w).Encode(v)
}
func writeErr(w http.ResponseWriter, code int, msg string) {
writeJSON(w, code, map[string]string{"message": msg})
}
// guard exige une session et, pour les requêtes qui modifient, l'en-tête anti-CSRF.
func (c *config) guard(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if c.sessionUser(r) == "" {
writeErr(w, http.StatusUnauthorized, "Connexion requise")
return
}
if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Header.Get(csrfHeader) == "" {
writeErr(w, http.StatusForbidden, "En-tête "+csrfHeader+" manquant")
return
}
next(w, r)
}
}
// --- Routes --------------------------------------------------------------------
func (c *config) handleConfig(w http.ResponseWriter, r *http.Request) {
user := c.sessionUser(r)
writeJSON(w, 200, map[string]any{
"title": c.title, "version": version, "auth": c.authEnabled(), "user": user,
"cli": c.cliBin != "", "s3Endpoint": c.s3Endpoint, "s3Region": c.s3Region,
})
}
func (c *config) handleLogin(w http.ResponseWriter, r *http.Request) {
if r.Header.Get(csrfHeader) == "" {
writeErr(w, http.StatusForbidden, "En-tête "+csrfHeader+" manquant")
return
}
var in struct{ User, Password string }
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&in); err != nil {
writeErr(w, 400, "Requête invalide")
return
}
okU := subtle.ConstantTimeCompare([]byte(in.User), []byte(c.user)) == 1
okP := subtle.ConstantTimeCompare([]byte(in.Password), []byte(c.password)) == 1
if !c.authEnabled() || !okU || !okP {
time.Sleep(700 * time.Millisecond) // ralentit les essais en série
writeErr(w, http.StatusUnauthorized, "Identifiants incorrects")
return
}
c.setCookie(w, c.newSession(in.User), int(c.sessionTTL.Seconds()))
writeJSON(w, 200, map[string]string{"user": in.User})
}
func (c *config) handleLogout(w http.ResponseWriter, _ *http.Request) {
c.setCookie(w, "", -1)
writeJSON(w, 200, map[string]bool{"ok": true})
}
// garageProxy relaie /api/garage/v2/... vers l'API d'administration de Garage.
func (c *config) garageProxy() http.Handler {
rp := &httputil.ReverseProxy{
Transport: c.transport,
Rewrite: func(pr *httputil.ProxyRequest) {
pr.Out.URL.Scheme = c.adminURL.Scheme
pr.Out.URL.Host = c.adminURL.Host
pr.Out.URL.Path = strings.TrimRight(c.adminURL.Path, "/") + strings.TrimPrefix(pr.In.URL.Path, "/api/garage")
pr.Out.URL.RawPath = ""
pr.Out.Host = c.adminURL.Host
pr.Out.Header.Del("Cookie")
pr.Out.Header.Del(csrfHeader)
pr.Out.Header.Set("Authorization", "Bearer "+c.adminToken)
},
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
log.Printf("garage injoignable: %v", err)
writeErr(w, http.StatusBadGateway, "API d'administration de Garage injoignable ("+c.adminURL.Host+")")
},
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := path.Clean(r.URL.Path)
if !strings.HasPrefix(p, "/api/garage/v2/") || (r.Method != http.MethodGet && r.Method != http.MethodPost) {
writeErr(w, http.StatusNotFound, "Route inconnue")
return
}
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
rp.ServeHTTP(w, r)
})
}
// Sous-commandes de la CLI garage accessibles depuis la console.
var cliAllowed = map[string]bool{
"status": true, "stats": true, "repair": true, "worker": true, "block": true,
"meta": true, "layout": true, "bucket": true, "key": true, "node": true,
}
type limitedBuf struct {
bytes.Buffer
truncated bool
}
func (b *limitedBuf) Write(p []byte) (int, error) {
const max = 1 << 20
if b.Len()+len(p) > max {
p = p[:max-b.Len()]
b.truncated = true
}
b.Buffer.Write(p)
return len(p), nil
}
func (c *config) handleCLI(w http.ResponseWriter, r *http.Request) {
if c.cliBin == "" {
writeErr(w, http.StatusNotImplemented, "Console CLI non configurée (GARAGE_BIN)")
return
}
var in struct {
Args []string `json:"args"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 16384)).Decode(&in); err != nil || len(in.Args) == 0 || len(in.Args) > 24 {
writeErr(w, 400, "Arguments invalides")
return
}
for _, a := range in.Args {
if len(a) > 300 || strings.ContainsRune(a, 0) {
writeErr(w, 400, "Argument invalide")
return
}
}
if !cliAllowed[in.Args[0]] {
writeErr(w, http.StatusForbidden, "Sous-commande non autorisée : "+in.Args[0])
return
}
args := in.Args
if c.cliConfig != "" {
args = append([]string{"-c", c.cliConfig}, args...)
}
ctx, cancel := context.WithTimeout(r.Context(), c.cliTimeout)
defer cancel()
cmd := exec.CommandContext(ctx, c.cliBin, args...)
var env []string
for _, e := range os.Environ() {
if !strings.HasPrefix(e, "UI_") && !strings.HasPrefix(e, "SESSION_") {
env = append(env, e)
}
}
cmd.Env = env
out := &limitedBuf{}
cmd.Stdout, cmd.Stderr = out, out
start := time.Now()
err := cmd.Run()
code := 0
var ee *exec.ExitError
switch {
case errors.As(err, &ee):
code = ee.ExitCode()
case ctx.Err() != nil:
code = -1
out.WriteString("\n[délai dépassé]")
case err != nil:
code = -1
out.WriteString(err.Error())
}
log.Printf("cli: garage %s -> %d", strings.Join(in.Args, " "), code)
text := out.String()
if out.truncated {
text += "\n[sortie tronquée]"
}
writeJSON(w, 200, map[string]any{"exitCode": code, "output": text, "ms": time.Since(start).Milliseconds()})
}
// spa sert le frontend embarqué, avec repli sur index.html.
func spa() http.Handler {
dist, err := fs.Sub(web.Dist, "dist")
if err != nil {
log.Fatal(err)
}
files := http.FileServer(http.FS(dist))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p := strings.TrimPrefix(path.Clean(r.URL.Path), "/")
if p == "" {
p = "index.html"
}
if _, err := fs.Stat(dist, p); err != nil {
if _, err := fs.Stat(dist, "index.html"); err != nil {
http.Error(w, "Frontend non compilé : cd frontend && npm ci && npm run build", http.StatusServiceUnavailable)
return
}
r.URL.Path = "/"
}
if p == "index.html" || r.URL.Path == "/" {
w.Header().Set("Cache-Control", "no-cache")
}
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-ancestors 'none'")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "same-origin")
files.ServeHTTP(w, r)
})
}
func (c *config) routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/health", func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, 200, map[string]bool{"ok": true}) })
mux.HandleFunc("GET /api/config", c.handleConfig)
mux.HandleFunc("POST /api/login", c.handleLogin)
mux.HandleFunc("POST /api/logout", c.handleLogout)
mux.HandleFunc("POST /api/cli", c.guard(c.handleCLI))
mux.Handle("/api/garage/", c.guard(c.garageProxy().ServeHTTP))
mux.Handle("/", spa())
return mux
}
func healthcheck() int {
addr := env("LISTEN_ADDR", ":8080")
if strings.HasPrefix(addr, ":") {
addr = "127.0.0.1" + addr
}
cl := http.Client{Timeout: 4 * time.Second}
resp, err := cl.Get("http://" + addr + "/api/health")
if err != nil || resp.StatusCode != 200 {
return 1
}
return 0
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
os.Exit(healthcheck())
}
c, err := loadConfig()
if err != nil {
log.Fatal(err)
}
if c.adminToken == "" {
log.Fatal("GARAGE_ADMIN_TOKEN est obligatoire")
}
if !c.authEnabled() {
log.Print("ATTENTION : UI_PASSWORD vide, aucune authentification (réservé à un reverse proxy qui authentifie)")
}
log.Printf("garage-ui %s sur %s, Garage : %s, CLI : %q", version, c.listen, c.adminURL.Host, c.cliBin)
srv := &http.Server{Addr: c.listen, Handler: c.routes(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 2 * time.Minute}
log.Fatal(srv.ListenAndServe())
}