fix(iam): authorize S3 object operations as the actions S3 documents (#5756)

Under IAM enforcement, CreateMultipartUpload, CompleteMultipartUpload, RestoreObject and
SelectObjectContent were never checked against the caller's identity policies. They are POST
requests, the registry had no S3 POST rule, and an action no rule maps is allowed. A user with no S3
permission could start and complete multipart uploads, restore objects and read them through
Select.

Many other S3 requests were checked as the wrong action:
- ListParts and AbortMultipartUpload as s3:GetObject and s3:DeleteObject.
- Object retention and legal hold as s3:GetObject and s3:PutObject, so a user allowed only to write
  objects could set a retention period or a legal hold.
- Object annotations as the plain object actions.
- A request naming a versionId as the current-version action. A deny on s3:DeleteObjectVersion, the
  usual guard against permanent deletes, did not stop one, and reading a version needed s3:GetObject
  rather than s3:GetObjectVersion.
- Analytics, inventory and Intelligent-Tiering configurations as s3:ListBucket, s3:CreateBucket or
  s3:DeleteBucket.
- DeleteBucketTagging as s3:DeleteBucketTagging, which is not an IAM action. A policy naming it
  granted the call, and one granting s3:PutBucketTagging, the action AWS checks, was refused.
- A request naming two sub-resources as the first one the registry looked for. The controller runs
  a different one: GET ?acl&tagging returns the tags while needing only s3:GetObjectAcl.

The object sub-resources are now resolved per method, in the order S3Controller dispatches them. A
versionId selects the version action AWS checks for a read, head, delete, ACL or annotation
request, and for Select, which S3Controller runs on the version named; the bucket configurations
follow the controller's bucket chains. Tagging keeps the tagging actions: the tagging operations
still act on the current version whatever versionId names, so a version tagging action would
authorize one version and let the request change another.

The actions come from the S3 user guide's "Required permissions for S3 API operations" and
multipart permissions tables, the API reference and the Service Reference:
- s3:PutObject for creating and completing an upload;
- s3:RestoreObject, and s3:GetObject for Select;
- s3:AbortMultipartUpload and s3:ListMultipartUploadParts;
- the retention, legal-hold, version and configuration actions;
- s3:PutBucketTagging for DeleteBucketTagging, and each configuration's Put action for its delete.

A write carrying If-Match already needed s3:GetObject as well. The conditional-writes guide lists
PutObject, CopyObject and CompleteMultipartUpload as the operations that take the header, so now
that completing an upload is checked as s3:PutObject it gets that check too, while
CreateMultipartUpload and UploadPart, which ignore the header, no longer do.

A conditional delete with an If-Match ETag already needed s3:GetObject. A delete naming a version is
now s3:DeleteObjectVersion, so that check covers it too, still as s3:GetObject: the
conditional-deletes guide evaluates the condition against the current version only.

Condition keys, per the Service Reference:
- s3:versionid is given to the version actions.
- s3:ExistingObjectTag is given to the version actions and the annotation actions, read from the
  version the request names.
- DeleteBucketTagging, checked as s3:PutBucketTagging, keeps the bucket's tags in its context.

CloudTrail denials name the version actions' operations, and give no name to a POST operation
rather than a wrong one.

The actions an operation needs besides its own, S3 behaviour behind these checks and S3's own
bucket-policy check follow separately (#5716).

Refs #5716
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-15 22:14:39 -05:00
1 parent c23641457a
commit 21184df828
11 files changed
+967 -51

No files matched your search

@@ -273,6 +273,31 @@ class IamConditionContextResolverTest {
assertFalse(conditions.containsKey("s3:RequestObjectTagKeys"));
}
@Test
void versionActionsCarryTheVersionTheyName() {
ContainerRequestContext request = s3Request("/bucket/object", "");
request.getUriInfo().getQueryParameters().putSingle("versionId", "v1");
when(s3Service.getObjectTagging("bucket", "object", "v1")).thenReturn(Map.of("env", "a"));
Map<String, List<String>> read = resolver.resolve("s3", "s3:GetObjectVersion", request);
assertEquals(List.of("v1"), read.get("s3:versionid"));
assertEquals(List.of("a"), read.get("s3:ExistingObjectTag/env"));
// DeleteObjectVersion carries the id but, as DeleteObject, not the object's tags.
assertEquals(Map.of("s3:versionid", List.of("v1")),
resolver.resolve("s3", "s3:DeleteObjectVersion", request));
// A base action never carries it.
assertFalse(resolver.resolve("s3", "s3:GetObject", request).containsKey("s3:versionid"));
}
@Test
void annotationActionsCarryTheObjectsTags() {
when(s3Service.getObjectTagging("bucket", "object", null)).thenReturn(Map.of("env", "a"));
for (String action : List.of("s3:GetObjectAnnotation", "s3:ListObjectAnnotations",
"s3:PutObjectAnnotation", "s3:DeleteObjectAnnotation")) {
assertEquals(List.of("a"), resolver.resolve("s3", action, s3Request("/bucket/object", ""))
.get("s3:ExistingObjectTag/env"), action);
}
}
@Test
void resolvesDynamoDbLeadingKeysForGetItem() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
@@ -458,11 +483,16 @@ class IamConditionContextResolverTest {
void bucketActionsResolveResourceTagsFromTheBucketsCurrentTags() {
when(s3Service.getBucketTagging("my-bucket")).thenReturn(Map.of("Owner", "alice"));
for (String action : List.of("s3:GetBucketTagging", "s3:DeleteBucketTagging", "s3:DeleteBucket")) {
for (String action : List.of("s3:GetBucketTagging", "s3:DeleteBucket")) {
Map<String, List<String>> conditions =
resolver.resolve("s3", action, s3Request("/my-bucket", ""));
assertEquals(List.of("alice"), conditions.get("aws:ResourceTag/Owner"), action);
}
// DeleteBucketTagging, which AWS checks as s3:PutBucketTagging.
ContainerRequestContext deleteTagging = s3Request("/my-bucket", "");
when(deleteTagging.getMethod()).thenReturn("DELETE");
assertEquals(List.of("alice"), resolver.resolve("s3", "s3:PutBucketTagging", deleteTagging)
.get("aws:ResourceTag/Owner"));
}
@Test
@@ -73,6 +73,28 @@ class IamEnforcementFilterUnitTest {
IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectTagging", "DELETE"));
}
@Test
void versionActions_emitAsTheOperationTheyCheck() {
assertEquals("GetObject",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersion", "GET"));
assertEquals("HeadObject",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersion", "HEAD"));
assertEquals("DeleteObject",
IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectVersion", "DELETE"));
assertEquals("GetObjectAcl",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersionAcl", "GET"));
assertEquals("PutObjectAcl",
IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectVersionAcl", "PUT"));
}
@Test
void postOperations_returnNullRatherThanTheWrongName() {
// CreateMultipartUpload and CompleteMultipartUpload are checked as s3:PutObject, and
// SelectObjectContent as s3:GetObject; neither name is the operation that ran.
assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:PutObject", "POST"));
assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:GetObject", "POST"));
}
@Test
void unknownAction_returnsNull() {
assertNull(IamEnforcementFilter.mapS3ActionToEventName("s3:GetBucketAcl", "GET"));
@@ -18,6 +18,7 @@ import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -362,6 +363,106 @@ class IamActionRegistryTest {
registry.resolve("s3", mockCtx("PUT", "/bucket/key.txt", accelerate, null, "")));
}
@Test
void s3PostOperationsResolveToTheActionsAwsChecks() {
assertEquals("s3:PutObject", s3Action("POST", "/bucket/key", "uploads"));
assertEquals("s3:PutObject", s3Action("POST", "/bucket/key", "uploadId=u1"));
assertEquals("s3:RestoreObject", s3Action("POST", "/bucket/key", "restore"));
assertEquals("s3:GetObject", s3Action("POST", "/bucket/key", "select", "select-type=2"));
// No bucket-level multipart POST is checked: S3VirtualHostFilter moves a virtual-hosted
// upload's bucket into the path before IAM sees it, so the upload reaches the object rules.
assertNull(s3Action("POST", "/key", "uploads"));
assertNull(s3Action("POST", "/key", "uploadId=u1"));
// DeleteObjects and a browser-form PostObject are checked per key in S3Controller.
assertNull(s3Action("POST", "/bucket", "delete"));
assertNull(s3Action("POST", "/bucket"));
}
@Test
void s3MultipartUploadOperationsResolveToTheirOwnActions() {
assertEquals("s3:ListMultipartUploadParts", s3Action("GET", "/bucket/key", "uploadId=u1"));
assertEquals("s3:AbortMultipartUpload", s3Action("DELETE", "/bucket/key", "uploadId=u1"));
assertEquals("s3:PutObject", s3Action("PUT", "/bucket/key", "uploadId=u1", "partNumber=1"));
assertEquals("s3:ListBucketMultipartUploads", s3Action("GET", "/bucket", "uploads"));
}
@Test
void s3ObjectLockAndAnnotationSubresourcesResolveToTheirOwnActions() {
assertEquals("s3:GetObjectRetention", s3Action("GET", "/bucket/key", "retention"));
assertEquals("s3:PutObjectRetention", s3Action("PUT", "/bucket/key", "retention"));
assertEquals("s3:GetObjectLegalHold", s3Action("GET", "/bucket/key", "legal-hold"));
assertEquals("s3:PutObjectLegalHold", s3Action("PUT", "/bucket/key", "legal-hold"));
assertEquals("s3:GetObjectAnnotation", s3Action("GET", "/bucket/key", "annotation", "annotationName=n"));
assertEquals("s3:ListObjectAnnotations", s3Action("GET", "/bucket/key", "annotation"));
assertEquals("s3:ListObjectAnnotations", s3Action("GET", "/bucket/key", "annotation", "annotationName="));
assertEquals("s3:GetObjectAnnotation", s3Action("HEAD", "/bucket/key", "annotation", "annotationName=n"));
assertEquals("s3:PutObjectAnnotation", s3Action("PUT", "/bucket/key", "annotation"));
assertEquals("s3:DeleteObjectAnnotation", s3Action("DELETE", "/bucket/key", "annotation"));
}
@Test
void s3ObjectSubresourcesFollowTheOrderTheControllerDispatchesThem() {
assertEquals("s3:GetObjectTagging", s3Action("GET", "/bucket/key", "acl", "tagging"));
assertEquals("s3:PutObjectTagging", s3Action("PUT", "/bucket/key", "acl", "tagging"));
assertEquals("s3:ListMultipartUploadParts", s3Action("GET", "/bucket/key", "acl", "uploadId=u1"));
assertEquals("s3:GetObjectRetention", s3Action("GET", "/bucket/key", "acl", "retention"));
assertEquals("s3:DeleteObjectTagging", s3Action("DELETE", "/bucket/key", "acl", "tagging"));
assertEquals("s3:DeleteObjectAnnotation", s3Action("DELETE", "/bucket/key", "annotation", "uploadId=u1"));
assertEquals("s3:PutObject", s3Action("POST", "/bucket/key", "uploads", "restore"));
assertEquals("s3:RestoreObject", s3Action("POST", "/bucket/key", "restore", "uploadId=u1"));
assertEquals("s3:GetObject", s3Action("POST", "/bucket/key", "select", "uploadId=u1"));
}
@Test
void s3VersionedObjectRequestsResolveToTheVersionActions() {
assertEquals("s3:GetObjectVersion", s3Action("GET", "/bucket/key", "versionId=v1"));
assertEquals("s3:GetObjectVersion", s3Action("HEAD", "/bucket/key", "versionId=v1"));
assertEquals("s3:DeleteObjectVersion", s3Action("DELETE", "/bucket/key", "versionId=v1"));
assertEquals("s3:GetObjectVersionAcl", s3Action("GET", "/bucket/key", "acl", "versionId=v1"));
assertEquals("s3:PutObjectVersionAcl", s3Action("PUT", "/bucket/key", "acl", "versionId=v1"));
// Tagging keeps its own actions: the tagging operations act on the current version.
assertEquals("s3:GetObjectTagging", s3Action("GET", "/bucket/key", "tagging", "versionId=v1"));
assertEquals("s3:PutObjectTagging", s3Action("PUT", "/bucket/key", "tagging", "versionId=v1"));
assertEquals("s3:DeleteObjectTagging", s3Action("DELETE", "/bucket/key", "tagging", "versionId=v1"));
assertEquals("s3:GetObjectVersionAnnotation",
s3Action("GET", "/bucket/key", "annotation", "annotationName=n", "versionId=v1"));
assertEquals("s3:GetObjectVersionAnnotation",
s3Action("HEAD", "/bucket/key", "annotation", "annotationName=n", "versionId=v1"));
assertEquals("s3:ListObjectVersionAnnotations",
s3Action("GET", "/bucket/key", "annotation", "versionId=v1"));
assertEquals("s3:PutObjectVersionAnnotation",
s3Action("PUT", "/bucket/key", "annotation", "annotationName=n", "versionId=v1"));
assertEquals("s3:DeleteObjectVersionAnnotation",
s3Action("DELETE", "/bucket/key", "annotation", "annotationName=n", "versionId=v1"));
// GetObjectAttributes of a version is checked as the read of that version.
assertEquals("s3:GetObjectVersion", s3Action("GET", "/bucket/key", "attributes", "versionId=v1"));
// S3Controller selects from the version a versionId names.
assertEquals("s3:GetObjectVersion", s3Action("POST", "/bucket/key", "select", "versionId=v1"));
// Retention and legal hold have no version action; the upload operations take no version.
assertEquals("s3:GetObjectRetention", s3Action("GET", "/bucket/key", "retention", "versionId=v1"));
assertEquals("s3:PutObjectLegalHold", s3Action("PUT", "/bucket/key", "legal-hold", "versionId=v1"));
assertEquals("s3:RestoreObject", s3Action("POST", "/bucket/key", "restore", "versionId=v1"));
assertEquals("s3:GetObject", s3Action("GET", "/bucket/key"));
}
@Test
void s3BucketConfigurationsResolveToTheirOwnActions() {
for (String config : List.of("analytics", "inventory", "intelligent-tiering")) {
String name = switch (config) {
case "analytics" -> "Analytics";
case "inventory" -> "Inventory";
default -> "IntelligentTiering";
};
assertEquals("s3:Get" + name + "Configuration", s3Action("GET", "/bucket", config, "id=c1"));
assertEquals("s3:Get" + name + "Configuration", s3Action("GET", "/bucket", config));
assertEquals("s3:Put" + name + "Configuration", s3Action("PUT", "/bucket", config, "id=c1"));
// AWS checks removing a configuration as the Put action that sets it.
assertEquals("s3:Put" + name + "Configuration", s3Action("DELETE", "/bucket", config, "id=c1"));
}
// s3:DeleteBucketTagging is not an IAM action; AWS checks DeleteBucketTagging as PutBucketTagging.
assertEquals("s3:PutBucketTagging", s3Action("DELETE", "/bucket", "tagging"));
}
@Test
void s3AccelerateYieldsToSubresourcesDispatchedFirst() {
MultivaluedMap<String, String> withRequestPayment = new MultivaluedHashMap<>();
@@ -474,7 +575,7 @@ class IamActionRegistryTest {
MultivaluedMap<String, String> withTagging = new MultivaluedHashMap<>();
withTagging.add("replication", "");
withTagging.add("tagging", "");
assertEquals("s3:DeleteBucketTagging",
assertEquals("s3:PutBucketTagging",
registry.resolve("s3", mockCtx("DELETE", "/bucket", withTagging, null, "")));
}
@@ -556,6 +657,16 @@ class IamActionRegistryTest {
// -------------------------------------------------------------------------
/** The action of an S3 request whose query names {@code params}, each {@code name} or {@code name=value}. */
private String s3Action(String method, String path, String... params) {
MultivaluedMap<String, String> query = new MultivaluedHashMap<>();
for (String param : params) {
int eq = param.indexOf('=');
query.add(eq < 0 ? param : param.substring(0, eq), eq < 0 ? "" : param.substring(eq + 1));
}
return registry.resolve("s3", mockCtx(method, path, query, null, ""));
}
private static ContainerRequestContext mockCtx(String method, String path,
MultivaluedMap<String, String> queryParams,
MediaType mediaType, String body) {
@@ -0,0 +1,514 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.common.http.TestHTTPResource;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.TestProfile;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.util.List;
import static io.github.hectorvent.floci.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/**
* Each S3 operation is checked as the action AWS documents for it: the multipart upload operations
* and the other POST operations, which no rule mapped, the multipart operations that were checked as
* a plain read or delete, the object-lock operations, the version actions a versionId selects, and
* the bucket configurations. A request naming several sub-resources is checked as the one S3 runs,
* and the version actions carry the version id and the version's tags.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
class S3ObjectOperationsIamEnforcementIntegrationTest {
private static final String ADMIN = "test";
private static final String EXISTING_A = "{\"StringEquals\":{\"s3:ExistingObjectTag/env\":\"a\"}}";
@TestHTTPResource("/")
static URI baseUri;
@RegisterExtension
final PartitionCleanup cleanup = new PartitionCleanup();
@Test
void creatingAMultipartUploadNeedsPutObject() {
Fixture f = new Fixture("create", false);
f.policy(f.allow("s3:GetObject"));
denied(f.user().queryParam("uploads", "").when().post(f.path("a/big")).then(), "s3:PutObject");
f.policy(f.allow("s3:PutObject"));
f.user().queryParam("uploads", "").when().post(f.path("a/big")).then().statusCode(200);
}
@Test
void completingAMultipartUploadNeedsPutObject() {
Fixture f = new Fixture("complete", false);
Upload upload = f.uploadOnePart("a/big");
f.policy(f.allow("s3:GetObject"));
denied(f.complete(upload), "s3:PutObject");
f.policy(f.allow("s3:PutObject"));
f.complete(upload).statusCode(200);
}
@Test
void onlyTheWritesThatTakeIfMatchNeedGetObjectForIt() {
// The user guide lists PutObject, CopyObject and CompleteMultipartUpload as the operations
// that take If-Match. Creating an upload and uploading a part ignore it, so it adds no
// s3:GetObject check to them, while completing the upload with it does.
Fixture f = new Fixture("if-match", false);
f.seed("a/big");
String etag = f.etag("a/big");
f.policy(f.allow("s3:PutObject"));
String uploadId = f.user().header("If-Match", etag).queryParam("uploads", "")
.when().post(f.path("a/big")).then().statusCode(200)
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
cleanup.register(() -> f.admin().queryParam("uploadId", uploadId).when().delete(f.path("a/big")));
String partEtag = f.user().header("If-Match", etag)
.queryParam("uploadId", uploadId).queryParam("partNumber", 1).body("part one")
.when().put(f.path("a/big")).then().statusCode(200).extract().header("ETag");
// A PUT naming an upload but no part number is not UploadPart: S3Controller runs it as a
// PutObject, which compares If-Match.
denied(f.user().header("If-Match", etag).queryParam("uploadId", uploadId).body("replaced")
.when().put(f.path("a/big")).then(), "s3:GetObject");
Upload upload = new Upload("a/big", uploadId, partEtag);
// A POST naming both ?uploads and an uploadId creates an upload, which S3Controller runs first.
String another = f.user().header("If-Match", etag).queryParam("uploads", "").queryParam("uploadId", uploadId)
.when().post(f.path("a/big")).then().statusCode(200)
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
cleanup.register(() -> f.admin().queryParam("uploadId", another).when().delete(f.path("a/big")));
denied(f.complete(upload, etag), "s3:GetObject");
f.policy(f.allow("s3:PutObject", "s3:GetObject"));
f.complete(upload, etag).statusCode(200);
}
@Test
void abortingAMultipartUploadNeedsAbortMultipartUpload() {
Fixture f = new Fixture("abort", false);
Upload upload = f.uploadOnePart("a/big");
f.policy(f.allow("s3:DeleteObject"));
denied(f.user().queryParam("uploadId", upload.id()).when().delete(f.path(upload.key())).then(),
"s3:AbortMultipartUpload");
f.policy(f.allow("s3:AbortMultipartUpload"));
f.user().queryParam("uploadId", upload.id()).when().delete(f.path(upload.key())).then().statusCode(204);
}
@Test
void listingThePartsOfAnUploadNeedsListMultipartUploadParts() {
Fixture f = new Fixture("parts", false);
Upload upload = f.uploadOnePart("a/big");
f.policy(f.allow("s3:GetObject"));
denied(f.user().queryParam("uploadId", upload.id()).when().get(f.path(upload.key())).then(),
"s3:ListMultipartUploadParts");
f.policy(f.allow("s3:ListMultipartUploadParts"));
f.user().queryParam("uploadId", upload.id()).when().get(f.path(upload.key())).then().statusCode(200);
}
@Test
void restoringAnObjectNeedsRestoreObject() {
Fixture f = new Fixture("restore", false);
f.seed("a/archived");
f.policy(f.allow("s3:GetObject", "s3:PutObject"));
denied(f.restore("a/archived"), "s3:RestoreObject");
f.policy(f.allow("s3:RestoreObject"));
f.restore("a/archived").statusCode(202);
}
@Test
void selectingFromAnObjectNeedsGetObject() {
Fixture f = new Fixture("select", false);
f.seed("a/rows.csv");
f.policy(f.allow("s3:PutObject"));
denied(f.select("a/rows.csv"), "s3:GetObject");
f.policy(f.allow("s3:GetObject"));
f.select("a/rows.csv").statusCode(200);
}
@Test
void selectingFromAVersionNeedsGetObjectVersion() {
// S3Controller selects from the version named, so it is checked as reading that version.
Fixture f = new Fixture("select-version", true);
String versionId = f.seedVersion("a/rows.csv");
f.policy(f.allow("s3:GetObject"));
denied(f.select("a/rows.csv", versionId), "s3:GetObjectVersion");
f.policy(f.allow("s3:GetObjectVersion"));
f.select("a/rows.csv", versionId).statusCode(200);
}
@Test
void retentionAndLegalHoldNeedTheirOwnActions() {
Fixture f = new Fixture("lock", true);
f.seed("a/locked");
f.policy(f.allow("s3:GetObject", "s3:PutObject"));
denied(f.putRetention("a/locked", "2031-01-01T00:00:00Z"), "s3:PutObjectRetention");
denied(f.user().queryParam("retention", "").when().get(f.path("a/locked")).then(),
"s3:GetObjectRetention");
denied(f.user().queryParam("legal-hold", "").when().get(f.path("a/locked")).then(),
"s3:GetObjectLegalHold");
denied(f.user().queryParam("legal-hold", "")
.body("<LegalHold><Status>OFF</Status></LegalHold>")
.when().put(f.path("a/locked")).then(), "s3:PutObjectLegalHold");
f.policy(f.allow("s3:PutObjectRetention", "s3:GetObjectRetention"));
f.putRetention("a/locked", "2031-01-01T00:00:00Z").statusCode(200);
f.user().queryParam("retention", "").when().get(f.path("a/locked")).then().statusCode(200);
}
@Test
void aRequestNamingTwoSubresourcesIsCheckedAsTheOneThatRuns() {
// S3 serves ?tagging before ?acl, so this request returns the object's tags.
Fixture f = new Fixture("order", false);
f.seed("a/tagged");
f.policy(f.allow("s3:GetObjectAcl"));
denied(f.user().queryParam("acl", "").queryParam("tagging", "").when().get(f.path("a/tagged")).then(),
"s3:GetObjectTagging");
f.policy(f.allow("s3:GetObjectTagging"));
f.user().queryParam("acl", "").queryParam("tagging", "").when().get(f.path("a/tagged")).then()
.statusCode(200)
.body(containsString("<Tagging"));
}
@Test
void readingAVersionNeedsGetObjectVersion() {
// The API reference: with a versionId, s3:GetObjectVersion is needed and s3:GetObject is not.
Fixture f = new Fixture("version-read", true);
String versionId = f.seedVersion("a/doc");
f.policy(f.allow("s3:GetObject"));
denied(f.user().queryParam("versionId", versionId).when().get(f.path("a/doc")).then(),
"s3:GetObjectVersion");
f.user().when().get(f.path("a/doc")).then().statusCode(200);
f.policy(f.allow("s3:GetObjectVersion"));
f.user().queryParam("versionId", versionId).when().get(f.path("a/doc")).then().statusCode(200);
}
@Test
void aDenyOnDeleteObjectVersionStopsAPermanentDelete() {
Fixture f = new Fixture("version-delete", true);
String versionId = f.seedVersion("a/kept");
f.policy(f.allow("s3:*") + ",{\"Effect\":\"Deny\",\"Action\":\"s3:DeleteObjectVersion\","
+ "\"Resource\":\"arn:aws:s3:::" + f.bucket + "/*\"}");
denied(f.user().queryParam("versionId", versionId).when().delete(f.path("a/kept")).then(),
"s3:DeleteObjectVersion");
// A plain delete only adds a delete marker, which s3:DeleteObject allows.
f.user().when().delete(f.path("a/kept")).then().statusCode(204);
}
@Test
void aConditionalDeleteOfAVersionAlsoNeedsGetObject() {
// The conditional-deletes guide: an ETag condition needs s3:GetObject beside the delete, and
// is evaluated against the current version only, so the read is of that one.
Fixture f = new Fixture("version-cas", true);
String versionId = f.seedVersion("a/doc");
String etag = f.etag("a/doc");
f.policy(f.allow("s3:DeleteObjectVersion"));
denied(f.user().header("If-Match", etag).queryParam("versionId", versionId)
.when().delete(f.path("a/doc")).then(), "s3:GetObject");
f.user().header("If-Match", "*").queryParam("versionId", versionId)
.when().delete(f.path("a/doc")).then().statusCode(204);
String next = f.seedVersion("a/doc");
f.policy(f.allow("s3:DeleteObjectVersion", "s3:GetObject"));
f.user().header("If-Match", f.etag("a/doc")).queryParam("versionId", next)
.when().delete(f.path("a/doc")).then().statusCode(204);
}
@Test
void theTagsOfAVersionAreCheckedAsTheTaggingActions() {
// The tagging operations act on the current version whatever versionId names, so a version
// tagging action alone must not let a caller read or change the current version's tags.
Fixture f = new Fixture("version-tags", true);
String versionId = f.seedVersion("a/tagged");
f.policy(f.allow("s3:GetObjectVersionTagging", "s3:PutObjectVersionTagging"));
denied(f.user().queryParam("tagging", "").queryParam("versionId", versionId)
.when().get(f.path("a/tagged")).then(), "s3:GetObjectTagging");
denied(f.user().queryParam("tagging", "").queryParam("versionId", versionId)
.body("<Tagging><TagSet/></Tagging>").when().put(f.path("a/tagged")).then(),
"s3:PutObjectTagging");
f.policy(f.allow("s3:GetObjectTagging"));
f.user().queryParam("tagging", "").queryParam("versionId", versionId)
.when().get(f.path("a/tagged")).then().statusCode(200);
}
@Test
void aVersionConditionMatchesTheVersionNamed() {
Fixture f = new Fixture("version-id", true);
String allowed = f.seedVersion("a/doc");
String other = f.seedVersion("a/doc");
f.policy(f.allowWhen("{\"StringEquals\":{\"s3:versionid\":\"" + allowed + "\"}}",
"s3:GetObjectVersion"));
f.user().queryParam("versionId", allowed).when().get(f.path("a/doc")).then().statusCode(200);
denied(f.user().queryParam("versionId", other).when().get(f.path("a/doc")).then(), "s3:GetObjectVersion");
}
@Test
void theAnnotationsOfAVersionNeedTheVersionAnnotationActions() {
Fixture f = new Fixture("version-annotation", true);
String versionId = f.seedVersion("a/doc");
f.admin().queryParam("annotation", "").queryParam("annotationName", "labels")
.queryParam("versionId", versionId).body("reviewed")
.when().put(f.path("a/doc")).then().statusCode(200);
f.policy(f.allow("s3:GetObjectAnnotation", "s3:ListObjectAnnotations", "s3:PutObjectAnnotation",
"s3:DeleteObjectAnnotation"));
denied(f.annotation(versionId).when().get(f.path("a/doc")).then(), "s3:GetObjectVersionAnnotation");
denied(f.user().queryParam("annotation", "").queryParam("versionId", versionId)
.when().get(f.path("a/doc")).then(), "s3:ListObjectVersionAnnotations");
denied(f.annotation(versionId).body("changed").when().put(f.path("a/doc")).then(),
"s3:PutObjectVersionAnnotation");
denied(f.annotation(versionId).when().delete(f.path("a/doc")).then(), "s3:DeleteObjectVersionAnnotation");
f.policy(f.allow("s3:GetObjectVersionAnnotation", "s3:DeleteObjectVersionAnnotation"));
f.annotation(versionId).when().get(f.path("a/doc")).then().statusCode(200);
f.annotation(versionId).when().delete(f.path("a/doc")).then().statusCode(204);
}
@Test
void anAnnotationIsAuthorizedAgainstTheObjectsTags() {
Fixture f = new Fixture("annotation-tags", false);
f.seed("a/ours");
f.admin().header("x-amz-tagging", "env=b").body("theirs").when().put(f.path("a/theirs"))
.then().statusCode(200);
for (String key : List.of("a/ours", "a/theirs")) {
f.admin().queryParam("annotation", "").queryParam("annotationName", "labels").body("x")
.when().put(f.path(key)).then().statusCode(200);
}
f.policy(f.allowWhen(EXISTING_A, "s3:GetObjectAnnotation"));
f.annotation(null).when().get(f.path("a/ours")).then().statusCode(200);
denied(f.annotation(null).when().get(f.path("a/theirs")).then(), "s3:GetObjectAnnotation");
}
@Test
void bucketConfigurationsAndTagRemovalUseTheActionsAwsChecks() {
Fixture f = new Fixture("bucket-config", false);
f.policy(f.allowOnBucket("s3:ListBucket", "s3:CreateBucket", "s3:DeleteBucket"));
denied(f.user().queryParam("analytics", "").queryParam("id", "a1").when().get("/" + f.bucket).then(),
"s3:GetAnalyticsConfiguration");
denied(f.user().queryParam("inventory", "").when().get("/" + f.bucket).then(),
"s3:GetInventoryConfiguration");
denied(f.user().queryParam("intelligent-tiering", "").queryParam("id", "t1")
.when().delete("/" + f.bucket).then(), "s3:PutIntelligentTieringConfiguration");
// s3:DeleteBucketTagging is no IAM action: AWS checks DeleteBucketTagging as s3:PutBucketTagging.
f.policy(f.allowOnBucket("s3:DeleteBucketTagging"));
denied(f.user().queryParam("tagging", "").when().delete("/" + f.bucket).then(), "s3:PutBucketTagging");
f.policy(f.allowOnBucket("s3:PutBucketTagging"));
f.user().queryParam("tagging", "").when().delete("/" + f.bucket).then().statusCode(204);
}
private static void denied(ValidatableResponse response, String action) {
response.statusCode(403)
.body(containsString("AccessDenied"))
.body(containsString(action));
}
private static String retention(String until) {
return """
<Retention xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Mode>GOVERNANCE</Mode>
<RetainUntilDate>%s</RetainUntilDate>
</Retention>
""".formatted(until);
}
private record Upload(String key, String id, String partEtag) {}
/** One bucket seeded as the admin, and one IAM user whose only policy each test replaces. */
private final class Fixture {
final String bucket;
final String userName;
final String accessKeyId;
Fixture(String name, boolean objectLock) {
String suffix = Long.toString(System.nanoTime(), 36);
bucket = "s3ops-" + name + "-" + suffix;
userName = "s3ops-" + name + "-" + suffix;
cleanup.register(() -> removeBucket(objectLock));
RequestSpecification create = admin();
if (objectLock) {
create = create.header("x-amz-bucket-object-lock-enabled", "true");
}
create.when().put("/" + bucket).then().statusCode(200);
accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(),
auth(ADMIN, "iam"), userName).accessKeyId();
}
RequestSpecification admin() {
return given().header("Authorization", auth(ADMIN, "s3"));
}
RequestSpecification user() {
return given().header("Authorization", auth(accessKeyId, "s3"));
}
String path(String key) {
return "/" + bucket + "/" + key;
}
String allowOnBucket(String... actions) {
return "{\"Effect\":\"Allow\",\"Action\":[\"" + String.join("\",\"", actions)
+ "\"],\"Resource\":\"arn:aws:s3:::" + bucket + "\"}";
}
String allowWhen(String condition, String... actions) {
String allow = allow(actions);
return allow.substring(0, allow.length() - 1) + ",\"Condition\":" + condition + "}";
}
String allow(String... actions) {
return "{\"Effect\":\"Allow\",\"Action\":[\"" + String.join("\",\"", actions)
+ "\"],\"Resource\":\"arn:aws:s3:::" + bucket + "/*\"}";
}
void policy(String statement) {
given().formParam("Action", "PutUserPolicy").formParam("UserName", userName)
.formParam("PolicyName", "p")
.formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[" + statement + "]}")
.header("Authorization", auth(ADMIN, "iam")).when().post("/").then().statusCode(200);
}
void seed(String key) {
admin().header("x-amz-tagging", "env=a").body("id,name\n1,one\n")
.when().put(path(key)).then().statusCode(200);
}
/** Writes a version of {@code key} as the admin and returns its version id. */
String seedVersion(String key) {
return seedVersion(key, "env=a");
}
String seedVersion(String key, String tagging) {
return admin().header("x-amz-tagging", tagging).body("version")
.when().put(path(key)).then().statusCode(200).extract().header("x-amz-version-id");
}
/** A user request on the annotation "labels", of the version {@code versionId} names when set. */
RequestSpecification annotation(String versionId) {
RequestSpecification request = user().queryParam("annotation", "").queryParam("annotationName", "labels");
return versionId == null ? request : request.queryParam("versionId", versionId);
}
String etag(String key) {
return admin().when().head(path(key)).then().statusCode(200).extract().header("ETag");
}
Upload uploadOnePart(String key) {
String uploadId = admin().queryParam("uploads", "").when().post(path(key))
.then().statusCode(200)
.extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");
cleanup.register(() -> admin().queryParam("uploadId", uploadId).when().delete(path(key)));
String partEtag = admin().queryParam("uploadId", uploadId).queryParam("partNumber", 1)
.body("part one")
.when().put(path(key)).then().statusCode(200).extract().header("ETag");
return new Upload(key, uploadId, partEtag);
}
ValidatableResponse complete(Upload upload) {
return complete(upload, null);
}
/** Completes {@code upload} as the user, with {@code ifMatch} as its If-Match header when set. */
ValidatableResponse complete(Upload upload, String ifMatch) {
RequestSpecification request = user();
if (ifMatch != null) {
request = request.header("If-Match", ifMatch);
}
return request.queryParam("uploadId", upload.id())
.contentType("application/xml")
.body("<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>"
+ upload.partEtag() + "</ETag></Part></CompleteMultipartUpload>")
.when().post(path(upload.key())).then();
}
ValidatableResponse restore(String key) {
return user().queryParam("restore", "").contentType("application/xml")
.body("<RestoreRequest><Days>1</Days></RestoreRequest>")
.when().post(path(key)).then();
}
ValidatableResponse select(String key) {
return select(key, null);
}
ValidatableResponse select(String key, String versionId) {
RequestSpecification request = user();
if (versionId != null) {
request = request.queryParam("versionId", versionId);
}
return request.queryParam("select", "").queryParam("select-type", "2")
.contentType("application/xml")
.body("""
<SelectObjectContentRequest>
<Expression>SELECT * FROM S3Object</Expression>
<ExpressionType>SQL</ExpressionType>
<InputSerialization><CSV><FileHeaderInfo>USE</FileHeaderInfo></CSV></InputSerialization>
<OutputSerialization><CSV/></OutputSerialization>
</SelectObjectContentRequest>
""")
.when().post(path(key)).then();
}
ValidatableResponse putRetention(String key, String until) {
return user().queryParam("retention", "").body(retention(until)).when().put(path(key)).then();
}
/**
* Removes every version and delete marker, bypassing governance retention where a test set
* one, then the bucket. No test sets compliance retention or a legal hold, which nothing
* could remove.
*/
void removeBucket(boolean objectLock) {
if (!objectLock) {
EnforcementFixtures.removeBucket(baseUri.getPort(), auth(ADMIN, "s3"), bucket);
return;
}
XmlPath versions = admin().queryParam("versions", "").when().get("/" + bucket)
.then().statusCode(200).extract().xmlPath();
for (String entry : List.of("Version", "DeleteMarker")) {
List<String> keys = versions.getList("ListVersionsResult." + entry + ".Key", String.class);
List<String> ids = versions.getList("ListVersionsResult." + entry + ".VersionId", String.class);
for (int i = 0; i < keys.size(); i++) {
admin().header("x-amz-bypass-governance-retention", "true")
.queryParam("versionId", ids.get(i))
.when().delete(path(keys.get(i))).then().statusCode(204);
}
}
admin().when().delete("/" + bucket).then().statusCode(204);
}
}
}
@@ -129,10 +129,12 @@ class S3ObjectTagConditionEnforcementIntegrationTest {
// Two versions of one key with different tags. The current version carries the tag the
// policy allows; the one under it does not.
String denied = f.seedVersion("a/rolled", "env=b");
f.seedVersion("a/rolled", "env=a");
String allowed = f.seedVersion("a/rolled", "env=a");
f.policy(allow("s3:GetObject", f.objects(), EXISTING_A));
// A read naming a version is checked as s3:GetObjectVersion, which carries the key too.
f.policy(allow("\"s3:GetObject\",\"s3:GetObjectVersion\"", f.objects(), EXISTING_A));
assertEquals(200, f.get("a/rolled"), "the current version carries the allowed tag");
assertEquals(200, f.getVersion("a/rolled", allowed), "the same version, named by its id");
assertEquals(403, f.getVersion("a/rolled", denied),
"the older version carries a foreign tag, so its own tags decide");
}
@@ -198,6 +198,29 @@ class GeneratedPreSignedUrlAuthEnforcementIntegrationTest {
.then().statusCode(200).body(equalTo("untagged"));
}
@Test
void aGeneratedUrlCannotBeTurnedToAnotherVersion() {
// A generated URL is scoped to its object's own action and signs only its X-Amz-*
// parameters, so a versionId appended to it breaks the signature: it never reaches the
// scope check as a request for a version.
String bucket = "generated-presign-version-" + UUID.randomUUID().toString().substring(0, 8);
given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
given().filter(OWNER).body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")
.when().put("/" + bucket + "?versioning").then().statusCode(200);
String older = given().filter(OWNER).body("older").when().put("/" + bucket + "/object.txt")
.then().statusCode(200).extract().header("x-amz-version-id");
given().filter(OWNER).body("current").when().put("/" + bucket + "/object.txt").then().statusCode(200);
URI uri = URI.create(presignGenerator.generatePresignedUrl(
"http://localhost:" + RestAssured.port, bucket, "object.txt", "GET", 60));
String pathAndQuery = uri.getRawPath() + "?" + uri.getRawQuery();
given().urlEncodingEnabled(false).when().get(pathAndQuery)
.then().statusCode(200).body(equalTo("current"));
given().urlEncodingEnabled(false).when().get(pathAndQuery + "&versionId=" + older)
.then().statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));
}
@Test
void generatedUrlsKeepLeadingSlashKeysDistinctUnderEnforcedIam() throws Exception {
String bucket = "generated-presign-slash-" + UUID.randomUUID().toString().substring(0, 8);