Commit Graph
54 Commits
Author SHA1 Message Date
Priamo Germosen c17bd49096 fix(s3): check bucket policies for the actions IAM checks (#5913)
S3's own access check under floci.services.s3.enforce-auth, which
evaluates bucket policies and ACLs, lagged behind IAM enforcement. It
checked a version's tagging, ACL and annotation requests as the base
actions, an object created with tags, an ACL or Object Lock settings as
s3:PutObject alone, GetObjectAttributes without the read, and a write
carrying If-Match without the read IAM checks for it. It offered a
bucket policy none of the request's condition keys, and asked for
s3:BypassGovernanceRetention on an annotation delete, which the user
guide says the permission "does not apply to".

The bucket-policy check now checks the actions IAM does: the version
counterpart when a request names a versionId, the tagging, ACL,
retention and legal-hold actions an object creation's settings need, a
copy of a tagged source included, s3:GetObject beside
s3:GetObjectAttributes and beside an If-Match write, and no bypass
permission on an annotation delete. A signed request's bucket policy is
offered the tag and Object Lock keys the request sets: an object
creation's headers and the tagging, retention and legal-hold bodies,
read by the same S3ObjectActions helpers IAM's condition resolver now
uses.

s3:BypassGovernanceRetention is asked for only by a request that
overrides a governance lock, by IAM and by the bucket policy. The user
guide's permissions table requires it "if you want to delete an object
that's protected by governance mode" and to "bypass the governance mode
of an Object Lock retention configuration", and DeleteObjects already
asked for it only then. DeleteObject and PutObjectRetention asked for
it whenever the header was sent; they now ask only for a delete that
removes a version under a governance lock, not one that only adds a
delete marker, and for a retention change that shortens or removes one.

The IAM condition resolver now reads the object key from the path as
it arrived, as S3Controller does, through the new S3ObjectKeys: the
normalized path drops a key's leading slash, so the lock and the
s3:ExistingObjectTag tags of "/doc" were looked up on "doc". A CopyObject
replacing its source's tags reads x-amz-tagging from the query as well,
as PutObject does, so it applies the tags both checks saw. An anonymous
creation that a public bucket ACL's WRITE grant admits may still apply
its ACL, tags and Object Lock settings, unless a public bucket policy
decides their actions, since an ACL grant names no actions.

The creation checks are told whether a request is a CopyObject rather
than guessing it from x-amz-copy-source, which a CreateMultipartUpload
ignores while it applies its own tags, so those tags are always
checked, by IAM and by the bucket policy. With an access check on, a
DeleteObject, a DeleteObjects entry and a PutObjectRetention hand
S3Service the bypass only when they override a lock whose bypass
permission the checks approved, IAM's decision travelling in
RequestContext, so a lock set after the checks is refused rather than
bypassed unchecked.

Refs #5716
2026-10-18 09:28:33 -05:00
Priamo Germosen 63cf09a396 fix(s3): make versionId=null name only the null version (#5887)
A request naming versionId=null asks for the null version, the one an
object written while versioning was off or suspended has. GetObject,
HeadObject, GetObjectAttributes, a copy source and the annotation
operations served the current version for it instead, even on a key
with no null version, so a request authorized for the null version was
served another. Retention, legal hold and the object ACL looked for a
version stored under the id "null", which never exists, so they never
found the null version even when there was one.

Every lookup now resolves the id the way tagging and DeleteObject
already did: the null version is the object at the plain key when it
has no version id, and a key without one answers as for any missing
version, NoSuchVersion, or NoSuchKey for the annotation operations as
for their other missing versions. A read of the null version goes
through the same optimistic snapshot as a read of the current version,
so a write landing mid-read cannot pair one version's metadata with
another's bytes. The s3:ExistingObjectTag lookup reads the null
version's tags the same way, and under s3.enforce-auth an anonymous
read naming the null version is checked against that version's ACL.

Refs #5716
2026-10-17 22:31:26 -05:00
XuJian d1509c368f fix(s3): default new buckets to BucketOwnerEnforced (#5782)
* fix(s3): default new buckets to bucket owner enforced

Initialize ownership controls at bucket creation and opt ACL-focused tests into legacy ownership modes. Repair existing import grouping so repository-wide Checkstyle passes.

* fix(s3): honor bucket ownership and ACL headers

Preserve explicit CreateBucket ownership and ACL grants, and reject grants incompatible with enforced ownership. Validate multipart grants at initiation and carry accepted grants through completion. Adapt ACL-focused regressions to opt into legacy ownership modes.

* fix(s3): respect account public ACL setting at bucket creation

* refactor(s3): share create-bucket ownership XML builder
2026-10-16 22:26:24 -04:00
Priamo Germosen 792260ed49 fix(s3): apply and check the Object Lock headers of every object creation (#5828)
CopyObject ignored its Object Lock headers, and CreateMultipartUpload
ignored those and its grant headers, so the copy or the completed upload
came out without the lock or the grants the request asked for. PutObject
read the lock headers without checking them: a malformed retain-until
date was a 500, and a mode without a date, a date without a mode or an
unknown mode was accepted.

PutObject, CopyObject and CreateMultipartUpload now read the lock headers
through one check that refuses them as S3 does, with InvalidArgument
naming the header: a mode and a date come together, checked first, and
the mode is GOVERNANCE or COMPLIANCE. A date that is not an ISO 8601
timestamp is refused the same way. CopyObject applies the settings to the
copy. CreateMultipartUpload keeps them and its grants, and applies them
when the upload completes. Its grants are checked when the upload is
created, under the bucket-owner-enforced rule PutObject uses, so a grant
S3 refuses fails the creation rather than the completion.

Refs #5716
2026-10-16 17:25:57 -05:00
jwoa95 cbd2f61dc4 feat(s3): apply lifecycle expiration rules (#5158)
A bucket's lifecycle configuration was stored and returned but never
evaluated. A background sweep now applies its expiration actions:

- Expiration (Days, Date) deletes the current version of a matching
  object, or adds a delete marker in a versioning-enabled bucket. Day
  counts run from the last-modified time and round up to the next
  midnight UTC, as on S3.
- ExpiredObjectDeleteMarker, and a Days or Date expiration once the
  marker is old enough, remove a delete marker with no other versions.
- NoncurrentVersionExpiration (NoncurrentDays, NewerNoncurrentVersions)
  permanently deletes noncurrent versions, counting from when the next
  newer version was written.
- AbortIncompleteMultipartUpload (DaysAfterInitiation) aborts uploads
  under a prefix-only filter.

Filters are Prefix, Tag, ObjectSizeGreaterThan, ObjectSizeLessThan, an
And of them, or the older rule-level Prefix. Disabled rules are skipped,
versions under Object Lock retention or a legal hold are never deleted,
and each bucket is swept in its owning account. Lifecycle deletions are
notified as s3:LifecycleExpiration:* rather than s3:ObjectRemoved:*,
with S3 itself as the requester, and their EventBridge reason is
"Lifecycle Expiration".

A rule S3 would have refused on put, such as Days 0, a size bound that
is not a number or a Tag without a Value, is skipped as a whole, so a
bad value never widens what a rule deletes. A body that is not one
well-formed LifecycleConfiguration document has no rules.

Each key is planned from one pass over its account's objects, then read
again by its known store keys and applied under the bucket monitor.
Lifecycle configuration changes and tagging now change under that
monitor too, and a multipart upload is aborted only
while its bucket and the rules are still the ones the sweep started on.
Versions written in the same millisecond keep the order they were
written in, for ListObjectVersions as well as for lifecycle.

PutObject, GetObject and HeadObject on a current version that an
Expiration rule matches return x-amz-expiration with the expiry date
and the URL-encoded rule id.

The sweep runs every 60 seconds by default, configured with
floci.services.s3.lifecycle-sweep-enabled and
floci.services.s3.lifecycle-sweep-interval-seconds. Transition actions
are still not applied.

Closes #5137
2026-10-15 20:52:43 -04:00
XuJian a4eb854614 fix(s3): enforce ownership controls and restore CFN updates (#5712)
* fix(cloudformation): apply S3 bucket OwnershipControls

* fix(s3): validate ownership controls in service

* fix(s3): return MalformedXML for invalid ownership controls

* fix(s3): enforce ownership controls and restore bucket updates

* fix(s3): reject ownership enforcement for nonprivate ACLs
2026-10-15 20:30:26 -04:00
Langning Zhang ea45f81a81 fix(s3): reject undersized multipart upload parts (#5718)
* fix(s3): reject undersized multipart upload parts

Signed-off-by: boulea7 <zln1905391059@163.com>

* fix(s3): reuse multipart size error helper

Signed-off-by: boulea7 <zln1905391059@163.com>

---------

Signed-off-by: boulea7 <zln1905391059@163.com>
2026-10-15 12:55:58 -04:00
Priamo Germosen 46f4977b23 fix(ses): publish to an SNS topic only when its policy allows SES (#5650)
Under IAM enforcement, SES published event-destination events and identity notifications to
whatever SNS topic it was configured with, through an internal call nothing checked, so a caller
refused sns:Publish could still put messages on a topic by pointing a configuration set at it. On
AWS, SES publishes as ses.amazonaws.com and the topic's policy decides: it has to allow SES, under
an aws:SourceArn naming the configuration set or identity whose configuration names the topic.

- ServiceCallAuthorizer decides a call one AWS service makes to another's resource on its own
  behalf from the target's resource policy alone, read through the same providers the request
  filter uses and picked by the target ARN's service. A target with no policy refuses, and with
  enforcement off every call is allowed. ResourcePolicyProviders collects what the providers
  supply, for the filter and the authorizer alike.
- IamConditionContextResolver.serviceCallContext builds that call's request context from the IAM
  User Guide's global keys: aws:PrincipalIsAWSService, aws:PrincipalServiceName and
  aws:PrincipalServiceNamesList, aws:SourceArn and aws:SourceAccount, aws:ResourceAccount and
  aws:RequestedRegion, and none of the keys that describe an IAM principal. A publish to an SNS
  topic from SES also carries aws:SourceOwner, which the SNS Developer Guide lists SES among the
  services setting, and which the default topic policy checks.
- SnsResourcePolicyProvider supplies a topic's policy and the account in its ARN, also when the
  topic does not exist. A topic with no Policy attribute gets the default a new topic has, for the
  topic's own account. Topic policies so also take part in a JSON-protocol request that names a
  topic, as any resource policy does.
- SesEventPublisher asks before publishing to SNS: for an event destination with the configuration
  set's ARN, for an identity notification with the ARN of the identity that names the topic, the
  sender's own or its domain's, both with the sending account. A refused event is dropped. A
  notification SES cannot publish, because the topic is gone from its own account or its policy
  refuses SES, also takes the topic out of the identity's bounce and complaint settings and turns
  email feedback forwarding back on, as the SES Developer Guide describes; a delivery setting
  stays. The identity's notification settings are written under the identity lock, so that
  write and an API call changing them cannot lose each other.
- CreateReceiptRule and UpdateReceiptRule ask the same question of an action's TopicArn, with the
  rule's ARN as aws:SourceArn, and answer InvalidSnsTopic when the topic's policy does not let SES
  publish, which the SES API Reference lists as "could not publish to the topic, possibly due to
  permissions issues". The rules still route no mail.
- A resource policy statement that names the caller only through its account, by its id, root ARN
  or S3 canonical user ID, delegates to that account (IAM User Guide, "AWS account principals"):
  across accounts it is still the owner's half of the grant, but within the account it no longer
  grants on its own, and the caller's identity policies have to allow the request. Floci let such
  a statement grant on its own, for bucket and function policies already, so a topic policy naming
  its own account would have let every user of the account publish.
- A Deny's NotPrincipal follows the IAM User Guide ("AWS JSON policy elements: NotPrincipal"): it
  spares an IAM caller only when it names the caller's account as well as the caller, since without
  the account AWS "might deny access to the entire account", and never spares one with a permissions
  boundary attached, which it "will always deny". CallerArns says whether a boundary is attached to
  the user or to the role a session assumed. An Allow's NotPrincipal still grants everyone it does
  not name, as Access Analyzer warns it can.
2026-10-14 17:32:55 -05:00
Mohith 4d6ecc1ac2 fix(s3): validate multipart upload object size (#5643)
* fix(s3): validate multipart upload object size

* fix(s3): reject invalid multipart object sizes
2026-10-14 13:10:12 -04:00
Priamo Germosen a88ef42b4b feat(s3): read one part of an object with GetObject and HeadObject partNumber (#5569)
GetObject and HeadObject ignored partNumber, so a client reading a
multipart object one part at a time downloaded the whole object for
every part, and never learned how many parts there were. The API
Reference describes partNumber as "effectively" a ranged GET or HEAD
for that part, with x-amz-mp-parts-count "only returned if you specify
partNumber in your request and the object was uploaded as a multipart
upload".

Both now answer partNumber as S3 does in LocalStack's AWS-validated
test_get_object_part, test_get_object_part_checksum and
test_complete_multipart_parts_checksum captures: 206 with the part's
Content-Range and Content-Length, the object's ETag, and
x-amz-mp-parts-count for an object completed from a multipart upload.
An object stored in one request is its own part 1. A part the object
does not have is 416 InvalidPartNumber, naming PartNumberRequested and
ActualPartCount, and partNumber with a Range header is 400
InvalidRequest. A part streams from storage like a range, so the parts
of a large object are read one at a time without holding it.

With checksum mode on, a part of an object with a COMPOSITE checksum
gets that part's own checksum, of type COMPOSITE, and a part that is all
of its object gets the object's checksum; any other part of a
FULL_OBJECT multipart object gets none, as the captures show.

A part number below 1 is 400 InvalidArgument, and one above the part
count, past 10,000 or not, is the 416, as the AWS SDK for Java documents
for partNumber; the 400 carries the wording and fields the captures
record for UploadPart. Part 1 of an empty object succeeds, as the AWS
SDKs' integration tests that download an empty object by part expect,
with no Content-Range, which the CRT client reads only from a part with
bytes, and so with 200, since a 206 must carry one (RFC 9110 15.3.7).

GetObject's ranged response and HeadObject now build their common
headers with GetObject's, given the length served.
2026-10-13 17:46:30 -05:00
Priamo Germosen 6d2aaba6a6 fix(s3): reject a PutObject or UploadPart over 5 GiB (#5469)
S3 takes at most 5 GB in one PutObject and 5 GiB in one part (User
Guide, "Uploading objects" and the multipart upload limits table), but
Floci only enforced that for UploadPartCopy. Since PutObject and
UploadPart stream to disk, the only cap was
FLOCI_PROTOCOLS_MAX_REQUEST_SIZE, so raising it past 5120 MB, as
docs/services/s3.md says to for 5 GiB uploads, let a single request
store any size up to the new limit.

A request that declares more than 5 GiB of data, in Content-Length or,
for an aws-chunked body, x-amz-decoded-content-length (its
Content-Length also counts the framing), now fails with EntityTooLarge
before any of its body is read. A body that declares no size, or less
than it sends, fails the same way once it passes 5 GiB: the stream that
digests a body on its way to disk counts it against the limit, while
memory mode already stops at about 2 GiB. PutObject's "5 GB" is taken
as 5 GiB, as CopyObject's is.

The error is now the one S3 sends, as S3's answer to an oversized
UploadPart logged in aws/aws-cli#5420 and an AWS-validated LocalStack
capture record it: the message "Your proposed upload exceeds the maximum
allowed size", not the error table's description, and the ProposedSize
and MaxSizeAllowed fields, ProposedSize left out when a body passes the
limit as it is read, since its whole size is then not known. It is built
in one place and shared with UploadPartCopy and the memory-mode cap,
which sent the table's wording and named neither size; the memory-mode
cap names the most memory mode can hold.

A client that sent Expect: 100-continue never sends a body it was not
told to continue with, so answering it before reading the body left the
connection waiting for that body and reading the client's next request
as it (#5291). Such an answer now says Connection: close and the
connection is closed after it, which covers this rejection as well as
NoSuchBucket or a failed precondition.

An aws-chunked body sent without a streaming x-amz-content-sha256 or an
x-amz-trailer is read whole to be decoded. That read now fails with
EntityTooLarge once it passes what one array holds, through the bounded
read memory mode uses, instead of running the heap out of memory.

Telling an aws-chunked body from its Content-Encoding is now one helper,
which the four places that repeated the check use too.
2026-10-11 21:47:48 -05:00
Priamo Germosen 09a2d5c005 fix(s3): answer GetObject Range requests as S3 does (#5436)
GetObject answered 416 InvalidRange to any Range that was not one valid
byte range: several ranges, a last byte before the first, or a malformed
value such as bytes=-, bytes=-1- or bytes=0--1. S3 answers those as a
GetObject without a Range, with the whole object and 200, as
LocalStack's AWS-validated capture of GetObject over a dozen ranges
(test_get_object_range) records it. Only a range that starts past the
end of the object, or bytes=-0, gets 416. HeadObject and a CloudFront S3
origin already answered them with the whole object.

Since every caller now treats a Range that is not one valid range as no
Range at all, ByteRange.resolve reports it as WHOLE, and the separate
INVALID outcome is gone.

The same capture shows a 206 for a range covering the whole object
(bytes=-15 and bytes=0-100 of 10 bytes) carrying the object's checksum,
which Floci left out of every ranged response. The User Guide's
"Checking object integrity" has GetObject and HeadObject return a part's
checksum for "a part number or byte range that aligns with a single
part", and an object stored in one request, or completed from one part,
is that part. Such a range now gets the stored checksum, from GetObject
and HeadObject, when the request asks for checksums and the checksum is
a full-object one. A composite checksum is not that of any one part, nor
is a checksum of an object of several parts, so their ranges still get
none.
2026-10-11 09:13:03 -05:00
Priamo Germosen 013a9214b5 fix(s3): answer an expired session with ExpiredToken when verifying signatures (#5435)
When S3 verified a signature, it answered a request signed with temporary
credentials past their expiry as if the key did not exist: 403
InvalidAccessKeyId for a header-signed request, and 403
SignatureDoesNotMatch for a presigned POST and, under
validate-signatures alone, for a presigned URL. S3's error list has 400
ExpiredToken, "The provided token has expired.", for an expired token,
and IAM enforcement already answers S3 with it.

The secret-key lookup finds nothing for an expired session, so when it
comes back empty the three placements (header, presigned URL, presigned
POST) now ask IamService whether the key and token belong to a session
that has expired on its clock and is still stored, and answer 400
ExpiredToken if so. The token has to match. Sent with another token or
none, an expired session is still answered as a key that is not
registered, so a caller that does not hold the credential learns nothing
about it. Once Floci has removed an expired session it no longer knows
the key, as with enforcement.

IamServiceTest moves a session past its expiry and checks that the new
lookup answers only to the session's own token, and the boundary test
now holds it to the same instant as the other lookups.
S3ValidateSignaturesIntegrationTest signs with Sign-In credentials
through a header, a presigned URL and a presigned POST: each is accepted
until the clock passes their expiry, then answered 400 ExpiredToken. An
expired session sent with another token still gets InvalidAccessKeyId.
Each placement's test fails without its part of the change, and the
token tests fail when the token is not checked. S3RequestSigner can now
write a presigned URL's query string, so the presigned URL test signs
the way an SDK presigner does.
2026-10-11 09:12:52 -05:00
Priamo Germosen ff20750d91 fix(cloudfront): serve viewer Range GETs (#5377)
A distribution ignored a viewer's Range header: an S3 origin answered
every GET with the whole object and 200, while advertising
Accept-Ranges: bytes, and a custom origin behind a cache or origin
request policy never saw the header, so seeking in a video or resuming
a download read the object from the start.

An S3 origin now serves the one byte range asked for as 206 with its
Content-Range, read from the snapshot GetObject serves, and answers 416
when the range starts past the end of the object. Any other Range gets
the whole object, as CloudFront answers a Range it does not accept and
as S3 does not serve several ranges in one request. A custom origin gets
the viewer's Range and If-Range on every GET or HEAD with a Range
whatever the forwarding settings, as CloudFront forwards a range GET to
the origin and a HEAD can then report the range's length, and its answer
is passed on. A custom error page is served whole.

A Range now applies only while the If-Range sent with it, if any, still
describes the object: a strong ETag equal to the object's, or an
HTTP-date equal to its Last-Modified, matched exactly as RFC 9110
section 13.1.5 requires. Otherwise the whole object is served. This
holds for GetObject, HeadObject and the S3 origin. A presigned URL that
signs Range must also sign an If-Range the request carries, as the S3
User Guide requires.

HeadObject honors Range as the API Reference describes: a satisfiable
range sets Content-Length to the length of the range, leaving out the
whole-object checksum as a ranged GetObject does, and one past the end
answers 416, while a Range that is not one valid range is ignored, as
before. An S3 origin answers a HEAD the same way.

A ranged GetObject is now recorded in CloudTrail like any other, with
the bytes of the range sent, and a range past the end of the object,
for GetObject or HeadObject, is recorded as InvalidRange.

The range parsing GetObject did is now ByteRange, which both use, and
UploadPartCopy's range stream becomes ByteRangeInputStream. GetObject
now matches the range unit in any case, as RFC 9110 section 14.1 has
it, and its InvalidRange error is the one S3 sends, as an AWS-validated
LocalStack capture records it: the message "The requested range is not
satisfiable", with no trailing period, and the RangeRequested and
ActualObjectSize fields.
2026-10-10 21:29:02 -05:00
David 9f224d9de6 fix(core): verify SigV4 header signatures for every service under validate-signatures (#5268)
* fix(core): verify SigV4 header signatures for every service under validate-signatures

FLOCI_AUTH_VALIDATE_SIGNATURES verified signatures for S3 only, so SQS,
KMS, IAM, Scheduler and every other service accepted a request signed
with the wrong secret. SigV4HeaderSignatureFilter verifies the
Authorization header of every request outside S3 and execute-api when
the flag is on, rebuilding the canonical request from the request as it
arrived and answering in the protocol the request used. Unsigned
requests are left alone, and the default configuration is unchanged.

The filter runs after matching so it can hash the body. The SQS
queue-URL router now records the bytes it appends to a Query body, and
the CBOR content type is read from the header that preserves it, so
neither rewrite breaks a valid signature.

With the flag on, an unknown or synthetic access key is now refused by
every service, as S3 already refused it.

Closes #5195

* fix(core): skip signature checks by matched resource, strip the spoofable content-type header

The filter skipped any request whose credential scope named s3 or
execute-api, so a caller could sign an SQS or KMS call under either and
pass with the wrong secret, and S3 Control was never checked. It now
steps aside only for the resources another verifier owns: S3Controller
and the API Gateway execute controllers.

AwsCborContentTypeFilter removes any client-sent
X-Floci-Original-Content-Type, so a signed Content-Type cannot be
swapped behind a forged copy. REST-XML services (Route 53, CloudFront,
S3 Control) get XML errors. Header and scope parsing reuse
SigV4AuthorizationHeader and CredentialScope, and the canonical request
moves into SigV4Canonicalization, shared with ExecuteApiSigV4Authorizer.

* fix(core): leave AppSync GraphQL signatures to AppSync's own check

AppSync's GraphQL endpoint verifies IAM signatures itself and answers a
failure with the UnauthorizedException envelope AppSync clients parse.
With validate-signatures on, the header filter reached it first and
answered with a JSON InvalidSignatureException. AppSyncExecutionController
joins the resources the filter steps aside for.
2026-10-09 16:31:22 -04:00
Vũ Thế Huy d39c7e1381 fix(s3): reject unverified credentials and malformed auth in account routing (#4825) (#5059)
* fix(s3): enforce SigV4/SigV4A algorithm prefix in AccountResolver

* fix(s3): require X-Amz-Algorithm in AccountContextFilter presigned query resolution

* fix(s3): reject malformed Authorization header in S3HeaderSignatureFilter

* fix(s3): reject query presigned requests missing X-Amz-Algorithm in PreSignedUrlFilter

* test(s3): add reproduction tests for unverified credential account routing (#4825)

* fix(s3): isolate presigned query auth and permit SigV4A headers (#4825)

* fix(s3): gate signature checks on validation setting and restore unsigned presigned steering (#4825)

* fix(s3): stop unverified credentials from selecting an account (#4825)

Account selection now requires a SigV4/SigV4A Authorization scheme or a
query string carrying X-Amz-Algorithm. A bare "Credential=" header or an
X-Amz-Credential without X-Amz-Algorithm keeps feeding region resolution
only, so it can no longer steer a request into another account.

Credentials rebuilt outside the header (IAM presigned query, presigned
POST form) now carry the AWS4-HMAC-SHA256 scheme so IAM enforcement still
recognises them. With signature validation on, a query holding only
X-Amz-Signature is rejected with AuthorizationQueryParametersError.

* fix(s3): ignore unsupported Authorization headers for region and keep credential-only download URLs working (#4825)

A header without a SigV4/SigV4A scheme now selects neither account nor
region, so it cannot misattribute S3 data events to another region.

Floci's own download URLs (Lambda layers, Kubernetes init containers)
carry only X-Amz-Credential, so that parameter steers the account and
region again without X-Amz-Algorithm.

* fix(s3): let a present Authorization header win over X-Amz-Credential in account routing (#4825)

IamEnforcementFilter reads the query credential only when no Authorization
header exists. AccountContextFilter fell back to the query whenever the
header was unrecognised, so a malformed header plus X-Amz-Credential picked
an account that IAM then skipped. Both filters now use the same precedence.

* fix(s3): treat a whitespace-only Authorization header as absent in account routing (#4825)

S3's authorization parser ignores a blank header and uses the presigned
query credential, so AccountContextFilter must do the same instead of
falling back to the default account.

* fix(iam): treat a whitespace-only Authorization header as absent in IAM enforcement (#4825)

AccountContextFilter and S3 already ignore a blank header and use the
presigned query credential. IamEnforcementFilter only checked for null, so
a blank header made it find no access key and skip authorization for the
account the query credential had selected. All three now agree.

* fix(s3): presign internal lambda download URLs

* test(macie2): include SigV4 algorithm in account routing check

* docs(s3): list the SigV4A and incomplete presigned URL 400s under signature verification (#4825)

* docs(s3): say Floci does not verify SigV4A signatures yet instead of cannot
2026-10-08 10:58:38 -04:00
Priamo Germosen a0a2a5f0d6 fix(s3): run S3 Select over CSV and JSON a record at a time (#5178)
SelectObjectContent loaded the whole object into a byte array and built
the whole response before sending it, so an object over about 2 GiB
failed with an internal error, and a large object or result could run
the heap out of memory.

The object is now opened as a stream, the snapshot GetObject uses. The
Java evaluator parses the statement before reading anything, then reads
CSV a line at a time and JSON a line or an array element at a time,
stops once a LIMIT is reached, and writes the result as it goes, in
Records events of whole records, then Stats and End. Queries floci-duck
runs read the object themselves and no longer load it just to count
BytesScanned.
2026-10-06 20:32:13 -05:00
Priamo Germosen 8fee66ae61 fix(s3): stream UploadPartCopy ranges into the part (#5162)
UploadPartCopy read the copied range into a byte array and stored it
through the byte-array UploadPart path, so one copied part was capped
near 2 GiB with EntityTooLarge, while S3 allows a part of up to 5 GiB.

The range is now read from the source stream as it is needed, by a new
CopyRangeInputStream that skips to the range on its first read and ends
after its last byte, and written straight into the part through the
streaming UploadPart path, so neither the source nor the part has to
fit in memory in the disk-backed modes. A range over S3's 5 GiB part
limit is rejected with EntityTooLarge, as the S3 API Reference error
table words it, before anything is copied. Memory mode keeps its limit
of about 2 GiB.
2026-10-05 23:04:48 -05:00
Priamo Germosen 583de3010c fix(s3): stream PutObject and UploadPart bodies to disk (#5106)
The object PUT endpoint took its body as a byte array, so a single
PutObject or UploadPart was held whole in the heap and capped near 2 GiB.

The body is now read as a stream. A streaming aws-chunked payload is
decoded as it arrives, and Content-MD5 and x-amz-checksum-* are checked
on the way through. In the disk-backed modes the body is staged under
.multipart/.incoming with no lock held, then a part is moved into its
upload under the upload's lock and an object is stored like an
assembled multipart object. Checks the request alone decides (bucket,
SSE-C headers, checksum algorithm, write preconditions, a malformed
Content-MD5) run before any of the body is read. Memory mode reads the
body into a capped array and fails past about 2 GiB with EntityTooLarge.
2026-10-05 17:11:47 -05:00
Priamo Germosen d97b21ae62 fix(s3): copy objects over 2 GiB without reading them into memory (#5080)
CopyObject read the whole source into a byte array with getObject and
wrote it back out for the copy, so a source of 2 GiB or more failed as an
internal error, even though S3 copies objects up to 5 GiB in one call.

In the disk-backed modes the source is now pinned with a temporary hard
link to the file generation its metadata describes, taken through the
same optimistic snapshot GetObject uses, and that link is moved into
place as the copy's file. The copy's ETag and checksum are prepared
before any bucket monitor is taken, and the pinned file is read, once and
streamed, only for what cannot carry over: a single-part source's ETag is
the MD5 of its bytes and is kept, while a multipart source needs the MD5
computed, and a requested or composite checksum becomes a full-object one
through a new incremental S3Checksum.Calculator. A failed copy removes its
pinned link. Memory mode still copies the byte array.

As on S3, a CopyObject source larger than 5 GiB (5368709120 bytes) is now
rejected with InvalidRequest, "The specified copy source is larger than
the maximum allowable size for a copy source: 5368709120"; such an object
is copied with UploadPartCopy.
2026-10-04 21:25:51 -05:00
Priamo Germosen d8728ac4d4 fix(s3): promote a version on delete without reading its body (#5064)
Deleting the current version in a versioned bucket made the previous
version current by reading its whole file into a byte array and writing
it out again as the current file, under the bucket lock. A version over
2 GiB could not be read that way, and because the new current version's
metadata was published before the file, the failure left the key pointing
at the promoted version while its current file still held the deleted
version's bytes.

The current file is now a hard link to the promoted version's file, the
way a versioned multipart upload already stores its current file, so a
version of any size is promoted without being read; in memory both
entries share the version's array, as they already did. The body is also
put in place before the metadata is published, the order PutObject
writes in, so a concurrent GET can no longer pair the promoted version
with the deleted version's bytes.
2026-10-04 10:37:49 -05:00
Priamo Germosen d400ea6b7e fix(s3): read only the copied range in UploadPartCopy, with offsets past 2 GiB (#5034)
UploadPartCopy loaded the whole source object into a byte array and parsed
x-amz-copy-source-range with Integer.parseInt, so a source of 2 GiB or
more, or any range offset past 2 GiB, failed as an internal error. A range
that ran past the end of the source was silently padded with zero bytes.

The source is now opened as a stream, the way GetObject serves it, and
only the requested range is read, with offsets parsed as longs. A bad
range gets the error S3 returns, as recorded in LocalStack's AWS-validated
snapshot for UploadPartCopy: anything but one bytes=first-last range with
first <= last is InvalidArgument naming the expected form, a range that
ends past the source is InvalidArgument naming its size, and one that
starts past it is InvalidRequest; the InvalidArgument errors carry
ArgumentName and ArgumentValue. A copied part is still held in a byte
array on its way into the upload, so a range over that limit returns
EntityTooLarge until UploadPart can store a part without one.
2026-10-03 22:56:00 -05:00
Priamo Germosen 2e87534941 fix(s3): complete multipart uploads larger than 2 GiB in disk storage modes (#4976)
CompleteMultipartUpload built the whole object as one byte array, so an
object over Integer.MAX_VALUE bytes failed with an ArithmeticException,
and anything smaller still needed the full object in the heap.

In the persistent, hybrid and wal modes the parts are now copied file to
file into one assembled file in the upload's directory, before the bucket
lock is taken, and that file is renamed into place under the lock. A
versioned bucket hard-links the current file to the versioned one rather
than writing a second copy, which is safe because object files are only
ever replaced by a rename, never modified in place.

The full-object checksum is combined from each part's CRC and size,
which is how S3 linearizes full-object checksums and why it offers them
only for the CRC algorithms, so the object's bytes are never read for it
and a mismatched expected checksum is rejected before assembly.

Since the ETag and checksum now come from the part records, each
UploadPart stores its bytes under its own storage ID kept on the record
and drops the bytes it replaced only after publishing the new record.
CompleteMultipartUpload reads each record once and assembles exactly the
bytes those records name, so an UploadPart racing a Complete makes that
Complete fail with InvalidPart instead of storing a checksum that
describes different bytes.

Memory mode still holds an object in one byte array, so an UploadPart
that takes an upload past the largest array the JDK allocates, or a
CompleteMultipartUpload over it, now fails with EntityTooLarge instead of
exhausting the heap or overflowing the array size.

Multipart uploads are tracked only in memory, so the part files under
.multipart are removed at startup and on reset. Without that, a crash
during assembly would leave a file as large as the object on disk for
good. The S3 docs describe the memory-mode limit, the disk space a
completion needs, and the operations that still read a whole object into
memory.
2026-10-03 14:34:54 -05:00
Priamo Germosen b679fe2312 fix(s3): match a bucket policy's Principal the way IAM does in S3's own checks (#4961)
Follow-up from the reviews of #4838 and #4839.

S3 checks a bucket policy itself in two places, and neither matched its
Principal the way the IAM evaluator does since #4839:

- The signed-request check (s3.enforce-auth) passed the caller to the IAM
  evaluator as a bare ARN, so a role session was matched through a role ARN
  rebuilt from the session ARN, which drops the role's path. A bucket policy
  naming role/team/App never reached that role's sessions.
- The CopyObject/UploadPartCopy source check used S3's own matcher, which
  compared each AWS entry with the caller's ARN as a string. A grant to the
  caller's account, by id or root ARN, or to its role, never matched, so a
  cross-account caller allowed to read an object could not copy it.

Both now pass the typed caller to the IAM evaluator, a role session with the
ARN of the role it assumed, through a RequestPrincipal.caller factory the
enforcement filter now uses too. The copy check's own matcher is gone: its
direct-grant rules (an exact user ARN, or "*" with aws:PrincipalArn pinned to
it) are the IAM evaluator's, and the unit tests that pinned them there move to
IamPolicyEvaluatorTest. S3PublicAccessEvaluator keeps its principal matching
for CloudFront's origin access identity check.

A CanonicalUser entry matched nothing since #4839, and docs/services/iam.md
described that as AWS behaviour. The IAM User Guide ("AWS account principals")
lets an S3 bucket policy name an account by its canonical user ID, which the
S3 User Guide describes as an obfuscated form of the account ID. It now
matches the IAM identities of that account, as an account principal does.
Floci's canonical ID for an account is its account id, the owner ID its S3 ACL
responses report.

Integration tests (IAM and S3 enforcement, real SigV4) read and copy across
accounts under bucket policies naming the caller's account, a role under a
path, and the account's canonical ID; each fails on main. docs/services/iam.md
and docs/services/s3.md describe the matching.
2026-10-02 17:17:27 -05:00
XuJian b2dd5665db fix(s3): validate notification destinations before storing configuration (#4747)
* fix(s3): validate notification destinations before storing configuration

* test(s3): consume validation events before POST notifications

* fix(s3): preserve bucket lifecycle during notification validation

* fix(s3): enforce SQS queue policies for notifications

* fix(s3): align notification validation with IAM enforcement

* fix(test): stub IAM config for S3 failure delivery

* fix(s3): validate cross-account SNS without test publish

* fix(sns): recognize legacy topics during destination validation

* docs(s3): describe cross-account notification validation

* fix(s3): skip cross-account SNS notification test publishes
2026-10-01 11:35:16 -04:00
Abhigya 8f904afa5a fix(s3): verify header and presigned POST signatures under validate-signatures (#4786)
* fix(s3): verify header and presigned POST signatures under validate-signatures

floci.auth.validate-signatures verified only presigned URL signatures. A
header-signed request or a presigned POST with a forged signature or an
unknown access key was accepted unless enforce-auth was on, and enforce-auth
also turns on bucket-policy evaluation, so there was no way to authenticate
S3 requests without authorizing them.

S3 verifies a signature before, and independently of, deciding from policies
and ACLs whether the caller may act. validate-signatures now does the first
step for every placement: S3HeaderSignatureFilter runs under either flag, and
a browser POST that carries SigV4 form fields is verified. Bucket policies are
still not evaluated, and unsigned requests are still left to enforce-auth,
which decides anonymous access from policies and ACLs as AWS does.

docs/services/s3.md now says what each flag verifies.

* chore(s3): keep validatePresignedPostAuth's Javadoc on its method

* docs(s3): clarify multi-account credentials under signature verification

* docs(s3): update docs/configuration/multi-account.md

Signed-off-by: Abhigya <abhigyakrishna21@gmail.com>

---------

Signed-off-by: Abhigya <abhigyakrishna21@gmail.com>
2026-10-01 10:14:41 -04:00
Abhigya cea6d3e99f fix(s3): journal the object index under persistent storage (#4642)
* fix(s3): journal the object index under persistent storage

Under persistent mode every PutObject, CopyObject and DeleteObject
rewrote s3-objects.json in full, and that file holds the metadata of
every object in every bucket, so the cost of one write grew with the
total object count (two rewrites per write on a versioned bucket).

Create the object store with WriteProfile.APPEND_HEAVY, as CloudWatch
Logs events already are: a change is appended to s3-objects.wal and the
JSON file is rewritten on the WAL compaction interval and at shutdown.
An existing s3-objects.json is read as the first snapshot.

* fix(s3): journal both index entries of a current version's metadata update

A versioned put indexes the new object under its version key and the latest
key. Tagging, retention, legal hold, ACL and the SSE-C fields set on multipart
completion wrote back only one of the two. With the object index journaled,
each entry replays on its own, so a restart before compaction brought the
other entry back with the old metadata.

Write both entries when the update targets the current version. The restart
tests now shut down every factory and replay a copy of the stopped process's
directory, so no two writers share a journal.

* test(lambda): stub the WriteProfile overload for S3 stores in the stream poller test

* fix(s3): write object metadata under the bucket lock and the owner account

A metadata update checked whether the latest key still pointed at the object
and then wrote it without holding the bucket lock that puts and deletes take,
so a concurrent delete marker or overwrite could be replaced by the object it
had superseded. The check and both writes now run under that lock, and the
latest key is written only while it still refers to the updated object.

Multipart completion wrote the SSE-C fields back through the caller's account
partition, so with the global bucket namespace a cross-account completion
left a shadow latest entry and version in the caller's partition. It now goes
through the same helper with the bucket owner's account.
2026-09-29 19:18:51 -05:00
Hector Ventura 833a43bfa7 feat(core): vendor the per-region hosted zones, SAML URLs and VPC endpoint prefixes (#4545)
* feat(core): vendor the per-region hosted zones, SAML URLs and VPC endpoint prefixes

tools/aws/regen_region_facts.py transcribes the per-region and per-partition constants AWS publishes only as prose tables into src/main/resources/aws/region-facts.json: the Terraform provider's load balancer and S3 website hosted-zone maps, the CloudFront hosted zone per partition (cross-checked against the CDK), and the CDK's SAML sign-on URLs and VPC endpoint service-name exceptions. AwsRegionFacts serves them, as Optionals where a partition publishes nothing (the ISO and EUSC partitions have no hosted zones). make aws-data-check regenerates and compares where the local reference checkouts exist, and verifies the file's shape where they do not.

Behaviour this changes: network load balancers report their own hosted zone per region instead of the Application one, Classic and Application load balancers report their region's zone, API Gateway EDGE domains carry the CloudFront zone of their partition, SAML assertions are checked against the sign-on URL of the provider's partition, and the AWS-managed S3 and DynamoDB prefix lists carry the partition's service-name prefix.

Also carries the follow-ups from the #4494 review: bucketRegionForCreate cites the S3 model for the us-east-1 rules, docs/services/s3.md gains a Bucket Regions section, and the Marketplace files are gated per line with stated reasons instead of being allowlisted by path, so a new region literal there is caught.

Part of #4272

* fix(core): harden the region facts against restarts, partitions without CloudFront, and CI without sources

The source-free data check rejected real twelve-character hosted zone ids such as ap-southeast-1's NLB zone ZKVM4W9LS7TM, which failed the vendored-data job. It now accepts Route 53's id length range and checks substance: every partition has an entry whose VPC endpoint prefix is its reversed DNS suffix, every region is published in partitions.json, SAML URLs are https sign-on URLs, and unknown fields are refused.

Load balancers restored from storage take the hosted zone of their region and type again, so balancers stored before the per-region lookup stop reporting the old fixed zone. An EDGE API Gateway custom domain is refused where the partition has no CloudFront, since it would have no distribution zone to alias to. A customer prefix list may not take the prefix of the AWS-managed lists its region carries, cn.com.amazonaws. in China. The partitions doc now says which ISO hosted zones exist.

* fix(core): hold only a changed endpoint type to the partition, and name malformed region facts

UpdateDomainName checked the partition for EDGE on every patch, so an EDGE custom domain stored in GovCloud before the rule could no longer take a certificate or security-policy update; only a patch that changes the endpoint type is held to the partition now. The source-free region-facts check reports a partition or region entry that is not an object by name instead of failing with a traceback, and its test asserts on computed results rather than on calls that write the fixture.

* fix(core): keep gateway endpoint names on com.amazonaws, allow EDGE only in the commercial partition, and keep SAML working where no sign-on URL is published

The AWS-managed prefix lists belong to the S3 and DynamoDB gateway endpoints, which the CDK names com.amazonaws.<region>.<service> in every partition (GatewayVpcEndpointAwsService); the reversed-suffix table applies to interface endpoints only. The managed lists are back to that name and the cn.com.amazonaws. reservation is gone; DescribeVpcEndpointServices now names the interface services through the table instead, keeping the S3 gateway entry on com.amazonaws.

Edge-optimized API Gateway exists only in the commercial partition: China has CloudFront but no edge-optimized APIs or domains (its API Gateway documentation says so), so EDGE custom domains are refused everywhere else. Where the CDK publishes no SAML sign-on URL (aws-iso-e, aws-iso-f, aws-eusc) assertions keep being checked against the commercial URL, as every partition was before, instead of all being refused. applyEndpointType has its javadoc back.
2026-09-28 23:52:35 -04:00
Matheus Oliveira 60b8fd2037 fix(s3): honor bucket-policy grants on presigned POST uploads (#4278)
A presigned POST was authorized against the signing principal's identity
policies alone, so a same-account caller that only the bucket policy named was
denied. The IAM filter now resolves the applicable resource policies on that
path too, letting either policy provide the grant while an explicit deny in
either still wins and cross-account access still requires both.

That resolution now also carries the global condition keys
(aws:PrincipalAccount, aws:ResourceAccount, aws:RequestedRegion) filter()
already supplies for every other enforcement path, instead of only
aws:PrincipalArn, so a conditional bucket-policy statement is judged
consistently between the two enforcement paths.

Per-action, header-derived keys (s3:RequestObjectTag/* from x-amz-tagging)
are deliberately not resolved here: a presigned POST's outer HTTP headers are
not covered by its signed policy document and do not correspond to any tag
S3Controller actually applies to the object, so trusting one would let a
caller satisfy a tag-scoped grant condition without the object ever carrying
that tag.

Closes #4243

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-09-26 16:32:47 -05:00
Abhigya bae7e0316a feat(s3): enforce Block Public Access on the data plane (#4253)
* feat(s3): enforce Block Public Access on the data plane

The four Block Public Access flags were stored and returned but never read
by any authorization path, so put-public-access-block was accepted and
changed nothing: a bucket left public by a policy or an ACL stayed readable.

Enforce all four, combining a bucket's configuration with its owner
account's and taking the most restrictive of the two, as AWS does.

BlockPublicPolicy and BlockPublicAcls reject the write that would introduce
public access, which AWS applies whoever the caller is, so they do not sit
behind enforce-auth. RestrictPublicBuckets and IgnorePublicAcls suppress
access an existing policy or ACL grants, which only has meaning once
anonymous authorization runs, so they take effect under enforce-auth.

Deciding what counts as public follows the documented AWS rules: an ACL is
public when it grants any permission to AllUsers or AuthenticatedUsers, and
a policy is assumed public unless a wildcard-principal statement pins a
recognised condition key to a fixed value. A single public statement makes
the whole policy public, so RestrictPublicBuckets also withholds the
cross-account delegation a separate non-public statement grants.

Enabling a setting never rewrites stored state; an existing public policy
or ACL is left exactly as written.

* test(s3): pin the Block Public Access contract at the wire

Cover the write-time flags under the default configuration and the
read-time flags under enforce-auth, including the reproduction that
motivated the fix: put-public-access-block followed by an anonymous
GetObject on a bucket whose policy is public.

Each enforcing assertion is paired with a negative control that must keep
passing without the fix, so a test cannot pass vacuously: the without-BPA
case still returns 200, and the owner's signed access is never affected.
Reverting the S3Service change fails the 11 enforcing assertions and leaves
the 10 controls green.

Unit tests cover the settings record's parsing and most-restrictive merge,
the ACL public-status rule, and the policy public-status rule against the
examples in the AWS documentation.

* test(s3): validate Block Public Access through the AWS SDK

Drives BlockPublicPolicy and BlockPublicAcls with S3Client so the rejection
is seen the way an SDK caller sees it: a 403 carrying the AccessDenied error
code, not just a status line. Both apply without enforce-auth, which is the
configuration this suite runs against.

* test(s3): drop the em-dash from the Block Public Access display name

* fix(s3): recognize scoped access point ARN in bucket policies

* fix(s3): honor ForAnyValue in public policy checks
2026-09-24 08:23:12 -04:00
XuJian b986b95074 fix(s3): reject reserved storage bucket names (#4289) 2026-09-23 23:41:20 -04:00
Priamo Germosen 2e21c013c5 fix(s3): keep a bucket's data inside its own account directory (#4244)
A bucket name went into the storage path unvalidated, so a bucket named .. resolved to the account storage root itself and the containment check then passed for any account's objects. Reject a name that is not a single directory at CreateBucket, and resolve every bucket path through a helper that asserts the directory sits directly under its account, which also covers a bucket persisted before the name was refused.
2026-09-23 18:07:48 -05:00
Simone Primarosa 3c23784ca7 feat(s3): evaluate bucket policies for authenticated callers (#3632) 2026-09-15 13:09:26 -04:00
Rafael Sierra f9f90cfc98 feat(s3): add object annotations support (#3324)
* feat(s3): add object annotations support

PutObjectAnnotation, GetObjectAnnotation, ListObjectAnnotations, DeleteObjectAnnotation
via the ?annotation subresource, with per-version storage, x-amz-annotation-directive
on CopyObject, s3:ObjectAnnotation:* notifications, and x-amz-object-if-match.

* fix(s3): serialize annotation restore with copy publication and sweep payloads on reset

* fix(s3): lock cross-account copy buckets via resolveBucket and log compat test cleanup
2026-09-11 10:00:16 -04:00
fracermaandPriamo Germosen d466ffe099 fix(s3): preserve SSE-KMS key ID metadata (#2145)
* fix(s3): preserve SSE-KMS key ID metadata

* fix(s3): validate and copy SSE-KMS key metadata

* fix(s3): return SSE headers on CopyObject and UploadPartCopy responses

Both handleCopyObject and handleUploadPartCopy stored the destination's
server-side-encryption settings correctly but never echoed
x-amz-server-side-encryption / x-amz-server-side-encryption-aws-kms-key-id
on their own response — only a follow-up GET/HEAD on the copy revealed it,
which is why the existing SSE tests (checking only via HEAD) never caught
this. Real S3 returns both headers on CopyObjectResult and CopyPartResult.

UploadPartCopy required threading the KMS key id through
CreateMultipartUpload too: MultipartUpload had no field for it, so a part's
destination upload had nowhere to read it back from.

* fix(s3): drop em dashes from merged UploadPartCopy comments

AGENTS.md rules out em dashes anywhere in content. The two comments moved
during the origin/main downmerge (handleUploadPartCopy's SSE-settings note
and the relocated uploadPartCopyPreservesDestinationServerSideEncryption
test) carried one each. Reworded to a period and a comma respectively.

---------

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
2026-09-09 16:03:24 -04:00
Allen Sanborn 83b010e6c3 docs(lambda,s3): mark two leniencies as Floci's call, not observed AWS (#3270)
* docs(lambda,s3): mark two leniencies as Floci's call, not observed AWS

Both lines read as parity claims for behaviour nobody probed against
AWS, which is the failure mode of keeping measured and inferred apart:
a later reader can cite either one as a probed result.

lambda.md: accepting ApplicationLogLevel and SystemLogLevel alongside
LogFormat=Text is justified in the text by Floci's own response shape,
which never surfaces those levels for Text. Request behaviour and
response behaviour are both our choice, so say so.

s3.md: log-delivery-write really does match AWS on PutBucketAcl, but
AWS documents that canned ACL as bucket-only and the SDK's
ObjectCannedACL enum omits it, so accepting it on PutObjectAcl is a
Floci leniency rather than parity. Both paths share one canned-ACL
helper, which is also why aws-exec-read, an object-only canned ACL in
the SDK model, is accepted on buckets. Name that mirror-image case so
the next reader sees the pattern instead of filing it again.

No behaviour change: both entries describe code that stays as it is.

* docs(s3): attribute the aws-exec-read narrowing to the SDK model, not to AWS

The sentence said aws-exec-read is one "which AWS lists only for objects". That is
the same mistake this PR exists to correct, made inside the correction: AWS's canned
ACL reference lists it under "Bucket and object". What is narrower is botocore's
BucketCannedACL enum, which omits it while ObjectCannedACL includes it, so the
client-side validation on PutBucketAcl is an SDK artefact rather than documented AWS
behaviour.

Verified against the shipped model: BucketCannedACL is private, public-read,
public-read-write, authenticated-read; ObjectCannedACL adds aws-exec-read,
bucket-owner-read and bucket-owner-full-control.

The log-delivery-write half of the sentence was accurate and is unchanged.
2026-09-09 15:21:04 -04:00
lex00 703744c9fb feat(s3): support bucket analytics and inventory configurations (#3213)
PutBucketAnalyticsConfiguration, GetBucketAnalyticsConfiguration,
ListBucketAnalyticsConfigurations and DeleteBucketAnalyticsConfiguration,
plus the four inventory counterparts, follow the shape the metrics and
intelligent-tiering configurations already use. Each body is validated
against the published schema and re-serialized in the AWS element
order, stored on the bucket record under its id, and returned from the
single and list reads. The PUT and DELETE forms are routed ahead of the
unqualified CreateBucket and DeleteBucket so they cannot fall through.
2026-09-07 21:43:19 -05:00
Mihai BlidaruandMihai Blidaru 724be0a6a7 fix(s3): return composite multipart checksums and match S3 on UploadPart, GetObjectAttributes and CopyObject responses (#3093)
* fix(s3): return composite checksums for multipart uploads

CompleteMultipartUpload stored the checksum of the whole object but labelled
it COMPOSITE, so clients that recompute the composite value from the part
checksums, as the AWS documentation describes, never matched it.

Follow the AWS checksum type rules, verified against real S3:

- SHA1/SHA256 are always COMPOSITE, CRC32/CRC32C default to COMPOSITE and
  CRC64NVME is always FULL_OBJECT. x-amz-checksum-type on CreateMultipartUpload
  selects FULL_OBJECT for CRC32/CRC32C; incompatible combinations fail with
  InvalidRequest, and the response echoes x-amz-checksum-algorithm/-type.
- The composite value is the algorithm applied to the concatenated binary part
  checksums, Base64 encoded, with a "-<part count>" suffix. It is returned by
  CompleteMultipartUpload, HeadObject and GetObject (with x-amz-checksum-type),
  while GetObjectAttributes omits the suffix, as AWS does.
- A checksum sent on CompleteMultipartUpload is validated against the stored
  type: a mismatching value is a BadDigest (the composite is accepted with or
  without its suffix), a checksum type different from the one the upload was
  created with is an InvalidRequest, per-part checksums in the request body
  that do not match the uploaded parts are an InvalidPart, and a COMPOSITE
  upload completed without the checksum of every part is an InvalidRequest
  (FULL_OBJECT uploads need none, as on S3). A non-numeric
  PartNumber is a MalformedXML instead of a 500.
- UploadPart echoes the part checksum (x-amz-checksum-<algorithm>) when the
  upload declared an algorithm, as S3 does; without one no header is returned.
- CopyObject writes a single object without a part manifest; a composite source
  gets a full-object checksum recomputed with its algorithm, and CopyObjectResult
  carries the checksum elements, matching AWS.
- GetObjectAttributes lists part-level checksums only for COMPOSITE objects: a
  FULL_OBJECT multipart object reports its PartsCount alone and a single-part
  object has no ObjectParts element.

The algorithm and type rules live in two new enums, ChecksumAlgorithm and
ChecksumType, parsed once from the request headers; S3Checksum builds the
full-object, composite and GetObjectAttributes views of a checksum.

The boto3 compatibility suite gains multipart upload_file cases for SHA256 and
for the SDK's default CRC32, asserting the composite value and the part list.

The S3 docs drop the stale note that checksum responses focus on SHA-1 and
SHA-256 (CRC32, CRC32C and CRC64NVME have been supported since #877) and list
the AWS algorithms Floci rejects.

* fix(s3): return the GetObjectAttributes ETag without quotes

S3 returns the ETag element of GetObjectAttributes without the surrounding
quotes that HeadObject, ListParts and CompleteMultipartUpload keep. Verified
against real S3 with the same object: head_object gives "af3c...-3" while
get_object_attributes gives af3c...-3, and the AWS CLI reference shows the same
in its get-object-attributes example. Floci echoed the quoted value, so a client
comparing both saw different strings on Floci and equal ones nowhere.

* fix(s3): give a copied object its own ETag

CopyObject kept the ETag of the source, so the copy of a multipart object
carried the "<md5-of-md5s>-N" value of its parts. S3 writes a copy as a single
object and returns the MD5 of the whole content as its ETag, in CopyObjectResult
and HeadObject alike (verified against real S3: source "af3c...-3", copy
"a5f04f..."). The copy now keeps the ETag storeObject computes.

* fix(s3): send CopyObjectResult as application/xml

The CopyObject response carried Content-Type: text/plain;charset=UTF-8 for an
XML body. S3 labels it application/xml like every other XML response.

* test(s3): cover multipart checksums in every SDK compatibility suite

Each SDK implements flexible checksums differently, so the multipart flows are
exercised per client rather than once: the Go transfer manager (what
terraform-provider-aws uses), @aws-sdk/lib-storage for Node, the Java SDK v2 both
low-level and through S3TransferManager on the multipart-enabled async client, the
AWS CLI (s3api, aws s3 cp --checksum-algorithm and a plain aws s3 cp that goes
multipart on its own) and boto3. Every case asserts the composite or full-object value computed in the
test itself, the UploadPart echo, the suffix-less GetObjectAttributes checksum
and unquoted ETag, the rejected Complete without part checksums, and the copy
of a multipart object as a single full object with its own ETag. The default
algorithm cases accept whatever the SDK version declares (CRC32 composite or
full object, or none) and check the stored value against it.

* test(terraform): upload a large aws_s3_object with Terraform and OpenTofu

The IaC suites created buckets but never an object, so the code path that
surfaced the composite checksum bug, an aws_s3_object above the provider's part
size uploaded through the SDK transfer manager, was not covered. Both suites now
upload a 12 MiB file generated by the test setup with checksum_algorithm SHA256
and check that HeadObject reports a COMPOSITE checksum equal to the composite
computed locally over the part sizes GetObjectAttributes lists, that the state
attribute holds the same value, and that re-planning the object shows no drift.

compat-opentofu moves to the same aws-cli image as compat-terraform (2.34.32):
2.15 predates the S3 checksum type and cannot show ChecksumType in its output.

* fix(s3): reject x-amz-checksum-type without a checksum algorithm

CreateMultipartUpload only parsed x-amz-checksum-type when an algorithm was
declared, so a type sent on its own, valid or not, was silently ignored. S3
validates the header regardless: an unknown value is InvalidRequest "Value for
x-amz-checksum-type header is invalid." and a valid one without an algorithm is
InvalidRequest "The x-amz-checksum-type header can only be used with the
x-amz-checksum-algorithm header." (both verified against real S3).

* test(s3): log cleanup failures in the multipart checksum compat tests

The Java, Node and Go cases swallowed errors while deleting their objects and
bucket. They now report what could not be deleted and why, so a leftover is
diagnosable instead of silent.

---------

Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
2026-09-05 15:12:13 -04:00
Chiara Forresi 96d16de998 feat(s3): add Intelligent-Tiering configuration CRUD (#2997)
* feat(s3): add Intelligent-Tiering configuration CRUD

Add AWS S3 Intelligent-Tiering configuration management through the
real REST XML subresource (?intelligent-tiering), mirroring the existing
metrics configuration pattern.

Operations:
- PutBucketIntelligentTieringConfiguration (PUT, 204)
- GetBucketIntelligentTieringConfiguration (GET by id)
- ListBucketIntelligentTieringConfigurations (GET without id)
- DeleteBucketIntelligentTieringConfiguration (DELETE, 204)

The parser validates Id, Status (Enabled/Disabled), optional Filter
(Prefix/Tag/And), and one or more Tiering entries (AccessTier + positive
Days), re-serializing through XmlBuilder/XmlParser/AwsNamespaces.S3 so
responses are built by floci rather than echoing the request body.
Malformed bodies return MalformedXML; missing configurations return
NoSuchConfiguration.

Configurations are stored on the Bucket model keyed by id (nullable map
for backward-compatible deserialization of older snapshots), persisted
through StorageFactory, and synchronized on the bucket monitor with the
same requireSameRecord guard as metrics to survive concurrent puts and
bucket delete/recreate races.

Tests:
- S3IntelligentTieringConfigurationTest: parser unit tests
- S3ServiceTest: service lifecycle, isolation, persistence, concurrency
- S3IntelligentTieringConfigurationIntegrationTest: REST integration
- compatibility-tests/sdk-test-awscli: AWS CLI bats coverage

* refactor(s3): rename METRICS_XML_DECLARATION to S3_XML_DECLARATION

The XML declaration constant is shared by both metrics and
intelligent-tiering configuration responses, so the name should reflect
its S3-wide scope rather than implying it is metrics-specific.

* fix(s3): enforce auth and validate Days overflow on intelligent-tiering

Address review feedback on PR #2997:

- PUT and DELETE ?intelligent-tiering now enforce S3 authorization via
  a new authorizeBucketWrite method, closing the bypass where mutations
  skipped the auth applied to reads.
- Days values above Integer.MAX_VALUE no longer throw NumberFormatException
  and return 500 InternalError; they are rejected as 400 MalformedXML.
- A PUT without a request body returns 400 MalformedXML instead of NPE/500.

Tests: unit coverage for Days overflow, integration coverage for empty body.

* fix(s3): enforce tier-specific Days range on intelligent-tiering

AWS enforces a tier-specific Days range for S3 Intelligent-Tiering:
- ARCHIVE_ACCESS: 90 to 730 days
- DEEP_ARCHIVE_ACCESS: 180 to 730 days

Out-of-range values now return InvalidArgument with ArgumentName and
ArgumentValue in the XML error body, matching the real S3 error shape.

Add unit and integration tests covering below-minimum, above-maximum,
boundary acceptance, and the full XML error response.

* refactor(s3): extract Days range constants in intelligent-tiering

Replace repeated magic numbers (90, 180, 730) with named constants
ARCHIVE_ACCESS_MIN_DAYS, DEEP_ARCHIVE_ACCESS_MIN_DAYS, and MAX_DAYS.
Pass min into daysOutOfRange instead of recomputing it, and use an
import for LinkedHashMap.
2026-09-04 09:06:15 -04:00
Allen Sanborn 2a014d2add fix(s3): accept the log-delivery-write canned ACL (#2653)
PutBucketAcl/PutObjectAcl rejected x-amz-acl: log-delivery-write with
"Unsupported x-amz-acl value", even though it is a standard AWS canned
ACL (Terraform's aws_s3_bucket_acl / access-logging modules send it to
grant the S3 log-delivery service group permission to write access logs
into a bucket). Of the eight AWS canned ACL values, this was the only
one missing from cannedObjectAclXml's switch - the rest were already
handled.

Add the log-delivery-write case, translating it to WRITE and READ_ACP
grants for the well-known LogDelivery group URI
(http://acs.amazonaws.com/groups/s3/LogDelivery), following the same
groupGrant pattern used for public-read/public-read-write.
2026-08-30 14:40:35 -05:00
Sam Fakhreddine c96dc98065 feat(s3): opt-in global bucket namespace and replication config (#2640)
* feat(s3): bucket replication configuration round-trip

PUT/GET/DELETE ?replication store the replication configuration verbatim
(validated for a Role and at least one Rule with a Destination/Bucket)
instead of falling through to CreateBucket. Storage-only fidelity — floci
performs no actual replication. Split from a cross-service commit; the IAM
password-policy and CloudFormation SSM-parameter changes ship separately.

* fix(s3): resolve buckets cross-account under a global bucket namespace

S3 bucket names are globally unique in AWS: a bucket lives in one account but is
legitimately reachable cross-account. floci's per-account isolation broke LZA,
which has member accounts read/write a management-owned shared assets bucket and
runs cross-account custom resources (e.g. Custom::S3PutBucketReplication) whose
Lambda calls back under a different account context than the bucket's owner.

Add an opt-in globalBucketNamespace mode (default off, preserving isolation):
bucket/object existence RESOLUTION spans every account's partition while LISTING
stays owner-scoped. Reads route through resolveBucket/resolveObject; bucket-config
MUTATIONS route through a new owner-aware mutateBucket helper that resolves the
owning account via AccountAwareStorageBackend.findAnyAccountEntry and writes back
to the owner's partition (putForAccount) rather than forking a phantom bucket into
the caller's partition. Applied to put/deleteBucketReplication — the path LZA's
Logging stage exercises cross-account.

* test(s3): guard getObject against torn reads under concurrent overwrite

LZA's Bootstrap stage fans out ~15 CodeBuild actions that redundantly re-upload
the same artifact keys (Source.zip/Config.zip) while other builds concurrently
download them. A non-atomic truncate-then-write would let a reader observe an
empty/partial object — which surfaced as an empty src-Config secondary source and
ENOENT: global-config.yaml. Add a stress test (4 writers / 4 readers) asserting
getObject never returns a torn view of a constant-size key.

* docs(s3): document the global bucket namespace flag

Describe FLOCI_SERVICES_S3_GLOBAL_BUCKET_NAMESPACE in s3.md, the
multi-account isolation exception, and the environment-variable reference.

* feat(s3): account-level Block Public Access (s3control PublicAccessBlock)

Add account-scoped PUT/GET/DELETE PublicAccessBlock to the s3control
controller, keyed by the x-amz-account-id header and stored separately
from the bucket-level configuration. LZA's Custom::PutPublicAccessBlock
custom resource calls this account-level op while building the
LoggingStack; without a route the resource reported FAILED and the
stack rolled back (NoStack on CDK readback).

(cherry picked from commit a1cdf186ac7909647350ced455c4e0ba5d2d26a0)

* fix(s3): persist account-level Block Public Access

The account-level (s3control) PublicAccessBlock configuration was held in a
plain ConcurrentHashMap, bypassing StorageFactory while every other piece of
S3 state goes through it. Block Public Access is a security control, and LZA's
Custom::PutPublicAccessBlock runs once per governed account during the
LoggingStack deploy — it does not re-run on a resumed pipeline. A restart
therefore dropped the control silently and every governed account started
reporting NoSuchPublicAccessBlockConfiguration.

Move it to a StorageFactory-backed store (s3-account-public-access-block.json)
addressed through the explicit *ForAccount overloads, so the account comes from
the validated x-amz-account-id header and globalBucketNamespace never widens it.
The s3 descriptor already declares storageKey/storageMode, so no catalog change
is needed and PersistentPathValidator now covers this state.

clear() no longer wipes the config: like the bucket and object stores, its
lifecycle belongs to StorageFactory.clearAll().

* fix(s3): check x-amz-account-id against the caller on Block Public Access

The account-level PublicAccessBlock operations took the account solely from the
x-amz-account-id header, which was only checked for being non-blank. Any caller
could read, overwrite or delete any account's Block Public Access configuration
by setting one header — and Block Public Access is a security control.

AWS s3control answers AccessDenied when the header does not name the caller's
own account: there a cross-account call carries credentials assumed into the
target account, so header and caller always agree. Compare the header against
the caller's resolved account and return the same AWS-shaped AccessDenied (403)
on a mismatch, resolving the caller exactly as AccountAwareStorageBackend does
so the check and the storage partition can never disagree.

One exception is kept deliberately: the configured default (management) account
may act on any account, because Floci's launched Lambdas run on placeholder
credentials that resolve to the management account instead of assuming a role in
the target account. Without it LZA's Custom::PutPublicAccessBlock — the reason
these operations exist — would be denied for every governed account. This is the
same allowance S3Service.mutateBucket already makes for
Custom::S3PutBucketReplication.

Enforcement is scoped to the three PublicAccessBlock routes; the tag routes on
this controller accept and ignore the header as before.

* docs(s3): state the global bucket namespace trade-off explicitly

No behaviour change. The flag widens bucket resolution across accounts, which
reads as an account-isolation violation to a reviewer working from a checklist.
Say the intent in place, on the config option and in the S3 guide: S3 bucket
names are globally unique in AWS, a bucket lives in one owning account, and
cross-account access is a policy decision — so a hard per-account partition
models a state AWS cannot reach and fails legitimate cross-account calls with
NoSuchBucket. Record what it costs too: with the flag on, only IAM and bucket
policy stand between a caller and another account's object. Mutations still
write back to the owning account and listing stays owner-scoped, and the flag
is off by default.

* fix(s3): keep the account-aware bucket replication over the upstream #2519 duplicate

Upstream landed its own Put/Get/DeleteBucketReplication (ce4f6d1c4), which
duplicated the branch implementation. The branch copy stays because it goes
through mutateBucket (the caller-scoped mutation the LZA
Custom::S3PutBucketReplication path requires) and validates Role, Rule and
Destination/Bucket; upstream's root-element MalformedXML check is folded
into it so nothing upstream tested is lost. Duplicate Bucket field and
accessors removed.

* fix(s3): enforce the modeled AccountId pattern and ReplicationRule status enum

Account-level Block Public Access took x-amz-account-id as its storage
partition key after only a blank check, so a value outside the s3control
AccountId shape (^\d{12}$) filed a security configuration under a partition
no account could address again.

PutBucketReplication stored the document after checking only that a Role, a
Rule and a Destination/Bucket were present, so a rule with a missing or
out-of-enum Status round-tripped through GetBucketReplication as a document
AWS would have rejected. Both now answer the error the operation already
uses for its other input guards.

* fix(s3): resolve GetBucketReplication cross-account under the global bucket namespace

putBucketReplication and every other bucket-config mutation resolve cross-account
through mutateBucket/resolveBucket when globalBucketNamespace is enabled, but
getBucketReplication still called bucketStore.get(bucketName) directly. A
management-account caller could write a bucket's replication configuration
cross-account (mirroring LZA's Custom::S3PutBucketReplication path) but a
follow-up GetBucketReplication under the same caller saw NoSuchBucket instead of
the configuration it just stored.

RED test: getBucketReplicationResolvesCrossAccount in
S3GlobalBucketNamespaceTest failed with NoSuchBucket before this change.

* fix(s3): validate each replication rule's own destination bucket

PutBucketReplication checked that at least one Bucket appeared anywhere in the
document, then validated only Status per rule. A multi-rule document where only
one rule carried a Destination/Bucket satisfied that document-wide check and
round-tripped through GetBucketReplication as a configuration AWS would have
rejected as MalformedXML.

Destination elements appear in the same document order as their owning Rule
(extractGroupsMulti can't see nested Destination/Bucket as a Rule leaf), so
pairing the Destination list position-for-position with the Rule list and
requiring an equal count plus a non-blank Bucket in each enforces that every
rule carries its own destination.

RED test: putReplicationRejectsARuleWithoutItsOwnDestinationBucket in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): remove unreachable duplicate ?replication dispatch

The PUT and GET handlers each had two identical `if (hasQueryParam(uriInfo,
"replication"))` branches — a rebase artifact. The earlier branch in each
method always returns first, so the second was dead code that risked a future
routing change updating only one copy.

* docs(s3): expose global-bucket-namespace in the canonical application.yml

globalBucketNamespace() was documented in EmulatorConfig and in
docs/services/s3.md but absent from the s3 block in both application.yml
files, leaving the runtime configuration surface out of sync with what the
code and docs describe.

* test(s3): assert torn-read stress threads actually finish

The writer/reader threads were joined with a 30s timeout but never checked for
liveness afterward. A thread still running past the timeout could leak past
the test (hanging the suite) or let the assertions pass vacuously without that
thread's reads or writes having completed.

* fix(s3): reject malformed PutPublicAccessBlock bodies

s3control's PutPublicAccessBlockRequest requires PublicAccessBlockConfiguration,
but the controller normalized any body — null, empty, unparseable, or a
different root element entirely — into a valid configuration with every flag
defaulted to false via canonicalPublicAccessBlockXml. For an account-level
Block Public Access control, that silently disabled every protection on a bad
request instead of failing it.

Reject a body whose root element is not PublicAccessBlockConfiguration with
the same MalformedXML the bucket-level replication path already uses for this
class of error, before normalization runs.

RED test: putRejectsAMalformedOrWrongRootBody in
S3ControlAccountIdEnforcementTest got 200 instead of 400 before this change.

* fix(s3): validate replication destinations against their own rule, not the document total

Counting Rule and Destination elements document-wide and requiring the totals to match let a
rule with two Destinations balance a rule with none, satisfying the check while storing a
configuration AWS would reject as MalformedXML. Destination is Required: Yes directly on Rule, so
PutBucketReplication now walks the parsed element tree and requires each Rule to have exactly one
Destination of its own with a non-blank Bucket, instead of comparing counts across the whole
document.

* fix(s3): reject a replication destination with multiple Bucket elements

Destination.Bucket is a required scalar member (botocore
s3/2006-03-01/service-2.json: "Bucket":{"shape":"BucketName"}), not a list.
child("Bucket") returns only the first match, so a Destination with two Bucket
children silently accepted the first and stored a document AWS would reject
as MalformedXML.

Count the Bucket children explicitly and require exactly one, instead of
taking child("Bucket")'s single match unconditionally.

RED test: putReplicationRejectsADestinationWithMultipleBucketElements in
S3ReplicationConfigurationIntegrationTest got 200 instead of 400 before this
change.

* fix(s3): wire bucket-policy operations through cross-account resolution

getBucketPolicy/putBucketPolicy/deleteBucketPolicy still resolved via
bucketStore directly, unlike object read/write and replication, so a
management-account caller got NoSuchBucket on a member-owned bucket's
policy even with the global bucket namespace enabled. Route them
through resolveBucket/mutateBucket like the rest of the cross-account
paths, and document the IAM-enforcement dependency and the same-name
non-determinism case in the trade-off writeup.

* docs(s3): name the flag that actually gates bucket-policy evaluation

The trade-off write-up said global-bucket-namespace's IAM/bucket-policy
protection depends on FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED, but that flag
only gates identity-policy checks in IamEnforcementFilter before a request
reaches S3 — bucket-policy evaluation itself (S3Service.authorizeS3Read/
authorizeS3Write, which reads the stored bucket policy) is gated separately
by FLOCI_SERVICES_S3_ENFORCE_AUTH, which also defaults false. Name both
flags and make explicit that the S3-specific one is what actually turns
bucket-policy evaluation on or off.
2026-08-28 11:24:47 -04:00
Aniket Shukla d8ef1c8d7b fix(s3): emit post events for browser uploads (#2577) 2026-08-27 09:49:51 -04:00
soreavis ce4f6d1c48 fix(s3): route the replication subresource instead of falling through (#2519)
PUT /{bucket}?replication fell through to CreateBucket: in the default
region the idempotent-create path answered 200 with a Location header
and stored no replication configuration, and elsewhere it failed with
BucketAlreadyOwnedByYou. GET fell through to ListObjects and returned
a ListBucketResult the SDK silently parsed as an empty replication
configuration. Only DELETE was routed, as a no-op.

Route PUT and GET alongside the existing DELETE case, per the issue's
suggested fix: the configuration is stored verbatim on the bucket and
echoed back — Floci does not model replication behavior, and neither
the SDK nor the Terraform provider needs it to. The PUT body's
ReplicationConfiguration root is validated (MalformedXML otherwise);
GET on a bucket with no stored configuration answers
ReplicationConfigurationNotFoundError (404), which is what the SDK and
aws_s3_bucket_replication_configuration treat as "not configured".

Now that PUT stores a configuration, DeleteBucketReplication clears it
instead of no-opping (still an unconditional 204, matching AWS), and a
DELETE on a missing bucket answers NoSuchBucket instead of the no-op's
204.

IamActionRegistry maps the three verbs to the documented actions:
s3:PutReplicationConfiguration for PUT and DELETE (AWS authorizes
DeleteBucketReplication with the put action) and
s3:GetReplicationConfiguration for GET. The mapping mirrors the
controller's per-method dispatch order: on PUT and GET accelerate is
dispatched ahead of replication, while the DELETE chain routes
replication and never routes accelerate to an operation.

Closes #2296
2026-08-25 22:51:56 -05:00
Michal Schreiber 8d33c65129 feat(s3): support bucket metrics configurations (#2382)
* feat(s3): support bucket metrics configurations

PutBucketMetricsConfiguration was not routed, so a metrics call fell through to
the unqualified CreateBucket and came back as BucketAlreadyOwnedByYou, which
tells the caller nothing about what happened. The DELETE was worse: it fell
through to DeleteBucket and silently removed the whole bucket while reporting
success, so delete-bucket-metrics-configuration destroyed the bucket it was
called on.

Adds the four actions, stored per bucket and keyed by id:

- PutBucketMetricsConfiguration, GetBucketMetricsConfiguration,
  ListBucketMetricsConfigurations, DeleteBucketMetricsConfiguration
- the body is parsed and re-serialized rather than echoed back, so responses are
  built by floci and a filter survives the round trip in AWS's shape: repeated
  Tag elements inside And, with no wrapping element
- an id in the body that disagrees with the query string is MalformedXML, and an
  unknown id is NoSuchConfiguration on both get and delete, neither of which AWS
  treats as a no-op
- put and delete take the bucket monitor the other bucket-scoped mutations use,
  so concurrent puts of different ids cannot drop one another

Behaviour taken from a live AWS account: the status codes (204 on put and
delete, 404 for an unknown id), both error codes, and the exact XML of the
single-configuration and list responses.

floci records the configurations and returns them; no metrics are produced from
them, and the listing is unpaged, so a continuation token is neither issued nor
honoured.

* fix(s3): validate metrics filters, use the shared XML utilities, guard the delete

Three problems in the previous commit.

The filter was normalized rather than validated, so bodies AWS rejects were
accepted: a filter naming more than one predicate or none, an And of fewer than
two conjuncts, an unknown predicate, and a tag missing its key or value.
Verified against a live account that each is MalformedXML, and the parser now
answers the same.

Parsing and response building went around XmlParser and XmlBuilder, which
AGENTS.md requires, and the S3 namespace was declared again rather than taken
from AwsNamespaces. The bespoke DocumentBuilderFactory carried its own security
configuration, where XmlParser disables DTDs and external entities for everyone
in one place. The controller branches now delegate to handler methods like their
siblings instead of inlining the work.

A metrics mutation resolved the bucket record before writing it back, while
DeleteBucket took no monitor, so a delete landing in between was undone by the
write and the bucket returned. DeleteBucket now takes the same bucket monitor as
the bucket-scoped mutations, and those re-read the record under it, so a
mutation that lost the race reports NoSuchBucket rather than restoring the
bucket. Its test forces that interleaving rather than racing for it.

* fix(s3): reject malformed metrics bodies and stale writes over a recreated bucket

Re-reading the record for presence was not enough. A bucket deleted and then
recreated under the same name leaves a different record in the store, so a
mutation that had resolved the old one passed the presence check and wrote it
back, replacing the new bucket with the old one's state. The check now compares
the record itself, and a mutation holding a superseded one reports NoSuchBucket.

The parser also accepted bodies whose elements were duplicated or misplaced: a
second Id or Filter, or a stray element under the root, was normalized away
rather than refused, so what was stored was not what was sent. The root now has
to be exactly one Id and at most one Filter, in either order.

The concurrency tests wait on thread state rather than sleeping, so they observe
the interleaving instead of hoping for it: instant on a fast machine and not
flaky on a slow one. DeleteBucket taking the bucket monitor is asserted directly,
since the window it closes — a delete between a mutation's re-read and its write
— is too narrow to force from a test.
2026-08-18 18:46:35 -04:00
Alex Banna 6d829ff7a4 feat(s3): resolve index documents for static-website directory requests (#1815)
* feat(s3): resolve static website index documents

* fix(s3): drop the query string from the website folder redirect

Verified against a live S3 website endpoint in us-east-1 rather than inferred: a
bucket with photos/index.html answers

  GET /photos?code=abc&state=xyz  ->  302, Location: /photos/

with a bare Location. Same for HEAD and for nested prefixes (/a/b?x=1 -> /a/b/).

An earlier commit added query-string preservation on the strength of a review
comment asserting AWS behaved that way; the probe shows it does not, and LocalStack's
website_hosting.py agrees with the probe. An SPA whose OAuth callback lands on a
slash-less folder loses its parameters on real AWS too, so the emulator matches
rather than improving on it.
2026-08-08 22:42:26 -05:00
Jason van Zyl 79bf0d39a6 Stream S3 range responses (#1255)
* fix(s3): stream object range responses

* test(s3): cover streamed object reads

* fix(s3): harden streamed range responses
2026-06-11 01:48:39 -05:00
Hector Ventura e725f38ac7 feat(s3): full SelectObjectContent evaluator with floci-duck integration (#835)
- Add recursive WHERE evaluator: AND, OR, NOT, LIKE, BETWEEN, IN, IS NULL,
  >=, <=, <> — replaces single-regex implementation
- Add JSON Lines and JSON array input support
- Add cross-format output (CSV→JSON, JSON→CSV)
- Emit real BytesScanned / BytesReturned stats
- Route CSV (USE headers) and JSON through floci-duck when available;
  fall back to Java evaluator in standalone mode
- Route Parquet S3 Select through floci-duck (existing)
- Move FlociDuckManager to services/floci/ and introduce FlociDuckClient
  as a shared duck HTTP client for Athena and S3 Select
- Promote CsvParser to core/common and consolidate AthenaService.splitCsv()
- Add compatibility tests: S3SelectTest (19 tests via S3AsyncClient)

Signed-off-by: Hector Ventura <hectorvent@gmail.com>
2026-05-14 20:32:27 -05:00
Hector Ventura c8c77c9e6e feat(s3): virtual-hosted style addressing support (#805)
*.s3.localhost.floci.io, *.localhost.localstack.cloud, and
  *.s3.localhost.localstack.cloud as virtual-hosted style regardless of
  FLOCI_HOSTNAME — fixes 405 when SDK uses endpointOverride("http://localhost:4566")
  without forcePathStyle (closes #801)
- EmbeddedDnsServer ships localhost.localstack.cloud and localhost.floci.io
  as built-in suffixes so spawned containers resolve these domains to Floci's
  IP without extra config
- Compatibility test S3VirtualHostStyleTest covers the full virtual-host path
  end-to-end; TestFixtures.s3VirtualHostClient() prefers s3.localhost.floci.io,
  falls back to s3.localhost.localstack.cloud, or uses FLOCI_S3_VHOST_ENDPOINT
  in Docker
- run-docker-tests.sh and compatibility.yml inject --dns <floci-ip> and
  FLOCI_S3_VHOST_ENDPOINT=http://floci:4566 into test containers
- S3 and migrate-from-localstack docs updated with virtual-hosted style details
2026-05-11 23:53:28 -05:00
Hector Ventura 9e35046647 Docs/enviroment instead yml (#764)
* docs: moving all config to env instead of yml
* docs: sync with main and new features
* docs: reverting docker-compose.yml
2026-05-10 11:53:31 -05:00
sf-jin-ku 2efb483390 feat(s3): preserve explicit object SSE headers (#515)
* feat(s3): preserve explicit object SSE headers
* refactor(s3): validate and encapsulate SSE write options
* fix(s3): make notification filter parsing deterministic
* fix(ses): harden identity deletion lookups
* fix(ses): reject padded identities literally
* fix(secretsmanager): keep a single previous stage
2026-04-19 23:36:36 -05:00