Light, fluffy, and always free - The AWS Local Emulator alternative
fix: Support S3 auth enforcement (#1689)
David Phillipsa3e8bf5a8b8c
diff --git a/README.md b/README.mdindex 7ef69dd742..f360c45dbc 100644--- a/README.md+++ b/README.md@@ -71,7 +71,7 @@ This short demo shows the CLI flow: start Floci, export the local AWS environmenhttps://github.com/user-attachments/assets/b55714dc-ef36-40ae-a734-cd2cadc288a8-All AWS services are available at `http://localhost:4566`. Any region works. Credentials can be any non-empty values.+All AWS services are available at `http://localhost:4566`. Any region works. Credentials can be any non-empty values unless you explicitly enable stricter service-specific auth checks.<details><summary>Prefer Docker Compose?</summary>@@ -754,6 +754,7 @@ All settings are overridable through environment variables with the `FLOCI_` pre| `FLOCI_STORAGE_MODE` | `memory` | Storage mode: `memory`, `persistent`, `hybrid`, or `wal` || `FLOCI_STORAGE_PERSISTENT_PATH` | `./data` | Directory used for persisted state || `FLOCI_ECR_BASE_URI` | `public.ecr.aws` | ECR base URI used when pulling container images |+| `FLOCI_SERVICES_S3_ENFORCE_AUTH` | `false` | Enforce S3 public/private read access and reject unknown signed S3 access keys |Full reference: [configuration docs](https://floci.io/floci/configuration/advanced/application-yml)diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3AuthEnforcementCompatibilityTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3AuthEnforcementCompatibilityTest.javanew file mode 100644index 0000000000..01ec8ea70a--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3AuthEnforcementCompatibilityTest.java@@ -0,0 +1,204 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.Assumptions;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;+import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;+import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;+import software.amazon.awssdk.core.ResponseBytes;+import software.amazon.awssdk.core.sync.RequestBody;+import software.amazon.awssdk.regions.Region;+import software.amazon.awssdk.services.s3.S3Client;+import software.amazon.awssdk.services.s3.model.CreateBucketRequest;+import software.amazon.awssdk.services.s3.model.GetObjectRequest;+import software.amazon.awssdk.services.s3.model.GetObjectResponse;+import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;+import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;+import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest;+import software.amazon.awssdk.services.s3.model.PutObjectRequest;+import software.amazon.awssdk.services.s3.model.S3Exception;++import java.nio.charset.StandardCharsets;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++@DisplayName("S3 Auth Enforcement")+class S3AuthEnforcementCompatibilityTest {++ private static final String PUBLIC_BUCKET = TestFixtures.uniqueName("sdk-s3-auth-public");+ private static final String PRIVATE_BUCKET = TestFixtures.uniqueName("sdk-s3-auth-private");+ private static final String KEY = "directory/known-file.txt";+ private static final String CONTENT = "anonymous read works";++ private static S3Client adminS3;+ private static S3Client anonymousS3;+ private static S3Client unknownCredentialS3;+ private static boolean enforcementEnabled;++ @BeforeAll+ static void setup() {+ adminS3 = TestFixtures.s3Client();+ anonymousS3 = s3WithAnonymousCredentials();+ unknownCredentialS3 = s3WithCredentials("bad-key", "bad-secret");++ adminS3.createBucket(CreateBucketRequest.builder().bucket(PUBLIC_BUCKET).build());+ adminS3.putBucketPolicy(PutBucketPolicyRequest.builder()+ .bucket(PUBLIC_BUCKET)+ .policy(publicReadPolicy(PUBLIC_BUCKET))+ .build());+ adminS3.putObject(PutObjectRequest.builder().bucket(PUBLIC_BUCKET).key(KEY).build(),+ RequestBody.fromString(CONTENT));++ adminS3.createBucket(CreateBucketRequest.builder().bucket(PRIVATE_BUCKET).build());+ adminS3.putObject(PutObjectRequest.builder().bucket(PRIVATE_BUCKET).key(KEY).build(),+ RequestBody.fromString(CONTENT));++ assertThat(readObject(anonymousS3, PUBLIC_BUCKET)).isEqualTo(CONTENT);+ enforcementEnabled = probeEnforcementEnabled();+ }++ @AfterAll+ static void cleanup() {+ close(adminS3);+ close(anonymousS3);+ close(unknownCredentialS3);+ }++ private static void close(S3Client client) {+ if (client != null) {+ client.close();+ }+ }++ @Test+ @DisplayName("anonymous public object read succeeds")+ void anonymousPublicObjectReadSucceeds() {+ assumeEnforcementEnabled();++ assertThat(readObject(anonymousS3, PUBLIC_BUCKET)).isEqualTo(CONTENT);+ }++ @Test+ @DisplayName("anonymous public directory list succeeds")+ void anonymousPublicDirectoryListSucceeds() {+ assumeEnforcementEnabled();++ ListObjectsV2Response response = anonymousS3.listObjectsV2(ListObjectsV2Request.builder()+ .bucket(PUBLIC_BUCKET)+ .delimiter("/")+ .build());+ assertThat(response.commonPrefixes())+ .anyMatch(prefix -> "directory/".equals(prefix.prefix()));+ }++ @Test+ @DisplayName("anonymous private object read fails")+ void anonymousPrivateObjectReadFails() {+ assumeEnforcementEnabled();++ assertThatThrownBy(() -> readObject(anonymousS3, PRIVATE_BUCKET))+ .isInstanceOfSatisfying(S3Exception.class, S3AuthEnforcementCompatibilityTest::assertAccessDenied);+ }++ @Test+ @DisplayName("anonymous private directory list fails")+ void anonymousPrivateDirectoryListFails() {+ assumeEnforcementEnabled();++ assertThatThrownBy(() -> anonymousS3.listObjectsV2(ListObjectsV2Request.builder()+ .bucket(PRIVATE_BUCKET)+ .delimiter("/")+ .build()))+ .isInstanceOfSatisfying(S3Exception.class, S3AuthEnforcementCompatibilityTest::assertAccessDenied);+ }++ @Test+ @DisplayName("public object read rejects unknown signed credentials")+ void publicObjectReadRejectsUnknownSignedCredentials() {+ assumeEnforcementEnabled();++ assertThatThrownBy(() -> readObject(unknownCredentialS3, PUBLIC_BUCKET))+ .isInstanceOfSatisfying(S3Exception.class, S3AuthEnforcementCompatibilityTest::assertInvalidAccessKey);+ }++ @Test+ @DisplayName("public bucket list rejects unknown signed credentials")+ void publicBucketListRejectsUnknownSignedCredentials() {+ assumeEnforcementEnabled();++ assertThatThrownBy(() -> unknownCredentialS3.listObjectsV2(+ ListObjectsV2Request.builder().bucket(PUBLIC_BUCKET).build()))+ .isInstanceOfSatisfying(S3Exception.class, S3AuthEnforcementCompatibilityTest::assertInvalidAccessKey);+ }++ private static boolean probeEnforcementEnabled() {+ try {+ readObject(unknownCredentialS3, PUBLIC_BUCKET);+ return false;+ } catch (S3Exception e) {+ if (e.statusCode() == 403+ && "InvalidAccessKeyId".equals(e.awsErrorDetails().errorCode())) {+ return true;+ }+ throw e;+ }+ }++ private static void assumeEnforcementEnabled() {+ Assumptions.assumeTrue(enforcementEnabled,+ "S3 auth enforcement is not enabled - set floci.services.s3.enforce-auth=true to run these tests");+ }++ private static String readObject(S3Client client, String bucket) {+ ResponseBytes<GetObjectResponse> response = client.getObjectAsBytes(+ GetObjectRequest.builder().bucket(bucket).key(KEY).build());+ return response.asString(StandardCharsets.UTF_8);+ }++ private static S3Client s3WithAnonymousCredentials() {+ return S3Client.builder()+ .endpointOverride(TestFixtures.endpoint())+ .region(Region.US_EAST_1)+ .credentialsProvider(AnonymousCredentialsProvider.create())+ .forcePathStyle(true)+ .build();+ }++ private static S3Client s3WithCredentials(String accessKeyId, String secretAccessKey) {+ return S3Client.builder()+ .endpointOverride(TestFixtures.endpoint())+ .region(Region.US_EAST_1)+ .credentialsProvider(StaticCredentialsProvider.create(+ AwsBasicCredentials.create(accessKeyId, secretAccessKey)))+ .forcePathStyle(true)+ .build();+ }++ private static void assertInvalidAccessKey(S3Exception e) {+ assertThat(e.statusCode()).isEqualTo(403);+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("InvalidAccessKeyId");+ }++ private static void assertAccessDenied(S3Exception e) {+ assertThat(e.statusCode()).isEqualTo(403);+ assertThat(e.awsErrorDetails().errorCode()).isEqualTo("AccessDenied");+ }++ private static String publicReadPolicy(String bucket) {+ return """+ {+ "Version": "2012-10-17",+ "Statement": {+ "Effect": "Allow",+ "Principal": {"AWS": ["*"]},+ "Action": ["s3:GetObject", "s3:ListBucket"],+ "Resource": ["arn:aws:s3:::%s/*", "arn:aws:s3:::%s"]+ }+ }+ """.formatted(bucket, bucket);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.javaindex 94c165fc99..a90e0468b6 100644--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java@@ -710,6 +710,9 @@ public interface EmulatorConfig {@WithDefault("true")boolean enabled();+ @WithDefault("false")+ boolean enforceAuth();+@WithDefault("3600")int defaultPresignExpirySeconds();}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.javaindex 4decc72520..38f83b5ad4 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/PreSignedUrlFilter.java@@ -28,16 +28,18 @@ public class PreSignedUrlFilter implements ContainerRequestFilter {return;}+ if (S3RequestAuthorizationParser.isMissingRequiredPresignedParameter(queryParams)) {+ requestContext.abortWith(errorResponse(+ S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS,+ S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_CODE,+ S3RequestAuthorizationParser.AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE));+ return;+ }+String amzDate = queryParams.getFirst("X-Amz-Date");String expiresStr = queryParams.getFirst("X-Amz-Expires");String signature = queryParams.getFirst("X-Amz-Signature");- if (amzDate == null || expiresStr == null || signature == null) {- requestContext.abortWith(errorResponse(403, "AccessDenied",- "Missing required pre-signed URL parameters."));- return;- }-int expires;try {expires = Integer.parseInt(expiresStr);diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.javanew file mode 100644index 0000000000..0fa0db329d--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.java@@ -0,0 +1,162 @@+package io.github.hectorvent.floci.services.s3;++import org.jboss.logging.Logger;+import org.w3c.dom.Document;+import org.w3c.dom.Element;+import org.w3c.dom.Node;+import org.w3c.dom.NodeList;+import org.xml.sax.ErrorHandler;+import org.xml.sax.InputSource;+import org.xml.sax.SAXException;+import org.xml.sax.SAXParseException;++import javax.xml.XMLConstants;+import javax.xml.parsers.DocumentBuilder;+import javax.xml.parsers.DocumentBuilderFactory;+import javax.xml.parsers.ParserConfigurationException;+import java.io.IOException;+import java.io.StringReader;+import java.util.ArrayList;+import java.util.List;++record S3AclPolicy(List<S3AclPolicy.Grant> grants) {++ private static final Logger LOG = Logger.getLogger(S3AclPolicy.class);+ static final String ALL_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AllUsers";++ static S3AclPolicy parse(String acl) throws AclParseException {+ try {+ return fromDocument(parseXml(acl));+ } catch (ParserConfigurationException | SAXException | IOException e) {+ throw new AclParseException(e);+ }+ }++ private static Document parseXml(String acl) throws ParserConfigurationException, SAXException, IOException {+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();+ factory.setNamespaceAware(true);+ factory.setExpandEntityReferences(false);+ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);+ factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);+ factory.setFeature("http://xml.org/sax/features/external-general-entities", false);+ factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);++ DocumentBuilder builder = factory.newDocumentBuilder();+ builder.setErrorHandler(new SilentThrowingErrorHandler());+ return builder.parse(new InputSource(new StringReader(acl)));+ }++ private static S3AclPolicy fromDocument(Document document) {+ Element accessControlPolicy = document.getDocumentElement();+ if (accessControlPolicy == null || !"AccessControlPolicy".equals(accessControlPolicy.getLocalName())) {+ return new S3AclPolicy(List.of());+ }+ Element accessControlList = firstChildElement(accessControlPolicy, "AccessControlList");+ if (accessControlList == null) {+ return new S3AclPolicy(List.of());+ }++ NodeList grantNodes = accessControlList.getChildNodes();+ List<Grant> grants = new ArrayList<>();+ for (int index = 0; index < grantNodes.getLength(); index++) {+ if (grantNodes.item(index) instanceof Element grantElement && "Grant".equals(grantElement.getLocalName())) {+ grants.add(parseGrant(grantElement));+ }+ }+ return new S3AclPolicy(List.copyOf(grants));+ }++ static final class AclParseException extends Exception {+ AclParseException(Throwable cause) {+ super("Failed to parse S3 ACL", cause);+ }+ }++ private static Grant parseGrant(Element grantElement) {+ Element granteeElement = firstChildElement(grantElement, "Grantee");+ String uri = granteeElement != null ? descendantText(granteeElement, "URI") : null;+ String permissionText = childText(grantElement, "Permission");+ return new Grant(new Grantee(uri), Permission.fromXml(permissionText));+ }++ private static Element firstChildElement(Element parent, String localName) {+ NodeList children = parent.getChildNodes();+ for (int index = 0; index < children.getLength(); index++) {+ Node child = children.item(index);+ if (child instanceof Element element && localName.equals(element.getLocalName())) {+ return element;+ }+ }+ return null;+ }++ private static String childText(Element parent, String localName) {+ Element child = firstChildElement(parent, localName);+ return child != null ? normalizedText(child) : null;+ }++ private static String descendantText(Element parent, String localName) {+ NodeList nodes = parent.getElementsByTagNameNS("*", localName);+ if (nodes.getLength() == 0) {+ return null;+ }+ return normalizedText(nodes.item(0));+ }++ private static String normalizedText(Node node) {+ String text = node.getTextContent();+ return text != null ? text.trim() : null;+ }++ record Grant(Grantee grantee, Permission permission) {+ boolean allowsPublicRead() {+ return grantee.isAllUsersGroup() && permission.allowsRead();+ }+ }++ record Grantee(String uri) {+ boolean isAllUsersGroup() {+ return ALL_USERS_GROUP_URI.equals(uri);+ }+ }++ enum Permission {+ READ,+ WRITE,+ READ_ACP,+ WRITE_ACP,+ FULL_CONTROL,+ UNKNOWN;++ static Permission fromXml(String value) {+ if (value == null || value.isBlank()) {+ return UNKNOWN;+ }+ try {+ return Permission.valueOf(value.trim());+ } catch (IllegalArgumentException e) {+ return UNKNOWN;+ }+ }++ boolean allowsRead() {+ return this == READ || this == FULL_CONTROL;+ }+ }++ private static final class SilentThrowingErrorHandler implements ErrorHandler {+ @Override+ public void warning(SAXParseException exception) {+ }++ @Override+ public void error(SAXParseException exception) {+ LOG.debugv(exception, "Recoverable S3 ACL XML parse error");+ }++ @Override+ public void fatalError(SAXParseException exception) throws SAXException {+ throw exception;+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.javanew file mode 100644index 0000000000..cfa24c5844--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java@@ -0,0 +1,26 @@+package io.github.hectorvent.floci.services.s3;++import org.jboss.logging.Logger;++final class S3AclPublicAccessEvaluator {++ static final String ALL_USERS_GROUP_URI = S3AclPolicy.ALL_USERS_GROUP_URI;++ private static final Logger LOG = Logger.getLogger(S3AclPublicAccessEvaluator.class);++ private S3AclPublicAccessEvaluator() {+ }++ static boolean aclAllowsPublicRead(String acl) {+ if (acl == null || acl.isBlank()) {+ return false;+ }+ try {+ S3AclPolicy policy = S3AclPolicy.parse(acl);+ return policy.grants().stream().anyMatch(S3AclPolicy.Grant::allowsPublicRead);+ } catch (S3AclPolicy.AclParseException e) {+ LOG.debugv(e, "Failed to parse S3 ACL for public read evaluation");+ return false;+ }+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.javaindex 2b71168996..2ee28a61b1 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java@@ -163,8 +163,13 @@ public class S3Controller {@HEAD@Path("/{bucket}")- public Response headBucket(@PathParam("bucket") String bucket) {+ public Response headBucket(@PathParam("bucket") String bucket,+ @Context UriInfo uriInfo,+ @Context HttpHeaders httpHeaders) {try {+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);+ s3Service.authorizeBucketRead(bucket, "s3:ListBucket", authorization);s3Service.headBucket(bucket);String bucketRegion = s3Service.getBucketRegion(bucket);if (bucketRegion == null || bucketRegion.isBlank()) {@@ -333,60 +338,79 @@ public class S3Controller {@Context HttpHeaders httpHeaders) {try {validateRawUri();+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);if (hasQueryParam(uriInfo, "uploads")) {+ s3Service.authorizeBucketRead(bucket, "s3:ListBucketMultipartUploads", authorization);return handleListMultipartUploads(bucket);}if (hasQueryParam(uriInfo, "notification")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketNotification", authorization);return handleGetBucketNotification(bucket);}if (hasQueryParam(uriInfo, "versioning")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketVersioning", authorization);return handleGetBucketVersioning(bucket);}if (hasQueryParam(uriInfo, "versions")) {+ s3Service.authorizeBucketRead(bucket, "s3:ListBucketVersions", authorization);return handleListObjectVersions(bucket, prefix, maxKeys, keyMarker);}if (hasQueryParam(uriInfo, "location")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketLocation", authorization);return handleGetBucketLocation(bucket);}if (hasQueryParam(uriInfo, "tagging")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketTagging", authorization);return handleGetBucketTagging(bucket);}if (hasQueryParam(uriInfo, "object-lock")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketObjectLockConfiguration", authorization);return handleGetObjectLockConfiguration(bucket);}if (hasQueryParam(uriInfo, "website")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketWebsite", authorization);return handleGetBucketWebsite(bucket);}if (hasQueryParam(uriInfo, "logging")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketLogging", authorization);return Response.ok(s3Service.getBucketLogging(bucket)).type("application/xml").build();}if (hasQueryParam(uriInfo, "policy")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketPolicy", authorization);return Response.ok(s3Service.getBucketPolicy(bucket)).build();}if (hasQueryParam(uriInfo, "cors")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketCORS", authorization);return Response.ok(s3Service.getBucketCors(bucket)).build();}if (hasQueryParam(uriInfo, "lifecycle")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetLifecycleConfiguration", authorization);S3Service.LifecycleConfigurationResult lc = s3Service.getBucketLifecycle(bucket);return Response.ok(lc.xml()).header("x-amz-transition-default-minimum-object-size", lc.transitionDefaultMinimumObjectSize()).build();}if (hasQueryParam(uriInfo, "acl")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketAcl", authorization);return Response.ok(s3Service.getBucketAcl(bucket)).build();}if (hasQueryParam(uriInfo, "encryption")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetEncryptionConfiguration", authorization);return Response.ok(s3Service.getBucketEncryption(bucket)).build();}if (hasQueryParam(uriInfo, "publicAccessBlock")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketPublicAccessBlock", authorization);return Response.ok(s3Service.getPublicAccessBlock(bucket)).build();}if (hasQueryParam(uriInfo, "ownershipControls")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketOwnershipControls", authorization);return Response.ok(s3Service.getBucketOwnershipControls(bucket)).build();}if (hasQueryParam(uriInfo, "requestPayment")) {+ s3Service.authorizeBucketRead(bucket, "s3:GetBucketRequestPayment", authorization);return Response.ok(s3Service.getBucketRequestPayment(bucket)).build();}@@ -396,6 +420,7 @@ public class S3Controller {WebsiteConfiguration webConfig = s3Service.getBucketWebsite(bucket);if (webConfig.getIndexDocument() != null) {try {+ s3Service.authorizeGetObject(bucket, webConfig.getIndexDocument(), null, authorization);S3Object indexObj = s3Service.getObject(bucket, webConfig.getIndexDocument());return Response.ok(indexObj.getData()).type(indexObj.getContentType())@@ -404,15 +429,25 @@ public class S3Controller {.header("x-amz-website-redirect-location", "index").build();} catch (AwsException e) {- Response r = serveErrorDocument(bucket, webConfig);- if (r != null) return r;+ if (!isWebsiteErrorDocumentTrigger(e)) {+ throw e;+ }+ Response r = serveErrorDocument(bucket, webConfig, authorization, e.getHttpStatus());+ if (r != null) {+ return r;+ }}}} catch (AwsException e) {+ if (!"NoSuchWebsiteConfiguration".equals(e.getErrorCode())) {+ throw e;+ }// Bucket is not a website, continue to listObjects}}+ s3Service.authorizeListBucket(bucket, authorization);+int max = (maxKeys != null && maxKeys > 0) ? maxKeys : 1000;boolean v1 = !"2".equals(listType);String effectiveStartAfter = v1 && marker != null ? marker : startAfter;@@ -605,31 +640,42 @@ public class S3Controller {@HeaderParam("Range") String rangeHeader,@Context UriInfo uriInfo,@Context HttpHeaders httpHeaders) {+ S3Service.RequestAuthorization authorization = S3Service.RequestAuthorization.unsigned();try {key = extractObjectKey(uriInfo, bucket);+ authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);if (uploadId != null) {+ s3Service.authorizeObjectRead(bucket, key, versionId, "s3:ListMultipartUploadParts", authorization);return handleListParts(bucket, key, uploadId, maxPartsQuery, partNumberMarkerQuery);}+if (hasQueryParam(uriInfo, "tagging")) {+ s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectTagging", authorization);return handleGetObjectTagging(bucket, key);}if (hasQueryParam(uriInfo, "retention")) {+ s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectRetention", authorization);return handleGetObjectRetention(bucket, key, versionId);}if (hasQueryParam(uriInfo, "legal-hold")) {+ s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectLegalHold", authorization);return handleGetObjectLegalHold(bucket, key, versionId);}if (hasQueryParam(uriInfo, "acl")) {+ s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAcl", authorization);return Response.ok(s3Service.getObjectAcl(bucket, key, versionId)).build();}if (hasQueryParam(uriInfo, "attributes")) {+ s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAttributes", authorization);// Merge all x-amz-object-attributes header values (SDK may send multiple lines)List<String> attrHeaders = httpHeaders.getRequestHeader("x-amz-object-attributes");String mergedAttributes = attrHeaders != null ? String.join(",", attrHeaders) : objectAttributesHeader;return handleGetObjectAttributes(bucket, key, versionId,mergedAttributes, maxParts, partNumberMarker);}+ s3Service.authorizeGetObject(bucket, key, versionId, authorization);if (hasPreconditions(ifMatch, ifNoneMatch, ifModifiedSince, ifUnmodifiedSince)) {// Fetch metadata only to evaluate preconditions, avoiding loading the full object unnecessarily.S3Object metadata = s3Service.headObject(bucket, key, versionId);@@ -647,7 +693,7 @@ public class S3Controller {ResponseHeaderOverrides overrides = new ResponseHeaderOverrides(responseContentType, responseContentLanguage, responseExpires,responseCacheControl, responseContentDisposition, responseContentEncoding);- if (overrides.hasAny() && !isSigned(httpHeaders, uriInfo)) {+ if (overrides.hasAny() && !S3RequestAuthorizationParser.isSigned(httpHeaders, uriInfo)) {return xmlErrorResponse(new AwsException("InvalidRequest","Request specific response headers cannot be used for anonymous GET requests.", 400));}@@ -658,12 +704,17 @@ public class S3Controller {return fullObjectResponse(bucket, key, versionId, obj, overrides);} catch (AwsException e) {- if ("NoSuchKey".equals(e.getErrorCode()) && isWebsiteRequest(httpHeaders)) {+ if (isWebsiteErrorDocumentTrigger(e) && isWebsiteRequest(httpHeaders)) {try {WebsiteConfiguration webConfig = s3Service.getBucketWebsite(bucket);- Response r = serveErrorDocument(bucket, webConfig);- if (r != null) return r;- } catch (AwsException ignored) {+ Response r = serveErrorDocument(bucket, webConfig, authorization, e.getHttpStatus());+ if (r != null) {+ return r;+ }+ } catch (AwsException websiteException) {+ if (!"NoSuchWebsiteConfiguration".equals(websiteException.getErrorCode())) {+ return xmlErrorResponse(websiteException);+ }}}return xmlErrorResponse(e);@@ -801,6 +852,10 @@ public class S3Controller {@Context HttpHeaders httpHeaders) {try {key = extractObjectKey(uriInfo, bucket);+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);+ s3Service.authorizeGetObject(bucket, key, versionId, authorization);+S3Object obj = s3Service.headObject(bucket, key, versionId);S3Service.validateSseCustomerAccess(obj,@@ -814,7 +869,7 @@ public class S3Controller {ResponseHeaderOverrides overrides = new ResponseHeaderOverrides(responseContentType, responseContentLanguage, responseExpires,responseCacheControl, responseContentDisposition, responseContentEncoding);- if (overrides.hasAny() && !isSigned(httpHeaders, uriInfo)) {+ if (overrides.hasAny() && !S3RequestAuthorizationParser.isSigned(httpHeaders, uriInfo)) {return xmlErrorResponse(new AwsException("InvalidRequest","Request specific response headers cannot be used for anonymous GET requests.", 400));}@@ -1010,6 +1065,9 @@ public class S3Controller {}if (hasQueryParam(uriInfo, "select")) {+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);+ s3Service.authorizeGetObject(bucket, key, versionId, authorization);S3Object obj = s3Service.getObject(bucket, key, versionId);byte[] result = s3SelectService.select(obj, new String(body, StandardCharsets.UTF_8));return Response.ok(result)@@ -2035,29 +2093,56 @@ public class S3Controller {return host != null && host.contains("s3-website");}- private Response serveErrorDocument(String bucket, WebsiteConfiguration cfg) {+ private Response serveErrorDocument(String bucket, WebsiteConfiguration cfg,+ S3Service.RequestAuthorization authorization, int status) {if (cfg.getErrorDocument() == null) {return null;}+ int responseStatus = status == 403 ? 403 : 404;try {+ s3Service.authorizeGetObject(bucket, cfg.getErrorDocument(), null, authorization);S3Object err = s3Service.getObject(bucket, cfg.getErrorDocument());- return Response.status(404)+ return Response.status(responseStatus).entity(err.getData()).type(err.getContentType()).header("Content-Length", err.getSize())- .header("x-amz-error-code", "NoSuchKey")- .header("x-amz-error-message", "The specified key does not exist.")+ .header("x-amz-error-code", websiteErrorCode(responseStatus))+ .header("x-amz-error-message", websiteErrorMessage(responseStatus)).build();- } catch (AwsException ignored) {- return Response.status(404)- .entity("<html><head><title>404 Not Found</title></head>\n<body><h1>404 Not Found</h1>\n<ul><li>Code: NoSuchKey</li><li>Message: The specified key does not exist.</li></ul></body></html>")+ } catch (AwsException e) {+ if (!isWebsiteErrorDocumentTrigger(e)) {+ throw e;+ }+ return Response.status(responseStatus)+ .entity(defaultWebsiteErrorBody(responseStatus)).type(MediaType.TEXT_HTML)- .header("x-amz-error-code", "NoSuchKey")- .header("x-amz-error-message", "The specified key does not exist.")+ .header("x-amz-error-code", websiteErrorCode(responseStatus))+ .header("x-amz-error-message", websiteErrorMessage(responseStatus)).build();}}+ private static boolean isWebsiteErrorDocumentTrigger(AwsException e) {+ return "NoSuchKey".equals(e.getErrorCode()) || "AccessDenied".equals(e.getErrorCode());+ }++ private static String websiteErrorCode(int status) {+ return status == 403 ? "AccessDenied" : "NoSuchKey";+ }++ private static String websiteErrorMessage(int status) {+ return status == 403 ? "Access Denied" : "The specified key does not exist.";+ }++ private static String defaultWebsiteErrorBody(int status) {+ String title = status + (status == 403 ? " Forbidden" : " Not Found");+ String code = websiteErrorCode(status);+ String message = websiteErrorMessage(status);+ return "<html><head><title>" + title + "</title></head>\n"+ + "<body><h1>" + title + "</h1>\n"+ + "<ul><li>Code: " + code + "</li><li>Message: " + message + "</li></ul></body></html>";+ }+private Response xmlErrorResponse(AwsException e) {String condition = e instanceof S3PreconditionFailedException preconditionFailedException? preconditionFailedException.condition()@@ -2138,13 +2223,8 @@ public class S3Controller {return null;}- private static boolean isSigned(HttpHeaders httpHeaders, UriInfo uriInfo) {- return httpHeaders.getHeaderString("Authorization") != null- || uriInfo.getQueryParameters().containsKey("X-Amz-Algorithm");- }-private boolean hasPreconditions(String ifMatch, String ifNoneMatch,- String ifModifiedSince, String ifUnmodifiedSince) {+ String ifModifiedSince, String ifUnmodifiedSince) {return ifMatch != null || ifNoneMatch != null || ifModifiedSince != null || ifUnmodifiedSince != null;}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.javanew file mode 100644index 0000000000..cca1fcbe07--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java@@ -0,0 +1,182 @@+package io.github.hectorvent.floci.services.s3;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;+import org.jboss.logging.Logger;++import java.util.Iterator;+import java.util.List;++final class S3PublicAccessEvaluator {++ private static final Logger LOG = Logger.getLogger(S3PublicAccessEvaluator.class);++ enum PublicAccessDecision {+ ALLOW,+ DENY,+ NEUTRAL+ }++ private S3PublicAccessEvaluator() {+ }++ static boolean publicPolicyAllows(ObjectMapper objectMapper, String policy, String action, String resourceArn) {+ return publicPolicyDecision(objectMapper, policy, action, resourceArn) == PublicAccessDecision.ALLOW;+ }++ static PublicAccessDecision publicPolicyDecision(ObjectMapper objectMapper, String policy, String action, String resourceArn) {+ if (policy == null || policy.isBlank()) {+ return PublicAccessDecision.NEUTRAL;+ }+ try {+ JsonNode statements = objectMapper.readTree(policy).path("Statement");+ boolean allowed = false;+ Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);+ for (JsonNode statement : iterable) {+ String effect = statement.path("Effect").asText("");+ if (!"Allow".equalsIgnoreCase(effect) && !"Deny".equalsIgnoreCase(effect)) {+ continue;+ }+ if (!statementMatchesPublicPrincipalActionResource(statement, action, resourceArn)) {+ continue;+ }+ if ("Deny".equalsIgnoreCase(effect)) {+ return PublicAccessDecision.DENY;+ }+ if (statement.hasNonNull("Condition")) {+ continue;+ }+ allowed = true;+ }+ return allowed ? PublicAccessDecision.ALLOW : PublicAccessDecision.NEUTRAL;+ } catch (JsonProcessingException e) {+ LOG.debugv("Failed to evaluate S3 bucket policy for public access: {0}", e.getMessage());+ return PublicAccessDecision.NEUTRAL;+ }+ }++ static String bucketArn(String bucketName) {+ return "arn:aws:s3:::" + bucketName;+ }++ static String objectArn(String bucketName, String key) {+ return bucketArn(bucketName) + "/" + key;+ }++ private static boolean statementMatchesPublicPrincipalActionResource(JsonNode statement, String action, String resourceArn) {+ return principalMatchesPublic(statement)+ && actionMatches(statement, action)+ && resourceMatches(statement, resourceArn);+ }++ private static boolean principalMatchesPublic(JsonNode statement) {+ if (statement.hasNonNull("Principal")) {+ return hasPublicPrincipal(statement.path("Principal"));+ }+ if (statement.hasNonNull("NotPrincipal")) {+ return !hasPublicPrincipal(statement.path("NotPrincipal"));+ }+ return false;+ }++ private static boolean actionMatches(JsonNode statement, String action) {+ if (statement.hasNonNull("Action")) {+ return nodeMatches(statement.get("Action"), action);+ }+ if (statement.hasNonNull("NotAction")) {+ JsonNode notAction = statement.get("NotAction");+ return nodeCanMatch(notAction) && !nodeMatches(notAction, action);+ }+ return false;+ }++ private static boolean resourceMatches(JsonNode statement, String resourceArn) {+ if (statement.hasNonNull("Resource")) {+ return nodeMatches(statement.get("Resource"), resourceArn);+ }+ if (statement.hasNonNull("NotResource")) {+ JsonNode notResource = statement.get("NotResource");+ return nodeCanMatch(notResource) && !nodeMatches(notResource, resourceArn);+ }+ return false;+ }++ private static boolean hasPublicPrincipal(JsonNode principal) {+ if (principal == null || principal.isMissingNode() || principal.isNull()) {+ return false;+ }+ if (principal.isTextual()) {+ return "*".equals(principal.asText());+ }+ if (principal.isArray()) {+ for (JsonNode item : principal) {+ if ("*".equals(item.asText())) {+ return true;+ }+ }+ return false;+ }+ if (principal.isObject()) {+ Iterator<JsonNode> values = principal.elements();+ while (values.hasNext()) {+ if (nodeContainsPublicPrincipal(values.next())) {+ return true;+ }+ }+ }+ return false;+ }++ private static boolean nodeContainsPublicPrincipal(JsonNode node) {+ if (node == null || node.isNull()) {+ return false;+ }+ if (node.isTextual()) {+ return "*".equals(node.asText());+ }+ if (node.isArray()) {+ for (JsonNode item : node) {+ if ("*".equals(item.asText())) {+ return true;+ }+ }+ }+ return false;+ }++ private static boolean nodeCanMatch(JsonNode node) {+ if (node == null || node.isNull()) {+ return false;+ }+ if (node.isTextual()) {+ return true;+ }+ if (node.isArray()) {+ for (JsonNode item : node) {+ if (item.isTextual()) {+ return true;+ }+ }+ }+ return false;+ }++ private static boolean nodeMatches(JsonNode node, String value) {+ if (node == null || node.isNull()) {+ return false;+ }+ if (node.isTextual()) {+ return IamPolicyEvaluator.globMatches(node.asText(), value);+ }+ if (node.isArray()) {+ for (JsonNode item : node) {+ if (item.isTextual() && IamPolicyEvaluator.globMatches(item.asText(), value)) {+ return true;+ }+ }+ }+ return false;+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParser.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParser.javanew file mode 100644index 0000000000..82bd215125--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParser.java@@ -0,0 +1,162 @@+package io.github.hectorvent.floci.services.s3;++import io.github.hectorvent.floci.core.common.AwsException;+import jakarta.ws.rs.core.HttpHeaders;+import jakarta.ws.rs.core.MultivaluedMap;+import jakarta.ws.rs.core.UriInfo;++import java.util.LinkedHashMap;+import java.util.Map;+import java.util.Set;++final class S3RequestAuthorizationParser {++ private static final String SIGV4_ALGORITHM = "AWS4-HMAC-SHA256";+ static final String AUTHORIZATION_QUERY_PARAMETERS_ERROR_CODE = "AuthorizationQueryParametersError";+ static final String AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE =+ "Query-string authentication version 4 requires the X-Amz-Algorithm, "+ + "X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, "+ + "and X-Amz-Expires parameters.";+ static final int AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS = 400;++ private static final Set<String> REQUIRED_PRESIGNED_PARAMETERS = Set.of(+ "X-Amz-Algorithm",+ "X-Amz-Credential",+ "X-Amz-Date",+ "X-Amz-Expires",+ "X-Amz-SignedHeaders",+ "X-Amz-Signature");++ private S3RequestAuthorizationParser() {+ }++ static boolean isSigned(HttpHeaders httpHeaders, UriInfo uriInfo) {+ return isSigned(httpHeaders.getHeaderString("Authorization"), uriInfo.getQueryParameters());+ }++ static boolean isSigned(String authorization, MultivaluedMap<String, String> queryParameters) {+ return (authorization != null && !authorization.isBlank())+ || queryParameters.containsKey("X-Amz-Algorithm");+ }++ static S3Service.RequestAuthorization parseIfRequired(+ boolean enforceAuth, HttpHeaders httpHeaders, UriInfo uriInfo) {+ if (!enforceAuth) {+ return S3Service.RequestAuthorization.unsigned();+ }+ return parse(httpHeaders, uriInfo);+ }++ static S3Service.RequestAuthorization parseIfRequired(+ boolean enforceAuth, String authorization, MultivaluedMap<String, String> queryParameters) {+ if (!enforceAuth) {+ return S3Service.RequestAuthorization.unsigned();+ }+ return parse(authorization, queryParameters);+ }++ static S3Service.RequestAuthorization parse(HttpHeaders httpHeaders, UriInfo uriInfo) {+ return parse(httpHeaders.getHeaderString("Authorization"), uriInfo.getQueryParameters());+ }++ static S3Service.RequestAuthorization parse(String authorization, MultivaluedMap<String, String> queryParameters) {+ if (authorization != null && !authorization.isBlank()) {+ String accessKeyId = extractAuthorizationHeaderAccessKeyId(authorization);+ if (accessKeyId == null) {+ // Only SigV4 is parsed; unsupported schemes are reported as malformed auth.+ String message = "The authorization header is malformed; the credential scope is invalid.";+ throw new AwsException("AuthorizationHeaderMalformed", message, 400);+ }+ return new S3Service.RequestAuthorization(true, accessKeyId);+ }++ if (queryParameters.containsKey("X-Amz-Algorithm")) {+ String accessKeyId = extractPresignedAccessKeyId(queryParameters);+ if (accessKeyId == null) {+ throw new AwsException(AUTHORIZATION_QUERY_PARAMETERS_ERROR_CODE,+ AUTHORIZATION_QUERY_PARAMETERS_ERROR_MESSAGE,+ AUTHORIZATION_QUERY_PARAMETERS_ERROR_STATUS);+ }+ return new S3Service.RequestAuthorization(true, accessKeyId);+ }++ return S3Service.RequestAuthorization.unsigned();+ }++ private static String extractAuthorizationHeaderAccessKeyId(String authorization) {+ String trimmed = authorization.trim();+ if (!trimmed.startsWith(SIGV4_ALGORITHM + " ")) {+ return null;+ }++ Map<String, String> parameters = authorizationParameters(trimmed.substring(SIGV4_ALGORITHM.length()).trim());+ if (isBlank(parameters.get("SignedHeaders")) || isBlank(parameters.get("Signature"))) {+ return null;+ }+ return extractCredentialAccessKeyId(parameters.get("Credential"));+ }++ private static String extractPresignedAccessKeyId(MultivaluedMap<String, String> queryParameters) {+ if (!SIGV4_ALGORITHM.equals(queryParameters.getFirst("X-Amz-Algorithm"))) {+ return null;+ }+ if (isMissingRequiredPresignedParameter(queryParameters)) {+ return null;+ }+ return extractCredentialAccessKeyId(queryParameters.getFirst("X-Amz-Credential"));+ }++ static boolean isMissingRequiredPresignedParameter(MultivaluedMap<String, String> queryParameters) {+ for (String parameter : REQUIRED_PRESIGNED_PARAMETERS) {+ if (isBlank(queryParameters.getFirst(parameter))) {+ return true;+ }+ }+ return false;+ }++ private static Map<String, String> authorizationParameters(String parameters) {+ Map<String, String> parsed = new LinkedHashMap<>();+ for (String part : parameters.split(",")) {+ int equals = part.indexOf('=');+ if (equals <= 0) {+ continue;+ }+ parsed.put(part.substring(0, equals).trim(), part.substring(equals + 1).trim());+ }+ return parsed;+ }++ private static String extractCredentialAccessKeyId(String credential) {+ if (isBlank(credential)) {+ return null;+ }+ String[] parts = credential.split("/", -1);+ if (parts.length != 5) {+ return null;+ }+ if (parts[0].isBlank() || !isEightDigitDate(parts[1]) || parts[2].isBlank()) {+ return null;+ }+ if (!"s3".equals(parts[3]) || !"aws4_request".equals(parts[4])) {+ return null;+ }+ return parts[0];+ }++ private static boolean isEightDigitDate(String value) {+ if (value.length() != 8) {+ return false;+ }+ for (int index = 0; index < value.length(); index++) {+ if (!Character.isDigit(value.charAt(index))) {+ return false;+ }+ }+ return true;+ }++ private static boolean isBlank(String value) {+ return value == null || value.isBlank();+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.javaindex 2b0d454954..c60cc0f03d 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java@@ -10,6 +10,7 @@ import io.github.hectorvent.floci.core.common.XmlParser;import io.github.hectorvent.floci.core.common.Resettable;import io.github.hectorvent.floci.core.storage.StorageBackend;import io.github.hectorvent.floci.core.storage.StorageFactory;+import io.github.hectorvent.floci.services.iam.IamService;import io.github.hectorvent.floci.services.lambda.LambdaService;import io.github.hectorvent.floci.services.lambda.model.InvocationType;import io.github.hectorvent.floci.services.s3.model.*;@@ -44,8 +45,8 @@ import java.util.concurrent.ConcurrentHashMap;public class S3Service implements Resettable {private String ownerId() { return regionResolver != null ? regionResolver.getAccountId() : "000000000000"; }private static final String DEFAULT_OWNER_DISPLAY_NAME = "floci";- private static final String ALL_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AllUsers";private static final String AUTHENTICATED_USERS_GROUP_URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";+ private static final String LEGACY_ACCESS_KEY_ID = "test";private static final Set<String> SUPPORTED_SERVER_SIDE_ENCRYPTION_VALUES = Set.of("AES256", "aws:kms", "aws:kms:dsse", "aws:fsx");private static final String SSE_C_ALGORITHM = "AES256";private static final int SSE_C_KEY_BYTES = 32;@@ -57,6 +58,12 @@ public class S3Service implements Resettable {private static final Logger LOG = Logger.getLogger(S3Service.class);+ record RequestAuthorization(boolean signed, String accessKeyId) {+ static RequestAuthorization unsigned() {+ return new RequestAuthorization(false, null);+ }+ }+private final StorageBackend<String, Bucket> bucketStore;private final StorageBackend<String, S3Object> objectStore;private final Path dataRoot;@@ -75,6 +82,8 @@ public class S3Service implements Resettable {private final RegionResolver regionResolver;private final String baseUrl;private final ObjectMapper objectMapper;+ private final boolean enforceAuth;+ private final IamService iamService;@Injectpublic S3Service(StorageFactory storageFactory, EmulatorConfig config,@@ -83,7 +92,8 @@ public class S3Service implements Resettable {EventBridgeService eventBridgeService,Event<S3ObjectUpdatedEvent> s3UpdatedEvent,RegionResolver regionResolver,- ObjectMapper objectMapper) {+ ObjectMapper objectMapper,+ IamService iamService) {this(storageFactory.create("s3", "s3-buckets.json",new TypeReference<Map<String, Bucket>>() {@@ -96,7 +106,8 @@ public class S3Service implements Resettable {sqsService, snsService, null, lambdaServiceProvider, null,eventBridgeService, s3UpdatedEvent,regionResolver,- config.effectiveBaseUrl(), objectMapper+ config.effectiveBaseUrl(), objectMapper,+ config.services().s3().enforceAuth(), iamService);}@@ -107,7 +118,7 @@ public class S3Service implements Resettable {StorageBackend<String, S3Object> objectStore,Path dataRoot, boolean inMemory) {this(bucketStore, objectStore, dataRoot, inMemory, null, null, null, null, null, null, null,- null, "http://localhost:4566", new ObjectMapper());+ null, "http://localhost:4566", new ObjectMapper(), false, null);}S3Service(StorageBackend<String, Bucket> bucketStore,@@ -116,7 +127,7 @@ public class S3Service implements Resettable {LambdaService lambdaService,RegionResolver regionResolver) {this(bucketStore, objectStore, dataRoot, inMemory, null, null, lambdaService, null, null, null, null,- regionResolver, "http://localhost:4566", new ObjectMapper());+ regionResolver, "http://localhost:4566", new ObjectMapper(), false, null);}S3Service(StorageBackend<String, Bucket> bucketStore,@@ -125,7 +136,7 @@ public class S3Service implements Resettable {LambdaInvoker lambdaInvoker,RegionResolver regionResolver) {this(bucketStore, objectStore, dataRoot, inMemory, null, null, null, null, lambdaInvoker, null, null,- regionResolver, "http://localhost:4566", new ObjectMapper());+ regionResolver, "http://localhost:4566", new ObjectMapper(), false, null);}private S3Service(StorageBackend<String, Bucket> bucketStore,@@ -136,7 +147,8 @@ public class S3Service implements Resettable {LambdaInvoker lambdaInvoker,EventBridgeService eventBridgeService,Event<S3ObjectUpdatedEvent> s3UpdatedEvent,- RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper) {+ RegionResolver regionResolver, String baseUrl, ObjectMapper objectMapper,+ boolean enforceAuth, IamService iamService) {this.bucketStore = bucketStore;this.objectStore = objectStore;this.dataRoot = dataRoot;@@ -151,6 +163,8 @@ public class S3Service implements Resettable {this.regionResolver = regionResolver;this.baseUrl = baseUrl;this.objectMapper = objectMapper;+ this.enforceAuth = enforceAuth;+ this.iamService = iamService;if (!inMemory) {try {Files.createDirectories(dataRoot);@@ -458,6 +472,115 @@ public class S3Service implements Resettable {return normalized;}+ public void authorizeListBucket(String bucketName, RequestAuthorization authorization) {+ authorizeBucketRead(bucketName, "s3:ListBucket", authorization);+ }++ public void authorizeGetObject(String bucketName, String key, String versionId, RequestAuthorization authorization) {+ String action = versionId != null ? "s3:GetObjectVersion" : "s3:GetObject";+ if (enforceAuth && versionId == null && isUnsignedRequest(authorization) && !readableObjectExists(bucketName, key)) {+ authorizeMissingObjectRead(bucketName, authorization);+ return;+ }+ authorizeObjectRead(bucketName, key, versionId, action, authorization);+ }++ void authorizeBucketRead(String bucketName, String action, RequestAuthorization authorization) {+ String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName);+ authorizeS3Read(bucketName, null, null, action, bucketArn, authorization);+ }++ void authorizeObjectRead(String bucketName, String key, String versionId, String action, RequestAuthorization authorization) {+ String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key);+ authorizeS3Read(bucketName, key, versionId, action, objectArn, authorization);+ }++ boolean isAuthEnforced() {+ return enforceAuth;+ }++ private void authorizeS3Read(String bucketName, String key, String versionId, String action, String resourceArn, RequestAuthorization authorization) {+ if (!enforceAuth) {+ return;+ }++ RequestAuthorization requestAuthorization = authorization != null+ ? authorization+ : RequestAuthorization.unsigned();++ if (requestAuthorization.signed()) {+ if (isKnownAccessKey(requestAuthorization.accessKeyId())) {+ return;+ }+ throw new AwsException("InvalidAccessKeyId",+ "The AWS Access Key Id you provided does not exist in our records.", 403);+ }++ Bucket bucket = bucketStore.get(bucketName)+ .orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));++ S3PublicAccessEvaluator.PublicAccessDecision policyDecision =+ S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, resourceArn);+ if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {+ throw new AwsException("AccessDenied", "Access Denied", 403);+ }+ if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {+ return;+ }+ if (key != null && isObjectDataReadAction(action) && publicObjectAclAllowsRead(bucketName, key, versionId)) {+ return;+ }+ if (key == null && "s3:ListBucket".equals(action) && publicBucketAclAllowsRead(bucket)) {+ return;+ }++ throw new AwsException("AccessDenied", "Access Denied", 403);+ }++ private boolean readableObjectExists(String bucketName, String key) {+ ensureBucketExists(bucketName);+ return objectStore.get(objectKey(bucketName, key))+ .filter(object -> !object.isDeleteMarker())+ .isPresent();+ }++ private void authorizeMissingObjectRead(String bucketName, RequestAuthorization authorization) {+ authorizeListBucket(bucketName, authorization);+ }++ private static boolean isObjectDataReadAction(String action) {+ return "s3:GetObject".equals(action) || "s3:GetObjectVersion".equals(action);+ }++ private static boolean isUnsignedRequest(RequestAuthorization authorization) {+ return authorization == null || !authorization.signed();+ }++ private boolean isKnownAccessKey(String accessKeyId) {+ if (accessKeyId == null || accessKeyId.isBlank()) {+ return false;+ }+ if (LEGACY_ACCESS_KEY_ID.equals(accessKeyId)) {+ return true;+ }+ return iamService != null && iamService.findSecretKey(accessKeyId).isPresent();+ }++ private boolean publicBucketAclAllowsRead(Bucket bucket) {+ return Optional.ofNullable(bucket.getAcl())+ .map(S3AclPublicAccessEvaluator::aclAllowsPublicRead)+ .orElse(false);+ }++ private boolean publicObjectAclAllowsRead(String bucketName, String key, String versionId) {+ String storeKey = versionId != null ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);+ return objectStore.get(storeKey)+ .filter(object -> !object.isDeleteMarker())+ .map(S3Object::getAcl)+ .map(S3AclPublicAccessEvaluator::aclAllowsPublicRead)+ .orElse(false);+ }+private void applyObjectLock(S3Object object, Bucket bucket,String objectLockMode, Instant retainUntilDate, String legalHoldStatus) {if (objectLockMode != null) {@@ -1784,11 +1907,11 @@ public class S3Service implements Resettable {case "aws-exec-read" -> defaultAclXml(ownerId(), DEFAULT_OWNER_DISPLAY_NAME);case "public-read" -> objectAclXml(ownerFullControlGrant(),- groupGrant(ALL_USERS_GROUP_URI, "READ"));+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"));case "public-read-write" -> objectAclXml(ownerFullControlGrant(),- groupGrant(ALL_USERS_GROUP_URI, "READ"),- groupGrant(ALL_USERS_GROUP_URI, "WRITE"));+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"),+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "WRITE"));case "authenticated-read" -> objectAclXml(ownerFullControlGrant(),groupGrant(AUTHENTICATED_USERS_GROUP_URI, "READ"));diff --git a/src/main/resources/application.yml b/src/main/resources/application.ymlindex 243c02f003..efbfe8df00 100644--- a/src/main/resources/application.yml+++ b/src/main/resources/application.yml@@ -198,6 +198,7 @@ floci:clear-fifo-deduplication-cache-on-purge: falses3:enabled: true+ enforce-auth: falsedefault-presign-expiry-seconds: 3600dynamodb:enabled: truediff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPolicyTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPolicyTest.javanew file mode 100644index 0000000000..ef0912f8d3--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPolicyTest.java@@ -0,0 +1,115 @@+package io.github.hectorvent.floci.services.s3;++import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class S3AclPolicyTest {++ @Test+ void parsesGrantFromAccessControlList() {+ S3AclPolicy policy = parse(acl(groupGrant(S3AclPolicy.ALL_USERS_GROUP_URI, "READ")));++ assertEquals(1, policy.grants().size());+ S3AclPolicy.Grant grant = policy.grants().getFirst();+ assertEquals(S3AclPolicy.ALL_USERS_GROUP_URI, grant.grantee().uri());+ assertEquals(S3AclPolicy.Permission.READ, grant.permission());+ assertTrue(grant.allowsPublicRead());+ }++ @Test+ void parsesNamespacedAcl() {+ String grant = groupGrant(S3AclPolicy.ALL_USERS_GROUP_URI, "FULL_CONTROL");+ S3AclPolicy policy = parse("""+ <AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <AccessControlList>+ %s+ </AccessControlList>+ </AccessControlPolicy>+ """.formatted(grant));++ assertEquals(1, policy.grants().size());+ assertEquals(S3AclPolicy.Permission.FULL_CONTROL, policy.grants().getFirst().permission());+ assertTrue(policy.grants().getFirst().allowsPublicRead());+ }++ @Test+ void ignoresGrantOutsideAccessControlList() {+ String grant = groupGrant(S3AclPolicy.ALL_USERS_GROUP_URI, "READ");+ S3AclPolicy policy = parse("""+ <AccessControlPolicy>+ <AccessControlList/>+ <Metadata>+ %s+ </Metadata>+ </AccessControlPolicy>+ """.formatted(grant));++ assertTrue(policy.grants().isEmpty());+ }++ @Test+ void returnsEmptyPolicyForUnsupportedShape() {+ assertTrue(parse("<NotAnAcl/>").grants().isEmpty());+ assertTrue(parse("<AccessControlPolicy/>").grants().isEmpty());+ }++ @Test+ void mapsUnknownPermission() {+ S3AclPolicy policy = parse(acl(groupGrant(S3AclPolicy.ALL_USERS_GROUP_URI, "DELETE")));++ assertEquals(S3AclPolicy.Permission.UNKNOWN, policy.grants().getFirst().permission());+ }++ @Test+ void rejectsMalformedAcl() {+ assertInvalidAcl("<AccessControlPolicy>");+ }++ @Test+ void rejectsDoctype() {+ assertInvalidAcl("""+ <!DOCTYPE AccessControlPolicy [+ <!ENTITY external SYSTEM "file:///etc/passwd">+ ]>+ <AccessControlPolicy>+ <AccessControlList/>+ </AccessControlPolicy>+ """);+ }++ private static void assertInvalidAcl(String acl) {+ assertThrows(S3AclPolicy.AclParseException.class, () -> S3AclPolicy.parse(acl));+ }++ private static S3AclPolicy parse(String acl) {+ try {+ return S3AclPolicy.parse(acl);+ } catch (S3AclPolicy.AclParseException e) {+ throw new AssertionError(e);+ }+ }++ private static String acl(String... grants) {+ return """+ <AccessControlPolicy>+ <AccessControlList>+ %s+ </AccessControlList>+ </AccessControlPolicy>+ """.formatted(String.join("\n", grants));+ }++ private static String groupGrant(String groupUri, String permission) {+ return """+ <Grant>+ <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">+ <URI>%s</URI>+ </Grantee>+ <Permission>%s</Permission>+ </Grant>+ """.formatted(groupUri, permission);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.javanew file mode 100644index 0000000000..6139978717--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.java@@ -0,0 +1,106 @@+package io.github.hectorvent.floci.services.s3;++import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++class S3AclPublicAccessEvaluatorTest {++ private static final String AUTHENTICATED_USERS_GROUP_URI =+ "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";++ @Test+ void allUsersReadAclAllowsPublicRead() {+ assertTrue(S3AclPublicAccessEvaluator.aclAllowsPublicRead(acl(+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"))));+ }++ @Test+ void allUsersFullControlAclAllowsPublicRead() {+ assertTrue(S3AclPublicAccessEvaluator.aclAllowsPublicRead(acl(+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "FULL_CONTROL"))));+ }++ @Test+ void allUsersWriteAclDoesNotAllowPublicRead() {+ assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead(acl(+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "WRITE"))));+ }++ @Test+ void authenticatedUsersReadAclDoesNotAllowPublicRead() {+ assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead(acl(+ groupGrant(AUTHENTICATED_USERS_GROUP_URI, "READ"))));+ }++ @Test+ void grantsDoNotCombineAcrossAclEntries() {+ String acl = acl(+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "WRITE"),+ groupGrant(AUTHENTICATED_USERS_GROUP_URI, "READ"));++ assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead(acl));+ }++ @Test+ void grantsOutsideAccessControlListDoNotAllowPublicRead() {+ String acl = """+ <AccessControlPolicy>+ <AccessControlList>+ </AccessControlList>+ <Metadata>+ %s+ </Metadata>+ </AccessControlPolicy>+ """.formatted(groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"));++ assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead(acl));+ }++ @Test+ void namespaceAttributesDoNotBlockPublicReadAcl() {+ String acl = """+ <AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <AccessControlList>+ <Grant>+ <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">+ <URI>%s</URI>+ </Grantee>+ <Permission>READ</Permission>+ </Grant>+ </AccessControlList>+ </AccessControlPolicy>+ """.formatted(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI);++ assertTrue(S3AclPublicAccessEvaluator.aclAllowsPublicRead(acl));+ }++ @Test+ void invalidAclDoesNotAllowPublicRead() {+ assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead(null));+ assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead(""));+ assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead("<AccessControlPolicy>"));+ }++ private static String acl(String... grants) {+ return """+ <AccessControlPolicy>+ <AccessControlList>+ %s+ </AccessControlList>+ </AccessControlPolicy>+ """.formatted(String.join("\n", grants));+ }++ private static String groupGrant(String groupUri, String permission) {+ return """+ <Grant>+ <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">+ <URI>%s</URI>+ </Grantee>+ <Permission>%s</Permission>+ </Grant>+ """.formatted(groupUri, permission);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.javanew file mode 100644index 0000000000..b908b8dfac--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AuthEnforcementIntegrationTest.java@@ -0,0 +1,666 @@+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.MethodOrderer;+import org.junit.jupiter.api.Order;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.TestMethodOrder;++import java.time.Instant;+import java.time.ZoneOffset;+import java.time.format.DateTimeFormatter;+import java.util.Map;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;++@QuarkusTest+@TestProfile(S3AuthEnforcementIntegrationTest.S3AuthProfile.class)+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class S3AuthEnforcementIntegrationTest {++ private static final String PUBLIC_BUCKET = "auth-public-bucket";+ private static final String PRIVATE_BUCKET = "auth-private-bucket";+ private static final String WEBSITE_BUCKET = "auth-website-bucket";+ private static final String WEBSITE_ERROR_BUCKET = "auth-website-error-bucket";+ private static final String BUCKET_ACL_BUCKET = "auth-bucket-acl-bucket";+ private static final String DENY_BUCKET = "auth-deny-bucket";+ private static final String GET_ONLY_BUCKET = "auth-get-only-bucket";+ private static final String VERSION_BUCKET = "auth-version-bucket";+ private static final String PUBLIC_KEY = "public.txt";+ private static final String PRIVATE_KEY = "private.txt";+ private static final String ERROR_KEY = "error.html";+ private static final String ACL_KEY = "acl-list.txt";+ private static final String DENY_KEY = "deny.txt";+ private static final String VERSION_KEY = "versioned.txt";+ private static final String SIGNING_TIMESTAMP = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")+ .withZone(ZoneOffset.UTC)+ .format(Instant.now());+ private static final String SIGNING_DATE = SIGNING_TIMESTAMP.substring(0, 8);+ private static final String LOCAL_AUTH_HEADER = authorizationHeader("test");+ private static final String BAD_AUTH_HEADER = authorizationHeader("bad-key");+ private static final String ACCOUNT_SHAPED_AUTH_HEADER = authorizationHeader("123456789012");++ @Test+ @Order(1)+ void createBucketsAndObjects() {+ given().when().put("/" + PUBLIC_BUCKET).then().statusCode(200);+ given().when().put("/" + PRIVATE_BUCKET).then().statusCode(200);++ given()+ .body("public body")+ .when()+ .put("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY)+ .then()+ .statusCode(200);++ given()+ .body("private body")+ .when()+ .put("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY)+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(publicReadPolicy(PUBLIC_BUCKET))+ .when()+ .put("/" + PUBLIC_BUCKET + "?policy")+ .then()+ .statusCode(200);+ }++ @Test+ @Order(2)+ void unsignedRequestCanReadPublicObject() {+ given()+ .when()+ .get("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY)+ .then()+ .statusCode(200)+ .body(equalTo("public body"));++ given()+ .when()+ .head("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY)+ .then()+ .statusCode(200);+ }++ @Test+ @Order(3)+ void unsignedRequestCanListPublicBucket() {+ given()+ .when()+ .get("/" + PUBLIC_BUCKET + "?list-type=2")+ .then()+ .statusCode(200)+ .body(containsString("<Key>" + PUBLIC_KEY + "</Key>"));+ }++ @Test+ @Order(4)+ void unsignedRequestCannotReadPrivateObject() {+ given()+ .when()+ .get("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));++ given()+ .when()+ .head("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY)+ .then()+ .statusCode(403);+ }++ @Test+ @Order(5)+ void unsignedRequestCannotListPrivateBucket() {+ given()+ .when()+ .get("/" + PRIVATE_BUCKET + "?list-type=2")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ @Test+ @Order(6)+ void signedRequestWithBadAccessKeyCannotUsePublicAccess() {+ given()+ .header("Authorization", BAD_AUTH_HEADER)+ .when()+ .get("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY)+ .then()+ .statusCode(403)+ .body(containsString("InvalidAccessKeyId"));+ }++ @Test+ @Order(7)+ void signedRequestWithAccountShapedAccessKeyCannotReadPrivateObject() {+ given()+ .header("Authorization", ACCOUNT_SHAPED_AUTH_HEADER)+ .when()+ .get("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY)+ .then()+ .statusCode(403)+ .body(containsString("InvalidAccessKeyId"));+ }++ @Test+ @Order(8)+ void presignedRequestWithBadAccessKeyCannotUsePublicAccess() {+ given()+ .queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")+ .queryParam("X-Amz-Credential", credential("bad-key"))+ .queryParam("X-Amz-Date", SIGNING_TIMESTAMP)+ .queryParam("X-Amz-Expires", "3600")+ .queryParam("X-Amz-SignedHeaders", "host")+ .queryParam("X-Amz-Signature", "test")+ .when()+ .get("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY)+ .then()+ .statusCode(403)+ .body(containsString("InvalidAccessKeyId"));+ }++ @Test+ @Order(9)+ void malformedPresignedRequestCannotUsePublicAccess() {+ given()+ .queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")+ .when()+ .get("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY)+ .then()+ .statusCode(400)+ .body("Error.Code", equalTo("AuthorizationQueryParametersError"))+ .body(containsString("Query-string authentication version 4 requires the X-Amz-Algorithm"));+ }++ @Test+ @Order(10)+ void signedRequestWithLocalAccessKeyCanReadPrivateObject() {+ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .get("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY)+ .then()+ .statusCode(200)+ .body(equalTo("private body"));+ }++ @Test+ @Order(11)+ void presignedRequestWithLocalAccessKeyCanReadPrivateObject() {+ given()+ .queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")+ .queryParam("X-Amz-Credential", credential("test"))+ .queryParam("X-Amz-Date", SIGNING_TIMESTAMP)+ .queryParam("X-Amz-Expires", "3600")+ .queryParam("X-Amz-SignedHeaders", "host")+ .queryParam("X-Amz-Signature", "test")+ .when()+ .get("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY)+ .then()+ .statusCode(200)+ .body(equalTo("private body"));+ }++ @Test+ @Order(12)+ void websiteRootAuthorizesIndexObjectReadNotBucketList() {+ given().when().put("/" + WEBSITE_BUCKET).then().statusCode(200);++ given()+ .contentType("text/html")+ .body("<html>index</html>")+ .when()+ .put("/" + WEBSITE_BUCKET + "/index.html")+ .then()+ .statusCode(200);++ given()+ .contentType("application/xml")+ .body(websiteConfiguration())+ .when()+ .put("/" + WEBSITE_BUCKET + "?website")+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(publicGetObjectPolicy(WEBSITE_BUCKET))+ .when()+ .put("/" + WEBSITE_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .header("Host", WEBSITE_BUCKET + ".s3-website-us-east-1.localhost:"+ + io.restassured.RestAssured.port)+ .when()+ .get("/")+ .then()+ .statusCode(200)+ .body(equalTo("<html>index</html>"));++ given()+ .when()+ .get("/" + WEBSITE_BUCKET + "?list-type=2")+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ @Test+ @Order(13)+ void websiteRootUsesErrorDocumentForDeniedIndexObject() {+ given().when().put("/" + WEBSITE_ERROR_BUCKET).then().statusCode(200);++ given()+ .contentType("text/html")+ .body("<html>private index</html>")+ .when()+ .put("/" + WEBSITE_ERROR_BUCKET + "/index.html")+ .then()+ .statusCode(200);++ given()+ .contentType("text/html")+ .body("<html>denied</html>")+ .when()+ .put("/" + WEBSITE_ERROR_BUCKET + "/" + ERROR_KEY)+ .then()+ .statusCode(200);++ given()+ .contentType("application/xml")+ .body(websiteConfiguration(ERROR_KEY))+ .when()+ .put("/" + WEBSITE_ERROR_BUCKET + "?website")+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(publicGetObjectPolicy(WEBSITE_ERROR_BUCKET, ERROR_KEY))+ .when()+ .put("/" + WEBSITE_ERROR_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .header("Host", WEBSITE_ERROR_BUCKET + ".s3-website-us-east-1.localhost:"+ + io.restassured.RestAssured.port)+ .when()+ .get("/")+ .then()+ .statusCode(403)+ .header("x-amz-error-code", "AccessDenied")+ .body(equalTo("<html>denied</html>"));+ }++ @Test+ @Order(14)+ void bucketAclPublicReadAllowsUnsignedList() {+ given().when().put("/" + BUCKET_ACL_BUCKET).then().statusCode(200);++ given()+ .body("listed")+ .when()+ .put("/" + BUCKET_ACL_BUCKET + "/" + ACL_KEY)+ .then()+ .statusCode(200);++ given()+ .contentType("application/xml")+ .body(publicReadAcl())+ .when()+ .put("/" + BUCKET_ACL_BUCKET + "?acl")+ .then()+ .statusCode(200);++ given()+ .when()+ .get("/" + BUCKET_ACL_BUCKET + "?list-type=2")+ .then()+ .statusCode(200)+ .body(containsString("<Key>" + ACL_KEY + "</Key>"));+ }++ @Test+ @Order(15)+ void explicitBucketPolicyDenyOverridesPublicObjectAcl() {+ given().when().put("/" + DENY_BUCKET).then().statusCode(200);++ given()+ .header("x-amz-acl", "public-read")+ .body("denied")+ .when()+ .put("/" + DENY_BUCKET + "/" + DENY_KEY)+ .then()+ .statusCode(200);++ given()+ .contentType("application/json")+ .body(denyGetObjectPolicy(DENY_BUCKET))+ .when()+ .put("/" + DENY_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .when()+ .get("/" + DENY_BUCKET + "/" + DENY_KEY)+ .then()+ .statusCode(403)+ .body(containsString("AccessDenied"));+ }++ @Test+ @Order(16)+ void unsignedRequestCannotReadPrivateBucketSubresources() {+ given()+ .when()+ .get("/" + PRIVATE_BUCKET + "?acl")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));++ given()+ .when()+ .get("/" + PRIVATE_BUCKET + "?versions")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));+ }++ @Test+ @Order(17)+ void publicGetObjectPolicyDoesNotAuthorizeObjectSubresources() {+ given()+ .when()+ .get("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY + "?acl")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));++ given()+ .when()+ .get("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY + "?tagging")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));+ }++ @Test+ @Order(18)+ void headBucketHonorsAuthEnforcement() {+ given()+ .when()+ .head("/" + PRIVATE_BUCKET)+ .then()+ .statusCode(403);++ given()+ .header("Authorization", BAD_AUTH_HEADER)+ .when()+ .head("/" + PUBLIC_BUCKET)+ .then()+ .statusCode(403);++ given()+ .header("Authorization", LOCAL_AUTH_HEADER)+ .when()+ .head("/" + PRIVATE_BUCKET)+ .then()+ .statusCode(200);+ }++ @Test+ @Order(19)+ void selectObjectContentHonorsReadAuthorization() {+ given()+ .contentType("application/xml")+ .body(selectRequest())+ .when()+ .post("/" + PRIVATE_BUCKET + "/" + PRIVATE_KEY + "?select&select-type=2")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));++ given()+ .header("Authorization", BAD_AUTH_HEADER)+ .contentType("application/xml")+ .body(selectRequest())+ .when()+ .post("/" + PUBLIC_BUCKET + "/" + PUBLIC_KEY + "?select&select-type=2")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("InvalidAccessKeyId"));+ }++ @Test+ @Order(20)+ void missingObjectRequiresListBucketToReturnNoSuchKey() {+ given().when().put("/" + GET_ONLY_BUCKET).then().statusCode(200);++ given()+ .contentType("application/json")+ .body(publicGetObjectPolicy(GET_ONLY_BUCKET))+ .when()+ .put("/" + GET_ONLY_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .when()+ .get("/" + GET_ONLY_BUCKET + "/missing.txt")+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));++ given()+ .when()+ .get("/" + PUBLIC_BUCKET + "/missing.txt")+ .then()+ .statusCode(404)+ .body("Error.Code", equalTo("NoSuchKey"));+ }++ @Test+ @Order(21)+ void versionedObjectReadRequiresGetObjectVersion() {+ given().when().put("/" + VERSION_BUCKET).then().statusCode(200);++ given()+ .contentType("application/xml")+ .body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")+ .when()+ .put("/" + VERSION_BUCKET + "?versioning")+ .then()+ .statusCode(200);++ String versionId = given()+ .body("versioned body")+ .when()+ .put("/" + VERSION_BUCKET + "/" + VERSION_KEY)+ .then()+ .statusCode(200)+ .extract().header("x-amz-version-id");++ given()+ .contentType("application/json")+ .body(publicObjectActionPolicy(VERSION_BUCKET, "s3:GetObject"))+ .when()+ .put("/" + VERSION_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .when()+ .get("/" + VERSION_BUCKET + "/" + VERSION_KEY + "?versionId=" + versionId)+ .then()+ .statusCode(403)+ .body("Error.Code", equalTo("AccessDenied"));++ given()+ .contentType("application/json")+ .body(publicObjectActionPolicy(VERSION_BUCKET, "s3:GetObjectVersion"))+ .when()+ .put("/" + VERSION_BUCKET + "?policy")+ .then()+ .statusCode(200);++ given()+ .when()+ .get("/" + VERSION_BUCKET + "/" + VERSION_KEY + "?versionId=" + versionId)+ .then()+ .statusCode(200)+ .body(equalTo("versioned body"));+ }++ private static String publicReadPolicy(String bucket) {+ return """+ {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Principal": "*",+ "Action": ["s3:GetObject"],+ "Resource": ["arn:aws:s3:::%s/*"]+ },+ {+ "Effect": "Allow",+ "Principal": "*",+ "Action": ["s3:ListBucket"],+ "Resource": ["arn:aws:s3:::%s"]+ }+ ]+ }+ """.formatted(bucket, bucket);+ }++ private static String authorizationHeader(String accessKeyId) {+ return "AWS4-HMAC-SHA256 Credential=" + credential(accessKeyId)+ + ", SignedHeaders=host;x-amz-date, Signature=test";+ }++ private static String credential(String accessKeyId) {+ return accessKeyId + "/" + SIGNING_DATE + "/us-east-1/s3/aws4_request";+ }++ private static String websiteConfiguration() {+ return websiteConfiguration(null);+ }++ private static String websiteConfiguration(String errorDocument) {+ if (errorDocument == null) {+ return """+ <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <IndexDocument>+ <Suffix>index.html</Suffix>+ </IndexDocument>+ </WebsiteConfiguration>+ """;+ }+ return """+ <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <IndexDocument>+ <Suffix>index.html</Suffix>+ </IndexDocument>+ <ErrorDocument>+ <Key>%s</Key>+ </ErrorDocument>+ </WebsiteConfiguration>+ """.formatted(errorDocument);+ }++ private static String publicGetObjectPolicy(String bucket) {+ return publicGetObjectPolicy(bucket, "*");+ }++ private static String publicGetObjectPolicy(String bucket, String key) {+ return publicObjectActionPolicy(bucket, key, "s3:GetObject");+ }++ private static String publicObjectActionPolicy(String bucket, String action) {+ return publicObjectActionPolicy(bucket, "*", action);+ }++ private static String publicObjectActionPolicy(String bucket, String key, String action) {+ return """+ {+ "Version": "2012-10-17",+ "Statement": {+ "Effect": "Allow",+ "Principal": "*",+ "Action": "%s",+ "Resource": "arn:aws:s3:::%s/%s"+ }+ }+ """.formatted(action, bucket, key);+ }++ private static String denyGetObjectPolicy(String bucket) {+ return """+ {+ "Version": "2012-10-17",+ "Statement": {+ "Effect": "Deny",+ "Principal": "*",+ "Action": "s3:GetObject",+ "Resource": "arn:aws:s3:::%s/*"+ }+ }+ """.formatted(bucket);+ }++ private static String publicReadAcl() {+ return """+ <AccessControlPolicy xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <Owner>+ <ID>owner</ID>+ </Owner>+ <AccessControlList>+ <Grant>+ <Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Group">+ <URI>http://acs.amazonaws.com/groups/global/AllUsers</URI>+ </Grantee>+ <Permission>READ</Permission>+ </Grant>+ </AccessControlList>+ </AccessControlPolicy>+ """;+ }++ private static String selectRequest() {+ return """+ <SelectObjectContentRequest>+ <Expression>SELECT * FROM S3Object</Expression>+ <InputSerialization>+ <CSV>+ <FileHeaderInfo>NONE</FileHeaderInfo>+ </CSV>+ </InputSerialization>+ <OutputSerialization>+ <CSV />+ </OutputSerialization>+ </SelectObjectContentRequest>+ """;+ }++ public static final class S3AuthProfile implements QuarkusTestProfile {+ @Override+ public Map<String, String> getConfigOverrides() {+ return Map.of("floci.services.s3.enforce-auth", "true");+ }+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.javaindex 76bdffd833..2ccd494a19 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java@@ -1855,6 +1855,35 @@ class S3IntegrationTest {.body(containsString("NoSuchPublicAccessBlockConfiguration"));}+ @Test+ @Order(104)+ void malformedAuthorizationHeaderIsIgnoredWhenAuthEnforcementDisabled() {+ String bucket = "auth-disabled-bucket";+ String key = "greeting.txt";+ given().when().put("/" + bucket).then().statusCode(200);+ given().body("Hello World from S3!").when().put("/" + bucket + "/" + key).then().statusCode(200);+ try {+ given()+ .header("Authorization", "not-a-valid-signature")+ .when()+ .get("/" + bucket + "/" + key)+ .then()+ .statusCode(200)+ .body(equalTo("Hello World from S3!"));++ given()+ .header("Authorization", "not-a-valid-signature")+ .when()+ .get("/" + bucket + "?list-type=2")+ .then()+ .statusCode(200)+ .body(containsString("<Key>" + key + "</Key>"));+ } finally {+ given().when().delete("/" + bucket + "/" + key);+ given().when().delete("/" + bucket);+ }+ }+// --- ListObjectsV2 pagination ---@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluatorTest.javanew file mode 100644index 0000000000..caf330f9a0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluatorTest.java@@ -0,0 +1,313 @@+package io.github.hectorvent.floci.services.s3;++import com.fasterxml.jackson.databind.ObjectMapper;+import org.junit.jupiter.api.Test;++import static io.github.hectorvent.floci.services.s3.S3PublicAccessEvaluator.PublicAccessDecision.DENY;+import static io.github.hectorvent.floci.services.s3.S3PublicAccessEvaluator.PublicAccessDecision.NEUTRAL;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;++class S3PublicAccessEvaluatorTest {++ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();+ private static final String BUCKET = "public-bucket";+ private static final String BUCKET_ARN = "arn:aws:s3:::" + BUCKET;+ private static final String OBJECT_ARN = BUCKET_ARN + "/folder/object.txt";++ @Test+ void blankPolicyDoesNotAllow() {+ assertFalse(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, "", "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void invalidJsonDoesNotAllow() {+ assertFalse(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, "{not-json", "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void publicStringPrincipalAllowsMatchingObjectAction() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertTrue(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void publicAwsPrincipalAllowsMatchingBucketAction() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":{"AWS":"*"},+ "Action":["s3:ListBucket"],+ "Resource":["arn:aws:s3:::public-bucket"]+ }}""";++ assertTrue(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:ListBucket", BUCKET_ARN));+ }++ @Test+ void publicPrincipalArrayAllowsMatchingAction() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":["arn:aws:iam::123456789012:root","*"],+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertTrue(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void nonPublicPrincipalDoesNotAllow() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":{"AWS":"arn:aws:iam::123456789012:root"},+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertEquals(NEUTRAL, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void conditionStatementDoesNotAllowAnonymousRead() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*",+ "Condition":{"StringEquals":{"aws:PrincipalAccount":"123456789012"}}+ }}""";++ assertEquals(NEUTRAL, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void missingEffectDoesNotAllowAnonymousRead() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertEquals(NEUTRAL, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void explicitDenyOverridesAllow() {+ String policy = """+ {"Version":"2012-10-17","Statement":[+ {+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ },+ {+ "Effect":"Deny",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/folder/object.txt"+ }+ ]}""";++ assertEquals(DENY, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void conditionalDenyFailsClosedAndOverridesAllow() {+ String policy = """+ {"Version":"2012-10-17","Statement":[+ {+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ },+ {+ "Effect":"Deny",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*",+ "Condition":{"StringEquals":{"aws:SourceVpc":"vpc-123"}}+ }+ ]}""";++ assertEquals(DENY, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void wildcardActionAndResourceMatch() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:Get*",+ "Resource":"arn:aws:s3:::public-bucket/folder/*"+ }}""";++ assertTrue(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void notActionAllowsWhenRequestedActionIsNotExcluded() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "NotAction":"s3:PutObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertTrue(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void notActionDoesNotAllowWhenRequestedActionIsExcluded() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "NotAction":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertEquals(NEUTRAL, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void notResourceAllowsWhenRequestedResourceIsNotExcluded() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "NotResource":"arn:aws:s3:::other-bucket/*"+ }}""";++ assertTrue(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void notResourceDoesNotAllowWhenRequestedResourceIsExcluded() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "NotResource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertEquals(NEUTRAL, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void notPrincipalAllowsAnonymousWhenOnlySpecificPrincipalIsExcluded() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "NotPrincipal":{"AWS":"arn:aws:iam::123456789012:root"},+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertTrue(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void notPrincipalWildcardDoesNotAllowAnonymous() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "NotPrincipal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertEquals(NEUTRAL, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void denyWithNotPrincipalOverridesAllowWhenAnonymousIsNotExcluded() {+ String policy = """+ {"Version":"2012-10-17","Statement":[+ {+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ },+ {+ "Effect":"Deny",+ "NotPrincipal":{"AWS":"arn:aws:iam::123456789012:root"},+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }+ ]}""";++ assertEquals(DENY, S3PublicAccessEvaluator.publicPolicyDecision(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void actionMismatchDoesNotAllow() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:PutObject",+ "Resource":"arn:aws:s3:::public-bucket/*"+ }}""";++ assertFalse(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void resourceMismatchDoesNotAllow() {+ String policy = """+ {"Version":"2012-10-17","Statement":{+ "Effect":"Allow",+ "Principal":"*",+ "Action":"s3:GetObject",+ "Resource":"arn:aws:s3:::other-bucket/*"+ }}""";++ assertFalse(S3PublicAccessEvaluator.publicPolicyAllows(+ OBJECT_MAPPER, policy, "s3:GetObject", OBJECT_ARN));+ }++ @Test+ void arnHelpersBuildBucketAndObjectArns() {+ assertEquals(BUCKET_ARN, S3PublicAccessEvaluator.bucketArn(BUCKET));+ assertEquals(OBJECT_ARN, S3PublicAccessEvaluator.objectArn(BUCKET, "folder/object.txt"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParserTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParserTest.javanew file mode 100644index 0000000000..7480ff34be--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3RequestAuthorizationParserTest.java@@ -0,0 +1,160 @@+package io.github.hectorvent.floci.services.s3;++import io.github.hectorvent.floci.core.common.AwsException;+import jakarta.ws.rs.core.MultivaluedHashMap;+import jakarta.ws.rs.core.MultivaluedMap;+import org.junit.jupiter.api.Test;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertNull;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;++class S3RequestAuthorizationParserTest {++ @Test+ void returnsUnsignedAuthorizationWithoutAuthMaterial() {+ S3Service.RequestAuthorization authorization = parse(null, query());++ assertFalse(authorization.signed());+ assertNull(authorization.accessKeyId());+ }++ @Test+ void parsesAuthorizationHeaderAccessKey() {+ S3Service.RequestAuthorization authorization = parse(authorizationHeader("test"), query());++ assertTrue(authorization.signed());+ assertEquals("test", authorization.accessKeyId());+ }++ @Test+ void parsesPresignedQueryAccessKey() {+ S3Service.RequestAuthorization authorization = parse(null, presignedQuery("bad-key"));++ assertTrue(authorization.signed());+ assertEquals("bad-key", authorization.accessKeyId());+ }++ @Test+ void authorizationHeaderTakesPrecedenceOverPresignedQuery() {+ String authorizationHeader = authorizationHeader("header-key");+ MultivaluedMap<String, String> query = presignedQuery("query-key");++ S3Service.RequestAuthorization authorization = parse(authorizationHeader, query);++ assertTrue(authorization.signed());+ assertEquals("header-key", authorization.accessKeyId());+ }++ @Test+ void rejectsMalformedAuthorizationHeader() {+ String authorization = "AWS4-HMAC-SHA256 Credential=test/20260702/us-east-1/s3/aws4_request, SignedHeaders=host";++ AwsException e = assertThrows(AwsException.class, () -> parse(authorization, query()));++ assertEquals("AuthorizationHeaderMalformed", e.getErrorCode());+ assertEquals(400, e.getHttpStatus());+ }++ @Test+ void rejectsMalformedPresignedQuery() {+ MultivaluedMap<String, String> query = query();+ query.add("X-Amz-Algorithm", "AWS4-HMAC-SHA256");+ query.add("X-Amz-Credential", "test/20260702/us-east-1/s3/aws4_request");+ query.add("X-Amz-Date", "20260702T120000Z");+ query.add("X-Amz-Expires", "3600");+ query.add("X-Amz-SignedHeaders", "host");++ AwsException e = assertThrows(AwsException.class, () -> parse(null, query));++ assertEquals("AuthorizationQueryParametersError", e.getErrorCode());+ assertEquals("Query-string authentication version 4 requires the X-Amz-Algorithm, "+ + "X-Amz-Credential, X-Amz-Signature, X-Amz-Date, X-Amz-SignedHeaders, "+ + "and X-Amz-Expires parameters.", e.getMessage());+ assertEquals(400, e.getHttpStatus());+ }++ @Test+ void ignoresNonPresignedQueryParameters() {+ MultivaluedMap<String, String> query = query();+ query.add("versionId", "123");++ S3Service.RequestAuthorization authorization = parse(null, query);++ assertFalse(authorization.signed());+ assertNull(authorization.accessKeyId());+ }++ @Test+ void ignoresStrayXAmzQueryParametersWithoutAlgorithm() {+ MultivaluedMap<String, String> query = query();+ query.add("X-Amz-Meta-Test", "ignored");++ S3Service.RequestAuthorization authorization = parse(null, query);++ assertFalse(authorization.signed());+ assertNull(authorization.accessKeyId());+ }++ @Test+ void disabledEnforcementDoesNotValidateMalformedAuthorizationHeader() {+ String authorization = "not-a-valid-signature";++ S3Service.RequestAuthorization parsed = S3RequestAuthorizationParser.parseIfRequired(+ false, authorization, query());++ assertFalse(parsed.signed());+ assertNull(parsed.accessKeyId());+ }++ @Test+ void disabledEnforcementDoesNotValidateMalformedPresignedQuery() {+ MultivaluedMap<String, String> query = query();+ query.add("X-Amz-Algorithm", "AWS4-HMAC-SHA256");++ S3Service.RequestAuthorization parsed = S3RequestAuthorizationParser.parseIfRequired(+ false, null, query);++ assertFalse(parsed.signed());+ assertNull(parsed.accessKeyId());+ }++ @Test+ void signedDetectionDoesNotValidateMalformedAuthMaterial() {+ MultivaluedMap<String, String> query = query();+ query.add("X-Amz-Algorithm", "AWS4-HMAC-SHA256");++ assertTrue(S3RequestAuthorizationParser.isSigned("not-a-valid-signature", query()));+ assertTrue(S3RequestAuthorizationParser.isSigned(null, query));+ }++ private static S3Service.RequestAuthorization parse(String authorization, MultivaluedMap<String, String> query) {+ return S3RequestAuthorizationParser.parse(authorization, query);+ }++ private static String authorizationHeader(String accessKeyId) {+ return "AWS4-HMAC-SHA256 Credential=" + credential(accessKeyId)+ + ", SignedHeaders=host;x-amz-date, Signature=test";+ }++ private static MultivaluedMap<String, String> presignedQuery(String accessKeyId) {+ MultivaluedMap<String, String> query = query();+ query.add("X-Amz-Algorithm", "AWS4-HMAC-SHA256");+ query.add("X-Amz-Credential", credential(accessKeyId));+ query.add("X-Amz-Date", "20260702T120000Z");+ query.add("X-Amz-Expires", "3600");+ query.add("X-Amz-SignedHeaders", "host");+ query.add("X-Amz-Signature", "test");+ return query;+ }++ private static String credential(String accessKeyId) {+ return accessKeyId + "/20260702/us-east-1/s3/aws4_request";+ }++ private static MultivaluedMap<String, String> query() {+ return new MultivaluedHashMap<>();+ }+}diff --git a/src/test/resources/application.yml b/src/test/resources/application.ymlindex c42761017f..5e0df5b4b8 100644--- a/src/test/resources/application.yml+++ b/src/test/resources/application.yml@@ -96,6 +96,7 @@ floci:max-message-size: 1048576s3:enabled: true+ enforce-auth: falsedefault-presign-expiry-seconds: 3600dynamodb:enabled: true