From a4eb854614bc8de8edfe3086ff7b274be58a8683 Mon Sep 17 00:00:00 2001
From: XuJian <265865031+xujiantop-crypto@users.noreply.github.com>
Date: Fri, 16 Oct 2026 08:30:26 +0800
Subject: [PATCH] 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
---
docs/services/s3.md | 2 +
.../provisioners/CfnRollback.java | 1 +
.../provisioners/S3CfnProvisioner.java | 89 +++++++--
.../s3/S3AclPublicAccessEvaluator.java | 14 ++
.../floci/services/s3/S3Service.java | 184 +++++++++++++++++-
...tionS3BucketPropertiesIntegrationTest.java | 86 ++++++++
.../provisioners/S3CfnProvisionerTest.java | 45 ++++-
.../s3/S3AuthEnforcementIntegrationTest.java | 48 +++++
.../S3OwnershipControlsIntegrationTest.java | 146 +++++++++++++-
9 files changed, 586 insertions(+), 29 deletions(-)
diff --git a/docs/services/s3.md b/docs/services/s3.md
index fa633f3098..dafc7e9c77 100644
--- a/docs/services/s3.md
+++ b/docs/services/s3.md
@@ -341,6 +341,8 @@ When a request is denied by bucket policy enforcement, Floci returns HTTP 403 wi
Floci enforces all four Block Public Access settings. A bucket's configuration is combined with the bucket owner account's and the most restrictive of the two wins, which for four independent booleans is a per-flag OR: a flag set at either level is in force.
+With `BucketOwnerEnforced` object ownership, ACL writes are rejected and existing object ACL grants no longer provide access. Before enabling it, the bucket ACL must grant access only to the owner; otherwise `PutBucketOwnershipControls` returns `InvalidBucketAclWithObjectOwnership` (400).
+
| Setting | What it does | Needs `enforce-auth` |
|---|---|---|
| `BlockPublicPolicy` | `PutBucketPolicy` returns `AccessDenied` (403) when the submitted policy is public | No |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
index 59614b62fc..1171e41212 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnRollback.java
@@ -87,6 +87,7 @@ public final class CfnRollback {
* {@code rollbackUpdate}.
*/
public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot";
+ public static final String S3_BUCKET_UPDATE_SNAPSHOT_ATTR = "__FlociS3BucketUpdateSnapshot";
/**
* Holds the description, event pattern and retention an EventBridge archive carried before an
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java
index b79b12afc0..15af61ffdf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java
@@ -26,19 +26,20 @@ import java.util.Set;
* Provisions {@code AWS::S3::Bucket} and {@code AWS::S3::BucketPolicy}.
*
*
A property this class covers is translated into the XML its own S3 API call takes and handed
- * to the same service method, so the service validates and stores it exactly as it would a direct
- * {@code PutBucket*} request. A property the template does not declare is left alone, except that
- * an update removing {@code NotificationConfiguration} clears it.
+ * to the same S3 service method used by a direct {@code PutBucket*} request. Ownership controls
+ * are validated here before the service stores their XML. A property the template does not declare is left alone, except that
+ * an update removing {@code NotificationConfiguration} or {@code OwnershipControls} clears it.
*
*
Covered on {@code AWS::S3::Bucket}: {@code BucketName}, {@code CorsConfiguration},
* {@code VersioningConfiguration}, {@code PublicAccessBlockConfiguration},
- * {@code BucketEncryption}, {@code LifecycleConfiguration}, {@code NotificationConfiguration} and
+ * {@code BucketEncryption}, {@code LifecycleConfiguration},
+ * {@code OwnershipControls}, {@code NotificationConfiguration} and
* {@code Tags}. {@code NotificationConfiguration} is the exception to the XML translation: its
* service method takes the parsed model, so the provisioner builds that model instead.
*
*
Silently dropped, each of which has a service method waiting for it:
* {@code WebsiteConfiguration}, {@code LoggingConfiguration},
- * {@code ObjectLockConfiguration}, {@code OwnershipControls}, {@code ReplicationConfiguration},
+ * {@code ObjectLockConfiguration}, {@code ReplicationConfiguration},
* {@code AccelerateConfiguration}, {@code AccessControl}, and the four numbered configuration
* lists ({@code AnalyticsConfigurations}, {@code IntelligentTieringConfigurations},
* {@code InventoryConfigurations}, {@code MetricsConfigurations}). Declaring one of these still
@@ -87,9 +88,15 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
// and only reconcile the bucket's configuration. A replacing update derives a different
// name and still creates, hence reusesPriorEntity rather than isUpdate.
Unwind unwind = new Unwind();
+ r.getAttributes().remove(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
try {
// Built before anything is created, so a configuration that fails validation creates nothing.
NotificationConfiguration notifications = notificationConfiguration(props, ctx);
+ String ownershipControlsXml = ownershipControlsXml(props, ctx);
+ if (ctx.reusesPriorEntity(bucketName)) {
+ r.getAttributes().put(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR,
+ s3Service.snapshotBucketConfiguration(bucketName));
+ }
if (!ctx.reusesPriorEntity(bucketName)) {
// In us-east-1 CreateBucket also answers for a bucket the account already owns,
// which this resource must never delete.
@@ -113,6 +120,7 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
applyBucketEncryption(bucketName, props, ctx);
applyLifecycleConfiguration(bucketName, props, ctx);
applyBucketTags(bucketName, props, ctx);
+ applyBucketOwnershipControls(bucketName, ownershipControlsXml, ctx);
} catch (RuntimeException failure) {
unwind(r, bucketName, unwind, ctx, failure);
throw failure;
@@ -228,6 +236,40 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
s3Service.putBucketLifecycle(bucketName, lifecycleXml(lifecycle.get("Rules"), ctx), null);
}
+ private String ownershipControlsXml(JsonNode props, ProvisionContext ctx) {
+ JsonNode declaredNode = declared(props, "OwnershipControls");
+ if (declaredNode == null) {
+ return null;
+ }
+ JsonNode controls = ctx.engine().resolveNodeOmittingNoValue(declaredNode);
+ if (controls == null || controls.isMissingNode() || controls.isNull()) {
+ return null;
+ }
+ String path = "#/OwnershipControls";
+ requireObject(controls, path);
+ JsonNode rules = declaredArray(controls, "Rules", path);
+ XmlBuilder xml = new XmlBuilder().start("OwnershipControls", AwsNamespaces.S3);
+ for (int index = 0; rules != null && index < rules.size(); index++) {
+ String rulePath = path + "/Rules/" + index;
+ JsonNode rule = requireObject(rules.get(index), rulePath);
+ String ownership = required(rule, "ObjectOwnership", rulePath);
+ xml.start("Rule");
+ xml.elem("ObjectOwnership", ownership);
+ xml.end("Rule");
+ }
+ String document = xml.end("OwnershipControls").build();
+ S3Service.validateOwnershipControls(document);
+ return document;
+ }
+
+ private void applyBucketOwnershipControls(String bucketName, String ownershipControlsXml,
+ ProvisionContext ctx) {
+ if (ownershipControlsXml != null) {
+ s3Service.putBucketOwnershipControls(bucketName, ownershipControlsXml);
+ } else if (ctx.reusesPriorEntity(bucketName) && ctx.previouslyDeclared("OwnershipControls")) {
+ s3Service.deleteBucketOwnershipControls(bucketName);
+ }
+ }
private void applyBucketTags(String bucketName, JsonNode props, ProvisionContext ctx) {
if (declared(props, "Tags") == null) {
return;
@@ -241,19 +283,14 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
private NotificationConfiguration replacedNotifications;
}
- /**
- * Undoes what a failed provision changed. On a failed update the engine restores the previous
- * resource record and reports it rolled back unless the provisioner records why it could not
- * be, so the bucket itself has to be put back: one this attempt created is deleted, and a
- * notification configuration it replaced is put back. The other properties have no restore;
- * the notification configuration goes ahead of them, so a destination S3 rejects leaves them
- * untouched.
- */
+ /** Restores an in-place bucket update or removes a newly created bucket after a failed provision. */
private void unwind(StackResource r, String bucketName, Unwind unwind, ProvisionContext ctx,
RuntimeException failure) {
try {
if (unwind.created) {
s3Service.deleteBucket(bucketName);
+ } else if (r.getAttributes().containsKey(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR)) {
+ rollbackUpdate(r);
} else if (unwind.replacedNotifications != null) {
// Valid when it was put; its destinations are not checked again on the way back.
s3Service.putBucketNotificationConfiguration(bucketName, unwind.replacedNotifications, true);
@@ -268,6 +305,32 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
}
}
+ @Override
+ public boolean rollbackUpdate(StackResource resource) {
+ if (!BUCKET.equals(resource.getResourceType())) {
+ return false;
+ }
+ String snapshot = resource.getAttributes().get(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
+ if (snapshot == null) {
+ return false;
+ }
+ s3Service.restoreBucketConfiguration(resource.getPhysicalId(), snapshot);
+ resource.getAttributes().remove(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
+ return true;
+ }
+
+ @Override
+ public UpdateCleanupResult completeUpdate(StackResource resource) {
+ return resource.getAttributes().containsKey(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR)
+ ? new UpdateCleanupResult(true, true, null, 0, null)
+ : UpdateCleanupResult.notApplicable();
+ }
+
+ @Override
+ public void clearUpdate(StackResource resource) {
+ resource.getAttributes().remove(CfnRollback.S3_BUCKET_UPDATE_SNAPSHOT_ATTR);
+ }
+
private static boolean sameConfiguration(NotificationConfiguration desired, NotificationConfiguration current) {
return desired.getQueueConfigurations().equals(current.getQueueConfigurations())
&& desired.getTopicConfigurations().equals(current.getTopicConfigurations())
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java
index e343a420cf..0eb988e083 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java
@@ -54,4 +54,18 @@ final class S3AclPublicAccessEvaluator {
return false;
}
}
+
+ static boolean aclGrantsNonOwner(String acl, String ownerId) {
+ if (acl == null || acl.isBlank()) {
+ return false;
+ }
+ try {
+ S3AclPolicy policy = S3AclPolicy.parse(acl);
+ return policy.grants().isEmpty() || policy.grants().stream()
+ .anyMatch(grant -> !grant.grantee().isCanonicalUser(ownerId));
+ } catch (S3AclPolicy.AclParseException e) {
+ LOG.debugv(e, "Failed to parse S3 ACL for ownership enforcement");
+ return true;
+ }
+ }
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
index 98c2a9ed07..b9450d4bfd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.services.s3;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -113,6 +115,8 @@ public class S3Service implements Resettable, ResourceProvider {
private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
private static final String LOG_DELIVERY_GROUP_URI = "http://acs.amazonaws.com/groups/s3/LogDelivery";
private static final String LEGACY_ACCESS_KEY_ID = "test";
+ private static final String S3_XML_SCHEMA_ERROR =
+ "The XML you provided was not well-formed or did not validate against our published schema.";
private static final Set SUPPORTED_SERVER_SIDE_ENCRYPTION_VALUES = Set.of("AES256", "aws:kms", "aws:kms:dsse", "aws:fsx");
private static final String SSE_C_ALGORITHM = "AES256";
private static final int SSE_C_KEY_BYTES = 32;
@@ -644,6 +648,7 @@ public class S3Service implements Resettable, ResourceProvider {
AccountAwareStorageBackend.OwnedEntry checkedBucket = resolveBucketEntry(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
+ rejectUploadAclWhenOwnershipEnforced(checkedBucket.value(), checkedBucket.account(), effectiveOptions);
rejectConflictingServerSideEncryption(
normalizeServerSideEncryption(effectiveOptions.getServerSideEncryption()),
validateSseCustomerKey(effectiveOptions.getSseCustomerAlgorithm(),
@@ -825,6 +830,7 @@ public class S3Service implements Resettable, ResourceProvider {
object.setSseCustomerAlgorithm(sseCustomerKey.algorithm());
object.setSseCustomerKeyMd5(sseCustomerKey.keyMd5());
}
+ rejectUploadAclWhenOwnershipEnforced(bucket, bucketOwnerAccount, effectiveOptions);
String objectAcl = resolveObjectAclXml(bucketOwnerAccount,
effectiveOptions.getAcl(), effectiveOptions.getGrantRead(),
effectiveOptions.getGrantWrite(), effectiveOptions.getGrantFullControl(),
@@ -1134,7 +1140,7 @@ public class S3Service implements Resettable, ResourceProvider {
throw new AwsException("AccessDenied", "Access Denied", 403);
}
if (decision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW
- || canonicalUserObjectAclAllowsRead(bucketName, key, canonicalUserId)) {
+ || canonicalUserObjectAclAllowsRead(bucket, bucketName, key, canonicalUserId)) {
return;
}
throw new AwsException("AccessDenied", "Access Denied", 403);
@@ -1271,6 +1277,9 @@ public class S3Service implements Resettable, ResourceProvider {
}
private boolean publicBucketAclAllowsWrite(Bucket bucket) {
+ if (ownershipIsEnforced(bucket)) {
+ return false;
+ }
return Optional.ofNullable(bucket.getAcl())
.map(S3AclPublicAccessEvaluator::aclAllowsPublicWrite)
.orElse(false);
@@ -1313,7 +1322,8 @@ public class S3Service implements Resettable, ResourceProvider {
return;
}
if (!blockPublicAccess.ignorePublicAcls()) {
- if (key != null && isObjectDataReadAction(action) && publicObjectAclAllowsRead(bucketName, key, versionId)) {
+ if (key != null && isObjectDataReadAction(action)
+ && publicObjectAclAllowsRead(bucket, bucketName, key, versionId)) {
return;
}
if (key == null && "s3:ListBucket".equals(action) && publicBucketAclAllowsRead(bucket)) {
@@ -1530,12 +1540,18 @@ public class S3Service implements Resettable, ResourceProvider {
}
private boolean publicBucketAclAllowsRead(Bucket bucket) {
+ if (ownershipIsEnforced(bucket)) {
+ return false;
+ }
return Optional.ofNullable(bucket.getAcl())
.map(S3AclPublicAccessEvaluator::aclAllowsPublicRead)
.orElse(false);
}
- private boolean publicObjectAclAllowsRead(String bucketName, String key, String versionId) {
+ private boolean publicObjectAclAllowsRead(Bucket bucket, String bucketName, String key, String versionId) {
+ if (ownershipIsEnforced(bucket)) {
+ return false;
+ }
String storeKey = versionId != null ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);
return objectStore.get(storeKey)
.filter(object -> !object.isDeleteMarker())
@@ -1545,8 +1561,8 @@ public class S3Service implements Resettable, ResourceProvider {
}
private boolean canonicalUserObjectAclAllowsRead(
- String bucketName, String key, String canonicalUserId) {
- if (canonicalUserId == null || canonicalUserId.isBlank()) {
+ Bucket bucket, String bucketName, String key, String canonicalUserId) {
+ if (ownershipIsEnforced(bucket) || canonicalUserId == null || canonicalUserId.isBlank()) {
return false;
}
return objectStore.get(objectKey(bucketName, key))
@@ -2504,6 +2520,78 @@ public class S3Service implements Resettable, ResourceProvider {
return bucket.getVersioningStatus();
}
+ /** Captures only the bucket settings CloudFormation can change during an in-place update. */
+ public String snapshotBucketConfiguration(String bucketName) {
+ Bucket bucket = bucketStore.get(bucketName)
+ .orElseThrow(() -> new AwsException("NoSuchBucket",
+ "The specified bucket does not exist.", 404));
+ ObjectNode snapshot = objectMapper.createObjectNode();
+ snapshot.put("bucketName", bucketName);
+ snapshot.put("versioningStatus", bucket.getVersioningStatus());
+ snapshot.put("corsConfiguration", bucket.getCorsConfiguration());
+ snapshot.put("publicAccessBlockConfiguration", bucket.getPublicAccessBlockConfiguration());
+ snapshot.put("publicAccessBlockDeleted", bucket.isPublicAccessBlockDeleted());
+ snapshot.put("encryptionConfiguration", bucket.getEncryptionConfiguration());
+ snapshot.put("lifecycleConfiguration", bucket.getLifecycleConfiguration());
+ snapshot.put("transitionDefaultMinimumObjectSize", bucket.getTransitionDefaultMinimumObjectSize());
+ snapshot.put("ownershipControlsConfiguration", bucket.getOwnershipControlsConfiguration());
+ snapshot.set("tags", objectMapper.valueToTree(bucket.getTags()));
+ snapshot.set("notificationConfiguration", objectMapper.valueToTree(bucket.getNotificationConfiguration()));
+ return snapshot.toString();
+ }
+
+ /** Restores a CloudFormation update snapshot without revalidating notification destinations. */
+ public void restoreBucketConfiguration(String bucketName, String rawSnapshot) {
+ JsonNode snapshot;
+ NotificationConfiguration notifications;
+ Map tags;
+ try {
+ snapshot = objectMapper.readTree(rawSnapshot);
+ if (snapshot == null || !snapshot.isObject() || !bucketName.equals(snapshot.path("bucketName").asText())
+ || !snapshot.has("notificationConfiguration") || !snapshot.path("tags").isObject()) {
+ throw new IllegalArgumentException("Invalid bucket configuration snapshot for " + bucketName);
+ }
+ JsonNode notificationNode = snapshot.get("notificationConfiguration");
+ notifications = notificationNode.isNull() ? null
+ : objectMapper.treeToValue(notificationNode, NotificationConfiguration.class);
+ tags = objectMapper.convertValue(snapshot.get("tags"), new TypeReference