Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(s3): enforce Block Public Access on the data plane (#4253)

Abhigyabae7e0316a4e
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3BlockPublicAccessTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3BlockPublicAccessTest.java
new file mode 100644
index 0000000000..6a49e8af80
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3BlockPublicAccessTest.java
@@ -0,0 +1,166 @@
+package com.floci.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.DisplayName;
+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 software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.BucketAlreadyOwnedByYouException;
+import software.amazon.awssdk.services.s3.model.BucketCannedACL;
+import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
+import software.amazon.awssdk.services.s3.model.GetBucketPolicyRequest;
+import software.amazon.awssdk.services.s3.model.GetPublicAccessBlockRequest;
+import software.amazon.awssdk.services.s3.model.GetPublicAccessBlockResponse;
+import software.amazon.awssdk.services.s3.model.ObjectCannedACL;
+import software.amazon.awssdk.services.s3.model.PublicAccessBlockConfiguration;
+import software.amazon.awssdk.services.s3.model.PutBucketAclRequest;
+import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest;
+import software.amazon.awssdk.services.s3.model.PutObjectRequest;
+import software.amazon.awssdk.services.s3.model.PutPublicAccessBlockRequest;
+import software.amazon.awssdk.services.s3.model.S3Exception;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.assertj.core.api.Assertions.catchThrowableOfType;
+
+/**
+ * S3 Block Public Access, driven through the real AWS SDK.
+ *
+ * <p>Covers the half AWS enforces whoever the caller is: {@code BlockPublicPolicy} rejecting a
+ * public bucket policy and {@code BlockPublicAcls} rejecting a public ACL. Both apply without
+ * {@code enforce-auth}, which is the configuration this suite runs against. The read-time flags
+ * ({@code RestrictPublicBuckets}, {@code IgnorePublicAcls}) need anonymous authorization to be
+ * running and are covered by the in-tree integration tests instead.
+ */
+@DisplayName("S3 Block Public Access: BlockPublicPolicy / BlockPublicAcls")
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class S3BlockPublicAccessTest {
+
+ private static S3Client s3;
+
+ private static final String BUCKET = "compat-bpa-bucket";
+
+ private static final String PUBLIC_POLICY = """
+ {"Version":"2012-10-17","Statement":[{"Sid":"PublicRead","Effect":"Allow",
+ "Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}
+ """.formatted(BUCKET);
+
+ private static final String ACCOUNT_SCOPED_POLICY = """
+ {"Version":"2012-10-17","Statement":[{"Sid":"OneAccount","Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::111122223333:root"},"Action":"s3:GetObject",
+ "Resource":"arn:aws:s3:::%s/*"}]}
+ """.formatted(BUCKET);
+
+ @BeforeAll
+ static void setup() {
+ s3 = TestFixtures.s3Client();
+ try {
+ s3.createBucket(CreateBucketRequest.builder().bucket(BUCKET).build());
+ } catch (BucketAlreadyOwnedByYouException expected) {
+ // A previous run of this suite left the bucket behind; reuse it.
+ }
+ s3.putPublicAccessBlock(PutPublicAccessBlockRequest.builder()
+ .bucket(BUCKET)
+ .publicAccessBlockConfiguration(PublicAccessBlockConfiguration.builder()
+ .blockPublicAcls(true)
+ .ignorePublicAcls(false)
+ .blockPublicPolicy(true)
+ .restrictPublicBuckets(false)
+ .build())
+ .build());
+ }
+
+ @AfterAll
+ static void teardown() {
+ if (s3 != null) {
+ s3.close();
+ }
+ }
+
+ @Test
+ @Order(1)
+ @DisplayName("GetPublicAccessBlock returns the flags PutPublicAccessBlock stored")
+ void publicAccessBlockRoundTrips() {
+ GetPublicAccessBlockResponse response = s3.getPublicAccessBlock(
+ GetPublicAccessBlockRequest.builder().bucket(BUCKET).build());
+
+ PublicAccessBlockConfiguration configuration = response.publicAccessBlockConfiguration();
+ assertThat(configuration.blockPublicAcls()).isTrue();
+ assertThat(configuration.blockPublicPolicy()).isTrue();
+ assertThat(configuration.ignorePublicAcls()).isFalse();
+ assertThat(configuration.restrictPublicBuckets()).isFalse();
+ }
+
+ @Test
+ @Order(2)
+ @DisplayName("BlockPublicPolicy rejects PutBucketPolicy with AccessDenied")
+ void blockPublicPolicyRejectsAPublicPolicy() {
+ S3Exception exception = catchThrowableOfType(
+ () -> s3.putBucketPolicy(PutBucketPolicyRequest.builder()
+ .bucket(BUCKET)
+ .policy(PUBLIC_POLICY)
+ .build()),
+ S3Exception.class);
+
+ assertThat(exception).isNotNull();
+ assertThat(exception.statusCode()).isEqualTo(403);
+ assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("AccessDenied");
+ }
+
+ @Test
+ @Order(3)
+ @DisplayName("BlockPublicPolicy leaves a policy scoped to one account alone")
+ void aNonPublicPolicyIsStillAccepted() {
+ s3.putBucketPolicy(PutBucketPolicyRequest.builder()
+ .bucket(BUCKET)
+ .policy(ACCOUNT_SCOPED_POLICY)
+ .build());
+
+ assertThat(s3.getBucketPolicy(GetBucketPolicyRequest.builder().bucket(BUCKET).build()).policy())
+ .contains("OneAccount");
+ }
+
+ @Test
+ @Order(4)
+ @DisplayName("BlockPublicAcls rejects a public bucket ACL with AccessDenied")
+ void blockPublicAclsRejectsAPublicBucketAcl() {
+ S3Exception exception = catchThrowableOfType(
+ () -> s3.putBucketAcl(PutBucketAclRequest.builder()
+ .bucket(BUCKET)
+ .acl(BucketCannedACL.PUBLIC_READ)
+ .build()),
+ S3Exception.class);
+
+ assertThat(exception).isNotNull();
+ assertThat(exception.statusCode()).isEqualTo(403);
+ assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("AccessDenied");
+ }
+
+ @Test
+ @Order(5)
+ @DisplayName("BlockPublicAcls rejects a PutObject carrying a public ACL")
+ void blockPublicAclsRejectsAPublicObjectAcl() {
+ assertThatThrownBy(() -> s3.putObject(
+ PutObjectRequest.builder()
+ .bucket(BUCKET)
+ .key("public.txt")
+ .acl(ObjectCannedACL.PUBLIC_READ)
+ .build(),
+ RequestBody.fromString("hello")))
+ .isInstanceOf(S3Exception.class)
+ .satisfies(thrown -> assertThat(((S3Exception) thrown).statusCode()).isEqualTo(403));
+ }
+
+ @Test
+ @Order(6)
+ @DisplayName("A PutObject without a public ACL is unaffected")
+ void aPrivatePutObjectIsUnaffected() {
+ s3.putObject(
+ PutObjectRequest.builder().bucket(BUCKET).key("private.txt").build(),
+ RequestBody.fromString("hello"));
+ }
+}
diff --git a/docs/services/s3.md b/docs/services/s3.md
index 891904aa0b..95bc906f99 100644
--- a/docs/services/s3.md
+++ b/docs/services/s3.md
@@ -259,7 +259,43 @@ When a request is denied by bucket policy enforcement, Floci returns HTTP 403 wi
</Error>
```
-## Account-Level Block Public Access
+## Block Public Access
+
+Floci enforces all four Block Public Access settings. A bucket's configuration is combined with the bucket owner account's and the most restrictive of the two wins, which for four independent booleans is a per-flag OR: a flag set at either level is in force.
+
+| Setting | What it does | Needs `enforce-auth` |
+|---|---|---|
+| `BlockPublicPolicy` | `PutBucketPolicy` returns `AccessDenied` (403) when the submitted policy is public | No |
+| `BlockPublicAcls` | `PutBucketAcl`, `PutObjectAcl` and a `PutObject` carrying a public ACL return `AccessDenied` (403) | No |
+| `RestrictPublicBuckets` | A bucket whose policy is public serves only the owner account: anonymous and cross-account callers are denied | Yes |
+| `IgnorePublicAcls` | A public ACL on the bucket or on an object stops granting access | Yes |
+
+The split follows AWS. The first two reject the write that would introduce public access, and AWS applies them whoever the caller is, so they need no flag: `put-public-access-block` followed by a public `put-bucket-policy` returns 403 in Floci's default configuration. The second two suppress access that an existing policy or ACL would grant, which only has meaning once anonymous authorization runs at all, so they take effect when `FLOCI_SERVICES_S3_ENFORCE_AUTH` is on. With that flag off, Floci cannot tell an anonymous caller from a signed one and every request is authorized regardless.
+
+When upgrading, a workflow that already sets `BlockPublicPolicy` or `BlockPublicAcls` may now receive 403 on a later public policy or ACL write, even with `enforce-auth` off. This matches AWS behavior.
+
+As in AWS, enabling a setting never rewrites stored state. An existing public policy or ACL stays exactly as written, and clearing the setting makes the bucket public again.
+
+### The meaning of "public"
+
+An **ACL** is public when it grants any permission to the `AllUsers` or `AuthenticatedUsers` predefined groups. This is broader than the grants anonymous authorization consults: a `WRITE_ACP` grant to `AllUsers` is public here even though it gives an anonymous caller no read.
+
+A **bucket policy** is assumed public and then checked for a reason it is not. A statement with a wildcard principal (`"Principal": "*"`, `{"AWS": "*"}`, or an `Allow` on `NotPrincipal`) is public unless a positive condition pins one of `aws:PrincipalArn`, `aws:PrincipalAccount`, `aws:PrincipalOrgID`, `aws:PrincipalOrgPaths`, `aws:SourceArn`, `aws:SourceVpc`, `aws:SourceVpce`, `aws:SourceOwner`, `aws:SourceAccount`, `aws:userid`, `s3:DataAccessPointArn` or `s3:DataAccessPointAccount` to a fixed value, one containing neither a wildcard nor an IAM policy variable. In a bucket policy, `s3:DataAccessPointArn` may contain a wildcard in the access point name if the account ID is fixed, for example `arn:aws:s3:us-west-2:123456789012:accesspoint/*`. `aws:SourceIp` counts too, but only for a range no broader than `/8` (IPv4) or `/32` (IPv6), matching AWS's treatment of very wide CIDR blocks as public.
+
+For multivalued condition keys such as `aws:PrincipalOrgPaths`, `ForAnyValue:` with a positive operator can narrow the grant when each value is fixed. `ForAllValues:` alone does not narrow it because the condition also matches when the key is missing.
+
+A single public statement makes the whole policy public. As on AWS, `RestrictPublicBuckets` then withholds even the non-public cross-account delegation another statement grants, until the public statement is removed.
+
+### Known gaps
+
+- Floci does not model access points, so the access-point variants (`PutAccessPointPolicy`, the VPC-origin rule, the different `s3:DataAccessPointArn` treatment) do not apply.
+- AWS's organization-level Block Public Access policies are not modelled; only the bucket and account levels combine.
+- `CreateBucket` does not apply an `x-amz-acl` at all in Floci, so there is no public bucket ACL at creation for the account-level `BlockPublicAcls` to reject.
+- `GetBucketAcl` returns the stored ACL rather than the effective one, so it does not reflect an `IgnorePublicAcls` that is suppressing a grant.
+- `GetBucketPolicyStatus` has no handler.
+- `RestrictPublicBuckets` exempts AWS service principals on AWS. Floci reaches the signed path only for IAM principals, so there is nothing to exempt.
+
+### Account-level operations
The s3control `PutPublicAccessBlock`, `GetPublicAccessBlock` and `DeletePublicAccessBlock` operations are keyed by the `x-amz-account-id` header, stored per account, and persisted like the rest of S3's state so a restart does not silently drop the control. As in AWS, the header must name the caller's own account; a mismatch returns `AccessDenied` (403). Floci keeps one deliberate exception: the configured default (management) account may act on any account, because Floci's launched Lambdas run on placeholder credentials that resolve to the management account instead of assuming a role in the target account — which is how LZA's `Custom::PutPublicAccessBlock` resource reaches this API.
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.java
index 50509d630c..c9b18949b4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPolicy.java
@@ -23,6 +23,8 @@ 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 final String AUTHENTICATED_USERS_GROUP_URI =
+ "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
static S3AclPolicy parse(String acl) throws AclParseException {
try {
@@ -118,6 +120,15 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {
return grantee.isAllUsersGroup() && permission.allowsWrite();
}
+ /**
+ * Block Public Access calls an ACL public when it grants any permission to the AllUsers
+ * or AuthenticatedUsers predefined groups, which is broader than the read and write
+ * grants anonymous authorization consults.
+ */
+ boolean grantsToPublicGroup() {
+ return grantee.isPublicGroup();
+ }
+
boolean allowsCanonicalUserRead(String canonicalUserId) {
return grantee.isCanonicalUser(canonicalUserId) && permission.allowsRead();
}
@@ -128,6 +139,10 @@ record S3AclPolicy(List<S3AclPolicy.Grant> grants) {
return ALL_USERS_GROUP_URI.equals(uri);
}
+ boolean isPublicGroup() {
+ return isAllUsersGroup() || AUTHENTICATED_USERS_GROUP_URI.equals(uri);
+ }
+
boolean isCanonicalUser(String canonicalUserId) {
return canonicalUserId != null && canonicalUserId.equals(id);
}
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.java
index 7297eccacf..e343a420cf 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluator.java
@@ -24,6 +24,24 @@ final class S3AclPublicAccessEvaluator {
}
}
+ /**
+ * Whether Block Public Access considers this ACL public: it grants any permission to the
+ * AllUsers or AuthenticatedUsers predefined groups. {@code BlockPublicAcls} rejects a write
+ * that submits such an ACL, and {@code IgnorePublicAcls} suppresses one already stored.
+ */
+ static boolean aclIsPublic(String acl) {
+ if (acl == null || acl.isBlank()) {
+ return false;
+ }
+ try {
+ S3AclPolicy policy = S3AclPolicy.parse(acl);
+ return policy.grants().stream().anyMatch(S3AclPolicy.Grant::grantsToPublicGroup);
+ } catch (S3AclPolicy.AclParseException e) {
+ LOG.debugv(e, "Failed to parse S3 ACL for public status evaluation");
+ return false;
+ }
+ }
+
static boolean aclAllowsPublicWrite(String acl) {
if (acl == null || acl.isBlank()) {
return false;
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessSettings.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessSettings.java
new file mode 100644
index 0000000000..6b939e836b
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessSettings.java
@@ -0,0 +1,58 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+
+/**
+ * The four S3 Block Public Access flags, read back from a stored
+ * {@code PublicAccessBlockConfiguration} document.
+ *
+ * <p>The flags are independent and split into two kinds. {@code BlockPublicAcls} and
+ * {@code BlockPublicPolicy} reject the write that would introduce public access, so they are
+ * evaluated when a policy or ACL is submitted and apply whoever the caller is.
+ * {@code IgnorePublicAcls} and {@code RestrictPublicBuckets} suppress access that an existing
+ * public ACL or policy would otherwise grant, so they are evaluated during authorization.
+ *
+ * <p>AWS evaluates a bucket's configuration together with the bucket owner account's
+ * configuration and applies the most restrictive combination, which for four independent
+ * booleans is a per-flag OR.
+ */
+record S3BlockPublicAccessSettings(
+ boolean blockPublicAcls,
+ boolean ignorePublicAcls,
+ boolean blockPublicPolicy,
+ boolean restrictPublicBuckets) {
+
+ static final S3BlockPublicAccessSettings NONE =
+ new S3BlockPublicAccessSettings(false, false, false, false);
+
+ static S3BlockPublicAccessSettings parse(String configurationXml) {
+ if (configurationXml == null || configurationXml.isBlank()) {
+ return NONE;
+ }
+ return new S3BlockPublicAccessSettings(
+ flag(configurationXml, "BlockPublicAcls"),
+ flag(configurationXml, "IgnorePublicAcls"),
+ flag(configurationXml, "BlockPublicPolicy"),
+ flag(configurationXml, "RestrictPublicBuckets"));
+ }
+
+ /** The per-flag OR that AWS describes as "the most restrictive combination". */
+ S3BlockPublicAccessSettings mostRestrictive(S3BlockPublicAccessSettings other) {
+ if (other == null) {
+ return this;
+ }
+ return new S3BlockPublicAccessSettings(
+ blockPublicAcls || other.blockPublicAcls,
+ ignorePublicAcls || other.ignorePublicAcls,
+ blockPublicPolicy || other.blockPublicPolicy,
+ restrictPublicBuckets || other.restrictPublicBuckets);
+ }
+
+ boolean blocksAnything() {
+ return blockPublicAcls || ignorePublicAcls || blockPublicPolicy || restrictPublicBuckets;
+ }
+
+ private static boolean flag(String configurationXml, String elementName) {
+ return Boolean.parseBoolean(XmlParser.extractFirst(configurationXml, elementName, "false"));
+ }
+}
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.java
index 4dcab3c9c8..938ae46938 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3PublicAccessEvaluator.java
@@ -8,12 +8,40 @@ import org.jboss.logging.Logger;
import java.util.Iterator;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
+import java.util.Set;
+import java.util.function.Predicate;
+import java.util.regex.Pattern;
final class S3PublicAccessEvaluator {
private static final Logger LOG = Logger.getLogger(S3PublicAccessEvaluator.class);
+ /**
+ * The condition keys that, pinned to a fixed value, keep a statement with a wildcard
+ * principal out of Block Public Access's definition of public.
+ */
+ private static final Set<String> NON_PUBLIC_CONDITION_KEYS = Set.of(
+ "aws:principalarn",
+ "aws:principalaccount",
+ "aws:principalorgid",
+ "aws:principalorgpaths",
+ "aws:sourcearn",
+ "aws:sourcevpc",
+ "aws:sourcevpce",
+ "aws:sourceowner",
+ "aws:sourceaccount",
+ "aws:userid",
+ "s3:dataaccesspointarn",
+ "s3:dataaccesspointaccount");
+
+ /** Recognised like the keys above, but the value additionally has to be a narrow range. */
+ private static final String SOURCE_IP_CONDITION_KEY = "aws:sourceip";
+ private static final String DATA_ACCESS_POINT_ARN_CONDITION_KEY = "s3:dataaccesspointarn";
+ private static final Pattern BUCKET_POLICY_ACCESS_POINT_ARN = Pattern.compile(
+ "arn:[a-z0-9-]+:s3:[a-z0-9-]+:[0-9]{12}:accesspoint/[a-zA-Z0-9*?._-]+");
+
enum PublicAccessDecision {
ALLOW,
DENY,
@@ -121,6 +149,170 @@ final class S3PublicAccessEvaluator {
}
}
+ /**
+ * Whether Block Public Access considers this bucket policy public. AWS begins by assuming a
+ * policy is public and then looks for a reason it is not: a statement that grants to everyone
+ * is non-public only when it pins one of the recognised condition keys to a fixed value, one
+ * containing neither a wildcard nor an IAM policy variable. A single public statement makes
+ * the whole policy public, which is what {@code RestrictPublicBuckets} keys off.
+ *
+ * <p>Bucket policies can use a wildcard in the access point name when the account is fixed.
+ * Floci does not model access points, so the different access-point-policy rule does not apply.
+ */
+ static boolean policyIsPublic(ObjectMapper objectMapper, String policy) {
+ if (policy == null || policy.isBlank()) {
+ return false;
+ }
+ try {
+ JsonNode statements = objectMapper.readTree(policy).path("Statement");
+ Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
+ for (JsonNode statement : iterable) {
+ if (statementIsPublic(statement)) {
+ return true;
+ }
+ }
+ return false;
+ } catch (JsonProcessingException e) {
+ LOG.debugv("Failed to evaluate S3 bucket policy status: {0}", e.getMessage());
+ return false;
+ }
+ }
+
+ private static boolean statementIsPublic(JsonNode statement) {
+ if (statement == null || !statement.isObject()) {
+ return false;
+ }
+ if (!"Allow".equalsIgnoreCase(statement.path("Effect").asText(""))) {
+ return false;
+ }
+ if (!grantsToEveryone(statement)) {
+ return false;
+ }
+ return !conditionPinsToFixedValues(statement.path("Condition"));
+ }
+
+ private static boolean grantsToEveryone(JsonNode statement) {
+ if (statement.hasNonNull("Principal")) {
+ return hasPublicPrincipal(statement.path("Principal"));
+ }
+ // An Allow on NotPrincipal grants to everyone the statement does not name.
+ return statement.hasNonNull("NotPrincipal");
+ }
+
+ private static boolean conditionPinsToFixedValues(JsonNode conditions) {
+ if (conditions == null || !conditions.isObject()) {
+ return false;
+ }
+ Iterator<Map.Entry<String, JsonNode>> operators = conditions.fields();
+ while (operators.hasNext()) {
+ Map.Entry<String, JsonNode> operator = operators.next();
+ String operatorName = operator.getKey();
+ if (operatorName.regionMatches(true, 0, "ForAnyValue:", 0, "ForAnyValue:".length())) {
+ operatorName = operatorName.substring("ForAnyValue:".length());
+ }
+ if (!operator.getValue().isObject() || !operatorNarrowsAccess(operatorName)) {
+ continue;
+ }
+ Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
+ while (entries.hasNext()) {
+ Map.Entry<String, JsonNode> entry = entries.next();
+ String key = entry.getKey().toLowerCase(Locale.ROOT);
+ if (DATA_ACCESS_POINT_ARN_CONDITION_KEY.equals(key)
+ && allValuesFixed(entry.getValue(), S3PublicAccessEvaluator::isFixedAccountAccessPointArn)) {
+ return true;
+ }
+ if (NON_PUBLIC_CONDITION_KEYS.contains(key)
+ && !operatorName.equalsIgnoreCase("IpAddress")
+ && allValuesFixed(entry.getValue(), S3PublicAccessEvaluator::isFixedValue)) {
+ return true;
+ }
+ if (SOURCE_IP_CONDITION_KEY.equals(key)
+ && operatorName.equalsIgnoreCase("IpAddress")
+ && allSourceIpRangesNarrow(entry.getValue())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ private static boolean operatorNarrowsAccess(String operator) {
+ return switch (operator.toLowerCase(Locale.ROOT)) {
+ case "stringequals", "stringlike", "arnequals", "arnlike", "ipaddress" -> true;
+ default -> false;
+ };
+ }
+
+ private static boolean allValuesFixed(JsonNode value, Predicate<String> isFixed) {
+ if (value == null || value.isNull()) {
+ return false;
+ }
+ if (value.isTextual()) {
+ return isFixed.test(value.asText());
+ }
+ if (value.isArray() && !value.isEmpty()) {
+ for (JsonNode item : value) {
+ if (!item.isTextual() || !isFixed.test(item.asText())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private static boolean isFixedValue(String value) {
+ return !value.isEmpty()
+ && value.indexOf('*') < 0
+ && value.indexOf('?') < 0
+ && !value.contains("${");
+ }
+
+ private static boolean isFixedAccountAccessPointArn(String value) {
+ return BUCKET_POLICY_ACCESS_POINT_ARN.matcher(value).matches();
+ }
+
+ private static boolean allSourceIpRangesNarrow(JsonNode value) {
+ if (value == null || value.isNull()) {
+ return false;
+ }
+ if (value.isTextual()) {
+ return isNarrowCidr(value.asText());
+ }
+ if (value.isArray() && !value.isEmpty()) {
+ for (JsonNode item : value) {
+ if (!item.isTextual() || !isNarrowCidr(item.asText())) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * AWS still calls a policy public when it is conditioned on an {@code aws:SourceIp} range
+ * broader than /8 for IPv4 or /32 for IPv6, so only a prefix at least that long makes the
+ * statement non-public. A bare address carries no prefix and is as narrow as a range gets.
+ */
+ private static boolean isNarrowCidr(String cidr) {
+ int slash = cidr.indexOf('/');
+ if (slash < 0) {
+ return isFixedValue(cidr);
+ }
+ String address = cidr.substring(0, slash);
+ if (!isFixedValue(address)) {
+ return false;
+ }
+ try {
+ int prefixLength = Integer.parseInt(cidr.substring(slash + 1).trim());
+ return address.indexOf(':') >= 0 ? prefixLength >= 32 : prefixLength >= 8;
+ } catch (NumberFormatException e) {
+ LOG.debugv("Treating aws:SourceIp value with an unparseable prefix as public: {0}", cidr);
+ return false;
+ }
+ }
+
static String bucketArn(String bucketName) {
return "arn:aws:s3:::" + bucketName;
}
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.java
index f9aec66fe3..952057a82a 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
@@ -570,10 +570,18 @@ public class S3Service implements Resettable, ResourceProvider {
object.setSseCustomerAlgorithm(sseCustomerKey.algorithm());
object.setSseCustomerKeyMd5(sseCustomerKey.keyMd5());
}
- object.setAcl(resolveObjectAclXml(bucketOwnerAccount,
+ String objectAcl = resolveObjectAclXml(bucketOwnerAccount,
effectiveOptions.getAcl(), effectiveOptions.getGrantRead(),
effectiveOptions.getGrantWrite(), effectiveOptions.getGrantFullControl(),
- effectiveOptions.getGrantReadAcp(), effectiveOptions.getGrantWriteAcp()));
+ effectiveOptions.getGrantReadAcp(), effectiveOptions.getGrantWriteAcp());
+ // BlockPublicAcls fails a PutObject that carries a public ACL. The bucket and its owner
+ // are already resolved here, so the settings are read without a second lookup.
+ if (objectAcl != null && S3AclPublicAccessEvaluator.aclIsPublic(objectAcl)
+ && blockPublicAccessFor(bucket, bucketOwnerAccount).blockPublicAcls()) {
+ LOG.debugv("BlockPublicAcls rejected a public ACL on PutObject {0}/{1}", bucketName, key);
+ throw accessDeniedException(bucketName, key);
+ }
+ object.setAcl(objectAcl);
if (effectiveOptions.getTagging() != null && !effectiveOptions.getTagging().isEmpty()) {
object.setTags(new HashMap<>(effectiveOptions.getTagging()));
}
@@ -919,8 +927,11 @@ public class S3Service implements Resettable, ResourceProvider {
return;
}
- Bucket bucket = resolveBucket(bucketName)
+ AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
+ Bucket bucket = ownedBucket.value();
+ S3BlockPublicAccessSettings blockPublicAccess =
+ blockPublicAccessFor(bucket, ownedBucket.account());
String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key);
S3PublicAccessEvaluator.PublicAccessDecision policyDecision =
@@ -929,10 +940,14 @@ public class S3Service implements Resettable, ResourceProvider {
throw accessDeniedException(bucketName, key);
}
if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {
+ if (restrictsPublicPolicy(blockPublicAccess, bucket)) {
+ LOG.debugv("RestrictPublicBuckets withheld anonymous {0} on bucket {1}", action, bucketName);
+ throw accessDeniedException(bucketName, key);
+ }
return;
}
- if (isObjectCreationAction(action) && !readableObjectExists(bucketName, key)
- && publicBucketAclAllowsWrite(bucket)) {
+ if (!blockPublicAccess.ignorePublicAcls() && isObjectCreationAction(action)
+ && !readableObjectExists(bucketName, key) && publicBucketAclAllowsWrite(bucket)) {
return;
}
@@ -981,8 +996,11 @@ public class S3Service implements Resettable, ResourceProvider {
return;
}
- Bucket bucket = resolveBucket(bucketName)
+ AccountAwareStorageBackend.OwnedEntry<Bucket> ownedBucket = resolveBucketEntry(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
+ Bucket bucket = ownedBucket.value();
+ S3BlockPublicAccessSettings blockPublicAccess =
+ blockPublicAccessFor(bucket, ownedBucket.account());
S3PublicAccessEvaluator.PublicAccessDecision policyDecision =
S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, resourceArn);
@@ -990,18 +1008,35 @@ public class S3Service implements Resettable, ResourceProvider {
throw accessDeniedException(bucketName, key);
}
if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {
+ if (restrictsPublicPolicy(blockPublicAccess, bucket)) {
+ LOG.debugv("RestrictPublicBuckets withheld anonymous {0} on bucket {1}", action, bucketName);
+ throw accessDeniedException(bucketName, key);
+ }
return;
}
- if (key != null && isObjectDataReadAction(action) && publicObjectAclAllowsRead(bucketName, key, versionId)) {
- return;
- }
- if (key == null && "s3:ListBucket".equals(action) && publicBucketAclAllowsRead(bucket)) {
- return;
+ if (!blockPublicAccess.ignorePublicAcls()) {
+ if (key != null && isObjectDataReadAction(action) && publicObjectAclAllowsRead(bucketName, key, versionId)) {
+ return;
+ }
+ if (key == null && "s3:ListBucket".equals(action) && publicBucketAclAllowsRead(bucket)) {
+ return;
+ }
}
throw accessDeniedException(bucketName, key);
}
+ /**
+ * {@code RestrictPublicBuckets} confines a bucket whose policy is public to the owner
+ * account, so the public statement stops granting anything to an anonymous or cross-account
+ * caller. One public statement makes the whole policy public, which is why the status is
+ * evaluated over the policy rather than over the statement that happened to match.
+ */
+ private boolean restrictsPublicPolicy(S3BlockPublicAccessSettings settings, Bucket bucket) {
+ return settings.restrictPublicBuckets()
+ && S3PublicAccessEvaluator.policyIsPublic(objectMapper, bucket.getPolicy());
+ }
+
private void authorizeSignedBucketPolicy(
String bucketName,
String key,
@@ -1026,6 +1061,15 @@ public class S3Service implements Resettable, ResourceProvider {
throw accessDeniedException(bucketName, key);
}
+ // RestrictPublicBuckets blocks cross-account access derived from a public bucket policy,
+ // including the non-public delegation a statement naming a specific account would grant.
+ // AWS exempts AWS service principals; this path is only ever reached by an IAM principal,
+ // so there is nothing to exempt here.
+ if (!sameAccountAsOwner && restrictsPublicPolicy(blockPublicAccessFor(bucket, bucketOwner), bucket)) {
+ LOG.debugv("RestrictPublicBuckets withheld cross-account {0} on bucket {1}", action, bucketName);
+ throw accessDeniedException(bucketName, key);
+ }
+
String policy = bucket.getPolicy();
if (policy == null || policy.isBlank()) {
if (sameAccountAsOwner) {
@@ -3501,7 +3545,17 @@ public class S3Service implements Resettable, ResourceProvider {
return bucket.getPolicy();
}
+ /**
+ * {@code BlockPublicPolicy} rejects a bucket policy that grants public access. As on AWS the
+ * check runs whoever the caller is, so it does not sit behind {@code enforce-auth}, and it
+ * leaves an already-stored public policy alone: the setting blocks the write, not the read.
+ */
public void putBucketPolicy(String bucketName, String policy) {
+ if (effectiveBlockPublicAccess(bucketName).blockPublicPolicy()
+ && S3PublicAccessEvaluator.policyIsPublic(objectMapper, policy)) {
+ LOG.debugv("BlockPublicPolicy rejected a public bucket policy on bucket {0}", bucketName);
+ throw accessDeniedException(bucketName, null);
+ }
mutateBucket(bucketName, bucket -> bucket.setPolicy(policy));
}
@@ -3671,7 +3725,9 @@ public class S3Service implements Resettable, ResourceProvider {
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
String resolvedAcl = resolveObjectAclXml(
cannedAcl, grantRead, grantWrite, grantFullControl, grantReadAcp, grantWriteAcp);
- bucket.setAcl(resolvedAcl != null ? resolvedAcl : (bodyAcl.isBlank() ? null : bodyAcl));
+ String newAcl = resolvedAcl != null ? resolvedAcl : (bodyAcl.isBlank() ? null : bodyAcl);
+ rejectPublicAclWhenBlocked(bucketName, newAcl);
+ bucket.setAcl(newAcl);
bucketStore.put(bucketName, bucket);
}
@@ -3692,7 +3748,9 @@ public class S3Service implements Resettable, ResourceProvider {
S3Object obj = ownedObject.value();
String resolvedAcl = resolveObjectAclXml(ownedObject.account(), cannedAcl, grantRead,
grantWrite, grantFullControl, grantReadAcp, grantWriteAcp);
- obj.setAcl(resolvedAcl != null ? resolvedAcl : (bodyAcl.isBlank() ? null : bodyAcl));
+ String newAcl = resolvedAcl != null ? resolvedAcl : (bodyAcl.isBlank() ? null : bodyAcl);
+ rejectPublicAclWhenBlocked(bucketName, newAcl);
+ obj.setAcl(newAcl);
String storeKey = (versionId != null) ? versionedKey(bucketName, key, versionId) : objectKey(bucketName, key);
putObjectForAccount(ownedObject.account(), storeKey, obj);
}
@@ -3761,6 +3819,47 @@ public class S3Service implements Resettable, ResourceProvider {
bucketStore.put(bucketName, bucket);
}
+ /**
+ * The Block Public Access settings in force for a bucket: its own configuration combined with
+ * the bucket owner account's, most restrictive wins. A bucket that does not resolve blocks
+ * nothing; the caller is about to fail on NoSuchBucket anyway.
+ */
+ private S3BlockPublicAccessSettings effectiveBlockPublicAccess(String bucketName) {
+ return resolveBucketEntry(bucketName)
+ .map(owned -> blockPublicAccessFor(owned.value(), owned.account()))
+ .orElse(S3BlockPublicAccessSettings.NONE);
+ }
+
+ private S3BlockPublicAccessSettings blockPublicAccessFor(Bucket bucket, String bucketOwnerAccount) {
+ return S3BlockPublicAccessSettings.parse(bucket.getPublicAccessBlockConfiguration())
+ .mostRestrictive(accountBlockPublicAccess(bucketOwnerAccount));
+ }
+
+ private S3BlockPublicAccessSettings accountBlockPublicAccess(String accountId) {
+ if (accountId == null || accountId.isBlank()) {
+ return S3BlockPublicAccessSettings.NONE;
+ }
+ return accountPublicAccessBlockStore
+ .getForAccount(accountId, ACCOUNT_PUBLIC_ACCESS_BLOCK_KEY)
+ .map(S3BlockPublicAccessSettings::parse)
+ .orElse(S3BlockPublicAccessSettings.NONE);
+ }
+
+ /**
+ * {@code BlockPublicAcls} rejects the write that would store a public ACL. AWS applies this
+ * whoever the caller is, so it does not sit behind {@code enforce-auth}: the call fails the
+ * same way for a signed and an unsigned caller.
+ */
+ private void rejectPublicAclWhenBlocked(String bucketName, String acl) {
+ if (acl == null || !S3AclPublicAccessEvaluator.aclIsPublic(acl)) {
+ return;
+ }
+ if (effectiveBlockPublicAccess(bucketName).blockPublicAcls()) {
+ LOG.debugv("BlockPublicAcls rejected a public ACL on bucket {0}", bucketName);
+ throw accessDeniedException(bucketName, null);
+ }
+ }
+
// --- Account-level (S3 Control) Public Access Block ---
// AWS s3control PutPublicAccessBlock / GetPublicAccessBlock / DeletePublicAccessBlock,
// keyed by AccountId (from the x-amz-account-id header). AWS LZA's
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.java
index 6139978717..af0f15d8f0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AclPublicAccessEvaluatorTest.java
@@ -83,6 +83,63 @@ class S3AclPublicAccessEvaluatorTest {
assertFalse(S3AclPublicAccessEvaluator.aclAllowsPublicRead("<AccessControlPolicy>"));
}
+ // Block Public Access asks a broader question than grant evaluation does: an ACL counts as
+ // public when it grants ANY permission to AllUsers or to AuthenticatedUsers, so a
+ // WRITE_ACP grant and an AuthenticatedUsers grant are both public here while neither
+ // grants an anonymous caller a read.
+
+ @Test
+ void allUsersReadAclIsPublic() {
+ assertTrue(S3AclPublicAccessEvaluator.aclIsPublic(acl(
+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ"))));
+ }
+
+ @Test
+ void authenticatedUsersAclIsPublic() {
+ assertTrue(S3AclPublicAccessEvaluator.aclIsPublic(acl(
+ groupGrant(AUTHENTICATED_USERS_GROUP_URI, "READ"))));
+ }
+
+ @Test
+ void anyPermissionToAPublicGroupIsPublic() {
+ assertTrue(S3AclPublicAccessEvaluator.aclIsPublic(acl(
+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "WRITE_ACP"))));
+ assertTrue(S3AclPublicAccessEvaluator.aclIsPublic(acl(
+ groupGrant(S3AclPublicAccessEvaluator.ALL_USERS_GROUP_URI, "READ_ACP"))));
+ }
+
+ @Test
+ void logDeliveryGroupAclIsNotPublic() {
+ assertFalse(S3AclPublicAccessEvaluator.aclIsPublic(acl(groupGrant(
+ "http://acs.amazonaws.com/groups/s3/LogDelivery", "WRITE"))));
+ }
+
+ @Test
+ void canonicalUserOnlyAclIsNotPublic() {
+ String acl = """
+ <AccessControlPolicy>
+ <AccessControlList>
+ <Grant>
+ <Grantee xsi:type="CanonicalUser"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+ <ID>000000000000</ID>
+ </Grantee>
+ <Permission>FULL_CONTROL</Permission>
+ </Grant>
+ </AccessControlList>
+ </AccessControlPolicy>
+ """;
+
+ assertFalse(S3AclPublicAccessEvaluator.aclIsPublic(acl));
+ }
+
+ @Test
+ void invalidAclIsNotPublic() {
+ assertFalse(S3AclPublicAccessEvaluator.aclIsPublic(null));
+ assertFalse(S3AclPublicAccessEvaluator.aclIsPublic(""));
+ assertFalse(S3AclPublicAccessEvaluator.aclIsPublic("<AccessControlPolicy>"));
+ }
+
private static String acl(String... grants) {
return """
<AccessControlPolicy>
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..0bd32f1fea
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessEnforcementIntegrationTest.java
@@ -0,0 +1,219 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.github.hectorvent.floci.testutil.S3RequestSigner;
+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.util.Map;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * The read-time half of Block Public Access: {@code RestrictPublicBuckets} withholds the access a
+ * public bucket policy grants, and {@code IgnorePublicAcls} withholds the access a public ACL
+ * grants. Both act on an existing policy or ACL rather than on the write that created it, so
+ * they only have meaning once anonymous authorization runs, which is what {@code enforce-auth}
+ * turns on.
+ */
+@QuarkusTest
+@TestProfile(S3BlockPublicAccessEnforcementIntegrationTest.EnforcementProfile.class)
+class S3BlockPublicAccessEnforcementIntegrationTest {
+
+ private static final S3RequestSigner OWNER = S3RequestSigner.signedAs("test", "test");
+
+ private static final String PUBLIC_READ_POLICY = """
+ {"Version":"2012-10-17","Statement":[{"Sid":"PublicRead","Effect":"Allow",
+ "Principal":"*","Action":["s3:GetObject","s3:ListBucket"],
+ "Resource":["arn:aws:s3:::%1$s","arn:aws:s3:::%1$s/*"]}]}
+ """;
+
+ public static final class EnforcementProfile implements QuarkusTestProfile {
+ @Override
+ public Map<String, String> getConfigOverrides() {
+ return Map.of("floci.services.s3.enforce-auth", "true");
+ }
+ }
+
+ @Test
+ void anonymousGetSucceedsOnAPublicPolicyWithoutRestrictPublicBuckets() {
+ String bucket = bucketWithPublicPolicy();
+
+ given().when().get("/" + bucket + "/object.txt")
+ .then().statusCode(200).body(equalTo("hello"));
+ }
+
+ @Test
+ void restrictPublicBucketsWithholdsAnonymousGetOnAPublicPolicy() {
+ String bucket = bucketWithPublicPolicy();
+ putBucketPublicAccessBlock(bucket, false, false, false, true);
+
+ given().when().get("/" + bucket + "/object.txt")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void restrictPublicBucketsWithholdsAnonymousListBucketOnAPublicPolicy() {
+ String bucket = bucketWithPublicPolicy();
+ putBucketPublicAccessBlock(bucket, false, false, false, true);
+
+ given().when().get("/" + bucket)
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void restrictPublicBucketsLeavesTheOwnersSignedAccessAlone() {
+ String bucket = bucketWithPublicPolicy();
+ putBucketPublicAccessBlock(bucket, false, false, false, true);
+
+ given().filter(OWNER).when().get("/" + bucket + "/object.txt")
+ .then().statusCode(200).body(equalTo("hello"));
+ }
+
+ @Test
+ void restrictPublicBucketsDoesNotAffectABucketWhosePolicyIsNotPublic() {
+ String bucket = createBucket();
+ putObject(bucket, "object.txt");
+ putBucketPolicy(bucket, """
+ {"Version":"2012-10-17","Statement":[{"Sid":"OneAccount","Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::111122223333:root"},"Action":"s3:GetObject",
+ "Resource":"arn:aws:s3:::%s/*"}]}
+ """.formatted(bucket));
+ putBucketPublicAccessBlock(bucket, false, false, false, true);
+
+ given().filter(OWNER).when().get("/" + bucket + "/object.txt")
+ .then().statusCode(200).body(equalTo("hello"));
+ }
+
+ @Test
+ void theAccountLevelRestrictPublicBucketsWithholdsAnonymousGet() {
+ String bucket = bucketWithPublicPolicy();
+ putAccountPublicAccessBlock(false, false, false, true);
+ try {
+ given().when().get("/" + bucket + "/object.txt")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ } finally {
+ deleteAccountPublicAccessBlock();
+ }
+ }
+
+ @Test
+ void anonymousGetSucceedsOnAPublicObjectAclWithoutIgnorePublicAcls() {
+ String bucket = bucketWithPublicObjectAcl();
+
+ given().when().get("/" + bucket + "/object.txt")
+ .then().statusCode(200).body(equalTo("hello"));
+ }
+
+ @Test
+ void ignorePublicAclsWithholdsAnonymousGetOnAPublicObjectAcl() {
+ String bucket = bucketWithPublicObjectAcl();
+ putBucketPublicAccessBlock(bucket, false, true, false, false);
+
+ given().when().get("/" + bucket + "/object.txt")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void ignorePublicAclsWithholdsAnonymousListBucketOnAPublicBucketAcl() {
+ String bucket = createBucket();
+ putObject(bucket, "object.txt");
+ given().filter(OWNER).header("x-amz-acl", "public-read")
+ .when().put("/" + bucket + "?acl")
+ .then().statusCode(200);
+
+ given().when().get("/" + bucket).then().statusCode(200);
+
+ putBucketPublicAccessBlock(bucket, false, true, false, false);
+
+ given().when().get("/" + bucket)
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void ignorePublicAclsLeavesTheOwnersSignedAccessAlone() {
+ String bucket = bucketWithPublicObjectAcl();
+ putBucketPublicAccessBlock(bucket, false, true, false, false);
+
+ given().filter(OWNER).when().get("/" + bucket + "/object.txt")
+ .then().statusCode(200).body(equalTo("hello"));
+ }
+
+ private static String bucketWithPublicPolicy() {
+ String bucket = createBucket();
+ putObject(bucket, "object.txt");
+ putBucketPolicy(bucket, PUBLIC_READ_POLICY.formatted(bucket));
+ return bucket;
+ }
+
+ private static String bucketWithPublicObjectAcl() {
+ String bucket = createBucket();
+ putObject(bucket, "object.txt");
+ given().filter(OWNER).header("x-amz-acl", "public-read")
+ .when().put("/" + bucket + "/object.txt?acl")
+ .then().statusCode(200);
+ return bucket;
+ }
+
+ private static String createBucket() {
+ String bucket = "bpa-enforce-" + UUID.randomUUID();
+ given().filter(OWNER).when().put("/" + bucket).then().statusCode(200);
+ return bucket;
+ }
+
+ private static void putObject(String bucket, String key) {
+ given().filter(OWNER).body("hello")
+ .when().put("/" + bucket + "/" + key)
+ .then().statusCode(200);
+ }
+
+ private static void putBucketPolicy(String bucket, String policy) {
+ given().filter(OWNER).body(policy)
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(200);
+ }
+
+ private static void putBucketPublicAccessBlock(String bucket, boolean blockPublicAcls,
+ boolean ignorePublicAcls, boolean blockPublicPolicy,
+ boolean restrictPublicBuckets) {
+ given().filter(OWNER)
+ .body(configuration(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets))
+ .when().put("/" + bucket + "?publicAccessBlock")
+ .then().statusCode(200);
+ }
+
+ private static void putAccountPublicAccessBlock(boolean blockPublicAcls, boolean ignorePublicAcls,
+ boolean blockPublicPolicy, boolean restrictPublicBuckets) {
+ given().filter(OWNER).header("x-amz-account-id", "000000000000")
+ .body(configuration(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets))
+ .when().put("/v20180820/configuration/publicAccessBlock")
+ .then().statusCode(200);
+ }
+
+ private static void deleteAccountPublicAccessBlock() {
+ given().filter(OWNER).header("x-amz-account-id", "000000000000")
+ .when().delete("/v20180820/configuration/publicAccessBlock")
+ .then().statusCode(204);
+ }
+
+ private static String configuration(boolean blockPublicAcls, boolean ignorePublicAcls,
+ boolean blockPublicPolicy, boolean restrictPublicBuckets) {
+ return """
+ <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+ <BlockPublicAcls>%s</BlockPublicAcls>
+ <IgnorePublicAcls>%s</IgnorePublicAcls>
+ <BlockPublicPolicy>%s</BlockPublicPolicy>
+ <RestrictPublicBuckets>%s</RestrictPublicBuckets>
+ </PublicAccessBlockConfiguration>
+ """.formatted(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessIntegrationTest.java
new file mode 100644
index 0000000000..ad5f1da031
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessIntegrationTest.java
@@ -0,0 +1,229 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.Test;
+
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+
+/**
+ * The write-time half of Block Public Access: {@code BlockPublicPolicy} and
+ * {@code BlockPublicAcls} reject the call that would introduce public access.
+ *
+ * <p>AWS applies both whoever the caller is, so these run under the default configuration with
+ * no {@code enforce-auth} and no IAM enforcement. The read-time half
+ * ({@code RestrictPublicBuckets}, {@code IgnorePublicAcls}) only has meaning once anonymous
+ * authorization runs at all, and is covered by
+ * {@link S3BlockPublicAccessEnforcementIntegrationTest}.
+ */
+@QuarkusTest
+class S3BlockPublicAccessIntegrationTest {
+
+ private static final String PUBLIC_POLICY = """
+ {"Version":"2012-10-17","Statement":[{"Sid":"PublicRead","Effect":"Allow",
+ "Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*"}]}
+ """;
+
+ private static final String ACCOUNT_SCOPED_POLICY = """
+ {"Version":"2012-10-17","Statement":[{"Sid":"OneAccount","Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::111122223333:root"},"Action":"s3:GetObject",
+ "Resource":"arn:aws:s3:::%s/*"}]}
+ """;
+
+ @Test
+ void blockPublicPolicyRejectsAPublicBucketPolicy() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, false, false, true, false);
+
+ given().body(PUBLIC_POLICY.formatted(bucket))
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void blockPublicPolicyLeavesANonPublicBucketPolicyAlone() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, false, false, true, false);
+
+ given().body(ACCOUNT_SCOPED_POLICY.formatted(bucket))
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void blockPublicPolicyAcceptsFixedAccountAccessPointWildcard() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, false, false, true, false);
+ String policy = """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*",
+ "Condition":{"ArnLike":{"s3:DataAccessPointArn":
+ "arn:aws:s3:us-west-2:123456789012:accesspoint/*"}}}]}
+ """.formatted(bucket);
+
+ given().body(policy)
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void blockPublicPolicyAcceptsForAnyValueWithFixedPrincipalOrgPath() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, false, false, true, false);
+ String policy = """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%s/*",
+ "Condition":{"ForAnyValue:StringLike":{"aws:PrincipalOrgPaths":
+ ["o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/"]}}}]}
+ """.formatted(bucket);
+
+ given().body(policy)
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void aPublicBucketPolicyIsAcceptedWithoutBlockPublicPolicy() {
+ String bucket = createBucket();
+
+ given().body(PUBLIC_POLICY.formatted(bucket))
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void blockPublicPolicyDoesNotRemoveAPolicyStoredBeforeItWasSet() {
+ String bucket = createBucket();
+ given().body(PUBLIC_POLICY.formatted(bucket))
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(200);
+
+ putBucketPublicAccessBlock(bucket, false, false, true, false);
+
+ given().when().get("/" + bucket + "?policy")
+ .then().statusCode(200)
+ .body(containsString("PublicRead"));
+ }
+
+ @Test
+ void theAccountLevelSettingBlocksAPublicPolicyOnItsOwn() {
+ String bucket = createBucket();
+ putAccountPublicAccessBlock(false, false, true, false);
+ try {
+ given().body(PUBLIC_POLICY.formatted(bucket))
+ .when().put("/" + bucket + "?policy")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ } finally {
+ deleteAccountPublicAccessBlock();
+ }
+ }
+
+ @Test
+ void blockPublicAclsRejectsAPublicBucketAcl() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, true, false, false, false);
+
+ given().header("x-amz-acl", "public-read")
+ .when().put("/" + bucket + "?acl")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void blockPublicAclsLeavesAPrivateBucketAclAlone() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, true, false, false, false);
+
+ given().header("x-amz-acl", "private")
+ .when().put("/" + bucket + "?acl")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void blockPublicAclsRejectsAPublicObjectAcl() {
+ String bucket = createBucket();
+ given().body("hello").when().put("/" + bucket + "/object.txt").then().statusCode(200);
+ putBucketPublicAccessBlock(bucket, true, false, false, false);
+
+ given().header("x-amz-acl", "public-read")
+ .when().put("/" + bucket + "/object.txt?acl")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void blockPublicAclsRejectsAPutObjectCarryingAPublicAcl() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, true, false, false, false);
+
+ given().header("x-amz-acl", "public-read").body("hello")
+ .when().put("/" + bucket + "/public.txt")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ @Test
+ void blockPublicAclsLeavesAPutObjectWithoutAPublicAclAlone() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, true, false, false, false);
+
+ given().body("hello")
+ .when().put("/" + bucket + "/private.txt")
+ .then().statusCode(200);
+ }
+
+ @Test
+ void anAuthenticatedUsersAclCountsAsPublic() {
+ String bucket = createBucket();
+ putBucketPublicAccessBlock(bucket, true, false, false, false);
+
+ given().header("x-amz-acl", "authenticated-read")
+ .when().put("/" + bucket + "?acl")
+ .then().statusCode(403)
+ .body(containsString("AccessDenied"));
+ }
+
+ private static String createBucket() {
+ String bucket = "bpa-" + UUID.randomUUID();
+ given().when().put("/" + bucket).then().statusCode(200);
+ return bucket;
+ }
+
+ private static void putBucketPublicAccessBlock(String bucket, boolean blockPublicAcls,
+ boolean ignorePublicAcls, boolean blockPublicPolicy,
+ boolean restrictPublicBuckets) {
+ given().body(configuration(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets))
+ .when().put("/" + bucket + "?publicAccessBlock")
+ .then().statusCode(200);
+ }
+
+ private static void putAccountPublicAccessBlock(boolean blockPublicAcls, boolean ignorePublicAcls,
+ boolean blockPublicPolicy, boolean restrictPublicBuckets) {
+ given().header("x-amz-account-id", "000000000000")
+ .body(configuration(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets))
+ .when().put("/v20180820/configuration/publicAccessBlock")
+ .then().statusCode(200);
+ }
+
+ private static void deleteAccountPublicAccessBlock() {
+ given().header("x-amz-account-id", "000000000000")
+ .when().delete("/v20180820/configuration/publicAccessBlock")
+ .then().statusCode(204);
+ }
+
+ private static String configuration(boolean blockPublicAcls, boolean ignorePublicAcls,
+ boolean blockPublicPolicy, boolean restrictPublicBuckets) {
+ return """
+ <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+ <BlockPublicAcls>%s</BlockPublicAcls>
+ <IgnorePublicAcls>%s</IgnorePublicAcls>
+ <BlockPublicPolicy>%s</BlockPublicPolicy>
+ <RestrictPublicBuckets>%s</RestrictPublicBuckets>
+ </PublicAccessBlockConfiguration>
+ """.formatted(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessSettingsTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessSettingsTest.java
new file mode 100644
index 0000000000..cec308e4e3
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3BlockPublicAccessSettingsTest.java
@@ -0,0 +1,109 @@
+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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class S3BlockPublicAccessSettingsTest {
+
+ @Test
+ void parsesAllFourFlags() {
+ S3BlockPublicAccessSettings settings = S3BlockPublicAccessSettings.parse(configuration(
+ true, true, true, true));
+
+ assertTrue(settings.blockPublicAcls());
+ assertTrue(settings.ignorePublicAcls());
+ assertTrue(settings.blockPublicPolicy());
+ assertTrue(settings.restrictPublicBuckets());
+ }
+
+ @Test
+ void parsesFlagsIndependently() {
+ S3BlockPublicAccessSettings settings = S3BlockPublicAccessSettings.parse(configuration(
+ false, true, false, true));
+
+ assertFalse(settings.blockPublicAcls());
+ assertTrue(settings.ignorePublicAcls());
+ assertFalse(settings.blockPublicPolicy());
+ assertTrue(settings.restrictPublicBuckets());
+ }
+
+ @Test
+ void anOmittedFlagIsOff() {
+ S3BlockPublicAccessSettings settings = S3BlockPublicAccessSettings.parse("""
+ <PublicAccessBlockConfiguration>
+ <BlockPublicPolicy>true</BlockPublicPolicy>
+ </PublicAccessBlockConfiguration>
+ """);
+
+ assertTrue(settings.blockPublicPolicy());
+ assertFalse(settings.blockPublicAcls());
+ assertFalse(settings.ignorePublicAcls());
+ assertFalse(settings.restrictPublicBuckets());
+ }
+
+ @Test
+ void anAbsentConfigurationBlocksNothing() {
+ assertEquals(S3BlockPublicAccessSettings.NONE, S3BlockPublicAccessSettings.parse(null));
+ assertEquals(S3BlockPublicAccessSettings.NONE, S3BlockPublicAccessSettings.parse(""));
+ }
+
+ @Test
+ void malformedXmlBlocksNothing() {
+ assertEquals(S3BlockPublicAccessSettings.NONE,
+ S3BlockPublicAccessSettings.parse("<PublicAccessBlockConfiguration"));
+ }
+
+ @Test
+ void mostRestrictiveCombinesFlagsFromBothLevels() {
+ S3BlockPublicAccessSettings bucket = S3BlockPublicAccessSettings.parse(configuration(
+ true, false, false, false));
+ S3BlockPublicAccessSettings account = S3BlockPublicAccessSettings.parse(configuration(
+ false, false, true, false));
+
+ S3BlockPublicAccessSettings effective = bucket.mostRestrictive(account);
+
+ assertTrue(effective.blockPublicAcls());
+ assertTrue(effective.blockPublicPolicy());
+ assertFalse(effective.ignorePublicAcls());
+ assertFalse(effective.restrictPublicBuckets());
+ }
+
+ @Test
+ void mostRestrictiveNeverRelaxesAFlag() {
+ S3BlockPublicAccessSettings all = S3BlockPublicAccessSettings.parse(configuration(
+ true, true, true, true));
+
+ assertEquals(all, all.mostRestrictive(S3BlockPublicAccessSettings.NONE));
+ assertEquals(all, S3BlockPublicAccessSettings.NONE.mostRestrictive(all));
+ }
+
+ @Test
+ void mostRestrictiveTreatsAMissingConfigurationAsNoFlags() {
+ S3BlockPublicAccessSettings bucket = S3BlockPublicAccessSettings.parse(configuration(
+ false, true, false, false));
+
+ assertEquals(bucket, bucket.mostRestrictive(null));
+ }
+
+ @Test
+ void anyFlagSetIsReported() {
+ assertFalse(S3BlockPublicAccessSettings.NONE.blocksAnything());
+ assertTrue(S3BlockPublicAccessSettings.parse(configuration(false, false, false, true))
+ .blocksAnything());
+ }
+
+ private static String configuration(boolean blockPublicAcls, boolean ignorePublicAcls,
+ boolean blockPublicPolicy, boolean restrictPublicBuckets) {
+ return """
+ <PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+ <BlockPublicAcls>%s</BlockPublicAcls>
+ <IgnorePublicAcls>%s</IgnorePublicAcls>
+ <BlockPublicPolicy>%s</BlockPublicPolicy>
+ <RestrictPublicBuckets>%s</RestrictPublicBuckets>
+ </PublicAccessBlockConfiguration>
+ """.formatted(blockPublicAcls, ignorePublicAcls, blockPublicPolicy, restrictPublicBuckets);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicPolicyStatusTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicPolicyStatusTest.java
new file mode 100644
index 0000000000..28c87b7561
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PublicPolicyStatusTest.java
@@ -0,0 +1,223 @@
+package io.github.hectorvent.floci.services.s3;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The "meaning of public" rules S3 Block Public Access applies to a bucket policy. S3 assumes a
+ * policy is public and then looks for a reason it is not: a wildcard principal is public unless
+ * the statement pins one of the recognised condition keys to a fixed, wildcard-free value.
+ */
+class S3PublicPolicyStatusTest {
+
+ private final ObjectMapper objectMapper = new ObjectMapper();
+
+ @Test
+ void wildcardPrincipalAllowIsPublic() {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:PutObject","Effect":"Allow"}]}
+ """));
+ }
+
+ @Test
+ void wildcardAwsPrincipalAllowIsPublic() {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":{"AWS":"*"},"Resource":"arn:aws:s3:::b/*",
+ "Action":"s3:GetObject","Effect":"Allow"}]}
+ """));
+ }
+
+ @Test
+ void wildcardPrincipalDenyIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:*","Effect":"Deny"}]}
+ """));
+ }
+
+ @Test
+ void fixedPrincipalAllowIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":{"AWS":"arn:aws:iam::111122223333:root"},
+ "Resource":"arn:aws:s3:::b/*","Action":"s3:GetObject","Effect":"Allow"}]}
+ """));
+ }
+
+ @Test
+ void servicePrincipalAllowIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":{"Service":"cloudtrail.amazonaws.com"},
+ "Resource":"arn:aws:s3:::b/*","Action":"s3:PutObject","Effect":"Allow"}]}
+ """));
+ }
+
+ @Test
+ void wildcardPrincipalPinnedToAFixedSourceVpcIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:PutObject","Effect":"Allow",
+ "Condition":{"StringEquals":{"aws:SourceVpc":"vpc-91237329"}}}]}
+ """));
+ }
+
+ @Test
+ void wildcardPrincipalWithAWildcardSourceVpcIsPublic() {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:PutObject","Effect":"Allow",
+ "Condition":{"StringLike":{"aws:SourceVpc":"vpc-*"}}}]}
+ """));
+ }
+
+ @Test
+ void wildcardPrincipalPinnedToAFixedPrincipalArnIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"arn:aws:iam::111122223333:role/app"}}}]}
+ """));
+ }
+
+ @Test
+ void wildcardPrincipalPinnedToAFixedSourceAccountIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"StringEquals":{"aws:SourceAccount":"111122223333"}}}]}
+ """));
+ }
+
+ @Test
+ void forAnyValueWithFixedPrincipalOrgPathIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"ForAnyValue:StringLike":{"aws:PrincipalOrgPaths":
+ ["o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/"]}}}]}
+ """));
+ }
+
+ @Test
+ void forAllValuesOrWildcardOrgPathDoesNotNarrowPublicAccess() {
+ for (String operator : new String[] {"ForAllValues:StringLike", "ForAnyValue:StringLike"}) {
+ String path = operator.startsWith("ForAllValues")
+ ? "o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/"
+ : "o-a1b2c3d4e5/r-ab12/ou-ab12-11111111/*";
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"%s":{"aws:PrincipalOrgPaths":["%s"]}}}]}
+ """.formatted(operator, path)));
+ }
+ }
+
+ @Test
+ void accessPointNameWildcardWithFixedAccountIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"arn:aws:s3:::b/*",
+ "Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"ArnLike":{"s3:DataAccessPointArn":
+ "arn:aws:s3:us-west-2:123456789012:accesspoint/*"}}}]}
+ """));
+ }
+
+ @Test
+ void accessPointArnWithWildcardAccountIsPublic() {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"arn:aws:s3:::b/*",
+ "Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"ArnLike":{"s3:DataAccessPointArn":
+ "arn:aws:s3:us-west-2:*:accesspoint/*"}}}]}
+ """));
+ }
+
+ @Test
+ void negatedOrOptionalConditionDoesNotMakePolicyNonPublic() {
+ for (String operator : new String[] {"StringNotEquals", "StringEqualsIfExists", "IpAddress"}) {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*",
+ "Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"%s":{"aws:SourceAccount":"123456789012"}}}]}
+ """.formatted(operator)));
+ }
+ }
+
+ @Test
+ void anUnrecognisedConditionKeyDoesNotMakeAWildcardPrincipalPrivate() {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"StringEquals":{"s3:x-amz-acl":"bucket-owner-full-control"}}}]}
+ """));
+ }
+
+ @Test
+ void aPolicyVariableIsNotAFixedValue() {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"StringEquals":{"aws:userid":"${aws:userid}"}}}]}
+ """));
+ }
+
+ @Test
+ void aNarrowSourceIpRangeIsNotPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"IpAddress":{"aws:SourceIp":"203.0.113.0/24"}}}]}
+ """));
+ }
+
+ @Test
+ void aVeryBroadSourceIpRangeIsPublic() {
+ assertTrue(isPublic("""
+ {"Statement":[{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow",
+ "Condition":{"IpAddress":{"aws:SourceIp":"0.0.0.0/1"}}}]}
+ """));
+ }
+
+ @Test
+ void onePublicStatementMakesTheWholePolicyPublic() {
+ assertTrue(isPublic("""
+ {"Statement":[
+ {"Principal":{"Service":"cloudtrail.amazonaws.com"},"Resource":"arn:aws:s3:::b/*",
+ "Action":"s3:PutObject","Effect":"Allow"},
+ {"Principal":{"AWS":"arn:aws:iam::444455556666:root"},"Resource":"arn:aws:s3:::b/*",
+ "Action":"s3:GetObject","Effect":"Allow"},
+ {"Principal":"*","Resource":"arn:aws:s3:::b/*","Action":"s3:GetObject","Effect":"Allow"}
+ ]}
+ """));
+ }
+
+ @Test
+ void removingThePublicStatementMakesThePolicyNonPublic() {
+ assertFalse(isPublic("""
+ {"Statement":[
+ {"Principal":{"Service":"cloudtrail.amazonaws.com"},"Resource":"arn:aws:s3:::b/*",
+ "Action":"s3:PutObject","Effect":"Allow"},
+ {"Principal":{"AWS":"arn:aws:iam::444455556666:root"},"Resource":"arn:aws:s3:::b/*",
+ "Action":"s3:GetObject","Effect":"Allow"}
+ ]}
+ """));
+ }
+
+ @Test
+ void notPrincipalAllowIsPublic() {
+ assertTrue(isPublic("""
+ {"Statement":[{"NotPrincipal":{"AWS":"arn:aws:iam::111122223333:root"},
+ "Resource":"*","Action":"s3:GetObject","Effect":"Allow"}]}
+ """));
+ }
+
+ @Test
+ void aSingleStatementObjectIsEvaluated() {
+ assertTrue(isPublic("""
+ {"Statement":{"Principal":"*","Resource":"*","Action":"s3:GetObject","Effect":"Allow"}}
+ """));
+ }
+
+ @Test
+ void anAbsentOrUnparseablePolicyIsNotPublic() {
+ assertFalse(isPublic(null));
+ assertFalse(isPublic(""));
+ assertFalse(isPublic("not json"));
+ }
+
+ private boolean isPublic(String policy) {
+ return S3PublicAccessEvaluator.policyIsPublic(objectMapper, policy);
+ }
+}