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,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