Garage UI : interface web d'administration pour Garage (API v2 + CLI)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
fdd5555100
36 files changed
+8486
No files matched your search
@@ -0,0 +1,339 @@
|
||||
// mockgarage : faux serveur d'administration Garage v2 (en mémoire), pour développer et tester
|
||||
// l'interface sans cluster. Ce n'est PAS Garage : il imite seulement la forme des réponses.
|
||||
//
|
||||
// go run ./cmd/mockgarage # écoute sur :3903, jeton « test »
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type perm struct {
|
||||
Read bool `json:"read"`
|
||||
Write bool `json:"write"`
|
||||
Owner bool `json:"owner"`
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
ID string
|
||||
Created string
|
||||
Aliases []string
|
||||
Objects int
|
||||
Bytes int64
|
||||
Site bool
|
||||
Index string
|
||||
ErrDoc *string
|
||||
MaxSize *int64
|
||||
MaxObjs *int64
|
||||
Keys map[string]perm
|
||||
}
|
||||
|
||||
type key struct {
|
||||
ID, Name, Secret, Created string
|
||||
Expiration *string
|
||||
CreateBucket bool
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
buckets = map[string]*bucket{}
|
||||
keys = map[string]*key{}
|
||||
nodeID = "563e1ac825ee3323aa441e72c26d1030d6d4414aeb3697544d1d7e0c3d8da3a2"
|
||||
staged bool
|
||||
version = 1
|
||||
)
|
||||
|
||||
func init() {
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
keys["GK31c2f218a2e44f485b94239e"] = &key{ID: "GK31c2f218a2e44f485b94239e", Name: "sauvegardes-proxmox", Secret: strings.Repeat("ab12", 16), Created: now, CreateBucket: true}
|
||||
keys["GKb5d1c6ef0a9d4a3f9c8e1b22"] = &key{ID: "GKb5d1c6ef0a9d4a3f9c8e1b22", Name: "lecture-seule", Secret: strings.Repeat("cd34", 16), Created: now}
|
||||
gb := int64(1 << 30)
|
||||
q := 50 * gb
|
||||
buckets["b1"] = &bucket{ID: "9a1f0c3e5b7d2f48a6c1e9d0b3a5f7c2e4d6b8a0c2e4f6a8b0d2c4e6f8a0b2c4", Created: now, Aliases: []string{"proxmox-backups"}, Objects: 1284, Bytes: 38 * gb, MaxSize: &q,
|
||||
Keys: map[string]perm{"GK31c2f218a2e44f485b94239e": {true, true, true}}}
|
||||
buckets["b2"] = &bucket{ID: "1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d", Created: now, Aliases: []string{"site-vitrine", "www"}, Objects: 42, Bytes: 12 << 20, Site: true, Index: "index.html",
|
||||
Keys: map[string]perm{"GKb5d1c6ef0a9d4a3f9c8e1b22": {true, false, false}}}
|
||||
buckets["b3"] = &bucket{ID: "7f6e5d4c3b2a19080f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a6978", Created: now, Aliases: []string{"vide"}, Keys: map[string]perm{}}
|
||||
}
|
||||
|
||||
func j(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(code)
|
||||
_ = json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func gerr(w http.ResponseWriter, code int, msg string) {
|
||||
j(w, code, map[string]any{"code": "MockError", "message": msg, "region": "garage", "path": ""})
|
||||
}
|
||||
|
||||
func findBucket(id string) *bucket {
|
||||
for _, b := range buckets {
|
||||
if b.ID == id {
|
||||
return b
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bucket) info() map[string]any {
|
||||
ks := []map[string]any{}
|
||||
for id, p := range b.Keys {
|
||||
if k := keys[id]; k != nil {
|
||||
ks = append(ks, map[string]any{"accessKeyId": id, "name": k.Name, "permissions": p, "bucketLocalAliases": []string{}})
|
||||
}
|
||||
}
|
||||
var wc any
|
||||
if b.Site {
|
||||
wc = map[string]any{"indexDocument": b.Index, "errorDocument": b.ErrDoc}
|
||||
}
|
||||
return map[string]any{
|
||||
"id": b.ID, "created": b.Created, "globalAliases": b.Aliases, "localAliases": []any{}, "websiteAccess": b.Site, "websiteConfig": wc,
|
||||
"keys": ks, "objects": b.Objects, "bytes": b.Bytes, "unfinishedUploads": 0, "unfinishedMultipartUploads": 2,
|
||||
"unfinishedMultipartUploadParts": 5, "unfinishedMultipartUploadBytes": 30 << 20,
|
||||
"quotas": map[string]any{"maxSize": b.MaxSize, "maxObjects": b.MaxObjs},
|
||||
}
|
||||
}
|
||||
|
||||
func (k *key) info(secret bool) map[string]any {
|
||||
bs := []map[string]any{}
|
||||
for _, b := range buckets {
|
||||
if p, ok := b.Keys[k.ID]; ok {
|
||||
bs = append(bs, map[string]any{"id": b.ID, "globalAliases": b.Aliases, "localAliases": []string{}, "permissions": p})
|
||||
}
|
||||
}
|
||||
var s any
|
||||
if secret {
|
||||
s = k.Secret
|
||||
}
|
||||
return map[string]any{"accessKeyId": k.ID, "name": k.Name, "created": k.Created, "expiration": k.Expiration, "expired": false,
|
||||
"secretAccessKey": s, "permissions": map[string]bool{"createBucket": k.CreateBucket}, "buckets": bs}
|
||||
}
|
||||
|
||||
func handle(token string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer "+token {
|
||||
gerr(w, 403, "jeton d'administration invalide")
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
op := strings.TrimPrefix(r.URL.Path, "/v2/")
|
||||
q := r.URL.Query()
|
||||
var body map[string]any
|
||||
var arr []any
|
||||
raw := json.NewDecoder(r.Body)
|
||||
var anyBody any
|
||||
_ = raw.Decode(&anyBody)
|
||||
switch v := anyBody.(type) {
|
||||
case map[string]any:
|
||||
body = v
|
||||
case []any:
|
||||
arr = v
|
||||
}
|
||||
str := func(k string) string { s, _ := body[k].(string); return s }
|
||||
log.Printf("%s %s", r.Method, op)
|
||||
|
||||
switch op {
|
||||
case "GetClusterHealth":
|
||||
j(w, 200, map[string]any{"status": "healthy", "knownNodes": 1, "connectedNodes": 1, "storageNodes": 1, "storageNodesUp": 1, "partitions": 256, "partitionsQuorum": 256, "partitionsAllOk": 256})
|
||||
case "GetClusterStatus":
|
||||
var role any = map[string]any{"zone": "dc1", "tags": []string{"lab"}, "capacity": int64(500e9)}
|
||||
j(w, 200, map[string]any{"layoutVersion": version, "nodes": []any{map[string]any{
|
||||
"id": nodeID, "role": role, "addr": "172.18.0.2:3901", "hostname": "garage", "isUp": true, "lastSeenSecsAgo": nil, "draining": false,
|
||||
"dataPartition": map[string]any{"available": int64(412e9), "total": int64(500e9)}, "metadataPartition": map[string]any{"available": int64(40e9), "total": int64(50e9)}, "garageVersion": "v2.3.0"}}})
|
||||
case "GetClusterStatistics":
|
||||
j(w, 200, map[string]any{"freeform": "Storage nodes:\n ID Hostname Zone Capacity Part. DataAvail MetaAvail\n 563e1ac8 garage dc1 500.0 GB 256 412.0 GB 40.0 GB"})
|
||||
case "GetClusterLayout":
|
||||
st := []any{}
|
||||
if staged {
|
||||
st = append(st, map[string]any{"id": nodeID, "zone": "dc1", "tags": []string{"lab"}, "capacity": int64(800e9)})
|
||||
}
|
||||
j(w, 200, map[string]any{"version": version, "roles": []any{map[string]any{"id": nodeID, "zone": "dc1", "tags": []string{"lab"}, "capacity": int64(500e9)}}, "partitionSize": 67108864, "stagedRoleChanges": st})
|
||||
case "UpdateClusterLayout":
|
||||
staged = true
|
||||
j(w, 200, map[string]any{"version": version})
|
||||
case "PreviewClusterLayoutChanges":
|
||||
j(w, 200, map[string]any{"message": []string{"==== NEW CLUSTER LAYOUT ====", "capacité 800 GB sur dc1", "(aperçu simulé)"}})
|
||||
case "ApplyClusterLayout":
|
||||
staged, version = false, version+1
|
||||
j(w, 200, map[string]any{"message": []string{"ok"}})
|
||||
case "RevertClusterLayout":
|
||||
staged = false
|
||||
j(w, 200, map[string]any{"version": version})
|
||||
case "ConnectClusterNodes":
|
||||
j(w, 200, []any{map[string]any{"success": len(arr) > 0 && strings.Contains(fmt.Sprint(arr[0]), "@")}})
|
||||
case "ListBuckets":
|
||||
out := []any{}
|
||||
for _, b := range buckets {
|
||||
out = append(out, map[string]any{"id": b.ID, "created": b.Created, "globalAliases": b.Aliases, "localAliases": []any{}})
|
||||
}
|
||||
j(w, 200, out)
|
||||
case "GetBucketInfo":
|
||||
if b := findBucket(q.Get("id")); b != nil {
|
||||
j(w, 200, b.info())
|
||||
return
|
||||
}
|
||||
gerr(w, 404, "bucket introuvable")
|
||||
case "CreateBucket":
|
||||
id := fmt.Sprintf("%064x", time.Now().UnixNano())
|
||||
b := &bucket{ID: id, Created: time.Now().UTC().Format(time.RFC3339), Aliases: []string{str("globalAlias")}, Keys: map[string]perm{}}
|
||||
buckets[id] = b
|
||||
j(w, 200, b.info())
|
||||
case "DeleteBucket":
|
||||
b := findBucket(q.Get("id"))
|
||||
switch {
|
||||
case b == nil:
|
||||
gerr(w, 404, "bucket introuvable")
|
||||
case b.Objects > 0:
|
||||
gerr(w, 409, "le bucket n'est pas vide")
|
||||
default:
|
||||
for k, x := range buckets {
|
||||
if x == b {
|
||||
delete(buckets, k)
|
||||
}
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
case "UpdateBucket":
|
||||
b := findBucket(q.Get("id"))
|
||||
if b == nil {
|
||||
gerr(w, 404, "bucket introuvable")
|
||||
return
|
||||
}
|
||||
if wa, ok := body["websiteAccess"].(map[string]any); ok {
|
||||
b.Site, _ = wa["enabled"].(bool)
|
||||
b.Index, _ = wa["indexDocument"].(string)
|
||||
}
|
||||
if qu, ok := body["quotas"].(map[string]any); ok {
|
||||
b.MaxSize, b.MaxObjs = nil, nil
|
||||
if f, ok := qu["maxSize"].(float64); ok {
|
||||
n := int64(f)
|
||||
b.MaxSize = &n
|
||||
}
|
||||
if f, ok := qu["maxObjects"].(float64); ok {
|
||||
n := int64(f)
|
||||
b.MaxObjs = &n
|
||||
}
|
||||
}
|
||||
j(w, 200, b.info())
|
||||
case "AddBucketAlias", "RemoveBucketAlias":
|
||||
b := findBucket(str("bucketId"))
|
||||
if b == nil {
|
||||
gerr(w, 404, "bucket introuvable")
|
||||
return
|
||||
}
|
||||
a := str("globalAlias")
|
||||
if op == "AddBucketAlias" {
|
||||
b.Aliases = append(b.Aliases, a)
|
||||
} else {
|
||||
out := b.Aliases[:0:0]
|
||||
for _, x := range b.Aliases {
|
||||
if x != a {
|
||||
out = append(out, x)
|
||||
}
|
||||
}
|
||||
b.Aliases = out
|
||||
}
|
||||
j(w, 200, b.info())
|
||||
case "AllowBucketKey", "DenyBucketKey":
|
||||
b := findBucket(str("bucketId"))
|
||||
if b == nil {
|
||||
gerr(w, 404, "bucket introuvable")
|
||||
return
|
||||
}
|
||||
p := b.Keys[str("accessKeyId")]
|
||||
pm, _ := body["permissions"].(map[string]any)
|
||||
on := op == "AllowBucketKey"
|
||||
if pm["read"] == true {
|
||||
p.Read = on
|
||||
}
|
||||
if pm["write"] == true {
|
||||
p.Write = on
|
||||
}
|
||||
if pm["owner"] == true {
|
||||
p.Owner = on
|
||||
}
|
||||
b.Keys[str("accessKeyId")] = p
|
||||
j(w, 200, b.info())
|
||||
case "CleanupIncompleteUploads":
|
||||
j(w, 200, map[string]any{"uploadsDeleted": 2})
|
||||
case "ListKeys":
|
||||
out := []any{}
|
||||
for _, k := range keys {
|
||||
out = append(out, map[string]any{"id": k.ID, "name": k.Name, "created": k.Created, "expiration": k.Expiration, "expired": false})
|
||||
}
|
||||
j(w, 200, out)
|
||||
case "GetKeyInfo":
|
||||
if k := keys[q.Get("id")]; k != nil {
|
||||
j(w, 200, k.info(q.Get("showSecretKey") == "true"))
|
||||
return
|
||||
}
|
||||
gerr(w, 404, "clé introuvable")
|
||||
case "CreateKey", "ImportKey":
|
||||
id := str("accessKeyId")
|
||||
sec := str("secretAccessKey")
|
||||
if id == "" {
|
||||
id = fmt.Sprintf("GK%024x", time.Now().UnixNano())
|
||||
sec = fmt.Sprintf("%064x", time.Now().UnixNano())
|
||||
}
|
||||
k := &key{ID: id, Name: str("name"), Secret: sec, Created: time.Now().UTC().Format(time.RFC3339)}
|
||||
keys[id] = k
|
||||
j(w, 200, k.info(true))
|
||||
case "UpdateKey":
|
||||
k := keys[q.Get("id")]
|
||||
if k == nil {
|
||||
gerr(w, 404, "clé introuvable")
|
||||
return
|
||||
}
|
||||
if n := str("name"); n != "" {
|
||||
k.Name = n
|
||||
}
|
||||
if a, ok := body["allow"].(map[string]any); ok && a["createBucket"] == true {
|
||||
k.CreateBucket = true
|
||||
}
|
||||
if d, ok := body["deny"].(map[string]any); ok && d["createBucket"] == true {
|
||||
k.CreateBucket = false
|
||||
}
|
||||
j(w, 200, k.info(false))
|
||||
case "DeleteKey":
|
||||
delete(keys, q.Get("id"))
|
||||
for _, b := range buckets {
|
||||
delete(b.Keys, q.Get("id"))
|
||||
}
|
||||
w.WriteHeader(204)
|
||||
case "ListWorkers":
|
||||
j(w, 200, map[string]any{"success": map[string]any{nodeID: []any{
|
||||
map[string]any{"id": 1, "name": "Block resync worker #1", "state": "idle", "errors": 0, "consecutiveErrors": 0, "queueLength": 0},
|
||||
map[string]any{"id": 2, "name": "Block scrub worker", "state": "busy", "errors": 0, "consecutiveErrors": 0, "progress": "42.0%"},
|
||||
map[string]any{"id": 3, "name": "object sync", "state": map[string]any{"throttled": map[string]any{"durationSecs": 5}}, "errors": 1, "consecutiveErrors": 1, "lastError": map[string]any{"message": "timeout", "secsAgo": 90}},
|
||||
}}, "error": map[string]any{}})
|
||||
case "ListBlockErrors":
|
||||
j(w, 200, map[string]any{"success": map[string]any{nodeID: []any{}}, "error": map[string]any{}})
|
||||
case "LaunchRepairOperation", "CreateMetadataSnapshot", "RetryBlockResync":
|
||||
j(w, 200, map[string]any{"success": map[string]any{nodeID: nil}, "error": map[string]any{}})
|
||||
default:
|
||||
gerr(w, 404, "opération inconnue : "+op)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
token := "test"
|
||||
if v := os.Getenv("MOCK_TOKEN"); v != "" {
|
||||
token = v
|
||||
}
|
||||
addr := ":3903"
|
||||
if v := os.Getenv("MOCK_ADDR"); v != "" {
|
||||
addr = v
|
||||
}
|
||||
log.Printf("mockgarage sur %s (jeton %q)", addr, token)
|
||||
http.Handle("/v2/", handle(token))
|
||||
log.Fatal(http.ListenAndServe(addr, nil))
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
// 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())
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
|
||||
// fakeGarage enregistre la dernière requête reçue et répond {"ok":true}, sans ouvrir de port.
|
||||
func fakeGarage(t *testing.T) (roundTripFunc, *http.Request) {
|
||||
t.Helper()
|
||||
last := &http.Request{}
|
||||
return func(r *http.Request) (*http.Response, error) {
|
||||
*last = *r
|
||||
rec := httptest.NewRecorder()
|
||||
rec.Header().Set("Content-Type", "application/json")
|
||||
_, _ = rec.WriteString(`{"ok":true}`)
|
||||
return rec.Result(), nil
|
||||
}, last
|
||||
}
|
||||
|
||||
func newTestConfig(t *testing.T, rt http.RoundTripper) *config {
|
||||
t.Helper()
|
||||
t.Setenv("GARAGE_ADMIN_URL", "http://garage.test:3903")
|
||||
t.Setenv("GARAGE_ADMIN_TOKEN", "tok")
|
||||
t.Setenv("UI_PASSWORD", "pw")
|
||||
t.Setenv("GARAGE_BIN", "")
|
||||
c, err := loadConfig()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.cliBin = "/bin/echo"
|
||||
c.transport = rt
|
||||
return c
|
||||
}
|
||||
|
||||
func login(t *testing.T, h http.Handler) *http.Cookie {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest("POST", "/api/login", strings.NewReader(`{"user":"admin","password":"pw"}`))
|
||||
req.Header.Set(csrfHeader, "x")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("login: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
for _, ck := range rec.Result().Cookies() {
|
||||
if ck.Name == cookieName {
|
||||
return ck
|
||||
}
|
||||
}
|
||||
t.Fatal("pas de cookie de session")
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestAuthRequiredAndBadLogin(t *testing.T) {
|
||||
g, _ := fakeGarage(t)
|
||||
h := newTestConfig(t, g).routes()
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("GET", "/api/garage/v2/ListBuckets", nil))
|
||||
if rec.Code != 401 {
|
||||
t.Fatalf("sans session : %d, attendu 401", rec.Code)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest("POST", "/api/login", strings.NewReader(`{"user":"admin","password":"nope"}`))
|
||||
req.Header.Set(csrfHeader, "x")
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 401 {
|
||||
t.Fatalf("mauvais mot de passe : %d, attendu 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyInjectsTokenAndRestrictsPaths(t *testing.T) {
|
||||
g, last := fakeGarage(t)
|
||||
h := newTestConfig(t, g).routes()
|
||||
ck := login(t, h)
|
||||
|
||||
req := httptest.NewRequest("GET", "/api/garage/v2/ListBuckets?x=1", nil)
|
||||
req.AddCookie(ck)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 || last.URL.Path != "/v2/ListBuckets" || last.URL.RawQuery != "x=1" {
|
||||
t.Fatalf("proxy : %d, chemin %q", rec.Code, last.URL.String())
|
||||
}
|
||||
if last.Header.Get("Authorization") != "Bearer tok" {
|
||||
t.Fatalf("jeton non injecté : %q", last.Header.Get("Authorization"))
|
||||
}
|
||||
if last.Header.Get("Cookie") != "" {
|
||||
t.Fatal("le cookie de session ne doit pas partir vers Garage")
|
||||
}
|
||||
|
||||
// Hors /v2/ (ex. /metrics) et traversée de chemin : refusés.
|
||||
for _, p := range []string{"/api/garage/metrics", "/api/garage/v2/../metrics", "/api/garage/v1/status"} {
|
||||
req = httptest.NewRequest("GET", p, nil)
|
||||
req.AddCookie(ck)
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
// 404, ou 307 vers le chemin nettoyé (le mux Go) : dans les deux cas rien n'est relayé.
|
||||
if rec.Code != 404 && rec.Code != 307 {
|
||||
t.Errorf("%s : %d, attendu 404 ou 307", p, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMutationNeedsCSRFHeader(t *testing.T) {
|
||||
g, _ := fakeGarage(t)
|
||||
h := newTestConfig(t, g).routes()
|
||||
ck := login(t, h)
|
||||
req := httptest.NewRequest("POST", "/api/garage/v2/DeleteBucket?id=x", strings.NewReader("{}"))
|
||||
req.AddCookie(ck)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 403 {
|
||||
t.Fatalf("sans en-tête anti-CSRF : %d, attendu 403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCLIWhitelist(t *testing.T) {
|
||||
g, _ := fakeGarage(t)
|
||||
h := newTestConfig(t, g).routes()
|
||||
ck := login(t, h)
|
||||
call := func(body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest("POST", "/api/cli", strings.NewReader(body))
|
||||
req.Header.Set(csrfHeader, "x")
|
||||
req.AddCookie(ck)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
if rec := call(`{"args":["status"]}`); rec.Code != 200 || !strings.Contains(rec.Body.String(), `"exitCode":0`) {
|
||||
t.Fatalf("status : %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
for _, b := range []string{`{"args":["server"]}`, `{"args":["offline-repair"]}`, `{"args":[]}`, `{"args":["status","a\u0000b"]}`} {
|
||||
if rec := call(b); rec.Code == 200 {
|
||||
t.Errorf("%s devrait être refusé", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user