fix(s3): evaluate IAM policy on presigned URL and presigned POST requests (#3504)

Presigned URL and presigned POST both skipped IAM identity-policy
evaluation. The POST-side check now also runs independent of
S3's enforce-auth flag, matching the presigned-URL path, and now
resolves the account from the parsed credential instead of the
ambient request context set before the multipart body was parsed.

* Fix #3195

Signed-off-by: Matheus Oliveira <matheus.6148@gmail.com>
This commit is contained in:
Matheus Oliveira authored and GitHub committed 2026-09-12 23:21:34 -04:00
1 parent b618fa9033
commit 8a452116bf
6 files changed
+720 -42

No files matched your search

@@ -45,6 +45,12 @@ import java.util.regex.Pattern;
* <p>Evaluates the caller's identity policies, optional session policy, and optional
* permissions boundary. Resource-based policies (S3 bucket policy, Lambda resource
* policy, etc.) are not yet supplied to this filter.
*
* <p>Reads the signing credential from either the {@code Authorization} header or, for a
* presigned URL, the {@code X-Amz-Credential} query parameter - both request shapes get the
* same policy evaluation. A presigned POST form carries its credential in the multipart body,
* which is unavailable at this JAX-RS filter stage; that shape is authorized separately via
* {@link #authorizeAdditionalResource} once {@code S3Controller} has parsed the form fields.
*/
@Provider
@ApplicationScoped
@@ -75,6 +81,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
private final CurrentVertxRequest currentVertxRequest;
private final ResolvedServiceCatalog catalog;
private final Instance<ScpProvider> scpProvider;
private final SessionAccountLookup sessionAccountLookup;
@Inject
public IamEnforcementFilter(EmulatorConfig config,
@@ -88,7 +95,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
CloudTrailService cloudTrailService,
CurrentVertxRequest currentVertxRequest,
ResolvedServiceCatalog catalog,
Instance<ScpProvider> scpProvider) {
Instance<ScpProvider> scpProvider,
SessionAccountLookup sessionAccountLookup) {
this.config = config;
this.accountResolver = accountResolver;
this.iamService = iamService;
@@ -101,6 +109,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
this.currentVertxRequest = currentVertxRequest;
this.catalog = catalog;
this.scpProvider = scpProvider;
this.sessionAccountLookup = sessionAccountLookup;
}
@Override
@@ -110,6 +119,9 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
String auth = ctx.getHeaderString("Authorization");
if (auth == null) {
auth = presignedCredentialAsAuthorization(ctx);
}
if (auth == null) {
return;
}
@@ -229,6 +241,15 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
* apply to this request (enforcement disabled, no Authorization header, root or
* unknown access key). Throws {@link AwsException} with the same AccessDenied
* shape as {@link #filter} when the caller's policies deny the action.
*
* <p>The account used for policy evaluation is always re-resolved from {@code akid} here
* (see {@link #resolveCredentialAccountId}) rather than trusted from {@link RequestContext},
* because a presigned POST's credential is invisible to {@code AccountContextFilter} - it
* arrives only in the multipart body, parsed well after that filter already set the ambient
* account to the configured default. The resolved account is pushed onto {@link RequestContext}
* for the duration of this call so that {@link IamService#resolveCallerContext} and
* {@link IamService#resolveCallerArn}, which both key their per-account lookups off the
* ambient account, resolve the credential's actual owner instead of the default account.
*/
public void authorizeAdditionalResource(String authorizationHeader, String action, String resource) {
if (!config.services().iam().enforcementEnabled()) {
@@ -245,46 +266,66 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return;
}
String accountId = requestContext.getAccountId() == null
? accountResolver.resolve(authorizationHeader)
: requestContext.getAccountId();
String accountId = resolveCredentialAccountId(akid, authorizationHeader);
String previousAccountId = requestContext.getAccountId();
requestContext.setAccountId(accountId);
try {
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId) : null;
List<List<String>> scpLevels = scpProvider.isResolvable()
? scpProvider.get().effectiveScpLevels(accountId) : null;
boolean accountRootPrincipal = false;
CallerContext caller = iamService.resolveCallerContext(akid);
if (caller == null) {
if (scpLevels == null || !akid.equals(accountId)) {
return;
}
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
accountRootPrincipal = true;
}
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
}
boolean accountRootPrincipal = false;
CallerContext caller = iamService.resolveCallerContext(akid);
if (caller == null) {
if (scpLevels == null || !akid.equals(accountId)) {
Map<String, List<String>> conditionContext = null;
Optional<String> principalArn = accountRootPrincipal
? Optional.of("arn:aws:iam::" + accountId + ":root")
: iamService.resolveCallerArn(akid);
if (principalArn.isPresent()) {
conditionContext = new HashMap<>();
conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));
}
Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext);
if (decision != Decision.DENY) {
return;
}
caller = CallerContext.of(List.of(ROOT_ALLOW_ALL));
accountRootPrincipal = true;
}
if (scpLevels != null) {
caller = caller.withScpLevels(scpLevels);
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
throw new AwsException("AccessDenied",
"User: arn:aws:iam::" + accountId + ":user/" + akid
+ " is not authorized to perform: " + action
+ " on resource: \"" + resource + "\""
+ " because no identity-based policy allows the " + action + " action",
403);
} finally {
requestContext.setAccountId(previousAccountId);
}
}
Map<String, List<String>> conditionContext = null;
Optional<String> principalArn = accountRootPrincipal
? Optional.of("arn:aws:iam::" + accountId + ":root")
: iamService.resolveCallerArn(akid);
if (principalArn.isPresent()) {
conditionContext = new HashMap<>();
conditionContext.put("aws:PrincipalArn", List.of(principalArn.get()));
/**
* Resolves the account that owns {@code akid} directly from the credential, following the
* same precedence {@link AccountContextFilter} applies to a header or presigned-URL request:
* a 12-digit access key ID is the account itself, otherwise {@link SessionAccountLookup}
* looks up the owning account for an IAM or session credential, falling back to the configured
* default account when neither resolves.
*/
private String resolveCredentialAccountId(String akid, String authorizationHeader) {
if (akid != null && !akid.matches("\\d{12}")) {
Optional<String> credentialAccount = sessionAccountLookup.resolveAccountId(akid);
if (credentialAccount.isPresent()) {
return credentialAccount.get();
}
}
Decision decision = evaluator.evaluate(caller, null, action, resource, conditionContext);
if (decision != Decision.DENY) {
return;
}
LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource);
throw new AwsException("AccessDenied",
"User: arn:aws:iam::" + accountId + ":user/" + akid
+ " is not authorized to perform: " + action
+ " on resource: \"" + resource + "\""
+ " because no identity-based policy allows the " + action + " action",
403);
return accountResolver.resolve(authorizationHeader);
}
/**
@@ -392,6 +433,21 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
return m.find() ? m.group(1) : null;
}
/**
* Presigned URLs (and presigned POST forms, handled separately via
* {@link #authorizeAdditionalResource}) sign via the {@code X-Amz-Credential} query
* parameter instead of the {@code Authorization} header, so {@code ctx.getHeaderString}
* alone misses them and this filter would silently skip IAM identity-policy evaluation for
* every presigned request. {@link AccountContextFilter} already resolves account/region the
* same way for the same reason. Synthesizing a {@code Credential=...} string from the query
* parameter lets every downstream step here - access key extraction, credential scope,
* action resolution, resource ARNs - run unchanged for both signing styles.
*/
private static String presignedCredentialAsAuthorization(ContainerRequestContext ctx) {
String credential = ctx.getUriInfo().getQueryParameters().getFirst("X-Amz-Credential");
return credential == null || credential.isBlank() ? null : "Credential=" + credential;
}
/**
* Builds a 403 Access Denied response in the wire format the calling SDK
* expects. AWS SDKs hard-fail when they receive the wrong shape: an XML
@@ -3227,6 +3227,22 @@ public class S3Controller {
lcFields.put(e.getKey().toLowerCase(Locale.ROOT), e.getValue());
}
/*
* IamEnforcementFilter's own filter() method only ever sees the Authorization header or,
* for a presigned URL, the X-Amz-Credential query parameter - a presigned POST's
* credential arrives only inside this multipart form body, invisible at that JAX-RS
* filter stage. Evaluate the signing principal's IAM identity policy here whenever a
* credential is present, independent of whether S3's own presigned-POST signature and
* condition checks (s3.enforce-auth) are enabled, so an IAM deny is not bypassed by
* running S3 without its own presigned-POST enforcement. authorizeAdditionalResource
* itself no-ops when IAM enforcement is disabled.
*/
String credential = lcFields.get("x-amz-credential");
if (credential != null && !credential.isEmpty()) {
iamEnforcementFilter.authorizeAdditionalResource(
"Credential=" + credential, "s3:PutObject", S3PublicAccessEvaluator.objectArn(bucket, key));
}
if (s3Service.isAuthEnforced()) {
validatePresignedPostAuth(lcFields, bucket, key, fileData.length);
} else {
@@ -3317,11 +3333,8 @@ public class S3Controller {
+ "Check your key and signing method.", 403);
}
// Route through the same authorization check every other S3 write path uses, so this
// path automatically inherits any future strengthening (e.g. per-principal IAM policy
// evaluation) instead of silently staying behind. Today it only confirms accessKeyId is
// known - strictly weaker than the signature check just performed above - but that will
// change if authorizeObjectWrite grows real policy evaluation.
// Route through the same bucket-policy/ACL check every other S3 write path uses, so this
// path automatically inherits any future strengthening there too.
s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject",
new S3Service.RequestAuthorization(true, accessKeyId, fields.get("x-amz-security-token")));
@@ -11,7 +11,9 @@ import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import jakarta.enterprise.inject.Instance;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.MultivaluedHashMap;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriInfo;
import jakarta.ws.rs.container.ContainerRequestContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@@ -54,6 +56,7 @@ class IamEnforcementFilterTest {
private RequestContext requestContext;
private IamConditionContextResolver conditionContextResolver;
private ResolvedServiceCatalog catalog;
private SessionAccountLookup sessionAccountLookup;
@BeforeEach
void setUp() {
@@ -68,6 +71,7 @@ class IamEnforcementFilterTest {
requestContext = new RequestContext();
conditionContextResolver = mock(IamConditionContextResolver.class);
catalog = mock(ResolvedServiceCatalog.class);
sessionAccountLookup = mock(SessionAccountLookup.class);
when(config.services()).thenReturn(services);
when(services.iam()).thenReturn(iamConfig);
@@ -89,7 +93,7 @@ class IamEnforcementFilterTest {
requestContext, conditionContextResolver,
mock(CloudTrailService.class),
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
catalog, scpProvider);
catalog, scpProvider, sessionAccountLookup);
}
@Test
@@ -428,7 +432,7 @@ class IamEnforcementFilterTest {
actionRegistry, arnBuilder, requestContext, conditionContextResolver,
mock(CloudTrailService.class),
mock(io.quarkus.vertx.http.runtime.CurrentVertxRequest.class),
catalog, scpProvider);
catalog, scpProvider, sessionAccountLookup);
}
@Test
@@ -705,6 +709,95 @@ class IamEnforcementFilterTest {
verify(arnBuilder).buildResources(eq("organizations"), eq(containerRequest), eq("us-east-1"), eq(account));
}
// --- Presigned URL query-string credential (#3195): a presigned PUT/GET carries its
// SigV4 credential in X-Amz-Credential, never in the Authorization header, so the filter
// must fall back to the query parameter instead of bypassing IAM evaluation entirely.
@Test
void filterEvaluatesPolicyForPresignedUrlDenyingWhenIdentityPolicyDenies() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
requestContext.setAccountId("222233334444");
requestContext.setRegion("us-east-1");
stubPresignedCredential(containerRequest,
"AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request");
when(containerRequest.getHeaderString("Authorization")).thenReturn(null);
when(containerRequest.getMediaType()).thenReturn(null);
when(accountResolver.extractAccessKeyId("Credential=AKIADENIEDUSER/20260907/us-east-1/s3/aws4_request"))
.thenReturn("AKIADENIEDUSER");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
when(iamService.resolveCallerContext("AKIADENIEDUSER"))
.thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""")));
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
.thenReturn(null);
when(evaluator.evaluate(any(), isNull(), eq("s3:PutObject"),
eq("arn:aws:s3:::some-bucket/test.txt"), any()))
.thenReturn(IamPolicyEvaluator.Decision.DENY);
newFilter().filter(containerRequest);
verify(containerRequest).abortWith(any(Response.class));
}
@Test
void filterAllowsPresignedUrlWhenIdentityPolicyAllows() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
requestContext.setAccountId("222233334444");
requestContext.setRegion("us-east-1");
stubPresignedCredential(containerRequest,
"AKIAALLOWEDUSER/20260907/us-east-1/s3/aws4_request");
when(containerRequest.getHeaderString("Authorization")).thenReturn(null);
when(accountResolver.extractAccessKeyId("Credential=AKIAALLOWEDUSER/20260907/us-east-1/s3/aws4_request"))
.thenReturn("AKIAALLOWEDUSER");
when(actionRegistry.resolve("s3", containerRequest)).thenReturn("s3:PutObject");
when(iamService.resolveCallerContext("AKIAALLOWEDUSER"))
.thenReturn(CallerContext.of(List.of("""
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"*"}
]}""")));
when(arnBuilder.buildResources("s3", containerRequest, "us-east-1", "222233334444"))
.thenReturn(List.of("arn:aws:s3:::some-bucket/test.txt"));
when(conditionContextResolver.resolve("s3", "s3:PutObject", containerRequest))
.thenReturn(null);
when(evaluator.evaluate(any(), isNull(), eq("s3:PutObject"),
eq("arn:aws:s3:::some-bucket/test.txt"), any()))
.thenReturn(IamPolicyEvaluator.Decision.ALLOW);
newFilter().filter(containerRequest);
verify(containerRequest, never()).abortWith(any());
verify(evaluator).evaluate(any(), isNull(), eq("s3:PutObject"),
eq("arn:aws:s3:::some-bucket/test.txt"), any());
}
@Test
void filterBypassesWhenNeitherAuthorizationHeaderNorPresignedCredentialIsPresent() {
ContainerRequestContext containerRequest = mock(ContainerRequestContext.class);
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
when(containerRequest.getHeaderString("Authorization")).thenReturn(null);
newFilter().filter(containerRequest);
verify(iamService, never()).resolveCallerContext(any());
verify(containerRequest, never()).abortWith(any());
}
private void stubPresignedCredential(ContainerRequestContext containerRequest, String credential) {
UriInfo uriInfo = mock(UriInfo.class);
MultivaluedHashMap<String, String> queryParams = new MultivaluedHashMap<>();
queryParams.putSingle("X-Amz-Credential", credential);
when(uriInfo.getQueryParameters()).thenReturn(queryParams);
when(containerRequest.getUriInfo()).thenReturn(uriInfo);
}
@Test
void queryProtocolGetsXmlErrorResponse() {
// IAM/STS/EC2/SQS/SNS/RDS/ELBv2/CFN/... — Query protocol, form-encoded body, XML response.
@@ -33,7 +33,9 @@ class S3PresignedPostAuthEnforcementIntegrationTest {
public static final class S3AuthProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.s3.enforce-auth", "true");
return Map.of(
"floci.services.s3.enforce-auth", "true",
"floci.services.iam.enforcement-enabled", "true");
}
}
@@ -324,6 +326,121 @@ class S3PresignedPostAuthEnforcementIntegrationTest {
.body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));
}
// --- IAM identity-policy enforcement (#3195): a genuinely-signed presigned POST from a
// real IAM user must still be evaluated against that user's identity policy, the same way
// a header-signed request is. Before the fix, IamEnforcementFilter never saw this credential
// at all (it arrives only in the multipart form body), so an explicit Deny had no effect.
@Test
@Order(30)
void rejectsGenuineSignatureWhenIdentityPolicyDeniesPutObject() {
String key = "uploads/iam-denied.txt";
String userName = "presigned-post-denied-user";
String[] credentials = createUserAndAccessKey(userName);
String accessKeyId = credentials[0];
String secretKey = credentials[1];
putUserPolicy(userName, "DenyPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""");
String policyBase64 = buildPolicyBase64(BUCKET, key);
String credential = accessKeyId + "/20260101/us-east-1/s3/aws4_request";
String signature = signPolicy(policyBase64, credential, secretKey);
given()
.multiPart("key", key)
.multiPart("policy", policyBase64)
.multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
.multiPart("x-amz-credential", credential)
.multiPart("x-amz-date", AMZ_DATE)
.multiPart("x-amz-signature", signature)
.multiPart("file", "iam-denied.txt",
"should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + BUCKET)
.then()
.statusCode(403)
.body("Error.Code", org.hamcrest.Matchers.equalTo("AccessDenied"));
}
@Test
@Order(31)
void acceptsGenuineSignatureWhenIdentityPolicyAllowsPutObject() {
String key = "uploads/iam-allowed.txt";
String fileContent = "uploaded by a permitted IAM user";
String userName = "presigned-post-allowed-user";
String[] credentials = createUserAndAccessKey(userName);
String accessKeyId = credentials[0];
String secretKey = credentials[1];
putUserPolicy(userName, "AllowPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%1$s/*"}
]}""".formatted(BUCKET));
String policyBase64 = buildPolicyBase64(BUCKET, key);
String credential = accessKeyId + "/20260101/us-east-1/s3/aws4_request";
String signature = signPolicy(policyBase64, credential, secretKey);
given()
.multiPart("key", key)
.multiPart("policy", policyBase64)
.multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
.multiPart("x-amz-credential", credential)
.multiPart("x-amz-date", AMZ_DATE)
.multiPart("x-amz-signature", signature)
.multiPart("file", "iam-allowed.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + BUCKET)
.then()
.statusCode(204)
.header("ETag", notNullValue());
}
private static final String IAM_ROOT_AUTH =
"AWS4-HMAC-SHA256 Credential=" + LEGACY_ACCESS_KEY_ID + "/20260101/us-east-1/iam/aws4_request"
+ ", SignedHeaders=host, Signature=abc";
/** Returns {accessKeyId, secretAccessKey} for a freshly created IAM user. */
private static String[] createUserAndAccessKey(String userName) {
given()
.formParam("Action", "CreateUser")
.formParam("UserName", userName)
.header("Authorization", IAM_ROOT_AUTH)
.when()
.post("/")
.then()
.statusCode(200);
io.restassured.response.ExtractableResponse<io.restassured.response.Response> response = given()
.formParam("Action", "CreateAccessKey")
.formParam("UserName", userName)
.header("Authorization", IAM_ROOT_AUTH)
.when()
.post("/")
.then()
.statusCode(200)
.extract();
return new String[] {
response.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId"),
response.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.SecretAccessKey")
};
}
private static void putUserPolicy(String userName, String policyName, String policyDocument) {
given()
.formParam("Action", "PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", policyName)
.formParam("PolicyDocument", policyDocument)
.header("Authorization", authorizationHeader(LEGACY_ACCESS_KEY_ID).replace("/s3/", "/iam/"))
.when()
.post("/")
.then()
.statusCode(200);
}
private static String authorizationHeader(String accessKeyId) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260101/us-east-1/s3/aws4_request"
+ ", SignedHeaders=host;x-amz-date, Signature=test";
@@ -0,0 +1,221 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
/**
* Regression coverage for the presigned POST gap in #3195/#3504: {@code S3Controller} only ran
* {@code IamEnforcementFilter#authorizeAdditionalResource} inside {@code validatePresignedPostAuth},
* which itself only runs when {@code floci.services.s3.enforce-auth} is enabled. With that flag
* left off (its default) and only {@code floci.services.iam.enforcement-enabled} turned on, a
* presigned POST never reached the signing principal's identity policy at all, so an explicit
* {@code Deny} had no effect even though the equivalent header-signed and presigned-URL requests
* were already correctly denied. This mirrors {@code S3PresignedUrlIamEnforcementIntegrationTest}'s
* IAM-only profile, which the combined-flags profile in
* {@code S3PresignedPostAuthEnforcementIntegrationTest} cannot exercise.
*/
@QuarkusTest
@TestProfile(S3PresignedPostIamOnlyEnforcementIntegrationTest.IamOnlyProfile.class)
class S3PresignedPostIamOnlyEnforcementIntegrationTest {
private static final String REGION = "us-east-1";
/** A non-default account, distinct from the configured {@code 000000000000} default. */
private static final String NON_DEFAULT_ACCOUNT = "222233334444";
private static final DateTimeFormatter AMZ_DATE_FMT =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
@Test
void presignedPostIsDeniedWhenIdentityPolicyDeniesPutObject() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-post-iam-deny-" + suffix;
String userName = "presigned-post-denied-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName);
putUserPolicy(userName, "DenyPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""");
given()
.multiPart("key", "denied.txt")
.multiPart("x-amz-credential", presignedCredential(accessKeyId))
.multiPart("file", "denied.txt",
"should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(403)
.body("Error.Code", equalTo("AccessDenied"));
}
@Test
void presignedPostSucceedsWhenIdentityPolicyAllowsPutObject() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-post-iam-allow-" + suffix;
String userName = "presigned-post-allowed-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName);
putUserPolicy(userName, "AllowPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%1$s/*"}
]}""".formatted(bucket));
given()
.multiPart("key", "allowed.txt")
.multiPart("x-amz-credential", presignedCredential(accessKeyId))
.multiPart("file", "allowed.txt",
"uploaded via presigned POST".getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(204);
}
/**
* Regression for the multi-account gap found in review on #3504: {@code AccountContextFilter}
* runs before the multipart body is parsed, so for a presigned POST it sets the ambient
* request account to the configured default. An IAM user (and access key) created in a
* non-default account must still be resolved from the parsed credential rather than looked
* up in that ambient default account, or its identity policy is silently skipped via the
* unknown-key bypass instead of being evaluated.
*/
@Test
void presignedPostIsDeniedForNonDefaultAccountKeyWhenIdentityPolicyDenies() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-post-iam-deny-xacct-" + suffix;
String userName = "presigned-post-denied-xacct-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName, NON_DEFAULT_ACCOUNT);
putUserPolicy(userName, "DenyPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""", NON_DEFAULT_ACCOUNT);
given()
.multiPart("key", "denied-xacct.txt")
.multiPart("x-amz-credential", presignedCredential(accessKeyId))
.multiPart("file", "denied-xacct.txt",
"should not be stored".getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(403)
.body("Error.Code", equalTo("AccessDenied"));
}
/** Allow counterpart of {@link #presignedPostIsDeniedForNonDefaultAccountKeyWhenIdentityPolicyDenies}. */
@Test
void presignedPostSucceedsForNonDefaultAccountKeyWhenIdentityPolicyAllows() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-post-iam-allow-xacct-" + suffix;
String userName = "presigned-post-allowed-xacct-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName, NON_DEFAULT_ACCOUNT);
putUserPolicy(userName, "AllowPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%1$s/*"}
]}""".formatted(bucket), NON_DEFAULT_ACCOUNT);
given()
.multiPart("key", "allowed-xacct.txt")
.multiPart("x-amz-credential", presignedCredential(accessKeyId))
.multiPart("file", "allowed-xacct.txt",
"uploaded via presigned POST".getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + bucket)
.then()
.statusCode(204);
}
private static String presignedCredential(String accessKeyId) {
String amzDate = AMZ_DATE_FMT.format(Instant.now());
String dateStamp = amzDate.substring(0, 8);
return accessKeyId + "/" + dateStamp + "/" + REGION + "/s3/aws4_request";
}
private static void createBucketAsRoot(String bucket) {
given()
.header("Authorization", auth("test", "s3"))
.when()
.put("/" + bucket)
.then()
.statusCode(200);
}
private static String createUser(String userName) {
return createUser(userName, null);
}
/** Creates the user (and its access key) as root in {@code accountId}, or the default account when null. */
private static String createUser(String userName, String accountId) {
String authHeader = auth(accountId == null ? "test" : accountId, "iam");
given()
.formParam("Action", "CreateUser")
.formParam("UserName", userName)
.header("Authorization", authHeader)
.when()
.post("/")
.then()
.statusCode(200);
return given()
.formParam("Action", "CreateAccessKey")
.formParam("UserName", userName)
.header("Authorization", authHeader)
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
}
private static void putUserPolicy(String userName, String policyName, String policyDocument) {
putUserPolicy(userName, policyName, policyDocument, null);
}
/** Attaches the policy as root in {@code accountId}, or the default account when null. */
private static void putUserPolicy(String userName, String policyName, String policyDocument, String accountId) {
given()
.formParam("Action", "PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", policyName)
.formParam("PolicyDocument", policyDocument)
.header("Authorization", auth(accountId == null ? "test" : accountId, "iam"))
.when()
.post("/")
.then()
.statusCode(200);
}
private static String auth(String accessKeyId, String service) {
String amzDate = AMZ_DATE_FMT.format(Instant.now()).substring(0, 8);
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/" + amzDate + "/" + REGION + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
public static final class IamOnlyProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of(
"floci.services.iam.enforcement-enabled", "true",
"floci.services.s3.enforce-auth", "false");
}
}
}
@@ -0,0 +1,178 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.QuarkusTestProfile;
import io.quarkus.test.junit.TestProfile;
import org.junit.jupiter.api.Test;
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.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
/**
* Regression tests for issue #3195: {@code IamEnforcementFilter} only ever read the signing
* credential from the {@code Authorization} header, so a presigned URL - which signs via the
* {@code X-Amz-Credential} query parameter instead - skipped IAM identity-policy evaluation
* entirely. A principal with an explicit {@code Deny} (or no grant at all) could still write
* through a presigned URL as long as the request was otherwise well-formed, exactly the
* privilege-escalation path a header-signed request was already correctly denied on.
*
* <p>Only {@code floci.services.iam.enforcement-enabled} is turned on here (matching
* {@code S3CopyObjectSourcePermissionIntegrationTest}); {@code floci.services.s3.enforce-auth}
* stays off, so these requests carry a syntactically valid but unverified {@code X-Amz-Signature}
* - IAM policy evaluation does not depend on the signature itself being checked.
*/
@QuarkusTest
@TestProfile(S3PresignedUrlIamEnforcementIntegrationTest.IamEnforcementProfile.class)
class S3PresignedUrlIamEnforcementIntegrationTest {
private static final String REGION = "us-east-1";
private static final DateTimeFormatter AMZ_DATE_FMT =
DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
@Test
void presignedPutIsDeniedWhenIdentityPolicyDeniesPutObject() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-iam-deny-" + suffix;
String userName = "presigned-denied-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName);
putUserPolicy(userName, "DenyPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Deny","Action":"s3:PutObject","Resource":"*"}
]}""");
given()
.urlEncodingEnabled(false)
.contentType("text/plain")
.body("should not be stored")
.when()
.put(presignedPutPath(bucket, "denied.txt", accessKeyId))
.then()
.statusCode(403)
.body(containsString("<Code>AccessDenied</Code>"));
}
@Test
void presignedPutIsDeniedWhenNoPolicyGrantsPutObject() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-iam-nogrant-" + suffix;
String userName = "presigned-nogrant-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName);
// No PutUserPolicy call at all: a real IAM user with no grants, matching the issue's
// reproduction (a user with an explicit Deny or, equally, simply no grant).
given()
.urlEncodingEnabled(false)
.contentType("text/plain")
.body("should not be stored")
.when()
.put(presignedPutPath(bucket, "no-grant.txt", accessKeyId))
.then()
.statusCode(403)
.body(containsString("<Code>AccessDenied</Code>"));
}
@Test
void presignedPutSucceedsWhenIdentityPolicyAllowsPutObject() {
String suffix = UUID.randomUUID().toString().substring(0, 8);
String bucket = "presigned-iam-allow-" + suffix;
String userName = "presigned-allowed-user-" + suffix;
createBucketAsRoot(bucket);
String accessKeyId = createUser(userName);
putUserPolicy(userName, "AllowPutObject", """
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%1$s/*"}
]}""".formatted(bucket));
given()
.urlEncodingEnabled(false)
.contentType("text/plain")
.body("uploaded via presigned URL")
.when()
.put(presignedPutPath(bucket, "allowed.txt", accessKeyId))
.then()
.statusCode(200);
}
private static String presignedPutPath(String bucket, String key, String accessKeyId) {
String amzDate = AMZ_DATE_FMT.format(Instant.now());
String dateStamp = amzDate.substring(0, 8);
String credential = URLEncoder.encode(
accessKeyId + "/" + dateStamp + "/" + REGION + "/s3/aws4_request", StandardCharsets.UTF_8);
return "/" + bucket + "/" + key
+ "?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";
}
private static void createBucketAsRoot(String bucket) {
given()
.header("Authorization", auth("test", "s3"))
.when()
.put("/" + bucket)
.then()
.statusCode(200);
}
private static String createUser(String userName) {
given()
.formParam("Action", "CreateUser")
.formParam("UserName", userName)
.header("Authorization", auth("test", "iam"))
.when()
.post("/")
.then()
.statusCode(200);
return given()
.formParam("Action", "CreateAccessKey")
.formParam("UserName", userName)
.header("Authorization", auth("test", "iam"))
.when()
.post("/")
.then()
.statusCode(200)
.extract()
.path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
}
private static void putUserPolicy(String userName, String policyName, String policyDocument) {
given()
.formParam("Action", "PutUserPolicy")
.formParam("UserName", userName)
.formParam("PolicyName", policyName)
.formParam("PolicyDocument", policyDocument)
.header("Authorization", auth("test", "iam"))
.when()
.post("/")
.then()
.statusCode(200);
}
private static String auth(String accessKeyId, String service) {
return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260629/" + REGION + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
public static final class IamEnforcementProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("floci.services.iam.enforcement-enabled", "true");
}
}
}