Vidage de bucket : client S3 (signature v4) et route /api/buckets/empty, avec tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LNfwm2bSk3o3YKYUP5P691
This commit is contained in:
1 parent
e21ef321f9
commit
3ff8bc2355
2 files changed
+602
No files matched your search
@@ -0,0 +1,413 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// Vidage d'un bucket. L'API d'administration de Garage ne sait ni lister ni supprimer des objets :
|
||||||
|
// il faut passer par l'API S3. Le serveur crée pour cela une clé temporaire, lui donne lecture et
|
||||||
|
// écriture sur le bucket, supprime les objets par lots de 1000 (DeleteObjects), nettoie les envois
|
||||||
|
// multipart inachevés (CleanupIncompleteUploads), puis supprime la clé, quoi qu'il arrive.
|
||||||
|
// Garage n'implémente pas le versioning S3 : il n'y a pas de versions ni de marqueurs à supprimer.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"crypto/hmac"
|
||||||
|
"crypto/md5"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// --- Appels à l'API d'administration ---------------------------------------------------
|
||||||
|
|
||||||
|
type adminError struct {
|
||||||
|
Status int
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *adminError) Error() string { return fmt.Sprintf("HTTP %d : %s", e.Status, e.Message) }
|
||||||
|
|
||||||
|
// admin appelle une opération de l'API d'administration v2 (body nil : GET, sinon POST JSON).
|
||||||
|
func (c *config) admin(ctx context.Context, op string, query url.Values, body, out any) error {
|
||||||
|
u := *c.adminURL
|
||||||
|
u.Path = strings.TrimRight(u.Path, "/") + "/v2/" + op
|
||||||
|
u.RawQuery = query.Encode()
|
||||||
|
method, rd := http.MethodGet, io.Reader(nil)
|
||||||
|
if body != nil {
|
||||||
|
b, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
method, rd = http.MethodPost, bytes.NewReader(b)
|
||||||
|
}
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, u.String(), rd)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", "Bearer "+c.adminToken)
|
||||||
|
if body != nil {
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
}
|
||||||
|
resp, err := (&http.Client{Transport: c.transport, Timeout: 60 * time.Second}).Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
data, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
var e struct{ Message string }
|
||||||
|
if json.Unmarshal(data, &e) != nil || e.Message == "" {
|
||||||
|
e.Message = strings.TrimSpace(string(data))
|
||||||
|
}
|
||||||
|
return &adminError{resp.StatusCode, e.Message}
|
||||||
|
}
|
||||||
|
if out != nil && len(data) > 0 {
|
||||||
|
return json.Unmarshal(data, out)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Client S3 minimal (signature v4, style « path ») ----------------------------------
|
||||||
|
|
||||||
|
type s3Client struct {
|
||||||
|
base *url.URL
|
||||||
|
region string
|
||||||
|
accessKey string
|
||||||
|
secretKey string
|
||||||
|
transport http.RoundTripper
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// uriEncode encode selon la RFC 3986, comme l'exige la signature v4 (slash conservé si path).
|
||||||
|
func uriEncode(s string, path bool) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for i := 0; i < len(s); i++ {
|
||||||
|
ch := s[i]
|
||||||
|
if ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' || ch == '-' || ch == '_' || ch == '.' || ch == '~' || (path && ch == '/') {
|
||||||
|
b.WriteByte(ch)
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(&b, "%%%02X", ch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return b.String()
|
||||||
|
}
|
||||||
|
|
||||||
|
func canonicalQuery(q url.Values) string {
|
||||||
|
keys := make([]string, 0, len(q))
|
||||||
|
for k := range q {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
sort.Strings(keys)
|
||||||
|
var parts []string
|
||||||
|
for _, k := range keys {
|
||||||
|
vs := append([]string(nil), q[k]...)
|
||||||
|
sort.Strings(vs)
|
||||||
|
for _, v := range vs {
|
||||||
|
parts = append(parts, uriEncode(k, false)+"="+uriEncode(v, false))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.Join(parts, "&")
|
||||||
|
}
|
||||||
|
|
||||||
|
func hmacSHA256(key []byte, msg string) []byte {
|
||||||
|
m := hmac.New(sha256.New, key)
|
||||||
|
m.Write([]byte(msg))
|
||||||
|
return m.Sum(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// sign ajoute les en-têtes x-amz-date, x-amz-content-sha256 et Authorization à req.
|
||||||
|
// Tous les en-têtes déjà présents (plus host) sont signés.
|
||||||
|
func (s *s3Client) sign(req *http.Request, payload []byte) {
|
||||||
|
t := s.now().UTC()
|
||||||
|
amzDate := t.Format("20060102T150405Z")
|
||||||
|
day := t.Format("20060102")
|
||||||
|
sum := sha256.Sum256(payload)
|
||||||
|
payloadHash := hex.EncodeToString(sum[:])
|
||||||
|
req.Header.Set("X-Amz-Date", amzDate)
|
||||||
|
req.Header.Set("X-Amz-Content-Sha256", payloadHash)
|
||||||
|
|
||||||
|
hdrs := map[string]string{"host": req.URL.Host}
|
||||||
|
for k, v := range req.Header {
|
||||||
|
hdrs[strings.ToLower(k)] = strings.Join(v, ",")
|
||||||
|
}
|
||||||
|
names := make([]string, 0, len(hdrs))
|
||||||
|
for k := range hdrs {
|
||||||
|
names = append(names, k)
|
||||||
|
}
|
||||||
|
sort.Strings(names)
|
||||||
|
var ch strings.Builder
|
||||||
|
for _, k := range names {
|
||||||
|
ch.WriteString(k + ":" + strings.TrimSpace(hdrs[k]) + "\n")
|
||||||
|
}
|
||||||
|
signed := strings.Join(names, ";")
|
||||||
|
canonical := strings.Join([]string{req.Method, uriEncode(req.URL.Path, true), canonicalQuery(req.URL.Query()), ch.String(), signed, payloadHash}, "\n")
|
||||||
|
scope := day + "/" + s.region + "/s3/aws4_request"
|
||||||
|
h := sha256.Sum256([]byte(canonical))
|
||||||
|
toSign := "AWS4-HMAC-SHA256\n" + amzDate + "\n" + scope + "\n" + hex.EncodeToString(h[:])
|
||||||
|
k := hmacSHA256([]byte("AWS4"+s.secretKey), day)
|
||||||
|
k = hmacSHA256(k, s.region)
|
||||||
|
k = hmacSHA256(k, "s3")
|
||||||
|
k = hmacSHA256(k, "aws4_request")
|
||||||
|
sig := hex.EncodeToString(hmacSHA256(k, toSign))
|
||||||
|
req.Header.Set("Authorization", "AWS4-HMAC-SHA256 Credential="+s.accessKey+"/"+scope+", SignedHeaders="+signed+", Signature="+sig)
|
||||||
|
}
|
||||||
|
|
||||||
|
type s3Error struct {
|
||||||
|
Status int
|
||||||
|
Code string `xml:"Code"`
|
||||||
|
Message string `xml:"Message"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *s3Error) Error() string {
|
||||||
|
if e.Code == "" {
|
||||||
|
return fmt.Sprintf("S3 : HTTP %d", e.Status)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("S3 : HTTP %d %s %s", e.Status, e.Code, e.Message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *s3Client) do(ctx context.Context, method, bucket string, q url.Values, body []byte, extra map[string]string, out any) error {
|
||||||
|
u := *s.base
|
||||||
|
u.Path = strings.TrimRight(u.Path, "/") + "/" + bucket
|
||||||
|
u.RawQuery = canonicalQuery(q)
|
||||||
|
req, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewReader(body))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
for k, v := range extra {
|
||||||
|
req.Header.Set(k, v)
|
||||||
|
}
|
||||||
|
s.sign(req, body)
|
||||||
|
resp, err := (&http.Client{Transport: s.transport, Timeout: 5 * time.Minute}).Do(req)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
data, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
|
||||||
|
if resp.StatusCode >= 300 {
|
||||||
|
e := &s3Error{Status: resp.StatusCode}
|
||||||
|
_ = xml.Unmarshal(data, e)
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
if out != nil {
|
||||||
|
return xml.Unmarshal(data, out)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type listResult struct {
|
||||||
|
Contents []struct {
|
||||||
|
Key string `xml:"Key"`
|
||||||
|
} `xml:"Contents"`
|
||||||
|
IsTruncated bool `xml:"IsTruncated"`
|
||||||
|
NextContinuationToken string `xml:"NextContinuationToken"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *s3Client) list(ctx context.Context, bucket, token string) (*listResult, error) {
|
||||||
|
q := url.Values{"list-type": {"2"}, "max-keys": {"1000"}}
|
||||||
|
if token != "" {
|
||||||
|
q.Set("continuation-token", token)
|
||||||
|
}
|
||||||
|
var out listResult
|
||||||
|
return &out, s.do(ctx, http.MethodGet, bucket, q, nil, nil, &out)
|
||||||
|
}
|
||||||
|
|
||||||
|
type deleteResult struct {
|
||||||
|
Deleted []struct {
|
||||||
|
Key string `xml:"Key"`
|
||||||
|
} `xml:"Deleted"`
|
||||||
|
Errors []struct {
|
||||||
|
Key string `xml:"Key"`
|
||||||
|
Code string `xml:"Code"`
|
||||||
|
Message string `xml:"Message"`
|
||||||
|
} `xml:"Error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *s3Client) deleteObjects(ctx context.Context, bucket string, keys []string) (*deleteResult, error) {
|
||||||
|
type obj struct {
|
||||||
|
Key string `xml:"Key"`
|
||||||
|
}
|
||||||
|
in := struct {
|
||||||
|
XMLName xml.Name `xml:"Delete"`
|
||||||
|
Quiet bool `xml:"Quiet"`
|
||||||
|
Objects []obj `xml:"Object"`
|
||||||
|
}{Quiet: true}
|
||||||
|
for _, k := range keys {
|
||||||
|
in.Objects = append(in.Objects, obj{k})
|
||||||
|
}
|
||||||
|
body, err := xml.Marshal(in)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sum := md5.Sum(body)
|
||||||
|
var out deleteResult
|
||||||
|
err = s.do(ctx, http.MethodPost, bucket, url.Values{"delete": {""}}, body,
|
||||||
|
map[string]string{"Content-Type": "application/xml", "Content-MD5": base64.StdEncoding.EncodeToString(sum[:])}, &out)
|
||||||
|
return &out, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Route /api/buckets/empty ----------------------------------------------------------
|
||||||
|
|
||||||
|
var emptying sync.Map // identifiants des buckets en cours de vidage
|
||||||
|
|
||||||
|
type emptyEvent struct {
|
||||||
|
Phase string `json:"phase"` // start, objects, uploads, done, error
|
||||||
|
Deleted int `json:"deleted"`
|
||||||
|
Failed int `json:"failed"`
|
||||||
|
UploadsDeleted int `json:"uploadsDeleted,omitempty"`
|
||||||
|
Errors []string `json:"errors,omitempty"`
|
||||||
|
Message string `json:"message,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleEmptyBucket vide le bucket ?id=... et diffuse l'avancement en NDJSON (une ligne par lot),
|
||||||
|
// ce qui garde la connexion active derrière un reverse proxy pendant les gros vidages.
|
||||||
|
func (c *config) handleEmptyBucket(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id := r.URL.Query().Get("id")
|
||||||
|
if len(id) != 64 {
|
||||||
|
writeErr(w, 400, "Identifiant de bucket invalide")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if _, busy := emptying.LoadOrStore(id, true); busy {
|
||||||
|
writeErr(w, http.StatusConflict, "Un vidage de ce bucket est déjà en cours")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer emptying.Delete(id)
|
||||||
|
ctx := r.Context()
|
||||||
|
|
||||||
|
var info struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
GlobalAliases []string `json:"globalAliases"`
|
||||||
|
}
|
||||||
|
if err := c.admin(ctx, "GetBucketInfo", url.Values{"id": {id}}, nil, &info); err != nil {
|
||||||
|
writeErr(w, http.StatusBadGateway, "GetBucketInfo : "+err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/x-ndjson")
|
||||||
|
w.Header().Set("Cache-Control", "no-store")
|
||||||
|
w.Header().Set("X-Accel-Buffering", "no")
|
||||||
|
w.WriteHeader(200)
|
||||||
|
fl, _ := w.(http.Flusher)
|
||||||
|
ev := emptyEvent{Phase: "start"}
|
||||||
|
send := func() {
|
||||||
|
_ = json.NewEncoder(w).Encode(ev)
|
||||||
|
if fl != nil {
|
||||||
|
fl.Flush()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fail := func(msg string) {
|
||||||
|
ev.Phase, ev.Message = "error", msg
|
||||||
|
send()
|
||||||
|
log.Printf("vidage %s : %s", id[:12], msg)
|
||||||
|
}
|
||||||
|
send()
|
||||||
|
|
||||||
|
// 1. Clé temporaire, supprimée en sortie même si la requête est interrompue.
|
||||||
|
var key struct {
|
||||||
|
AccessKeyID string `json:"accessKeyId"`
|
||||||
|
SecretAccessKey string `json:"secretAccessKey"`
|
||||||
|
}
|
||||||
|
rnd := make([]byte, 4)
|
||||||
|
_, _ = rand.Read(rnd)
|
||||||
|
keyName := "garage-ui-vidage-" + id[:8] + "-" + hex.EncodeToString(rnd)
|
||||||
|
if err := c.admin(ctx, "CreateKey", nil, map[string]any{"name": keyName}, &key); err != nil || key.AccessKeyID == "" || key.SecretAccessKey == "" {
|
||||||
|
fail(fmt.Sprintf("Création de la clé temporaire impossible : %v", err))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
cctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := c.admin(cctx, "DeleteKey", url.Values{"id": {key.AccessKeyID}}, map[string]any{}, nil); err != nil {
|
||||||
|
log.Printf("vidage %s : clé temporaire %s NON supprimée : %v", id[:12], key.AccessKeyID, err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
if err := c.admin(ctx, "AllowBucketKey", nil, map[string]any{
|
||||||
|
"bucketId": id, "accessKeyId": key.AccessKeyID, "permissions": map[string]bool{"read": true, "write": true, "owner": false},
|
||||||
|
}, nil); err != nil {
|
||||||
|
fail("Autorisation de la clé temporaire impossible : " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Nom S3 du bucket : un alias global, sinon un alias local de la clé temporaire
|
||||||
|
// (supprimé avec elle).
|
||||||
|
bucket := ""
|
||||||
|
if len(info.GlobalAliases) > 0 {
|
||||||
|
bucket = info.GlobalAliases[0]
|
||||||
|
} else {
|
||||||
|
bucket = "garage-ui-vidage"
|
||||||
|
if err := c.admin(ctx, "AddBucketAlias", nil, map[string]any{"bucketId": id, "accessKeyId": key.AccessKeyID, "localAlias": bucket}, nil); err != nil {
|
||||||
|
fail("Alias local temporaire impossible : " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
s3 := &s3Client{base: c.s3URL, region: c.s3Region, accessKey: key.AccessKeyID, secretKey: key.SecretAccessKey, transport: c.transport, now: time.Now}
|
||||||
|
|
||||||
|
// 3. Objets, par lots de 1000.
|
||||||
|
ev.Phase = "objects"
|
||||||
|
token := ""
|
||||||
|
for {
|
||||||
|
var page *listResult
|
||||||
|
var err error
|
||||||
|
// La clé vient d'être créée : le nœud S3 peut ne pas la connaître encore (propagation).
|
||||||
|
for try := 0; ; try++ {
|
||||||
|
page, err = s3.list(ctx, bucket, token)
|
||||||
|
var se *s3Error
|
||||||
|
if err == nil || try >= 5 || !errors.As(err, &se) || (se.Status != 403 && se.Status != 404) || ctx.Err() != nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
fail("Liste des objets : " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(page.Contents) > 0 {
|
||||||
|
keys := make([]string, len(page.Contents))
|
||||||
|
for i, o := range page.Contents {
|
||||||
|
keys[i] = o.Key
|
||||||
|
}
|
||||||
|
res, err := s3.deleteObjects(ctx, bucket, keys)
|
||||||
|
if err != nil {
|
||||||
|
fail("Suppression des objets : " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ev.Failed += len(res.Errors)
|
||||||
|
ev.Deleted += len(keys) - len(res.Errors)
|
||||||
|
for _, e := range res.Errors {
|
||||||
|
if len(ev.Errors) < 10 {
|
||||||
|
ev.Errors = append(ev.Errors, e.Key+" : "+e.Code+" "+e.Message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
send()
|
||||||
|
}
|
||||||
|
if !page.IsTruncated || page.NextContinuationToken == "" {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
token = page.NextContinuationToken
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Envois multipart inachevés, quel que soit leur âge.
|
||||||
|
ev.Phase = "uploads"
|
||||||
|
var up struct {
|
||||||
|
UploadsDeleted int `json:"uploadsDeleted"`
|
||||||
|
}
|
||||||
|
if err := c.admin(ctx, "CleanupIncompleteUploads", nil, map[string]any{"bucketId": id, "olderThanSecs": 0}, &up); err != nil {
|
||||||
|
fail("Nettoyage des envois inachevés : " + err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ev.UploadsDeleted = up.UploadsDeleted
|
||||||
|
ev.Phase = "done"
|
||||||
|
send()
|
||||||
|
log.Printf("vidage %s : %d objets supprimés, %d échecs, %d envois inachevés", id[:12], ev.Deleted, ev.Failed, ev.UploadsDeleted)
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"encoding/json"
|
||||||
|
"encoding/xml"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Exemple « GET Object » de la documentation AWS (Signature Version 4, en-tête Authorization).
|
||||||
|
func TestSigV4AWSExample(t *testing.T) {
|
||||||
|
s := &s3Client{region: "us-east-1", accessKey: "AKIAIOSFODNN7EXAMPLE", secretKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
|
||||||
|
now: func() time.Time { return time.Date(2013, 5, 24, 0, 0, 0, 0, time.UTC) }}
|
||||||
|
req, _ := http.NewRequest("GET", "https://examplebucket.s3.amazonaws.com/test.txt", nil)
|
||||||
|
req.Header.Set("Range", "bytes=0-9")
|
||||||
|
s.sign(req, nil)
|
||||||
|
want := "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
|
||||||
|
if got := req.Header.Get("Authorization"); got != want {
|
||||||
|
t.Fatalf("signature :\n %s\nattendu :\n %s", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fakeCluster imite l'API d'administration et l'API S3 de Garage pour un bucket de n objets.
|
||||||
|
type fakeCluster struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
objects map[string]bool
|
||||||
|
keys map[string]bool
|
||||||
|
ops []string
|
||||||
|
s3Auth []string
|
||||||
|
cleanups int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeCluster) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||||
|
f.mu.Lock()
|
||||||
|
defer f.mu.Unlock()
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
var body []byte
|
||||||
|
if r.Body != nil {
|
||||||
|
body, _ = io.ReadAll(r.Body)
|
||||||
|
}
|
||||||
|
if r.URL.Host == "garage.test:3903" {
|
||||||
|
if r.Header.Get("Authorization") != "Bearer tok" {
|
||||||
|
rec.WriteHeader(403)
|
||||||
|
return rec.Result(), nil
|
||||||
|
}
|
||||||
|
op := strings.TrimPrefix(r.URL.Path, "/v2/")
|
||||||
|
f.ops = append(f.ops, op)
|
||||||
|
switch op {
|
||||||
|
case "GetBucketInfo":
|
||||||
|
fmt.Fprintf(rec, `{"id":%q,"globalAliases":["photos"]}`, r.URL.Query().Get("id"))
|
||||||
|
case "CreateKey":
|
||||||
|
f.keys["GKtemp"] = true
|
||||||
|
rec.WriteString(`{"accessKeyId":"GKtemp","secretAccessKey":"secret"}`)
|
||||||
|
case "DeleteKey":
|
||||||
|
delete(f.keys, r.URL.Query().Get("id"))
|
||||||
|
case "CleanupIncompleteUploads":
|
||||||
|
f.cleanups++
|
||||||
|
if !strings.Contains(string(body), `"olderThanSecs":0`) {
|
||||||
|
rec.WriteHeader(400)
|
||||||
|
}
|
||||||
|
rec.WriteString(`{"uploadsDeleted":3}`)
|
||||||
|
default:
|
||||||
|
rec.WriteString(`{}`)
|
||||||
|
}
|
||||||
|
return rec.Result(), nil
|
||||||
|
}
|
||||||
|
if r.URL.Host != "garage.test:3900" || r.URL.Path != "/photos" {
|
||||||
|
rec.WriteHeader(404)
|
||||||
|
return rec.Result(), nil
|
||||||
|
}
|
||||||
|
f.s3Auth = append(f.s3Auth, r.Header.Get("Authorization"))
|
||||||
|
if !strings.Contains(r.Header.Get("Authorization"), "Credential=GKtemp/") {
|
||||||
|
rec.WriteHeader(403)
|
||||||
|
return rec.Result(), nil
|
||||||
|
}
|
||||||
|
q := r.URL.Query()
|
||||||
|
switch {
|
||||||
|
case r.Method == "GET" && q.Get("list-type") == "2":
|
||||||
|
all := make([]string, 0, len(f.objects))
|
||||||
|
for k := range f.objects {
|
||||||
|
if k > q.Get("continuation-token") {
|
||||||
|
all = append(all, k)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(all)
|
||||||
|
trunc := len(all) > 1000
|
||||||
|
if trunc {
|
||||||
|
all = all[:1000]
|
||||||
|
}
|
||||||
|
rec.WriteString(`<ListBucketResult>`)
|
||||||
|
for _, k := range all {
|
||||||
|
fmt.Fprintf(rec, `<Contents><Key>%s</Key></Contents>`, k)
|
||||||
|
}
|
||||||
|
if trunc {
|
||||||
|
fmt.Fprintf(rec, `<IsTruncated>true</IsTruncated><NextContinuationToken>%s</NextContinuationToken>`, all[len(all)-1])
|
||||||
|
}
|
||||||
|
rec.WriteString(`</ListBucketResult>`)
|
||||||
|
case r.Method == "POST" && q.Has("delete"):
|
||||||
|
if r.Header.Get("Content-Md5") == "" {
|
||||||
|
rec.WriteHeader(400)
|
||||||
|
return rec.Result(), nil
|
||||||
|
}
|
||||||
|
var in struct {
|
||||||
|
Objects []struct{ Key string } `xml:"Object"`
|
||||||
|
}
|
||||||
|
_ = xml.Unmarshal(body, &in)
|
||||||
|
rec.WriteString(`<DeleteResult>`)
|
||||||
|
for _, o := range in.Objects {
|
||||||
|
if o.Key == "verrou" {
|
||||||
|
rec.WriteString(`<Error><Key>verrou</Key><Code>AccessDenied</Code><Message>non</Message></Error>`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
delete(f.objects, o.Key)
|
||||||
|
}
|
||||||
|
rec.WriteString(`</DeleteResult>`)
|
||||||
|
default:
|
||||||
|
rec.WriteHeader(400)
|
||||||
|
}
|
||||||
|
return rec.Result(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmptyBucket(t *testing.T) {
|
||||||
|
f := &fakeCluster{objects: map[string]bool{"verrou": true}, keys: map[string]bool{}}
|
||||||
|
for i := 0; i < 2500; i++ {
|
||||||
|
f.objects[fmt.Sprintf("dir/obj %05d+é", i)] = true
|
||||||
|
}
|
||||||
|
c := newTestConfig(t, f)
|
||||||
|
h := c.routes()
|
||||||
|
ck := login(t, h)
|
||||||
|
id := strings.Repeat("ab", 32)
|
||||||
|
|
||||||
|
req := httptest.NewRequest("POST", "/api/buckets/empty?id="+id, strings.NewReader("{}"))
|
||||||
|
req.Header.Set(csrfHeader, "x")
|
||||||
|
req.AddCookie(ck)
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != 200 {
|
||||||
|
t.Fatalf("code %d : %s", rec.Code, rec.Body)
|
||||||
|
}
|
||||||
|
var last emptyEvent
|
||||||
|
lines := 0
|
||||||
|
sc := bufio.NewScanner(rec.Body)
|
||||||
|
for sc.Scan() {
|
||||||
|
lines++
|
||||||
|
if err := json.Unmarshal(sc.Bytes(), &last); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if last.Phase != "done" || last.Deleted != 2500 || last.Failed != 1 || last.UploadsDeleted != 3 || len(last.Errors) != 1 {
|
||||||
|
t.Fatalf("résultat : %+v", last)
|
||||||
|
}
|
||||||
|
if lines < 4 { // start + 3 lots + done
|
||||||
|
t.Fatalf("%d lignes d'avancement", lines)
|
||||||
|
}
|
||||||
|
if len(f.objects) != 1 || f.cleanups != 1 {
|
||||||
|
t.Fatalf("restent %d objets, %d nettoyages", len(f.objects), f.cleanups)
|
||||||
|
}
|
||||||
|
if len(f.keys) != 0 {
|
||||||
|
t.Fatal("la clé temporaire n'a pas été supprimée")
|
||||||
|
}
|
||||||
|
if f.ops[len(f.ops)-1] != "DeleteKey" {
|
||||||
|
t.Fatalf("dernière opération : %s", f.ops[len(f.ops)-1])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sans en-tête anti-CSRF, ou identifiant invalide : refusé.
|
||||||
|
req = httptest.NewRequest("POST", "/api/buckets/empty?id="+id, nil)
|
||||||
|
req.AddCookie(ck)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != 403 {
|
||||||
|
t.Fatalf("sans CSRF : %d", rec.Code)
|
||||||
|
}
|
||||||
|
req = httptest.NewRequest("POST", "/api/buckets/empty?id=../x", nil)
|
||||||
|
req.Header.Set(csrfHeader, "x")
|
||||||
|
req.AddCookie(ck)
|
||||||
|
rec = httptest.NewRecorder()
|
||||||
|
h.ServeHTTP(rec, req)
|
||||||
|
if rec.Code != 400 {
|
||||||
|
t.Fatalf("id invalide : %d", rec.Code)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user