Commit Graph
66 Commits
Author SHA1 Message Date
Matheus Oliveira 97ecbdd656 fix(iam): authorize S3 Control routes as their own s3 actions (#6681)
* fix(iam): authorize S3 Control routes as their own s3 actions

S3 Control clients sign with the s3 scope, so under IAM enforcement its
/v20180820 routes fell through to the S3 data-plane rules and were
checked as s3:GetObject, PutObject or DeleteObject on a bucket named
v20180820, which no policy can name: a role allowed
s3:ListTagsForResource on a bucket was denied its tag list, and
Terraform's AWS provider, which reads bucket tags through S3 Control,
never fell back to GetBucketTagging, leaving aws_s3_bucket unrefreshable.

Map the routes to the actions the Service Authorization Reference gives
them: ListTagsForResource, TagResource and UntagResource are checked
against the ARN the route names, as written and decoded as the handler
decodes it; ListAccessPoints and the account-level Block Public Access,
to which the S3 User Guide gives no resource, against every bucket in
the request's partition; the account control takes the
PutAccountPublicAccessBlock and GetAccountPublicAccessBlock actions. A
data-plane operation under the same prefix keeps its own bucket-and-object
ARN. A denial now answers in S3 Control's own ErrorResponse envelope, the
only one the s3control SDK deserializers read, so the message naming the
missing action survives to the client.

Closes #6537

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(iam): answer the three control-route gaps the review found

A tagging query on a control route still reached the data-plane override,
so GET /v20180820/tags/<arn>?tagging was checked as s3:GetObjectTagging
while the handler read the bucket's tags: the control rules now match
before the query overrides, and a caller holding only the object action
is denied where one holding the control action passes. A tagging ARN in
the regional form was rewritten to the global form downstream and its
bucket misread, so a policy naming the regional form the API reference
requires was denied; the provider now keeps a control tagging ARN as
written and reads the bucket it names. The account actions returned
arn:<partition>:s3:::*, which a bucket-scoped statement matches; they
now return the literal wildcard, so a bucket-scoped statement grants no
account-wide action, the convention the KMS no-resource actions
follow.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(iam): drive S3 Control route authorization from AWS's own data

The s3control model is vendored in rest-routes.json, regen_rest_routes
carries it under the s3 scope, as s3control signs with s3, and
IamRestRouteCoverageTest checks every S3 Control route Floci serves
against the Service Reference. The hand-written S3_CONTROL_RULES and
S3_CONTROL_ACTIONS lists are gone: the control routes are entries of the
one rules table, flagged to match before the S3 data-plane query
overrides so ?tagging on a tagging route cannot re-point the
authorization, and a denial answers in S3 Control's ErrorResponse
envelope by following the route instead of an action-name list. The
account-level Block Public Access is the one written-down exception, as
the reference files S3's and S3 Control's Get, Put and
DeletePublicAccessBlock under the bucket actions and the Block Public
Access page gives the account level its own actions.

A tagging ARN is read once, by the handler, the IAM check and the
bucket-policy lookup together: S3ControlArnUtils decodes and parses it
with AwsArnUtils.parse, and the regional form's account is the account
whose bucket the request acts on, so a grant on
arn:aws:s3:us-east-1:222222222222:bucket/reports no longer lets a
caller in 111111111111 read and change the tags of its own same-named
bucket: it reads and writes 222222222222's bucket, and answers
NoSuchBucket when that account holds no bucket of the name.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* fix(s3): read the policy provider's ARNs without decoding them

The provider received every ARN already decoded, the data plane's from
the request path and a control tagging one re-minted by the rule that
read it off the wire, but the one-parse helper decoded again, so an
object key carrying a plus sign or a literal percent sequence changed
its bytes before IAM checked it: a policy on arn:aws:s3:::example/a+b.txt
denied the very object it named. The provider parses without decoding
now; the wire decode stays where it belongs, at the control request
boundary.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-27 10:12:51 -04:00
Matheus Oliveira 56196fec1c fix(s3): report the owner and ACL grantees as a canonical user id (#6549)
* fix(s3): report the owner and ACL grantees as a canonical user id

S3 reported the 12-digit account id where AWS reports the account's
canonical user id: the bucket owner in ListBuckets, the owner and the
multipart initiator in ListParts, and every CanonicalUser grantee and
Owner the ACL responses name. All of them now answer the canonical id,
a 64-character lowercase hex string Floci derives as the SHA-256 of the
account id, so the same account answers the same id across calls,
restarts and storage modes and two accounts never share one. The
account id stays the internal identity; only the emitted value changes,
and ACLs persisted by an older Floci keep serving the form they store.
Owner evaluations, the public-access checks and bucket-policy
CanonicalUser principals accept the canonical id and the account id
alike, so stored policies and scripts written against the old form keep
working.

Closes #6242

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* test(s3): say why the cleanup catches stay silent

The two new compatibility cleanup catches swallowed without a word,
which the guide allows only for a named, explained tolerance. Both now
name the reason: cleanup must not mask the assertion.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* test(s3): expect the canonical owner in the namespace ACL assertions

The cross-account object metadata test still expected the raw account id
in the ACLs, which the canonical owner id broke, and its ACCOUNT_B
assertFalse checks passed whatever the ACL held. All four assertions now
name the accounts the way the ACLs do, through AwsCanonicalUserId.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

* test(s3): share the compatibility cleanup between the two tests

The explained cleanup catches landed on the wrong method, a helper that
was already on main, leaving the new canonical owner test with bare
catches. One deleteObjectAndBucketQuietly helper now holds the commented
catches and serves both tests.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>

---------

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-25 22:11:19 -04:00
Andre Kurait 2bc53956fd fix(s3): preserve bucket collision errors with IAM enforcement (#6539)
Exclude foreign bucket policies from CreateBucket authorization while preserving caller permission checks, creation-setting checks and same-owner policy enforcement.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
2026-10-25 16:33:29 -04:00
Matheus Oliveira 781a68b6cb fix(s3): store object key segments past the file-name limit (#6438)
A disk-backed storage mode lays an object body out as the bucket
directory, the key, and a data suffix, so a single key segment longer
than the 255-byte file-name limit made every write of the object fail
with FileSystemException, where AWS takes keys up to 1024 bytes and
memory mode always did.

A segment that fits its byte budget is stored as written, so every path
an earlier Floci could create is still found. A longer one, and a segment
shaped like an encoded one so a crafted short key cannot land on it,
becomes a readable prefix, a separator, and the SHA-256 of the whole
segment: deterministic, so a key always resolves to one file, and
injective, so two keys never share one. The object index keeps the key,
so listing answers with the key the client used.

The temporary file a write stages beside its target no longer derives
from the target's name either: at the limit that name ran 41 bytes past
it. A constant-length name does not.

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
2026-10-24 15:03:52 -04:00
Jimmy Liu Jia be7b0ed62b fix(s3): expose bucket policy status (#6397)
* fix(s3): expose bucket policy status

* fix(s3): align bucket policy status response

* test(s3): verify policy status through SDK and IAM

* refactor(s3): reuse bucket policy lookup for status
2026-10-24 13:49:10 -04:00
TiM 212a424ed2 fix(s3): keep Object Lock buckets versioning-enabled (#6322)
A bucket with Object Lock is versioned for good. PutBucketVersioning
with Suspended on such a bucket now answers 409 InvalidBucketState and
leaves it Enabled, and PutObjectLockConfiguration on a bucket whose
versioning is unset or suspended answers 409 InvalidBucketState and
enables nothing, matching the AWS-recorded messages. CloudFormation goes
through the same PutBucketVersioning path, so an update that suspends a
locked bucket rolls back.

Both checks run with the write under the bucket monitor, and CreateBucket
with Object Lock now enables versioning and the lock in one step, so no
concurrent request can leave a locked bucket suspended.

Buckets stored in either state by an earlier release load as they were;
the null-version protection for them is unchanged, and its tests now set
that state on the stored bucket.
2026-10-23 00:00:01 -04:00
Aniket Shukla 95387d1906 fix(s3): include bucket regions in parameterized listings (#6315) 2026-10-22 22:29:38 -04:00
TiM e01fbd8bf8 fix(s3): preserve archived null versions (#6104)
* fix(s3): preserve archived null versions

* fix(s3): address null version archive review

Preserve locked null versions under new versions and markers while checking protection before suspended cleanup. Avoid locking never-versioned body reads, reject reserved service keys, and recover original null bodies and metadata after failed publication.

Remove obsolete marker bodies and retry reads that race marker creation. Refresh promoted null generations so archival and configuration rollback cannot hide a body replacement.

* fix(s3): serialize null version metadata updates with promotion

Hold the bucket monitor while resolving, validating and persisting retention, legal hold and ACL changes so promotion cannot discard an acknowledged update. Cover the race with a two-thread regression and preserve numbered-version references during demotion.

* fix(analysis): protect null history after bucket configuration rollback

Apply archived-null protection and cleanup in every non-enabled mutation path so restoring an unversioned bucket configuration cannot erase locks or leave stale history. Cover replacement, deletion and protected annotations in memory and disk modes.

* fix(analysis): assert preservation immediately after each denied operation

Check current and archived bytes before another request can repair corruption, use a distinct copy source, and compare replacement metadata with the listed null entry.

* fix(analysis): compare listed null history with replacement metadata

Assert the null listing identifies the latest replacement and its ETag so stale history cannot satisfy the count-only check.

* fix(analysis): qualify missing null version documentation

Describe keys that have no null version without excluding keys that gain one after versioning is suspended.

* fix(s3): retain archived null history until replacement publication succeeds

Keep the archived body, metadata and annotations when a non-enabled replacement metadata write throws, including after configuration rollback. Clean history after successful publication under the bucket monitor and cover failures before and after publication in memory and disk modes.

* fix(s3): restore the current pointer after archived null publication failures

Recover the prior current body and metadata when a non-enabled PUT with archived null history fails publication. Handle numbered versions, promoted null versions and markers with a fresh read generation, and keep archive annotations publicly associated with their original version. All 199 focused tests pass.

* test(s3): prove reads retry across failed publication recovery

Observe replacement bytes during a publication fault and require latest and explicit-null reads to retry against the restored promoted null version. Both new cases and all 27 archive/read tests pass.

* docs(s3): use repository punctuation style

Replace existing em dash punctuation in the touched S3 service documentation as required by the repository documentation rules.

* fix(analysis): assert canonical cleanup when failed publication restores a marker

Check memory payloads and the disk canonical path before retrying, so the marker-before-publication cells detect orphaned replacement bodies as well as metadata restoration. All 27 archive/read cases pass.
2026-10-22 21:12:45 -04:00
Andre Kurait 88be39a7d4 fix(s3): preserve bucket ownership across account routing (#6117)
Signed-off-by: Andre Kurait <akurait@amazon.com>
2026-10-22 12:33:06 -04:00
Vũ Thế Huy 6355474ad2 feat(s3): verify SigV4A (AWS4-ECDSA-P256-SHA256) request signatures (#6092)
* feat(s3): verify SigV4A (AWS4-ECDSA-P256-SHA256) request signatures

Derive the ECDSA P-256 key pair from the secret access key, as AWS does, and
check SigV4A signatures in the Authorization header and in presigned URLs when
signature verification is on. The region-less credential scope now resolves
its region from the signed region set instead of reading the service name as
a region.

Closes #5210

* fix(s3): address SigV4A review feedback and edge cases

- Reject forged SigV4A headers to non-S3 services
- Handle comma-only X-Amz-Region-Set safely in RegionResolver
- Support SigV4A credential scope in IamEnforcementFilter
- Reject duplicate Credential components in Authorization header
- Tighten SigV4CredentialScope SERVICE_PATTERN regex
- Reuse S3RequestSigner host and bodyBytes in S3SigV4aRequestSigner
- Fix Checkstyle import ordering and redundant FQCN

* fix(core): support nested credentials in SigV4CredentialScope service patterns

* refactor(core): apply SigV4A region set without service-specific check

* docs(iam): update SigV4A Javadoc on refuseUnreadableCredential
2026-10-21 21:14:18 -04:00
Huan Jiang 3a913ca8d6 fix(s3): ignore hoisted upload checksum query parameters (#5977)
* fix(s3): ignore hoisted upload checksum query parameters

* fix(s3): ignore hoisted multipart checksum types
2026-10-19 09:30:12 -04:00
Priamo Germosen 36b315d77b fix(s3): refuse Object Lock settings on a bucket without Object Lock (#5969)
PutObjectRetention, GetObjectRetention, PutObjectLegalHold and
GetObjectLegalHold on a bucket without Object Lock set or returned the
setting with a 200. S3 refuses them with 400 InvalidRequest, "Bucket is
missing Object Lock Configuration", as LocalStack's AWS-validated
recordings show, and Floci now does too, before it looks for the key.
A legal hold without a status is still refused as malformed first, as
recorded.

PutObject, CopyObject and CreateMultipartUpload applied a mode, a
retain-until date or a legal hold of ON on such a bucket as well, and
since deletes enforce the lock there too, a COMPLIANCE object in it
could not be deleted until its date passed. They are refused the same
way. No AWS document or recording covers object creation; moto refuses
the same headers with InvalidRequest under its own message, so the
recorded one is used. A legal hold of OFF sets no lock and is still
accepted.

In a bucket with Object Lock, GetObjectRetention and GetObjectLegalHold
of an object without a retention or a legal hold answered 200, with no
mode or with OFF. S3 was recorded answering both with 404
NoSuchObjectLockConfiguration, which they answer now.

PutObjectRetention saved a mode without a date, a date without a mode,
or a mode S3 does not know. S3 was recorded refusing a mode without a
date, and an unknown mode, with 400 MalformedXML, and a date without a
mode would now read as no retention at all, so all three are refused
that way. A retention naming neither still removes it.
2026-10-19 07:43:15 -05:00
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