fix(iam): check the actions an S3 operation needs besides its own (#5846)

Under IAM enforcement an S3 object operation was checked only as its own
action. A PutObject, CopyObject or CreateMultipartUpload that set tags,
an ACL, a retention period or a legal hold needed only s3:PutObject,
GetObjectAttributes needed only the read, and a retention change or a
delete asking to bypass governance retention needed no
s3:BypassGovernanceRetention. No Object Lock condition key was offered.

Each now also needs the actions the S3 user guide's permissions table
and the API references require besides its own. An object creation
needs the action of each setting it applies: s3:PutObjectTagging,
s3:PutObjectAcl, s3:PutObjectRetention or s3:PutObjectLegalHold. A copy
under the default COPY tagging directive keeps a tagged source's tags,
so it needs s3:PutObjectTagging too, checked where the source is read
against the request's credential, a presigned URL's included, and it
offers no request tag keys from the x-amz-tagging header it ignores.
GetObjectAttributes needs s3:GetObjectAttributes, or
s3:GetObjectVersionAttributes for a version. A PutObjectRetention or
DeleteObject that sends x-amz-bypass-governance-retention needs
s3:BypassGovernanceRetention; an annotation delete does not, as the
user guide says the permission does not apply to annotation operations.

s3:PutObject, s3:PutObjectRetention and s3:PutObjectLegalHold are
offered the Object Lock keys from the request's headers or body, and an
object creation offers its tag and Object Lock keys to each extra action.
A denial names the missing permission, and CloudTrail records the
operation that was refused, PutObjectRetention and GetObjectAttributes
included. Generated presigned URLs refuse all four creation settings,
as they refused tags.

Refs #5716
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-17 10:17:28 -05:00
1 parent 30d8d3ff5c
commit b0777a4020
13 files changed
+880 -97

No files matched your search

@@ -27,6 +27,9 @@ import org.mockito.ArgumentCaptor;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -49,6 +52,8 @@ import static org.mockito.Mockito.when;
class IamConditionContextResolverTest {
private static final Instant LOCK_NOW = Instant.parse("2026-01-01T00:00:00Z");
private final ObjectMapper mapper = new ObjectMapper();
private DynamoDbService dynamoDbService;
private Instance<DynamoDbFacade> dynamoDbFacadeInstance;
@@ -315,6 +320,48 @@ class IamConditionContextResolverTest {
}
}
@Test
void objectLockKeysComeFromTheHeadersOfTheObjectCreated() {
ContainerRequestContext request = s3Request("/bucket/object", "");
when(request.getHeaderString("x-amz-object-lock-mode")).thenReturn("GOVERNANCE");
when(request.getHeaderString("x-amz-object-lock-retain-until-date")).thenReturn("2026-01-11T00:00:00Z");
when(request.getHeaderString("x-amz-object-lock-legal-hold")).thenReturn("ON");
Map<String, List<String>> conditions = resolverAt(LOCK_NOW).resolve("s3", "s3:PutObject", request);
assertEquals(List.of("GOVERNANCE"), conditions.get("s3:object-lock-mode"));
assertEquals(List.of("2026-01-11T00:00:00Z"), conditions.get("s3:object-lock-retain-until-date"));
assertEquals(List.of("10"), conditions.get("s3:object-lock-remaining-retention-days"));
assertEquals(List.of("ON"), conditions.get("s3:object-lock-legal-hold"));
}
@Test
void remainingRetentionDaysCountAPartDayAsAWholeOne() {
assertEquals(List.of("10"), remainingRetentionDays("2026-01-11T00:00:00Z"));
assertEquals(List.of("11"), remainingRetentionDays("2026-01-11T00:00:01Z"));
assertEquals(List.of("1"), remainingRetentionDays("2026-01-01T00:00:01Z"));
assertEquals(List.of("0"), remainingRetentionDays("2025-12-31T00:00:00Z"));
assertNull(remainingRetentionDays("not-a-date"), "a date S3 would not parse offers no count");
}
@Test
void legalHoldStatusComesFromTheBody() {
ContainerRequestContext request = s3Request("/bucket/object", "<LegalHold><Status>OFF</Status></LegalHold>");
assertEquals(Map.of("s3:object-lock-legal-hold", List.of("OFF")),
resolver.resolve("s3", "s3:PutObjectLegalHold", request));
}
private List<String> remainingRetentionDays(String until) {
ContainerRequestContext request = s3Request("/bucket/object",
"<Retention><Mode>GOVERNANCE</Mode><RetainUntilDate>" + until + "</RetainUntilDate></Retention>");
return resolverAt(LOCK_NOW).resolve("s3", "s3:PutObjectRetention", request)
.get("s3:object-lock-remaining-retention-days");
}
@SuppressWarnings("unchecked")
private IamConditionContextResolver resolverAt(Instant now) {
return new IamConditionContextResolver(mock(Instance.class), mock(Instance.class), mock(Instance.class),
mock(Instance.class), requestContext, config, Clock.fixed(now, ZoneOffset.UTC));
}
@Test
void resolvesDynamoDbLeadingKeysForGetItem() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
@@ -115,6 +115,10 @@ class IamEnforcementFilterTest {
}
private IamEnforcementFilter newFilter(CurrentVertxRequest currentVertxRequest) {
return newFilter(currentVertxRequest, mock(CloudTrailService.class));
}
private IamEnforcementFilter newFilter(CurrentVertxRequest currentVertxRequest, CloudTrailService cloudTrail) {
@SuppressWarnings("unchecked")
Instance<ScpProvider> scpProvider =
mock(Instance.class);
@@ -122,7 +126,7 @@ class IamEnforcementFilterTest {
return new IamEnforcementFilter(
config, accountResolver, iamService, evaluator, actionRegistry, arnBuilder,
requestContext, conditionContextResolver,
mock(CloudTrailService.class),
cloudTrail,
currentVertxRequest,
catalog, scpProvider, sessionAccountLookup);
}
@@ -948,6 +952,45 @@ class IamEnforcementFilterTest {
eq("s3:GetObject"), eq("arn:aws:s3:::bucket//key"), any());
}
@Test
void aScopedPresignedPutCannotApplyASettingItsUrlDoesNotGrant() {
// A generated URL's session policy grants only its own action, and the scope guard refuses
// the extra actions of an object creation on its own: the policies here allow everything,
// so only the guard can deny the legal hold.
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
CurrentVertxRequest currentVertxRequest = mock(CurrentVertxRequest.class);
RoutingContext routingContext = mock(RoutingContext.class);
HttpServerRequest httpRequest = mock(HttpServerRequest.class);
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
when(containerRequest.getMethod()).thenReturn("PUT");
String auth = "AWS4-HMAC-SHA256 Credential=ASIASCOPE/20260927/us-east-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc";
requestContext.setAccountId("000000000000");
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(containerRequest.getHeaderString("x-amz-object-lock-legal-hold")).thenReturn("ON");
when(accountResolver.extractAccessKeyId(auth)).thenReturn("ASIASCOPE");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
when(iamService.resolveCallerContext(eq("ASIASCOPE"), any()))
.thenReturn(CallerContext.of(List.of("{\"Version\":\"2012-10-17\",\"Statement\":[]}")));
when(iamService.presignedScope("ASIASCOPE"))
.thenReturn(Optional.of(new IamService.PresignedScope(
"s3:PutObject", "arn:aws:s3:::bucket/key")));
when(currentVertxRequest.getCurrent()).thenReturn(routingContext);
when(routingContext.request()).thenReturn(httpRequest);
when(httpRequest.path()).thenReturn("/bucket/key");
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), any(), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
newFilter(currentVertxRequest).filter(containerRequest);
ArgumentCaptor<Response> denied = ArgumentCaptor.captor();
verify(containerRequest).abortWith(denied.capture());
assertEquals(403, denied.getValue().getStatus());
assertTrue(entityString(denied.getValue()).contains("s3:PutObjectLegalHold"));
}
private void assertScopedPresignedRequestWithoutHttpRequestIsDenied(RoutingContext routingContext) {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
CurrentVertxRequest currentVertxRequest = mock(CurrentVertxRequest.class);
@@ -1968,6 +2011,66 @@ class IamEnforcementFilterTest {
return entity.toString();
}
@Test
void aDeniedExtraActionNamesThePermissionAndRecordsTheOperation() {
// A PutObject placing a legal hold also needs s3:PutObjectLegalHold. The denial names that
// permission, while CloudTrail records PutObject, the operation that was refused.
assertEquals("PutObject", deniedExtraActionEvent("PUT", new MultivaluedHashMap<>(),
"x-amz-object-lock-legal-hold", "ON", "s3:PutObject", "s3:PutObjectLegalHold"));
// A retention change asking for the bypass is recorded as the retention change.
MultivaluedHashMap<String, String> retention = new MultivaluedHashMap<>();
retention.putSingle("retention", "");
assertEquals("PutObjectRetention", deniedExtraActionEvent("PUT", retention,
"x-amz-bypass-governance-retention", "true", "s3:PutObjectRetention",
"s3:BypassGovernanceRetention"));
// GetObjectAttributes is checked as the read and as its own action; denied the second, it is
// recorded as GetObjectAttributes, not as the read.
MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>();
attributes.putSingle("attributes", "");
assertEquals("GetObjectAttributes", deniedExtraActionEvent("GET", attributes,
"x-amz-object-attributes", "ETag", "s3:GetObject", "s3:GetObjectAttributes"));
}
/**
* Runs an S3 request whose own action is allowed and whose extra action is denied, asserts the
* denial names the extra action, and returns the event name CloudTrail recorded for it.
*/
private String deniedExtraActionEvent(String method, MultivaluedHashMap<String, String> query, String header,
String headerValue, String allowedAction, String deniedAction) {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getPath()).thenReturn("/bucket/object");
when(uriInfo.getQueryParameters()).thenReturn(query);
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
when(containerRequest.getMethod()).thenReturn(method);
String auth = "AWS4-HMAC-SHA256 Credential=AKIAEXTRA/20260706/us-east-1/s3/aws4_request, "
+ "SignedHeaders=host, Signature=abc";
requestContext.setAccountId("222233334444");
requestContext.setRegion("us-east-1");
when(accountResolver.extractAccessKeyId(auth)).thenReturn("AKIAEXTRA");
when(containerRequest.getHeaderString("Authorization")).thenReturn(auth);
when(containerRequest.getHeaderString(header)).thenReturn(headerValue);
when(actionRegistry.resolve("s3", containerRequest)).thenReturn(allowedAction);
when(iamService.resolveCallerContext(eq("AKIAEXTRA"), any())).thenReturn(CallerContext.of(List.of()));
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
.thenReturn(List.of("arn:aws:s3:::bucket/object"));
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(allowedAction), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
when(evaluator.evaluateResolvedResourcePolicy(any(), any(), any(), eq(deniedAction), any(), any()))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
CloudTrailService cloudTrail = mock(CloudTrailService.class);
newFilter(mock(CurrentVertxRequest.class), cloudTrail).filter(containerRequest);
ArgumentCaptor<Response> denied = ArgumentCaptor.captor();
verify(containerRequest).abortWith(denied.capture());
assertEquals(403, denied.getValue().getStatus());
assertTrue(entityString(denied.getValue()).contains(deniedAction));
ArgumentCaptor<CloudTrailService.S3EventInput> event = ArgumentCaptor.captor();
verify(cloudTrail).emitS3DataEvent(event.capture());
return event.getValue().eventName();
}
@Test
void s3ResourceAccountIsTheBucketOwnerNotTheCallerOnCrossAccountAccess() {
// An S3 bucket ARN carries no account, so aws:ResourceAccount has to come from S3 state.
@@ -93,6 +93,16 @@ class IamEnforcementFilterUnitTest {
IamEnforcementFilter.mapS3ActionToEventName("s3:DeleteObjectVersionTagging", "DELETE"));
}
@Test
void extraActionChecks_emitAsTheOperationTheyRefuse() {
assertEquals("PutObjectRetention",
IamEnforcementFilter.mapS3ActionToEventName("s3:PutObjectRetention", "PUT"));
assertEquals("GetObjectAttributes",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectAttributes", "GET"));
assertEquals("GetObjectAttributes",
IamEnforcementFilter.mapS3ActionToEventName("s3:GetObjectVersionAttributes", "GET"));
}
@Test
void postOperations_returnNullRatherThanTheWrongName() {
// CreateMultipartUpload and CompleteMultipartUpload are checked as s3:PutObject, and
@@ -69,7 +69,7 @@ class IamTagKeysEnforcementIntegrationTest {
@ValueSource(strings = {"Admin", "team"})
void s3ObjectUploadRestrictsAllRequestedKeysWithoutNullGuard(String forbiddenKey) {
String bucket = bucket();
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
String key = scopedUploader();
String path = "/" + bucket + "/object";
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "%54eam=payments")
.body("original").put(path).then().statusCode(200);
@@ -117,7 +117,7 @@ class IamTagKeysEnforcementIntegrationTest {
@ValueSource(strings = {"Admin", "team"})
void s3QueryTagKeysAreCheckedBeforeAnUpload(String forbiddenKey) {
String bucket = bucket();
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
String key = scopedUploader();
String path = "/" + bucket + "/object";
given().header("Authorization", auth(key, "s3")).queryParam("x-amz-tagging", "%54eam=payments")
.body("original").put(path).then().statusCode(200);
@@ -134,7 +134,7 @@ class IamTagKeysEnforcementIntegrationTest {
@Test
void s3TagHeaderTakesPrecedenceOverTheQuery() {
String bucket = bucket();
String key = scopedUser("s3:PutObject", "s3:RequestObjectTagKeys");
String key = scopedUploader();
String path = "/" + bucket + "/object";
given().header("Authorization", auth(key, "s3")).header("x-amz-tagging", "Team=payments")
.queryParam("x-amz-tagging", "Admin=true").body("original").put(path).then().statusCode(200);
@@ -155,7 +155,7 @@ class IamTagKeysEnforcementIntegrationTest {
.put(path).then().statusCode(200).extract().header("ETag");
String key = userWithPolicy("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"},
{"Effect":"Allow","Action":["s3:PutObject","s3:PutObjectTagging"],"Resource":"*"},
{"Effect":"Allow","Action":"s3:GetObject","Resource":"*",
"Condition":{"ForAnyValue:StringEquals":{"s3:RequestObjectTagKeys":["Team"]}}}]}
""");
@@ -165,7 +165,7 @@ class IamTagKeysEnforcementIntegrationTest {
.then().statusCode(200).body(equalTo("original"));
String allowedKey = userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["s3:PutObject","s3:GetObject"],"Resource":"*"}]}
"Action":["s3:PutObject","s3:PutObjectTagging","s3:GetObject"],"Resource":"*"}]}
""");
given().header("Authorization", auth(allowedKey, "s3")).header("x-amz-tagging", "Team=payments")
.header("If-Match", etag).body("allowed").put(path).then().statusCode(200);
@@ -188,6 +188,15 @@ class IamTagKeysEnforcementIntegrationTest {
""".formatted(action, conditionKey));
}
/** A tagged upload needs s3:PutObjectTagging beside s3:PutObject, and both are held to the keys. */
private String scopedUploader() {
return userWithPolicy("""
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
"Action":["s3:PutObject","s3:PutObjectTagging"],"Resource":"*",
"Condition":{"ForAllValues:StringEquals":{"s3:RequestObjectTagKeys":["Team"]}}}]}
""");
}
private String userWithPolicy(String policy) {
String user = "tagkeys-" + UUID.randomUUID();
String accessKey = createUser(cleanup, endpoint.getPort(), auth("test", "iam"), user).accessKeyId();
@@ -25,7 +25,9 @@ import static org.hamcrest.Matchers.not;
* 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.
* and the version actions carry the version id and the version's tags. An operation also needs the
* actions it requires besides its own: an object creation those of the settings it applies,
* GetObjectAttributes its own action beside the read, and a governance bypass its permission.
*/
@QuarkusTest
@TestProfile(IamEnforcementProfile.class)
@@ -178,6 +180,216 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
f.user().queryParam("retention", "").when().get(f.path("a/locked")).then().statusCode(200);
}
@Test
void bypassingGovernanceRetentionNeedsBypassGovernanceRetention() {
Fixture f = new Fixture("bypass", true);
f.seed("a/governed");
f.admin().queryParam("retention", "")
.body(retention("2031-01-01T00:00:00Z"))
.when().put(f.path("a/governed")).then().statusCode(200);
f.policy(f.allow("s3:PutObjectRetention"));
denied(f.putRetention("a/governed", "2030-01-01T00:00:00Z", true), "s3:BypassGovernanceRetention");
f.policy(f.allow("s3:PutObjectRetention", "s3:BypassGovernanceRetention"));
f.putRetention("a/governed", "2030-01-01T00:00:00Z", true).statusCode(200);
}
@Test
void deletingWithTheBypassNeedsBypassGovernanceRetention() {
// The DeleteObject API reference: "To use this header, you must have the
// s3:BypassGovernanceRetention permission", whether or not the request names a version.
Fixture f = new Fixture("delete-bypass", true);
String versionId = f.seedVersion("a/governed");
f.admin().queryParam("retention", "").queryParam("versionId", versionId)
.body(retention("2031-01-01T00:00:00Z"))
.when().put(f.path("a/governed")).then().statusCode(200);
f.policy(f.allow("s3:DeleteObject", "s3:DeleteObjectVersion"));
denied(f.user().header("x-amz-bypass-governance-retention", "true")
.when().delete(f.path("a/governed")).then(), "s3:BypassGovernanceRetention");
denied(f.user().header("x-amz-bypass-governance-retention", "true").queryParam("versionId", versionId)
.when().delete(f.path("a/governed")).then(), "s3:BypassGovernanceRetention");
f.policy(f.allow("s3:DeleteObjectVersion", "s3:BypassGovernanceRetention"));
f.user().header("x-amz-bypass-governance-retention", "true").queryParam("versionId", versionId)
.when().delete(f.path("a/governed")).then().statusCode(204);
}
@Test
void deletingAnAnnotationWithTheBypassHeaderNeedsNoBypassPermission() {
// The user guide: "The BypassGovernanceRetention permission does not apply to annotation
// operations."
Fixture f = new Fixture("annotation-bypass", false);
f.seed("a/doc");
f.admin().queryParam("annotation", "").queryParam("annotationName", "labels").body("x")
.when().put(f.path("a/doc")).then().statusCode(200);
f.policy(f.allow("s3:DeleteObjectAnnotation"));
f.annotation(null).header("x-amz-bypass-governance-retention", "true")
.when().delete(f.path("a/doc")).then().statusCode(204);
}
@Test
void getObjectAttributesNeedsItsOwnActionAndTheRead() {
// The API reference: s3:GetObject and s3:GetObjectAttributes, or for a version
// s3:GetObjectVersion and s3:GetObjectVersionAttributes.
Fixture f = new Fixture("attributes", true);
String versionId = f.seedVersion("a/doc");
f.policy(f.allow("s3:GetObject", "s3:GetObjectVersion"));
denied(f.attributes("a/doc", null), "s3:GetObjectAttributes");
denied(f.attributes("a/doc", versionId), "s3:GetObjectVersionAttributes");
f.policy(f.allow("s3:GetObjectAttributes", "s3:GetObjectVersionAttributes"));
denied(f.attributes("a/doc", null), "s3:GetObject");
denied(f.attributes("a/doc", versionId), "s3:GetObjectVersion");
f.policy(f.allow("s3:GetObject", "s3:GetObjectAttributes"));
f.attributes("a/doc", null).statusCode(200);
f.policy(f.allow("s3:GetObjectVersion", "s3:GetObjectVersionAttributes"));
f.attributes("a/doc", versionId).statusCode(200);
}
@Test
void anObjectCreatedWithTagsOrAnAclNeedsThoseActionsToo() {
// The permissions table: s3:PutObjectTagging and s3:PutObjectAcl are conditionally required
// for PutObject, CopyObject and CreateMultipartUpload.
Fixture f = new Fixture("create-extras", false);
f.seed("a/source");
f.policy(f.allow("s3:PutObject", "s3:GetObject"));
f.user().body("plain").when().put(f.path("a/plain")).then().statusCode(200);
denied(f.user().header("x-amz-tagging", "env=a").body("tagged").when().put(f.path("a/tagged")).then(),
"s3:PutObjectTagging");
denied(f.user().header("x-amz-acl", "bucket-owner-full-control").body("acl")
.when().put(f.path("a/acl")).then(), "s3:PutObjectAcl");
denied(f.user().header("x-amz-grant-read", "id=000000000000").body("grant")
.when().put(f.path("a/grant")).then(), "s3:PutObjectAcl");
denied(f.user().header("x-amz-tagging", "env=a").queryParam("uploads", "")
.when().post(f.path("a/upload")).then(), "s3:PutObjectTagging");
denied(f.user().header("x-amz-acl", "private").queryParam("uploads", "")
.when().post(f.path("a/upload")).then(), "s3:PutObjectAcl");
denied(f.copy().header("x-amz-tagging-directive", "REPLACE").header("x-amz-tagging", "env=a")
.when().put(f.path("a/copy")).then(), "s3:PutObjectTagging");
denied(f.copy().header("x-amz-tagging-directive", "REPLACE").header("x-amz-acl", "private")
.when().put(f.path("a/copy")).then(), "s3:PutObjectAcl");
// Without REPLACE a copy puts the source's tags on the new object, so a tagged source needs
// the tagging action too, and an untagged one does not, whatever tags the request sends.
denied(f.copy().when().put(f.path("a/copy")).then(), "s3:PutObjectTagging");
f.admin().body("untagged").when().put(f.path("a/untagged")).then().statusCode(200);
f.copyOf("a/untagged").header("x-amz-tagging", "env=a").when().put(f.path("a/copy")).then()
.statusCode(200);
f.policy(f.allow("s3:PutObject", "s3:GetObject", "s3:PutObjectTagging", "s3:PutObjectAcl"));
f.user().header("x-amz-tagging", "env=a").body("tagged").when().put(f.path("a/tagged")).then()
.statusCode(200);
f.user().header("x-amz-acl", "bucket-owner-full-control").body("acl").when().put(f.path("a/acl")).then()
.statusCode(200);
f.copy().header("x-amz-tagging-directive", "REPLACE").header("x-amz-tagging", "env=a")
.when().put(f.path("a/copy")).then().statusCode(200);
f.copy().when().put(f.path("a/copied-tags")).then().statusCode(200);
f.admin().queryParam("tagging", "").when().get(f.path("a/copied-tags")).then()
.statusCode(200).body(containsString("<Value>a</Value>"));
}
@Test
void aCopyIsNotAuthorizedByTheTagsItIgnores() {
// Under the default COPY directive a copy ignores x-amz-tagging, so the tags it names cannot
// satisfy a condition on the new object's tags, on s3:PutObject or on an extra action.
Fixture f = new Fixture("copy-ignored-tags", false);
f.admin().body("untagged").when().put(f.path("a/untagged")).then().statusCode(200);
String taggedB = "{\"StringEquals\":{\"s3:RequestObjectTag/env\":\"b\"}}";
f.policy(f.allow("s3:GetObject") + "," + f.allowWhen(taggedB, "s3:PutObject"));
denied(f.copyOf("a/untagged").header("x-amz-tagging", "env=b").when().put(f.path("a/copy")).then(),
"s3:PutObject");
f.policy(f.allow("s3:GetObject", "s3:PutObject") + ","
+ f.allowWhen(taggedB, "s3:PutObjectAcl", "s3:PutObjectTagging"));
denied(f.copyOf("a/untagged").header("x-amz-tagging", "env=b").header("x-amz-acl", "bucket-owner-full-control")
.when().put(f.path("a/copy")).then(), "s3:PutObjectAcl");
f.copyOf("a/untagged").header("x-amz-tagging-directive", "REPLACE").header("x-amz-tagging", "env=b")
.header("x-amz-acl", "bucket-owner-full-control").when().put(f.path("a/copy")).then().statusCode(200);
}
@Test
void aPresignedCopyOfATaggedSourceNeedsTheTaggingActionToo() {
// The source's tags are checked against the presigned URL's credential, as a signed copy's
// are against its Authorization header, and an empty header does not shed that credential.
Fixture f = new Fixture("presigned-copy", false);
f.seed("a/source");
String source = "/" + f.bucket + "/a/source";
f.policy(f.allow("s3:PutObject", "s3:GetObject"));
denied(f.presigned().header("x-amz-copy-source", source)
.when().put(f.presignedPath("a/copy")).then(), "s3:PutObjectTagging");
denied(f.presigned().header("Authorization", "").header("x-amz-copy-source", source)
.when().put(f.presignedPath("a/copy")).then(), "s3:PutObjectTagging");
f.policy(f.allow("s3:PutObject", "s3:GetObject", "s3:PutObjectTagging"));
f.presigned().header("x-amz-copy-source", source)
.when().put(f.presignedPath("a/copy")).then().statusCode(200);
}
@Test
void aCopyFromAMissingSourceIsReportedMissing() {
// A source that is not there has no tags to check, and the copy answers for it.
Fixture f = new Fixture("copy-missing", false);
f.policy(f.allow("s3:PutObject", "s3:GetObject"));
f.copyOf("a/missing").when().put(f.path("a/copy")).then()
.statusCode(404).body(containsString("NoSuchKey"));
}
@Test
void anObjectCreatedWithObjectLockSettingsNeedsTheirActions() {
// The permissions table: s3:PutObjectRetention and s3:PutObjectLegalHold are conditionally
// required for PutObject, CopyObject and CreateMultipartUpload.
Fixture f = new Fixture("create-lock", true);
f.policy(f.allow("s3:PutObject"));
denied(f.user().header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z").body("locked")
.when().put(f.path("a/retained")).then(), "s3:PutObjectRetention");
denied(f.user().header("x-amz-object-lock-legal-hold", "OFF").body("held")
.when().put(f.path("a/held")).then(), "s3:PutObjectLegalHold");
denied(f.user().header("x-amz-object-lock-legal-hold", "OFF").queryParam("uploads", "")
.when().post(f.path("a/upload")).then(), "s3:PutObjectLegalHold");
f.policy(f.allow("s3:PutObject", "s3:PutObjectRetention", "s3:PutObjectLegalHold"));
f.user().header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z").body("locked")
.when().put(f.path("a/retained")).then().statusCode(200);
f.user().header("x-amz-object-lock-legal-hold", "OFF").body("held")
.when().put(f.path("a/held")).then().statusCode(200);
}
@Test
void objectLockConditionKeysLimitWhatARequestMaySet() {
// The keys come from the retention and legal-hold bodies, and from an object creation's
// headers, which reach the extra actions it is checked as.
Fixture f = new Fixture("lock-keys", true);
f.seed("a/locked");
f.policy(f.allow("s3:PutObject", "s3:PutObjectRetention", "s3:PutObjectLegalHold") + ","
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:PutObjectRetention\",\"Resource\":\"arn:aws:s3:::"
+ f.bucket + "/*\",\"Condition\":{\"DateGreaterThan\":"
+ "{\"s3:object-lock-retain-until-date\":\"2035-01-01T00:00:00Z\"}}},"
+ "{\"Effect\":\"Deny\",\"Action\":\"s3:PutObjectLegalHold\",\"Resource\":\"arn:aws:s3:::"
+ f.bucket + "/*\",\"Condition\":{\"StringEquals\":{\"s3:object-lock-legal-hold\":\"ON\"}}}");
denied(f.putRetention("a/locked", "2036-01-01T00:00:00Z"), "s3:PutObjectRetention");
f.putRetention("a/locked", "2031-01-01T00:00:00Z").statusCode(200);
denied(f.legalHold("a/locked", "ON"), "s3:PutObjectLegalHold");
f.legalHold("a/locked", "OFF").statusCode(200);
denied(f.user().header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2036-01-01T00:00:00Z").body("locked")
.when().put(f.path("a/created")).then(), "s3:PutObjectRetention");
f.user().header("x-amz-object-lock-mode", "GOVERNANCE")
.header("x-amz-object-lock-retain-until-date", "2031-01-01T00:00:00Z").body("locked")
.when().put(f.path("a/created")).then().statusCode(200);
}
@Test
void aRequestNamingTwoSubresourcesIsCheckedAsTheOneThatRuns() {
// S3 serves ?tagging before ?acl, so this request returns the object's tags.
@@ -510,7 +722,48 @@ class S3ObjectOperationsIamEnforcementIntegrationTest {
}
ValidatableResponse putRetention(String key, String until) {
return user().queryParam("retention", "").body(retention(until)).when().put(path(key)).then();
return putRetention(key, until, false);
}
ValidatableResponse putRetention(String key, String until, boolean bypass) {
RequestSpecification request = user().queryParam("retention", "").body(retention(until));
if (bypass) {
request = request.header("x-amz-bypass-governance-retention", "true");
}
return request.when().put(path(key)).then();
}
ValidatableResponse legalHold(String key, String status) {
return user().queryParam("legal-hold", "")
.body("<LegalHold><Status>" + status + "</Status></LegalHold>")
.when().put(path(key)).then();
}
ValidatableResponse attributes(String key, String versionId) {
RequestSpecification request = user().queryParam("attributes", "")
.header("x-amz-object-attributes", "ETag");
if (versionId != null) {
request = request.queryParam("versionId", versionId);
}
return request.when().get(path(key)).then();
}
/** A user CopyObject request from the seeded {@code a/source}. */
RequestSpecification copy() {
return copyOf("a/source");
}
RequestSpecification copyOf(String key) {
return user().header("x-amz-copy-source", "/" + bucket + "/" + key);
}
/** A request the user presigns with {@link #presignedPath}, which carries its credential. */
RequestSpecification presigned() {
return given().urlEncodingEnabled(false);
}
String presignedPath(String key) {
return path(key) + "?" + EnforcementFixtures.presignedQuery(accessKeyId, "s3");
}
/**
@@ -221,6 +221,22 @@ class GeneratedPreSignedUrlAuthEnforcementIntegrationTest {
.then().statusCode(403).body("Error.Code", equalTo("SignatureDoesNotMatch"));
}
@Test
void generatedPutUrlCannotSetAnAclWithoutAclPermission() {
String bucket = "generated-presign-acl-" + UUID.randomUUID().toString().substring(0, 8);
given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
URI uri = URI.create(presignGenerator.generatePresignedUrl(
"http://localhost:" + RestAssured.port, bucket, "object.txt", "PUT", 60));
String pathAndQuery = uri.getRawPath() + "?" + uri.getRawQuery();
given().urlEncodingEnabled(false).header("x-amz-acl", "bucket-owner-full-control").body("with acl")
.when().put(pathAndQuery)
.then().statusCode(403).body("Error.Code", equalTo("AccessDenied"));
given().urlEncodingEnabled(false).body("without acl")
.when().put(pathAndQuery).then().statusCode(200);
}
@Test
void generatedUrlsKeepLeadingSlashKeysDistinctUnderEnforcedIam() throws Exception {
String bucket = "generated-presign-slash-" + UUID.randomUUID().toString().substring(0, 8);
@@ -14,11 +14,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
@@ -42,10 +38,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
class S3DeleteObjectsIamEnforcementIntegrationTest {
private static final String ADMIN = "test";
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
@Inject
IamService iamService;
@@ -428,16 +421,7 @@ class S3DeleteObjectsIamEnforcementIntegrationTest {
}
private static String presignedDeletePath(String bucket, String accessKeyId) {
String amzDate = AMZ_DATE.format(Instant.now());
String credential = URLEncoder.encode(
accessKeyId + "/" + amzDate.substring(0, 8) + "/" + REGION + "/s3/aws4_request", StandardCharsets.UTF_8);
return "/" + bucket + "?delete"
+ "&X-Amz-Algorithm=AWS4-HMAC-SHA256"
+ "&X-Amz-Credential=" + credential
+ "&X-Amz-Date=" + amzDate
+ "&X-Amz-Expires=3600"
+ "&X-Amz-SignedHeaders=host"
+ "&X-Amz-Signature=fakesig";
return "/" + bucket + "?delete&" + EnforcementFixtures.presignedQuery(accessKeyId, "s3");
}
private static String bucket(String prefix) {
@@ -7,6 +7,9 @@ import io.restassured.specification.RequestSpecification;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
@@ -34,6 +37,9 @@ import static io.restassured.RestAssured.given;
*/
public final class EnforcementFixtures {
private static final DateTimeFormatter AMZ_DATE =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
private EnforcementFixtures() {
// Utility class, prevent instantiation
}
@@ -171,6 +177,25 @@ public final class EnforcementFixtures {
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
/**
* The {@code X-Amz-*} query parameters of a SigV4 presigned request naming {@code accessKeyId},
* scoped to {@code service} in {@code us-east-1}, to append to a path after {@code ?} or
* {@code &}. They are dated now, so the URL has not expired, and the signature is a placeholder,
* as {@link #auth}'s is.
*/
public static String presignedQuery(String accessKeyId, String service) {
String amzDate = AMZ_DATE.format(Instant.now());
String credential = URLEncoder.encode(
accessKeyId + "/" + amzDate.substring(0, 8) + "/us-east-1/" + service + "/aws4_request",
StandardCharsets.UTF_8);
return "X-Amz-Algorithm=AWS4-HMAC-SHA256"
+ "&X-Amz-Credential=" + credential
+ "&X-Amz-Date=" + amzDate
+ "&X-Amz-Expires=3600"
+ "&X-Amz-SignedHeaders=host"
+ "&X-Amz-Signature=fakesig";
}
/**
* Deletes a managed policy, and first the versions and attachments IAM wants gone before it
* will. Returns quietly when the policy is already absent, so a caller can register the