mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
* util: one admission rule for upload limits * operation: mark gateway fan-out holder writes as client traffic * volume: bound upload admission, limit gateway holder writes, 503 on timeout * volume: charge unknown-length uploads half the budget, document client wait cap * s3, filer: admit uploads by inFlight+size and charge unknown lengths a chunk * s3: answer a volume overload as SlowDown with Retry-After * operation: cut an upload whose body crawls below the minimum rate on any host * operation: make the slow-commit deadline test honour the request context * s3: stop chunk uploads when the client goes away * operation: treat a body deadline cut as back-pressure, not a same-holder retry A body that crawls past the body deadline returns from retriedUploadData at once, like an overload, and counts toward the single reassign the chunk loop and the filer retry gate give back-pressure. A watchdog cut keeps its retry on a fresh conn. Both still match ErrUploadStalled and stay reassignable. * operation: apply the body deadline only to uploads that opt in UploadOption.BodyDeadline and ChunkedUploadOption.BodyDeadline turn the body deadline on; S3 chunk uploads (relay and fan-out) and the filer's chunk loop set it. Mount, filer.sync, filer.copy and UploadWithRetry keep the stall watchdog only, as before the deadline existed. * s3, operation: check a chunk cancelled with its client is deleted from every holder A volume commits on a context that ignores the cancel, so a chunk whose caller went away after sending the body may still land. The chunk loop already deletes the fid from every holder after a failed attempt; pin that for the relay and fan-out paths and for an S3 PUT whose client goes away. * s3: count a request's declared bytes in the circuit breaker byte limits The per-bucket and global byte counters go back to the declared length (an unknown length counts one chunk), so a bucket bytes limit still rejects a single PUT larger than it. Only the upload budget uses the capped gateway charge. * s3: answer copy chunk overloads as SlowDown, tidy the client-gone checks CopyObject and UploadPartCopy map a volume overload or an exhausted stall to SlowDown, as PutObject does. The client-gone log check matches the mapper's context.Canceled test, the truncated-body case drops a check the first case already makes, and the Retry-After test reads the headers actually sent. * filer, volume: clamp the filer charge chunk, set the upload gauge under the lock A filer with -maxMB 0 charges its default chunk size instead of nothing. The volume server sets its in-flight upload gauge inside the critical section. The upload limit tests wait until the waiter is parked before releasing, check handleUploadRequest gives its charge back, and use CI-safe bounds. * volume: cap the Rust server's client upload-slot wait at 5s Same cap as the Go volume server's volumeClientUploadWaitCap, so a gateway's body deadline never fires before the 503. * operation: reflow the body deadline comment * volume(rs): count a gateway's src=client holder write against the upload limit Mirrors operation.IsReplicaForward: only a primary-to-replica forward skips the upload budget; a gateway's ?type=replicate&src=client fan-out waits like any client write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): admit uploads by inFlight+size, reserved atomically Mirrors the Go volume server's waitForUploadSlot: an upload is admitted by util.UploadAdmits (idle server, or inFlight + size within the limit) and reserves its bytes in the same step, so concurrent waiters cannot all pass one check. Primary-to-replica forwards and unlimited servers are counted but never refused. UploadLimitCond counts once per waiting upload, and the wake-up is armed before each check so a release in between is not missed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): charge an unknown-length upload against the upload limit Mirrors the Go volume server's uploadCharge: a chunked upload without Content-Length reserves one file's worth of budget, at most half the limit and at least 1 byte, instead of 0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): a zero -inflightUploadDataTimeout waits the 5s client cap The Go volume server now reads 0 as the 5s cap (its flag help says so); the Rust server used a 2s wait. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): close a rejected large or unknown-length HTTP/1 upload Mirrors the Go volume server's uploadRejectCloseThreshold: the 503 for a body over 256 KiB, or one without a length, carries Connection: close instead of keeping the connection for a body nobody reads. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): drop src from a primary's replica forward A client upload carrying src=client kept it on the forward, so replicas treated the forward as gateway fan-out and could refuse it after the primary had already appended. Go's ReplicatedWrite builds a fresh query. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): keep the upload admission CAS buildable on rust 1.91.1 Atomic try_update is stable only since 1.95. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume(rs): refuse an upload the in-flight counter cannot hold A replica forward added its charge with fetch_add, so a Content-Length near i64::MAX wrapped the shared counter negative and let later client uploads past admission. The forward now reserves with a checked add and answers 503 when the size does not fit; the client CAS adds only after admission passes. With no upload limit the counter only feeds the gauge, so it keeps wrapping arithmetic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: refuse an upload the in-flight counter cannot hold A replica forward added its charge unchecked, so a Content-Length near math.MaxInt64 wrapped inFlightUploadDataSize negative and let later client uploads past admission. Under the lock the reservation now checks that the counter can hold the charge and answers 503 otherwise, matching the Rust volume server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * volume: keep the request body on a rejected upload Replacing r.Body with http.NoBody hid the server's early close of the unread body from net/http before Go 1.27, so it skipped the FIN-then-wait close and reset the connection under a client still sending. Go 1.26.6, the version go.mod declares, then failed TestUploadLimit503ReachesGoClientForLargeBody with a write error instead of the 503. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * util: compare upload admission without forming inFlight+size * operation: reassign a chunk after a 429 as after a 503 * s3: do not count a chunk assignment the client cancelled as a filer failure * filer: charge an upload by its request chunk size, and an inline upload by its whole body * s3: hold an aws-chunked body to its X-Amz-Decoded-Content-Length * volume: answer a rejected small-body upload without waiting for its body * s3: fill the upload budget before testing that a release wakes every waiter --------- Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
371 lines
12 KiB
Go
371 lines
12 KiB
Go
package s3api
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"hash/crc32"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/seaweedfs/seaweedfs/weed/credential"
|
|
_ "github.com/seaweedfs/seaweedfs/weed/credential/memory"
|
|
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
|
)
|
|
|
|
func TestGetRequestDataReader_ChunkedEncodingWithoutIAM(t *testing.T) {
|
|
// Create an S3ApiServer with IAM disabled
|
|
s3a := &S3ApiServer{
|
|
iam: NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, string(credential.StoreTypeMemory)),
|
|
}
|
|
// Ensure IAM is disabled for this test
|
|
s3a.iam.isAuthEnabled = false
|
|
|
|
tests := []struct {
|
|
name string
|
|
contentSha256 string
|
|
expectedError s3err.ErrorCode
|
|
shouldProcess bool
|
|
description string
|
|
}{
|
|
{
|
|
name: "RegularRequest",
|
|
contentSha256: "",
|
|
expectedError: s3err.ErrNone,
|
|
shouldProcess: false,
|
|
description: "Regular requests without chunked encoding should pass through unchanged",
|
|
},
|
|
{
|
|
name: "StreamingSignedWithoutIAM",
|
|
contentSha256: "STREAMING-AWS4-HMAC-SHA256-PAYLOAD",
|
|
expectedError: s3err.ErrNone,
|
|
shouldProcess: true,
|
|
description: "Streaming signed requests are decoded when IAM is disabled; signatures are skipped since there is nothing to verify them against",
|
|
},
|
|
{
|
|
name: "StreamingUnsignedWithoutIAM",
|
|
contentSha256: "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
|
|
expectedError: s3err.ErrNone,
|
|
shouldProcess: true,
|
|
description: "Streaming unsigned requests should be processed even when IAM is disabled",
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
body := strings.NewReader("test data")
|
|
req, _ := http.NewRequest("PUT", "/bucket/key", body)
|
|
|
|
if tt.contentSha256 != "" {
|
|
req.Header.Set("x-amz-content-sha256", tt.contentSha256)
|
|
}
|
|
|
|
dataReader, errCode := getRequestDataReader(s3a, req)
|
|
|
|
// Check error code
|
|
if errCode != tt.expectedError {
|
|
t.Errorf("Expected error code %v, got %v", tt.expectedError, errCode)
|
|
}
|
|
|
|
// For successful cases, check if processing occurred
|
|
if errCode == s3err.ErrNone {
|
|
if tt.shouldProcess {
|
|
// For chunked requests, the reader should be different from the original body
|
|
if dataReader == req.Body {
|
|
t.Error("Expected dataReader to be processed by newChunkedReader, but got raw request body")
|
|
}
|
|
} else {
|
|
// For regular requests, the reader should be the same as the original body
|
|
if dataReader != req.Body {
|
|
t.Error("Expected dataReader to be the same as request body for regular requests")
|
|
}
|
|
}
|
|
}
|
|
|
|
t.Logf("Test case: %s - %s", tt.name, tt.description)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestGetRequestDataReader_AuthTypeDetection(t *testing.T) {
|
|
// Create an S3ApiServer with IAM disabled
|
|
s3a := &S3ApiServer{
|
|
iam: NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, string(credential.StoreTypeMemory)),
|
|
}
|
|
s3a.iam.isAuthEnabled = false
|
|
|
|
// Test the specific case mentioned in the issue where chunked data
|
|
// with checksum headers would be stored incorrectly
|
|
t.Run("ChunkedDataWithChecksum", func(t *testing.T) {
|
|
// Simulate a request with chunked data and checksum trailer
|
|
body := strings.NewReader("test content")
|
|
req, _ := http.NewRequest("PUT", "/bucket/key", body)
|
|
req.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
|
|
req.Header.Set("x-amz-trailer", "x-amz-checksum-crc32")
|
|
|
|
// Verify the auth type is detected correctly
|
|
authType := getRequestAuthType(req)
|
|
if authType != authTypeStreamingUnsigned {
|
|
t.Errorf("Expected authTypeStreamingUnsigned, got %v", authType)
|
|
}
|
|
|
|
// Verify the request is processed correctly
|
|
dataReader, errCode := getRequestDataReader(s3a, req)
|
|
if errCode != s3err.ErrNone {
|
|
t.Errorf("Expected no error, got %v", errCode)
|
|
}
|
|
|
|
// The dataReader should be processed by newChunkedReader
|
|
if dataReader == req.Body {
|
|
t.Error("Expected dataReader to be processed by newChunkedReader to handle chunked encoding")
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestGetRequestDataReader_IAMEnabled(t *testing.T) {
|
|
// Create an S3ApiServer with IAM enabled
|
|
s3a := &S3ApiServer{
|
|
iam: NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, string(credential.StoreTypeMemory)),
|
|
}
|
|
s3a.iam.isAuthEnabled = true
|
|
|
|
t.Run("StreamingUnsignedWithIAMEnabled", func(t *testing.T) {
|
|
body := strings.NewReader("test data")
|
|
req, _ := http.NewRequest("PUT", "/bucket/key", body)
|
|
req.Header.Set("x-amz-content-sha256", "STREAMING-UNSIGNED-PAYLOAD-TRAILER")
|
|
|
|
dataReader, errCode := getRequestDataReader(s3a, req)
|
|
|
|
// Should succeed and be processed
|
|
if errCode != s3err.ErrNone {
|
|
t.Errorf("Expected no error, got %v", errCode)
|
|
}
|
|
|
|
// Should be processed by newChunkedReader
|
|
if dataReader == req.Body {
|
|
t.Error("Expected dataReader to be processed by newChunkedReader")
|
|
}
|
|
})
|
|
}
|
|
|
|
// Test helper to verify auth type detection works correctly
|
|
func TestAuthTypeDetection(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
headers map[string]string
|
|
expectedType authType
|
|
}{
|
|
{
|
|
name: "StreamingUnsigned",
|
|
headers: map[string]string{"x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER"},
|
|
expectedType: authTypeStreamingUnsigned,
|
|
},
|
|
{
|
|
name: "StreamingSigned",
|
|
headers: map[string]string{"x-amz-content-sha256": "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"},
|
|
expectedType: authTypeStreamingSigned,
|
|
},
|
|
{
|
|
name: "Regular",
|
|
headers: map[string]string{},
|
|
expectedType: authTypeAnonymous,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
req, _ := http.NewRequest("PUT", "/bucket/key", strings.NewReader("test"))
|
|
for key, value := range tt.headers {
|
|
req.Header.Set(key, value)
|
|
}
|
|
|
|
authType := getRequestAuthType(req)
|
|
if authType != tt.expectedType {
|
|
t.Errorf("Expected auth type %v, got %v", tt.expectedType, authType)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func sha256Hex(t *testing.T, b []byte) string {
|
|
t.Helper()
|
|
sum := sha256.Sum256(b)
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
func TestExpectedContentSha256(t *testing.T) {
|
|
good := sha256Hex(t, []byte("payload"))
|
|
|
|
tests := []struct {
|
|
name string
|
|
header string
|
|
wantValid bool
|
|
wantNil bool
|
|
}{
|
|
{"absent", "", true, true},
|
|
{"unsigned", unsignedPayload, true, true},
|
|
{"streaming signed", streamingContentSHA256, true, true},
|
|
{"streaming trailer", streamingContentSHA256Trailer, true, true},
|
|
{"streaming unsigned", streamingUnsignedPayload, true, true},
|
|
{"hex", good, true, false},
|
|
{"not hex", "nothex", false, true},
|
|
{"short hex", "deadbeef", false, true},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
r := httptest.NewRequest("PUT", "/b/o", nil)
|
|
if tt.header != "" {
|
|
r.Header.Set("X-Amz-Content-Sha256", tt.header)
|
|
}
|
|
got, valid := expectedContentSha256(r)
|
|
if valid != tt.wantValid {
|
|
t.Fatalf("valid=%v want %v", valid, tt.wantValid)
|
|
}
|
|
if (got == nil) != tt.wantNil {
|
|
t.Fatalf("expected nil=%v, got %x", tt.wantNil, got)
|
|
}
|
|
})
|
|
}
|
|
|
|
t.Run("base64 decodes to sha256", func(t *testing.T) {
|
|
sum := sha256.Sum256([]byte("payload"))
|
|
r := httptest.NewRequest("PUT", "/b/o", nil)
|
|
r.Header.Set("X-Amz-Content-Sha256", base64.StdEncoding.EncodeToString(sum[:]))
|
|
got, valid := expectedContentSha256(r)
|
|
if !valid || !bytes.Equal(got, sum[:]) {
|
|
t.Fatalf("valid=%v got=%x", valid, got)
|
|
}
|
|
})
|
|
}
|
|
|
|
func newVerifier(body string, expectedHex string) *contentSha256Verifier {
|
|
expected, _ := hex.DecodeString(expectedHex)
|
|
return &contentSha256Verifier{
|
|
reader: io.NopCloser(strings.NewReader(body)),
|
|
hasher: sha256.New(),
|
|
expected: expected,
|
|
}
|
|
}
|
|
|
|
func TestContentSha256VerifierMatch(t *testing.T) {
|
|
v := newVerifier("hello", sha256Hex(t, []byte("hello")))
|
|
got, err := io.ReadAll(v)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if string(got) != "hello" {
|
|
t.Fatalf("got %q", got)
|
|
}
|
|
}
|
|
|
|
func TestContentSha256VerifierMismatch(t *testing.T) {
|
|
v := newVerifier("hello", sha256Hex(t, []byte("other")))
|
|
_, err := io.ReadAll(v)
|
|
if err == nil || !strings.Contains(err.Error(), "does not match") {
|
|
t.Fatalf("expected mismatch error, got %v", err)
|
|
}
|
|
if _, err := v.Read(make([]byte, 8)); err == nil {
|
|
t.Fatal("expected error to persist")
|
|
}
|
|
}
|
|
|
|
// mimeDetect performs a single Read and ignores its error; the verifier must
|
|
// defer the mismatch so a dropped (n>0, err) result still surfaces later.
|
|
func TestContentSha256VerifierSurvivesDroppedError(t *testing.T) {
|
|
v := newVerifier("hello", sha256Hex(t, []byte("other")))
|
|
buf := make([]byte, 512)
|
|
n, _ := v.Read(buf)
|
|
rest := io.MultiReader(bytes.NewReader(buf[:n]), v)
|
|
_, err := io.ReadAll(rest)
|
|
if err == nil || !strings.Contains(err.Error(), "does not match") {
|
|
t.Fatalf("expected deferred mismatch error, got %v", err)
|
|
}
|
|
}
|
|
|
|
// A zero-length body never reaches the verifier, so the declared hash is
|
|
// compared against the empty-payload digest up front.
|
|
func TestGetRequestDataReaderEmptyBodyHash(t *testing.T) {
|
|
s3a := &S3ApiServer{
|
|
iam: NewIdentityAccessManagementWithStore(&S3ApiServerOption{}, nil, string(credential.StoreTypeMemory)),
|
|
}
|
|
s3a.iam.isAuthEnabled = false
|
|
|
|
mismatch := httptest.NewRequest("PUT", "/b/dir/", http.NoBody)
|
|
mismatch.Header.Set("X-Amz-Content-Sha256", sha256Hex(t, []byte("other")))
|
|
if _, code := getRequestDataReader(s3a, mismatch); code != s3err.ErrContentSHA256Mismatch {
|
|
t.Fatalf("empty body with wrong hash: code=%v", code)
|
|
}
|
|
|
|
malformed := httptest.NewRequest("PUT", "/b/o", strings.NewReader("x"))
|
|
malformed.Header.Set("X-Amz-Content-Sha256", "nothex")
|
|
if _, code := getRequestDataReader(s3a, malformed); code != s3err.ErrInvalidArgument {
|
|
t.Fatalf("malformed sha256 header: code=%v", code)
|
|
}
|
|
|
|
emptySum := sha256.Sum256(nil)
|
|
match := httptest.NewRequest("PUT", "/b/dir/", http.NoBody)
|
|
match.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(emptySum[:]))
|
|
if _, code := getRequestDataReader(s3a, match); code != s3err.ErrNone {
|
|
t.Fatalf("empty body with empty hash: code=%v", code)
|
|
}
|
|
}
|
|
|
|
// unsignedChunkedRequest is an anonymous aws-chunked PUT with unknown
|
|
// Content-Length, whose body decodes to payload and which declares declared as
|
|
// its X-Amz-Decoded-Content-Length.
|
|
func unsignedChunkedRequest(payload string, declared string) *http.Request {
|
|
checksum := crc32.ChecksumIEEE([]byte(payload))
|
|
sum := []byte{byte(checksum >> 24), byte(checksum >> 16), byte(checksum >> 8), byte(checksum)}
|
|
body := fmt.Sprintf("%x\r\n%s\r\n0\r\n\r\nx-amz-checksum-crc32:%s\r\n\r\n", len(payload), payload, base64.StdEncoding.EncodeToString(sum))
|
|
req := httptest.NewRequest(http.MethodPut, "/bucket/key", strings.NewReader(body))
|
|
req.ContentLength = -1
|
|
req.Header.Set("X-Amz-Content-Sha256", streamingUnsignedPayload)
|
|
req.Header.Set("X-Amz-Trailer", "x-amz-checksum-crc32")
|
|
req.Header.Set("Content-Encoding", "aws-chunked")
|
|
req.Header.Set("X-Amz-Decoded-Content-Length", declared)
|
|
return req
|
|
}
|
|
|
|
// The upload budget charges an aws-chunked request of unknown Content-Length
|
|
// by its X-Amz-Decoded-Content-Length, so the body is held to it: a client
|
|
// cannot declare a few bytes and stream gigabytes past its reservation.
|
|
func TestGetRequestDataReaderHoldsAwsChunkedBodyToDecodedLength(t *testing.T) {
|
|
s3a := &S3ApiServer{iam: &IdentityAccessManagement{}}
|
|
|
|
t.Run("matches", func(t *testing.T) {
|
|
reader, code := getRequestDataReader(s3a, unsignedChunkedRequest("hello world", "11"))
|
|
if code != s3err.ErrNone {
|
|
t.Fatalf("getRequestDataReader: %v", code)
|
|
}
|
|
got, err := io.ReadAll(reader)
|
|
if err != nil || string(got) != "hello world" {
|
|
t.Fatalf("got %q, %v", got, err)
|
|
}
|
|
})
|
|
|
|
t.Run("longer than declared", func(t *testing.T) {
|
|
reader, code := getRequestDataReader(s3a, unsignedChunkedRequest("hello world", "5"))
|
|
if code != s3err.ErrNone {
|
|
t.Fatalf("getRequestDataReader: %v", code)
|
|
}
|
|
got, err := io.ReadAll(reader)
|
|
if !errors.Is(err, errDecodedLengthExceeded) {
|
|
t.Fatalf("want errDecodedLengthExceeded, got %q, %v", got, err)
|
|
}
|
|
if len(got) > 5 {
|
|
t.Fatalf("read %d bytes past a declared 5", len(got))
|
|
}
|
|
wrapped := fmt.Errorf("upload chunk: read chunk at offset 0: %w", err)
|
|
if code := mapChunkedUploadErrorToS3Error(context.Background(), wrapped); code != s3err.ErrInvalidRequest {
|
|
t.Fatalf("mapped to %v, want ErrInvalidRequest", code)
|
|
}
|
|
})
|
|
}
|