Commit Graph
21 Commits
Author SHA1 Message Date
77a6787335 Bound upload memory: admission by size, gateway holder writes, 503/SlowDown back-pressure, body deadline (#13021)
* 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>
2026-11-26 08:34:47 -08:00
cbce146a63 s3api: keep a long CopyObject/UploadPartCopy alive with whitespace, as AWS does (#12862)
* s3api: keep a long CopyObject/UploadPartCopy alive with whitespace, as AWS does

CopyObject and UploadPartCopy copy every chunk and only then write the
response. On a slow volume disk (~10 MB/s), or when the source is a
remote-only file of a remote-mounted bucket that is fetched first, a copy of
tens of MB sends no byte for 20-30 s. Clients with a low-speed check give up
while the copy finishes: the AWS SDK for C++ (pyarrow, among others) sets
libcurl's CURLOPT_LOW_SPEED_LIMIT to 1 byte/s over a few seconds, and the
abandoned copy leaves an orphan.

AWS S3's documented behaviour for long copies: answer 200 at once, keep the
connection alive with whitespace, then send <CopyObjectResult> (or an
<Error> document) in the body. This does the same:

- Once every check that refuses with its own status has run (auth, missing
  source, preconditions, invalid arguments, ACL and lock headers, the
  remote-cache 503), a copy still running after 1 s commits to 200,
  application/xml and the XML declaration, then sends one space a second,
  flushed, until <CopyObjectResult>/<CopyPartResult> (checksum in the body)
  or an <Error> with the code the handler would have answered. A copy that
  ends sooner answers byte for byte as before.
- Armed before a remote-only source is fetched into the cluster, which is
  the slow part on a remote-mounted bucket.
- Never kept alive: the metadata-only self-copy; a destination with
  versioning Enabled (x-amz-version-id is known only after the copy); a part
  copy whose upload or request carries SSE (its response headers are known
  only after the copy).
- One goroutine owns the ResponseWriter from arming until halt() returns;
  a client that leaves ends it without touching the copy.
- s3err gains StartStreamingResponse, ErrorResponseFor and EncodeXMLBody,
  shared with WriteErrorResponse.

Accepted: a slow failure is 200 + <Error>, as on AWS, and the request is
counted as 200.

Tests: s3api_object_handlers_copy_keepalive_test.go (slow success and
failure, fast unchanged, a refusal keeps its status, part copy, versioned
destination, SSE-C part, checksum in the body, remote fill covered, client
gone under -race, slow lookup then bad tag = 400, self-copy 412 under the
lock, part range on a remote-only source). With the keep-alive forced off,
the slow-copy tests fail.

* s3api: send a block of spaces per copy keep-alive tick

libcurl rounds its measured rate down, so one byte a second sits right
at the AWS SDK for C++'s 1 byte/s low-speed limit and jitter can trip it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: audit a kept-alive copy error at the 200 it was sent with

Once the keep-alive has sent 200, the <Error> rides in that response, so
the access log records 200 and the error code, as AWS server access logs do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fill a conditional remote-only copy source before the keep-alive

A source condition read the filled entry only after the keep-alive had
committed 200, so a slow fill turned its 412 (or the 400 of a malformed
date) into an <Error> inside a 200. With any x-amz-copy-source-if-*
header the fill runs first, as it did before the keep-alive.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: fill a remote-only self-copy that moves data under the keep-alive

Only a self-copy that can stay metadata-only needs its source filled
before the keep-alive; one that re-encrypts takes the data path, so its
fill is the slow part the keep-alive is for. A fill changes no
encryption state, so the unfilled entry decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: test that the copy keep-alive reaches a client mid-copy

A ResponseRecorder keeps every write, flushed or not; over a real
connection the declaration and the spaces must arrive while the copy is
still held.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* s3api: bound the copy keep-alive streaming test with a request deadline

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 13:05:04 -08:00
Chris LuandDevin 7ff77a4f3b s3api: skip error response body when http forbids it (#11931)
WriteResponse wrote the payload even for HEAD requests and statuses
that disallow a body (1xx, 204, 304), which made net/http return
ErrBodyNotAllowed and logged 'write err: http: request method or
response status code does not allow body' for ordinary requests.

Generated with [Devin](https://devin.ai)

Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-21 20:43:32 -07:00
Chris Lu 93d4a6aefd s3: drain request body before error response (#11334)
* s3: drain request body before error response

* s3: keep oversized request bodies drainable
2026-09-15 13:09:07 -07:00
Chris Lu 2da24cc230 fix(s3): return 403 on POST policy violation instead of 307 redirect (#9122)
* fix(s3): return 403 on POST policy violation instead of 307 redirect

CheckPostPolicy failures previously responded with HTTP 307 Temporary
Redirect to the request URL, which causes clients to re-POST and
obscures the failure. Return 403 AccessDenied so the client surfaces
the error.

* test(s3): exercise PostPolicyBucketHandler end-to-end for 403 mapping

Replace the shallow ErrAccessDenied tautology test with one that builds
a signed POST multipart request whose policy conditions cannot be
satisfied, calls PostPolicyBucketHandler directly, and asserts HTTP 403
with no Location redirect header. Addresses gemini-code-assist review on
PR #9122.

* fix(s3): surface POST policy failure reason in AccessDenied response

Add s3err.WriteErrorResponseWithMessage so a caller can keep the
standard error code mapping while providing a specific Message. Use it
from PostPolicyBucketHandler so the XML body carries the CheckPostPolicy
error (e.g. which condition failed or that the policy expired) rather
than the generic "Access Denied." description. Addresses gemini-code-
assist review on PR #9122.

* refactor(s3err): delegate WriteErrorResponse to WriteErrorResponseWithMessage

The two helpers shared every line except the Message override. Fold
WriteErrorResponse into a one-line delegation that passes an empty
message, so the request-id/mux/apiError logic lives in exactly one
place. Addresses gemini-code-assist review on PR #9122.
2026-04-17 14:54:58 -07:00
Chris Lu 540fc97e00 s3/iam: reuse one request id per request (#8538)
* request_id: add shared request middleware

* s3err: preserve request ids in responses and logs

* iam: reuse request ids in XML responses

* sts: reuse request ids in XML responses

* request_id: drop legacy header fallback

* request_id: use AWS-style request id format

* iam: fix AWS-compatible XML format for ErrorResponse and field ordering

- ErrorResponse uses bare <RequestId> at root level instead of
  <ResponseMetadata> wrapper, matching the AWS IAM error response spec
- Move CommonResponse to last field in success response structs so
  <ResponseMetadata> serializes after result elements
- Add randomness to request ID generation to avoid collisions
- Add tests for XML ordering and ErrorResponse format

* iam: remove duplicate error_response_test.go

Test is already covered by responses_test.go.

* address PR review comments

- Guard against typed nil pointers in SetResponseRequestID before
  interface assertion (CodeRabbit)
- Use regexp instead of strings.Index in test helpers for extracting
  request IDs (Gemini)

* request_id: prevent spoofing, fix nil-error branch, thread reqID to error writers

- Ensure() now always generates a server-side ID, ignoring client-sent
  x-amz-request-id headers to prevent request ID spoofing. Uses a
  private context key (contextKey{}) instead of the header string.
- writeIamErrorResponse in both iamapi and embedded IAM now accepts
  reqID as a parameter instead of calling Ensure() internally, ensuring
  a single request ID per request lifecycle.
- The nil-iamError branch in writeIamErrorResponse now writes a 500
  Internal Server Error response instead of returning silently.
- Updated tests to set request IDs via context (not headers) and added
  tests for spoofing prevention and context reuse.

* sts: add request-id consistency assertions to ActionInBody tests

* test: update admin test to expect server-generated request IDs

The test previously sent a client x-amz-request-id header and expected
it echoed back. Since Ensure() now ignores client headers to prevent
spoofing, update the test to verify the server returns a non-empty
server-generated request ID instead.

* iam: add generic WithRequestID helper alongside reflection-based fallback

Add WithRequestID[T] that uses generics to take the address of a value
type, satisfying the pointer receiver on SetRequestId without reflection.

The existing SetResponseRequestID is kept for the two call sites that
operate on interface{} (from large action switches where the concrete
type varies at runtime). Generics cannot replace reflection there since
Go cannot infer type parameters from interface{}.

* Remove reflection and generics from request ID setting

Call SetRequestId directly on concrete response types in each switch
branch before boxing into interface{}, eliminating the need for
WithRequestID (generics) and SetResponseRequestID (reflection).

* iam: return pointer responses in action dispatch

* Fix IAM error handling consistency and ensure request IDs on all responses

- UpdateUser/CreatePolicy error branches: use writeIamErrorResponse instead
  of s3err.WriteErrorResponse to preserve IAM formatting and request ID
- ExecuteAction: accept reqID parameter and generate one if empty, ensuring
  every response carries a RequestId regardless of caller

* Clean up inline policies on DeleteUser and UpdateUser rename

DeleteUser: remove InlinePolicies[userName] from policy storage before
removing the identity, so policies are not orphaned.

UpdateUser: move InlinePolicies[userName] to InlinePolicies[newUserName]
when renaming, so GetUserPolicy/DeleteUserPolicy work under the new name.

Both operations persist the updated policies and return an error if
the storage write fails, preventing partial state.
2026-03-06 15:22:39 -08:00
Chris Luandgemini-code-assist[bot] ca84a8a713 S3: Directly read write volume servers (#7481)
* Lazy Versioning Check, Conditional SSE Entry Fetch, HEAD Request Optimization

* revert

Reverted the conditional versioning check to always check versioning status
Reverted the conditional SSE entry fetch to always fetch entry metadata
Reverted the conditional versioning check to always check versioning status
Reverted the conditional SSE entry fetch to always fetch entry metadata

* Lazy Entry Fetch for SSE, Skip Conditional Header Check

* SSE-KMS headers are present, this is not an SSE-C request (mutually exclusive)

* SSE-C is mutually exclusive with SSE-S3 and SSE-KMS

* refactor

* Removed Premature Mutual Exclusivity Check

* check for the presence of the X-Amz-Server-Side-Encryption header

* not used

* fmt

* directly read write volume servers

* HTTP Range Request Support

* set header

* md5

* copy object

* fix sse

* fmt

* implement sse

* sse continue

* fixed the suffix range bug (bytes=-N for "last N bytes")

* debug logs

* Missing PartsCount Header

* profiling

* url encoding

* test_multipart_get_part

* headers

* debug

* adjust log level

* handle part number

* Update s3api_object_handlers.go

* nil safety

* set ModifiedTsNs

* remove

* nil check

* fix sse header

* same logic as filer

* decode values

* decode ivBase64

* s3: Fix SSE decryption JWT authentication and streaming errors

Critical fix for SSE (Server-Side Encryption) test failures:

1. **JWT Authentication Bug** (Root Cause):
   - Changed from GenJwtForFilerServer to GenJwtForVolumeServer
   - S3 API now uses correct JWT when directly reading from volume servers
   - Matches filer's authentication pattern for direct volume access
   - Fixes 'unexpected EOF' and 500 errors in SSE tests

2. **Streaming Error Handling**:
   - Added error propagation in getEncryptedStreamFromVolumes goroutine
   - Use CloseWithError() to properly communicate stream failures
   - Added debug logging for streaming errors

3. **Response Header Timing**:
   - Removed premature WriteHeader(http.StatusOK) call
   - Let Go's http package write status automatically on first write
   - Prevents header lock when errors occur during streaming

4. **Enhanced SSE Decryption Debugging**:
   - Added IV/Key validation and logging for SSE-C, SSE-KMS, SSE-S3
   - Better error messages for missing or invalid encryption metadata
   - Added glog.V(2) debugging for decryption setup

This fixes SSE integration test failures where encrypted objects
could not be retrieved due to volume server authentication failures.
The JWT bug was causing volume servers to reject requests, resulting
in truncated/empty streams (EOF) or internal errors.

* s3: Fix SSE multipart upload metadata preservation

Critical fix for SSE multipart upload test failures (SSE-C and SSE-KMS):

**Root Cause - Incomplete SSE Metadata Copying**:
The old code only tried to copy 'SeaweedFSSSEKMSKey' from the first
part to the completed object. This had TWO bugs:

1. **Wrong Constant Name** (Key Mismatch Bug):
   - Storage uses: SeaweedFSSSEKMSKeyHeader = 'X-SeaweedFS-SSE-KMS-Key'
   - Old code read: SeaweedFSSSEKMSKey = 'x-seaweedfs-sse-kms-key'
   - Result: SSE-KMS metadata was NEVER copied → 500 errors

2. **Missing SSE-C and SSE-S3 Headers**:
   - SSE-C requires: IV, Algorithm, KeyMD5
   - SSE-S3 requires: encrypted key data + standard headers
   - Old code: copied nothing for SSE-C/SSE-S3 → decryption failures

**Fix - Complete SSE Header Preservation**:
Now copies ALL SSE headers from first part to completed object:

- SSE-C: SeaweedFSSSEIV, CustomerAlgorithm, CustomerKeyMD5
- SSE-KMS: SeaweedFSSSEKMSKeyHeader, AwsKmsKeyId, ServerSideEncryption
- SSE-S3: SeaweedFSSSES3Key, ServerSideEncryption

Applied consistently to all 3 code paths:
1. Versioned buckets (creates version file)
2. Suspended versioning (creates main object with null versionId)
3. Non-versioned buckets (creates main object)

**Why This Is Correct**:
The headers copied EXACTLY match what putToFiler stores during part
upload (lines 496-521 in s3api_object_handlers_put.go). This ensures
detectPrimarySSEType() can correctly identify encrypted multipart
objects and trigger inline decryption with proper metadata.

Fixes: TestSSEMultipartUploadIntegration (SSE-C and SSE-KMS subtests)

* s3: Add debug logging for versioning state diagnosis

Temporary debug logging to diagnose test_versioning_obj_plain_null_version_overwrite_suspended failure.

Added glog.V(0) logging to show:
1. setBucketVersioningStatus: when versioning status is changed
2. PutObjectHandler: what versioning state is detected (Enabled/Suspended/none)
3. PutObjectHandler: which code path is taken (putVersionedObject vs putSuspendedVersioningObject)

This will help identify if:
- The versioning status is being set correctly in bucket config
- The cache is returning stale/incorrect versioning state
- The switch statement is correctly routing to suspended vs enabled handlers

* s3: Enhanced versioning state tracing for suspended versioning diagnosis

Added comprehensive logging across the entire versioning state flow:

PutBucketVersioningHandler:
- Log requested status (Enabled/Suspended)
- Log when calling setBucketVersioningStatus
- Log success/failure of status change

setBucketVersioningStatus:
- Log bucket and status being set
- Log when config is updated
- Log completion with error code

updateBucketConfig:
- Log versioning state being written to cache
- Immediate cache verification after Set
- Log if cache verification fails

getVersioningState:
- Log bucket name and state being returned
- Log if object lock forces VersioningEnabled
- Log errors

This will reveal:
1. If PutBucketVersioning(Suspended) is reaching the handler
2. If the cache update succeeds
3. What state getVersioningState returns during PUT
4. Any cache consistency issues

Expected to show why bucket still reports 'Enabled' after 'Suspended' call.

* s3: Add SSE chunk detection debugging for multipart uploads

Added comprehensive logging to diagnose why TestSSEMultipartUploadIntegration fails:

detectPrimarySSEType now logs:
1. Total chunk count and extended header count
2. All extended headers with 'sse'/'SSE'/'encryption' in the name
3. For each chunk: index, SseType, and whether it has metadata
4. Final SSE type counts (SSE-C, SSE-KMS, SSE-S3)

This will reveal if:
- Chunks are missing SSE metadata after multipart completion
- Extended headers are copied correctly from first part
- The SSE detection logic is working correctly

Expected to show if chunks have SseType=0 (none) or proper SSE types set.

* s3: Trace SSE chunk metadata through multipart completion and retrieval

Added end-to-end logging to track SSE chunk metadata lifecycle:

**During Multipart Completion (filer_multipart.go)**:
1. Log finalParts chunks BEFORE mkFile - shows SseType and metadata
2. Log versionEntry.Chunks INSIDE mkFile callback - shows if mkFile preserves SSE info
3. Log success after mkFile completes

**During GET Retrieval (s3api_object_handlers.go)**:
1. Log retrieved entry chunks - shows SseType and metadata after retrieval
2. Log detected SSE type result

This will reveal at which point SSE chunk metadata is lost:
- If finalParts have SSE metadata but versionEntry.Chunks don't → mkFile bug
- If versionEntry.Chunks have SSE metadata but retrieved chunks don't → storage/retrieval bug
- If chunks never have SSE metadata → multipart completion SSE processing bug

Expected to show chunks with SseType=NONE during retrieval even though
they were created with proper SseType during multipart completion.

* s3: Fix SSE-C multipart IV base64 decoding bug

**Critical Bug Found**: SSE-C multipart uploads were failing because:

Root Cause:
- entry.Extended[SeaweedFSSSEIV] stores base64-encoded IV (24 bytes for 16-byte IV)
- SerializeSSECMetadata expects raw IV bytes (16 bytes)
- During multipart completion, we were passing base64 IV directly → serialization error

Error Message:
"Failed to serialize SSE-C metadata for chunk in part X: invalid IV length: expected 16 bytes, got 24"

Fix:
- Base64-decode IV before passing to SerializeSSECMetadata
- Added error handling for decode failures

Impact:
- SSE-C multipart uploads will now correctly serialize chunk metadata
- Chunks will have proper SSE metadata for decryption during GET

This fixes the SSE-C subtest of TestSSEMultipartUploadIntegration.
SSE-KMS still has a separate issue (error code 23) being investigated.

* fixes

* kms sse

* handle retry if not found in .versions folder and should read the normal object

* quick check (no retries) to see if the .versions/ directory exists

* skip retry if object is not found

* explicit update to avoid sync delay

* fix map update lock

* Remove fmt.Printf debug statements

* Fix SSE-KMS multipart base IV fallback to fail instead of regenerating

* fmt

* Fix ACL grants storage logic

* header handling

* nil handling

* range read for sse content

* test range requests for sse objects

* fmt

* unused code

* upload in chunks

* header case

* fix url

* bucket policy error vs bucket not found

* jwt handling

* fmt

* jwt in request header

* Optimize Case-Insensitive Prefix Check

* dead code

* Eliminated Unnecessary Stream Prefetch for Multipart SSE

* range sse

* sse

* refactor

* context

* fmt

* fix type

* fix SSE-C IV Mismatch

* Fix Headers Being Set After WriteHeader

* fix url parsing

* propergate sse headers

* multipart sse-s3

* aws sig v4 authen

* sse kms

* set content range

* better errors

* Update s3api_object_handlers_copy.go

* Update s3api_object_handlers.go

* Update s3api_object_handlers.go

* avoid magic number

* clean up

* Update s3api_bucket_policy_handlers.go

* fix url parsing

* context

* data and metadata both use background context

* adjust the offset

* SSE Range Request IV Calculation

* adjust logs

* IV relative to offset in each part, not the whole file

* collect logs

* offset

* fix offset

* fix url

* logs

* variable

* jwt

* Multipart ETag semantics: conditionally set object-level Md5 for single-chunk uploads only.

* sse

* adjust IV and offset

* multipart boundaries

* ensures PUT and GET operations return consistent ETags

* Metadata Header Case

* CommonPrefixes Sorting with URL Encoding

* always sort

* remove the extra PathUnescape call

* fix the multipart get part ETag

* the FileChunk is created without setting ModifiedTsNs

* Sort CommonPrefixes lexicographically to match AWS S3 behavior

* set md5 for multipart uploads

* prevents any potential data loss or corruption in the small-file inline storage path

* compiles correctly

* decryptedReader will now be properly closed after use

* Fixed URL encoding and sort order for CommonPrefixes

* Update s3api_object_handlers_list.go

* SSE-x Chunk View Decryption

* Different IV offset calculations for single-part vs multipart objects

* still too verbose in logs

* less logs

* ensure correct conversion

* fix listing

* nil check

* minor fixes

* nil check

* single character delimiter

* optimize

* range on empty object or zero-length

* correct IV based on its position within that part, not its position in the entire object

* adjust offset

* offset

Fetch FULL encrypted chunk (not just the range)
Adjust IV by PartOffset/ChunkOffset only
Decrypt full chunk
Skip in the DECRYPTED stream to reach OffsetInChunk

* look breaking

* refactor

* error on no content

* handle intra-block byte skipping

* Incomplete HTTP Response Error Handling

* multipart SSE

* Update s3api_object_handlers.go

* address comments

* less logs

* handling directory

* Optimized rejectDirectoryObjectWithoutSlash() to avoid unnecessary lookups

* Revert "handling directory"

This reverts commit 3a335f0ac33c63f51975abc63c40e5328857a74b.

* constant

* Consolidate nil entry checks in GetObjectHandler

* add range tests

* Consolidate redundant nil entry checks in HeadObjectHandler

* adjust logs

* SSE type

* large files

* large files

Reverted the plain-object range test

* ErrNoEncryptionConfig

* Fixed SSERangeReader Infinite Loop Vulnerability

* Fixed SSE-KMS Multipart ChunkReader HTTP Body Leak

* handle empty directory in S3, added PyArrow tests

* purge unused code

* Update s3_parquet_test.py

* Update requirements.txt

* According to S3 specifications, when both partNumber and Range are present, the Range should apply within the selected part's boundaries, not to the full object.

* handle errors

* errors after writing header

* https

* fix: Wait for volume assignment readiness before running Parquet tests

The test-implicit-dir-with-server test was failing with an Internal Error
because volume assignment was not ready when tests started. This fix adds
a check that attempts a volume assignment and waits for it to succeed
before proceeding with tests.

This ensures that:
1. Volume servers are registered with the master
2. Volume growth is triggered if needed
3. The system can successfully assign volumes for writes

Fixes the timeout issue where boto3 would retry 4 times and fail with
'We encountered an internal error, please try again.'

* sse tests

* store derived IV

* fix: Clean up gRPC ports between tests to prevent port conflicts

The second test (test-implicit-dir-with-server) was failing because the
volume server's gRPC port (18080 = VOLUME_PORT + 10000) was still in use
from the first test. The cleanup code only killed HTTP port processes,
not gRPC port processes.

Added cleanup for gRPC ports in all stop targets:
- Master gRPC: MASTER_PORT + 10000 (19333)
- Volume gRPC: VOLUME_PORT + 10000 (18080)
- Filer gRPC: FILER_PORT + 10000 (18888)

This ensures clean state between test runs in CI.

* add import

* address comments

* docs: Add placeholder documentation files for Parquet test suite

Added three missing documentation files referenced in test/s3/parquet/README.md:

1. TEST_COVERAGE.md - Documents 43 total test cases (17 Go unit tests,
   6 Python integration tests, 20 Python end-to-end tests)

2. FINAL_ROOT_CAUSE_ANALYSIS.md - Explains the s3fs compatibility issue
   with PyArrow, the implicit directory problem, and how the fix works

3. MINIO_DIRECTORY_HANDLING.md - Compares MinIO's directory handling
   approach with SeaweedFS's implementation

Each file contains:
- Title and overview
- Key technical details relevant to the topic
- TODO sections for future expansion

These placeholder files resolve the broken README links and provide
structure for future detailed documentation.

* clean up if metadata operation failed

* Update s3_parquet_test.py

* clean up

* Update Makefile

* Update s3_parquet_test.py

* Update Makefile

* Handle ivSkip for non-block-aligned offsets

* Update README.md

* stop volume server faster

* stop volume server in 1 second

* different IV for each chunk in SSE-S3 and SSE-KMS

* clean up if fails

* testing upload

* error propagation

* fmt

* simplify

* fix copying

* less logs

* endian

* Added marshaling error handling

* handling invalid ranges

* error handling for adding to log buffer

* fix logging

* avoid returning too quickly and ensure proper cleaning up

* Activity Tracking for Disk Reads

* Cleanup Unused Parameters

* Activity Tracking for Kafka Publishers

* Proper Test Error Reporting

* refactoring

* less logs

* less logs

* go fmt

* guard it with if entry.Attributes.TtlSec > 0 to match the pattern used elsewhere.

* Handle bucket-default encryption config errors explicitly for multipart

* consistent activity tracking

* obsolete code for s3 on filer read/write handlers

* Update weed/s3api/s3api_object_handlers_list.go

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>

---------

Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
2025-11-18 23:18:35 -08:00
Chris Lu 33b9017b48 fix listing objects (#7008)
* fix listing objects

* add more list testing

* address comments

* fix next marker

* fix isTruncated in listing

* fix tests

* address tests

* Update s3api_object_handlers_multipart.go

* fixes

* store json into bucket content, for tagging and cors

* switch bucket metadata from json to proto

* fix

* Update s3api_bucket_config.go

* fix test issue

* fix test_bucket_listv2_delimiter_prefix

* Update cors.go

* skip special characters

* passing listing

* fix test_bucket_list_delimiter_prefix

* ok. fix the xsd generated go code now

* fix cors tests

* fix test

* fix test_bucket_list_unordered and test_bucket_listv2_unordered

do not accept the allow-unordered and delimiter parameter combination

* fix test_bucket_list_objects_anonymous and test_bucket_listv2_objects_anonymous

The tests test_bucket_list_objects_anonymous and test_bucket_listv2_objects_anonymous were failing because they try to set bucket ACL to public-read, but SeaweedFS only supported private ACL.

Updated PutBucketAclHandler to use the existing ExtractAcl function which already supports all standard S3 canned ACLs
Replaced the hardcoded check for only private ACL with proper ACL parsing that handles public-read, public-read-write, authenticated-read, bucket-owner-read, bucket-owner-full-control, etc.
Added unit tests to verify all standard canned ACLs are accepted

* fix list unordered

The test is expecting the error code to be InvalidArgument instead of InvalidRequest

* allow anonymous listing( and head, get)

* fix test_bucket_list_maxkeys_invalid

Invalid values: max-keys=blah → Returns ErrInvalidMaxKeys (HTTP 400)

* updating IsPublicRead when parsing acl

* more logs

* CORS Test Fix

* fix test_bucket_list_return_data

* default to private

* fix test_bucket_list_delimiter_not_skip_special

* default no acl

* add debug logging

* more logs

* use basic http client

remove logs also

* fixes

* debug

* Update stats.go

* debugging

* fix anonymous test expectation

anonymous user can read, as configured in s3 json.
2025-07-22 01:07:15 -07:00
Chris LuandCopilot 4b040e8a87 adding cors support (#6987)
* adding cors support

* address some comments

* optimize matchesWildcard

* address comments

* fix for tests

* address comments

* address comments

* address comments

* path building

* refactor

* Update weed/s3api/s3api_bucket_config.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* address comment

Service-level responses need both Access-Control-Allow-Methods and Access-Control-Allow-Headers. After setting Access-Control-Allow-Origin and Access-Control-Expose-Headers, also set Access-Control-Allow-Methods: * and Access-Control-Allow-Headers: * so service endpoints satisfy CORS preflight requirements.

* Update weed/s3api/s3api_bucket_config.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update weed/s3api/s3api_object_handlers.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update weed/s3api/s3api_object_handlers.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* fix

* refactor

* Update weed/s3api/s3api_bucket_config.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update weed/s3api/s3api_object_handlers.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* Update weed/s3api/s3api_server.go

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* simplify

* add cors tests

* fix tests

* fix tests

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-15 00:23:54 -07:00
chrislu 50e22864cf refactor 2024-09-17 23:10:41 -07:00
Kamran Sarwar 63c707f9c1 added access-control-expose-headers to put request (#5876) 2024-08-09 15:52:05 -07:00
LHHDZ e9584d9661 add ownership rest apis (#3765) 2022-10-01 19:18:00 -07:00
chrislu 26dbc6c905 move to https://github.com/seaweedfs/seaweedfs 2022-07-29 00:17:28 -07:00
Konstantin Lebedev 10678cde81 audit log config 2021-12-07 18:20:52 +05:00
Konstantin Lebedev 4ec8715f20 audit log 2021-12-07 12:15:48 +05:00
Chris Lu 9cf756b188 S3: support CORS
related to https://github.com/chrislusf/seaweedfs/issues/1271
2021-10-31 18:06:43 -07:00
Chris Lu f17fa400d5 refactoring 2021-10-31 18:05:34 -07:00
Chris Lu 006b4ec0f8 refactoring 2021-10-31 18:02:08 -07:00
Chris Lu b71c3cfba4 avoid possible empty object 2021-06-10 22:17:53 -07:00
Chris Lu 310e31424e adjust the error output
fix https://github.com/chrislusf/seaweedfs/issues/2123
2021-06-10 21:55:13 -07:00
Chris Lu 8b382a8209 refactor 2021-06-10 21:50:21 -07:00