fix(s3): honour If-Match on DeleteObject and the ETag element on DeleteObjects (#4526)

* fix(s3): honour If-Match on DeleteObject and the ETag element on DeleteObjects

A conditional delete was ignored: DeleteObject with a stale If-Match answered
204 and deleted the object, and a DeleteObjects entry carrying a stale <ETag>
was reported under <Deleted> and removed. S3 treats both as preconditions.

The precondition is evaluated against the current version of the key, as S3
documents, including when versionId addresses an older version. A matching
ETag (or *) proceeds; a mismatch answers 412 PreconditionFailed and leaves the
object in place; a missing key or a current delete marker answers 404 NoSuchKey.
In DeleteObjects each entry is checked on its own and a failure is reported
under <Error> while the rest of the batch proceeds.

The check runs under the bucket monitor that PutObject's conditional write
already holds, so an overwrite cannot land between the check and the delete.

* fix(s3): require s3:GetObject for a conditional delete by ETag

An ETag condition on DeleteObject, or an <ETag> element in DeleteObjects,
tells the caller whether the object still has that ETag, so S3 requires
s3:GetObject alongside s3:DeleteObject for it. The If-Match: * existence
check needs only s3:DeleteObject. DeleteObjects reports a refused entry
under <Error> as AccessDenied and deletes the rest.

* fix(s3): require s3:GetObject for an ETag-conditional delete under IAM

The bucket-policy check added earlier left the IAM identity-policy layer
alone, so an IAM user allowed s3:DeleteObject but not s3:GetObject could
still delete by ETag. IamEnforcementFilter now authorizes that read for a
DeleteObject whose If-Match is an ETag, the way it already does for a
conditional PutObject. If-Match: * still needs only s3:DeleteObject.

* fix(s3): limit the IAM conditional-delete read to DeleteObject

AbortMultipartUpload is also a DELETE on an object key filed under
s3:DeleteObject, and it has no object ETag to compare, so an If-Match on it
must not ask for s3:GetObject. The read is now required only when the DELETE
carries no subresource besides versionId.

* fix(s3): skip the IAM delete read only for routed subresources

Allowing only versionId as a query key let any other parameter bypass the
check, including the x-id=DeleteObject SDKs add and the X-Amz-* parameters of
a presigned URL, while the controller still handled the request as a
conditional DeleteObject. The read is now skipped only for the subresources
S3Controller routes elsewhere: uploadId, tagging and annotation.

* style(s3): import XmlPath in the conditional-write test

* docs(s3): record why a delete marker answers 404 on a conditional delete

The conditional-deletes guide says 412, real S3 answered 404 when measured. The comment keeps the next reader of the guide from flipping it back.
This commit is contained in:
TiM authored and GitHub committed 2026-09-29 11:44:08 -04:00
1 parent 95cbe7de34
commit 18ef1f58e9
8 files changed
+487 -9

No files matched your search

@@ -423,6 +423,33 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
abortIfDenied(ctx, caller, "s3:GetObject", credentialScope, resources,
withoutObjectTags(targetContexts), region, accountId, akid);
}
// A DeleteObject conditioned on an ETag reveals whether the object still has it, and the
// conditional-deletes guide requires s3:GetObject for it; If-Match: * (existence only)
// needs just s3:DeleteObject. The read is checked the way the PutObject case above is.
if ("s3:DeleteObject".equals(action) && isPlainDeleteObject(ctx)
&& isETagCondition(ctx.getHeaderString("If-Match"))) {
abortIfDenied(ctx, caller, "s3:GetObject", credentialScope, resources,
withoutObjectTags(targetContexts), region, accountId, akid);
}
}
// The DELETE subresources S3Controller.deleteObject routes away from DeleteObject (?uploadId= is
// AbortMultipartUpload, which the action registry also files under s3:DeleteObject). Everything
// else, including the x-id and X-Amz-* parameters SDKs and presigned URLs add, is a DeleteObject.
private static final Set<String> NON_DELETE_OBJECT_SUBRESOURCES = Set.of("uploadId", "tagging", "annotation");
private static boolean isPlainDeleteObject(ContainerRequestContext ctx) {
return "DELETE".equalsIgnoreCase(ctx.getMethod())
&& ctx.getUriInfo().getQueryParameters().keySet().stream()
.noneMatch(NON_DELETE_OBJECT_SUBRESOURCES::contains);
}
private static boolean isETagCondition(String ifMatch) {
if (ifMatch == null) {
return false;
}
String value = ifMatch.trim();
return !value.equals("*") && !value.equals("\"*\"");
}
/**
@@ -187,11 +187,18 @@ public final class XmlParser {
return extractAll(xml, elementName).stream().anyMatch(value::equals);
}
/** A key paired with an optional version id, extracted from a {@code Delete} request's {@code <Object>} block. */
public record KeyVersion(String key, String versionId) {}
/**
* A key paired with an optional version id and an optional {@code If-Match} ETag, extracted from a
* {@code Delete} request's {@code <Object>} block.
*/
public record KeyVersion(String key, String versionId, String eTag) {
public KeyVersion(String key, String versionId) {
this(key, versionId, null);
}
}
/**
* Extracts {@code (Key, VersionId)} pairs from an S3 {@code DeleteObjects} request body,
* Extracts {@code (Key, VersionId, ETag)} entries from an S3 {@code DeleteObjects} request body,
* one entry per {@code <Object>} block.
*
* <p>Unlike {@link #extractAll(String, String)}, which flattens every {@code <Key>} across
@@ -199,8 +206,9 @@ public final class XmlParser {
* {@code <Object>} block. This is needed so a batch delete can target the exact version named,
* rather than discarding it and always falling back to "no version specified".
*
* <p>{@code <VersionId>} is optional per the {@code Delete} request schema; an {@code <Object>}
* block that omits it yields an entry with a {@code null} versionId.
* <p>{@code <VersionId>} and {@code <ETag>} are optional per the {@code Delete} request schema; an
* {@code <Object>} block that omits one yields an entry with {@code null} in its place. The ETag is a
* conditional-delete precondition, checked like an {@code If-Match} header on DeleteObject.
*
* <pre>{@code
* List<XmlParser.KeyVersion> entries = XmlParser.extractDeleteObjectEntries(body);
@@ -216,6 +224,7 @@ public final class XmlParser {
boolean inObject = false;
String key = null;
String versionId = null;
String eTag = null;
while (r.hasNext()) {
int event = r.next();
if (event == XMLStreamConstants.START_ELEMENT) {
@@ -224,15 +233,18 @@ public final class XmlParser {
inObject = true;
key = null;
versionId = null;
eTag = null;
} else if (inObject && "Key".equals(local)) {
key = r.getElementText();
} else if (inObject && "VersionId".equals(local)) {
versionId = r.getElementText();
} else if (inObject && "ETag".equals(local)) {
eTag = r.getElementText();
}
} else if (event == XMLStreamConstants.END_ELEMENT
&& inObject && "Object".equals(r.getLocalName())) {
if (key != null) {
result.add(new KeyVersion(key, versionId));
result.add(new KeyVersion(key, versionId, eTag));
}
inObject = false;
}
@@ -1347,11 +1347,13 @@ public class S3Controller {
}
boolean bypass = "true".equalsIgnoreCase(
httpHeaders.getHeaderString("x-amz-bypass-governance-retention"));
String ifMatch = httpHeaders.getHeaderString("If-Match");
s3Service.authorizeDeleteObject(bucket, key, versionId, authorization);
authorizeDeleteETagRead(bucket, key, ifMatch, authorization);
if (bypass) {
s3Service.authorizeObjectWrite(bucket, key, "s3:BypassGovernanceRetention", authorization);
}
S3Object result = s3Service.deleteObject(bucket, key, versionId, bypass);
S3Object result = s3Service.deleteObject(bucket, key, versionId, bypass, ifMatch);
var resp = Response.noContent();
if (result != null) {
if (result.isDeleteMarker()) {
@@ -1542,6 +1544,7 @@ public class S3Controller {
for (XmlParser.KeyVersion entry : entries) {
try {
s3Service.authorizeDeleteObject(bucket, entry.key(), entry.versionId(), authorization);
authorizeDeleteETagRead(bucket, entry.key(), entry.eTag(), authorization);
if (bypass && s3Service.isGovernanceRetentionActive(
bucket, entry.key(), entry.versionId())) {
s3Service.authorizeObjectWrite(bucket, entry.key(),
@@ -1591,6 +1594,20 @@ public class S3Controller {
return Response.ok(builder.build()).type(MediaType.APPLICATION_XML).build();
}
// A conditional delete against an ETag reveals whether the object still has it, so S3 requires
// s3:GetObject as well as s3:DeleteObject. The existence check (If-Match: *) needs only the delete.
private void authorizeDeleteETagRead(String bucket, String key, String ifMatch,
S3Service.RequestAuthorization authorization) {
if (ifMatch == null) {
return;
}
String value = ifMatch.trim();
if (value.equals("*") || value.equals("\"*\"")) {
return;
}
s3Service.authorizeGetObject(bucket, key, null, authorization);
}
private Response handleListParts(String bucket, String key, String uploadId,
Integer maxPartsParam, String partNumberMarkerParam) {
MultipartUpload upload = s3Service.listParts(bucket, key, uploadId);
@@ -1503,18 +1503,50 @@ public class S3Service implements Resettable, ResourceProvider {
}
public S3Object deleteObject(String bucketName, String key, String versionId, boolean bypassGovernance) {
return deleteObject(bucketName, key, versionId, bypassGovernance, null);
}
/**
* Deletes an object, first checking an {@code If-Match} precondition when one is given.
*
* <p>As on S3, the precondition is evaluated against the current version of the key even
* when {@code versionId} addresses an older one: a missing key, or a current delete marker,
* answers {@code NoSuchKey}, and an ETag that does not match answers {@code 412}.
*/
public S3Object deleteObject(String bucketName, String key, String versionId, boolean bypassGovernance,
String ifMatch) {
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
// The bucket monitor serializes this against PutObject's annotation cleanup and the
// annotation subresource writes, which hold the same monitor (storeObjectInternal
// already runs under it via storeObject).
// already runs under it via storeObject). The precondition is checked under it too,
// so a concurrent overwrite cannot land between the check and the delete.
synchronized (bucket) {
checkDeletePrecondition(bucketName, key, ifMatch);
return deleteObjectLocked(bucket, bucketName, key, versionId, bypassGovernance);
}
}
// A current delete marker answers 404 NoSuchKey, the same as a missing key. That is deliberate:
// the S3 conditional-deletes guide says "If the latest version of the object is a delete marker,
// the object doesn't exist and the DeleteObject API will fail and return a 412 Precondition
// Failed response", but real S3 (general purpose bucket, ap-southeast-2, measured 2026-09-07)
// answered 404 NoSuchKey for If-Match: * over a current delete marker. Follow the measurement.
private void checkDeletePrecondition(String bucketName, String key, String ifMatch) {
if (ifMatch == null) {
return;
}
S3Object current = objectStore.get(objectKey(bucketName, key)).orElse(null);
if (current == null || current.isDeleteMarker()) {
throw new AwsException("NoSuchKey", "The specified key does not exist.", 404);
}
if (!eTagMatches(ifMatch, current.getETag())) {
throw new S3PreconditionFailedException("If-Match");
}
}
private S3Object deleteObjectLocked(Bucket bucket, String bucketName, String key,
String versionId, boolean bypassGovernance) {
if (bucket.isVersioningEnabled() && versionId == null) {
@@ -2028,7 +2060,8 @@ public class S3Service implements Resettable, ResourceProvider {
List<DeleteError> errors = new ArrayList<>();
for (XmlParser.KeyVersion entry : entries) {
try {
S3Object result = deleteObject(bucketName, entry.key(), entry.versionId(), bypassGovernance);
S3Object result = deleteObject(bucketName, entry.key(), entry.versionId(), bypassGovernance,
entry.eTag());
if (result != null && result.isDeleteMarker()) {
deleted.add(new DeleteResult(entry.key(), entry.versionId(), true, result.getVersionId()));
} else {