mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): preserve JSON policies returned by intrinsics (#9574)
AWS::S3::BucketPolicy resolves its PolicyDocument through resolveJsonAttribute before storing it, so a Ref or Fn::Sub that returns the policy as text is stored as written instead of being serialized again into a quoted string. AWS::ECR::Repository's RepositoryPolicyText uses the same resolver in place of its own copy of the unwrap. An SDK test covers a policy written as an object, as a string and through Fn::Sub, checking the stored JSON and the denied read after create and after an unchanged update.
This commit is contained in:
1 parent
9c5f57808a
commit
0285a3df5b
6 files changed
+110
-7
No files matched your search
+1
-2
@@ -236,8 +236,7 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner {
|
||||
if (props == null || !props.has("RepositoryPolicyText")) {
|
||||
return null;
|
||||
}
|
||||
JsonNode pol = ctx.engine().resolveNode(props.get("RepositoryPolicyText"));
|
||||
String policyText = pol.isTextual() ? pol.asText() : pol.toString();
|
||||
String policyText = ctx.engine().resolveJsonAttribute(props.get("RepositoryPolicyText"));
|
||||
return policyText == null || policyText.isEmpty() ? null : policyText;
|
||||
}
|
||||
|
||||
|
||||
+1
-5
@@ -718,11 +718,7 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
|
||||
if (document == null) {
|
||||
return;
|
||||
}
|
||||
// A document given as a JSON string is already the policy; one given as an object may
|
||||
// carry Ref / Fn::GetAtt / Fn::Sub anywhere inside it.
|
||||
String policy = document.isTextual()
|
||||
? document.asText()
|
||||
: ctx.engine().resolveNode(document).toString();
|
||||
String policy = ctx.engine().resolveJsonAttribute(document);
|
||||
s3Service.putBucketPolicy(bucketName, policy);
|
||||
}
|
||||
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package io.floci.aws.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.testing.AwsTestClients;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.S3IamEnforcementProfile;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(S3IamEnforcementProfile.class)
|
||||
class CloudFormationS3PolicyJsonIntegrationTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"object", "string", "substitution"})
|
||||
void aPolicyRemainsAJsonObjectAfterItsTemplateRepresentationIsResolved(String form) throws Exception {
|
||||
String name = "policy-json-" + UUID.randomUUID().toString().replace("-", "");
|
||||
String resourceArn = "arn:aws:s3:::" + name + "/*";
|
||||
ObjectNode template = MAPPER.createObjectNode();
|
||||
ObjectNode resources = template.putObject("Resources");
|
||||
resources.putObject("Bucket").put("Type", "AWS::S3::Bucket")
|
||||
.putObject("Properties").put("BucketName", name);
|
||||
ObjectNode properties = resources.putObject("Policy").put("Type", "AWS::S3::BucketPolicy")
|
||||
.putObject("Properties");
|
||||
properties.putObject("Bucket").put("Ref", "Bucket");
|
||||
String policy = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"},
|
||||
"Action":"s3:GetObject","Resource":"%s"}]}
|
||||
""".formatted(ACCOUNT, resourceArn);
|
||||
switch (form) {
|
||||
case "object" -> properties.set("PolicyDocument", MAPPER.readTree(policy));
|
||||
case "string" -> properties.put("PolicyDocument", policy);
|
||||
case "substitution" -> properties.putObject("PolicyDocument")
|
||||
.put("Fn::Sub", policy.replace(resourceArn, "${Bucket.Arn}/*"));
|
||||
default -> throw new IllegalArgumentException(form);
|
||||
}
|
||||
try (CloudFormationClient cfn = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", "test", Region.US_EAST_1);
|
||||
S3Client s3 = AwsTestClients.create(S3Client.builder(), "test", "test", Region.US_EAST_1)) {
|
||||
cfn.createStack(request -> request.stackName(name).templateBody(template.toString()));
|
||||
boolean objectCreated = false;
|
||||
try {
|
||||
assertEquals("CREATE_COMPLETE",
|
||||
CfnStackWaits.awaitStatus(cfn, name, "CREATE_COMPLETE").stackStatusAsString());
|
||||
JsonNode stored = MAPPER.readTree(s3.getBucketPolicy(request -> request.bucket(name)).policy());
|
||||
assertTrue(stored.isObject());
|
||||
assertEquals(resourceArn, stored.path("Statement").get(0).path("Resource").asText());
|
||||
s3.putObject(request -> request.bucket(name).key("owned"), RequestBody.fromString("owned"));
|
||||
objectCreated = true;
|
||||
S3Exception denied = assertThrows(S3Exception.class,
|
||||
() -> s3.getObjectAsBytes(request -> request.bucket(name).key("owned")));
|
||||
assertEquals("AccessDenied", denied.awsErrorDetails().errorCode());
|
||||
|
||||
((ObjectNode) resources.path("Bucket").path("Properties")).putArray("Tags")
|
||||
.addObject().put("Key", "Revision").put("Value", "updated");
|
||||
cfn.updateStack(request -> request.stackName(name).templateBody(template.toString()));
|
||||
assertEquals("UPDATE_COMPLETE",
|
||||
CfnStackWaits.awaitStatus(cfn, name, "UPDATE_COMPLETE").stackStatusAsString());
|
||||
JsonNode updated = MAPPER.readTree(s3.getBucketPolicy(request -> request.bucket(name)).policy());
|
||||
assertTrue(updated.isObject());
|
||||
assertEquals(stored, updated);
|
||||
S3Exception deniedAfterUpdate = assertThrows(S3Exception.class,
|
||||
() -> s3.getObjectAsBytes(request -> request.bucket(name).key("owned")));
|
||||
assertEquals("AccessDenied", deniedAfterUpdate.awsErrorDetails().errorCode());
|
||||
} finally {
|
||||
if (objectCreated) {
|
||||
s3.deleteObject(request -> request.bucket(name).key("owned"));
|
||||
}
|
||||
CfnStackWaits.deleteStack(cfn, name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -66,6 +66,7 @@ class CfnStableNameUpdatePathTest {
|
||||
return node == null ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(engine.resolveJsonAttribute(any())).thenCallRealMethod();
|
||||
return priorPhysicalId == null
|
||||
? new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack")
|
||||
: new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
|
||||
|
||||
+1
@@ -61,6 +61,7 @@ class LeafCfnProvisionerTest {
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
|
||||
when(engine.resolveJsonAttribute(any())).thenCallRealMethod();
|
||||
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> i.getArgument(0));
|
||||
ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack");
|
||||
}
|
||||
|
||||
+15
@@ -56,6 +56,7 @@ class S3CfnProvisionerTest {
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));
|
||||
when(engine.resolveJsonAttribute(any())).thenCallRealMethod();
|
||||
when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> i.getArgument(0));
|
||||
// A bucket carrying a configuration no test declares, so every declared one is a change.
|
||||
when(s3.getBucketNotificationConfiguration(anyString())).thenReturn(queueNotification("existing"));
|
||||
@@ -881,6 +882,20 @@ class S3CfnProvisionerTest {
|
||||
assertTrue(r.getAttributes().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBucketPolicyIntrinsicReturningJsonTextIsNotEncodedTwice() {
|
||||
JsonNode document = props("""
|
||||
{"Fn::Sub": "{\\"Version\\":\\"2012-10-17\\",\\"Statement\\":[]}"}
|
||||
""");
|
||||
String resolved = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
|
||||
when(ctx.engine().resolveNode(document)).thenReturn(MAPPER.getNodeFactory().textNode(resolved));
|
||||
JsonNode properties = MAPPER.createObjectNode().put("Bucket", "b").set("PolicyDocument", document);
|
||||
|
||||
provisioner.provision(resource("Policy", "AWS::S3::BucketPolicy"), properties, ctx);
|
||||
|
||||
verify(s3).putBucketPolicy("b", resolved);
|
||||
}
|
||||
|
||||
/**
|
||||
* provision runs again on every UpdateStack. The id follows the bucket, which is create-only,
|
||||
* so an unchanged policy keeps its id and does not look like a replaced resource.
|
||||
|
||||
Reference in new issue
Block a user