mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 06:00:46 -05:00
fix(cloudformation): check S3 ownership rules against the resource schema (#5834)
* fix(cloudformation): check S3 ownership rules against the resource schema #5712 made AWS::S3::Bucket apply OwnershipControls, with the provisioner answering a wrong type and a rule without ObjectOwnership, and S3 answering two rules, no rule and an unknown mode with MalformedXML. Two constraints of AWS's published resource schema were still missing. A key the schema does not define was dropped unread: next to a valid rule the stack reached CREATE_COMPLETE, and a misspelt ObjectOwnership was reported as missing. A rule listed twice was refused by S3 for the rule count, not by the schema for the repeat. Both now fail the resource before the bucket is created or changed, in the provisioner's "Model validation failed (#/OwnershipControls...)" form: "extraneous key [<key>] is not permitted" on OwnershipControls and on each rule, and "array items are not unique" on Rules, compared once intrinsic functions are resolved. Every other case keeps #5712's answer: two different rules, no rule and an unknown mode still get MalformedXML, and a rule without ObjectOwnership still reports the missing key. Its type checks get tests for the shapes it did not cover. docs/services/cloudformation.md gains an S3 ownership controls section. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): check each ownership rule before the repeat The uniqueness check ran before each rule's own checks, so a repeated rule that is malformed by itself, such as {"Rules": [{}, {}]} or two string rules, was refused as "array items are not unique" rather than for its own fault, which is the answer #5712 gives the same rule alone. The repeat is now checked once every rule passes on its own, still before S3's rule count. Tests now pin the order and the key each level allows: an extra key beside a Rules of the wrong type, ObjectOwnership on OwnershipControls, Rules on a rule, and a repeat that is not adjacent. The update test checks the error it gets. The previous commit's "Every other case keeps #5712's answer" holds from this commit on. Where the schema and S3 disagree, a missing Rules key and a mode outside the enum still get S3's MalformedXML. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(cloudformation): correct the S3 ownership controls section Say which key each level allows, that S3 rather than the resource schema requires ObjectOwnership, and that a repeated rule is checked once every rule passes its own checks. Name the two cases, a missing Rules and a mode outside the enum, where Floci keeps S3's answer and the schema would refuse the template itself. Describe the reason a stack reports rather than error codes it never shows, and flatten the nested list, which Python-Markdown renders as siblings at a two-space indent. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudformation): pin the repeat check after every ownership rule A repeat ahead of a malformed rule, as in [A, A, {}], must still fail for the third rule's missing ObjectOwnership, as a single malformed rule does. Without this row, checking each rule against the earlier ones inside the rule loop passed every test. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(cloudformation): say S3 ownership rules are checked in turn The section said that what the resource schema refuses is reported first. The provisioner checks each rule in turn, so a rule without ObjectOwnership, which only S3 requires, is reported ahead of a schema fault in a later rule. Give the order the checks run in, and say that CloudFormation's reason can differ for such a rule, since the schema accepts it. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
b6bc3032f1
commit
9099cec5e8
4 files changed
+205
-2
No files matched your search
@@ -505,6 +505,41 @@ Dynamic-reference expansion is currently scoped to these RDS credential properti
|
||||
- On `UpdateStack` (no interruption, as in AWS), a cluster's list is checked first, then the roles the template gained are added, and the roles the previous template declared and the new one drops are removed. A role associated outside the stack is kept while the template leaves it out; declaring it fails the update with `DBClusterRoleAlreadyExists`, as in AWS. If any step of an update is refused, the roles it already added are removed and the ones it removed are put back, so the database matches what the stack still records and a retry starts from there. A rolled-back cluster replacement restores the record of which roles the stack declared.
|
||||
- An Aurora cluster member (`AWS::RDS::DBInstance` with `DBClusterIdentifier`) cannot carry `AssociatedRoles`: the schema documents the property as not applicable there, since the cluster manages its roles. The resource fails with a `ValidationError` pointing at the cluster's `AssociatedRoles`.
|
||||
|
||||
## S3 ownership controls
|
||||
|
||||
`AWS::S3::Bucket` applies `OwnershipControls` through the same S3 call as
|
||||
`PutBucketOwnershipControls`, on create and in place on update.
|
||||
|
||||
- A malformed rule fails the resource before the bucket is created or changed, and the stack
|
||||
rolls back. The resource's status reason gives the first fault found: `OwnershipControls` is
|
||||
checked first, then each rule in turn, then whether a rule repeats another, then S3's own check.
|
||||
- A fault the resource schema defines is reported as
|
||||
`Model validation failed (#/OwnershipControls...: <reason>)`: a value of the wrong type
|
||||
(`OwnershipControls` or a rule that is not an object, `Rules` that is not a list, an
|
||||
`ObjectOwnership` that is a list or an object), a key other than `Rules` on `OwnershipControls`
|
||||
or other than `ObjectOwnership` on a rule (`extraneous key [<key>] is not permitted`), or a
|
||||
rule listed twice (`array items are not unique`), comparing the rules after intrinsic
|
||||
functions such as `Ref` are resolved.
|
||||
- A rule without `ObjectOwnership`, which S3 requires, fails among that rule's own checks in the
|
||||
same form, with `required key [ObjectOwnership] not found`. The schema accepts such a rule, so
|
||||
CloudFormation's reason for a template with one can differ.
|
||||
- What S3 refuses then fails with the message of the `MalformedXML` error that
|
||||
`PutBucketOwnershipControls` returns, `The XML you provided was not well-formed or did not
|
||||
validate against our published schema.`: no rule, more than one rule, or a mode other than
|
||||
`BucketOwnerEnforced`, `BucketOwnerPreferred` or `ObjectWriter`. AWS's published resource
|
||||
schema refuses two of these itself, a missing `Rules` (`required key [Rules] not found`) and a
|
||||
mode outside the three (its `enum`), so CloudFormation's reason for them may differ.
|
||||
- An update that removes `OwnershipControls` from a template that declared it deletes the
|
||||
controls, as a removed `NotificationConfiguration` is cleared; real AWS's answer for that
|
||||
removal is unmeasured. Controls set outside the stack are left alone while neither the previous
|
||||
nor the new template declares the property.
|
||||
- A failed update, including one where a later resource fails, puts back the controls the bucket
|
||||
had before the update, with the rest of its configuration (see
|
||||
[Failed update rollbacks](#failed-update-rollbacks)).
|
||||
- Floci's S3 gives a new bucket no ownership controls, so a bucket that never declares the
|
||||
property answers `GetBucketOwnershipControls` with `OwnershipControlsNotFoundError`, where AWS
|
||||
reports its default, `BucketOwnerEnforced`.
|
||||
|
||||
## Account-Aware Provisioning
|
||||
|
||||
Resources provisioned by `CreateStack` / `UpdateStack` land in the **caller's account** namespace
|
||||
|
||||
+43
-2
@@ -19,6 +19,8 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -246,6 +248,14 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
|
||||
s3Service.putBucketLifecycle(bucketName, lifecycleXml(lifecycle.get("Rules"), ctx), null);
|
||||
}
|
||||
|
||||
/**
|
||||
* The document the template declares, or null when it declares none. A key the registry schema
|
||||
* does not define, a value of the wrong type, a rule without {@code ObjectOwnership} or a rule
|
||||
* listed twice fails in the class's {@code Model validation failed} form. The repeat is checked
|
||||
* once every rule passes on its own, so a malformed rule fails for its own fault even when
|
||||
* repeated. The document then goes through S3's own check, which answers {@code MalformedXML}
|
||||
* for no rule, more than one, or an unknown mode.
|
||||
*/
|
||||
private String ownershipControlsXml(JsonNode props, ProvisionContext ctx) {
|
||||
JsonNode declaredNode = declared(props, "OwnershipControls");
|
||||
if (declaredNode == null) {
|
||||
@@ -256,17 +266,18 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
|
||||
return null;
|
||||
}
|
||||
String path = "#/OwnershipControls";
|
||||
requireObject(controls, path);
|
||||
requireOnly(requireObject(controls, path), path, "Rules");
|
||||
JsonNode rules = declaredArray(controls, "Rules", path);
|
||||
XmlBuilder xml = new XmlBuilder().start("OwnershipControls", AwsNamespaces.S3);
|
||||
for (int index = 0; rules != null && index < rules.size(); index++) {
|
||||
String rulePath = path + "/Rules/" + index;
|
||||
JsonNode rule = requireObject(rules.get(index), rulePath);
|
||||
JsonNode rule = requireOnly(requireObject(rules.get(index), rulePath), rulePath, "ObjectOwnership");
|
||||
String ownership = required(rule, "ObjectOwnership", rulePath);
|
||||
xml.start("Rule");
|
||||
xml.elem("ObjectOwnership", ownership);
|
||||
xml.end("Rule");
|
||||
}
|
||||
requireDistinct(rules, path + "/Rules");
|
||||
String document = xml.end("OwnershipControls").build();
|
||||
S3Service.validateOwnershipControls(document);
|
||||
return document;
|
||||
@@ -474,6 +485,36 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The object itself when it holds no key besides {@code keys}. Any other key fails, as the
|
||||
* schema's {@code additionalProperties: false} does, rather than being dropped unread.
|
||||
*/
|
||||
private static JsonNode requireOnly(JsonNode object, String pointer, String... keys) {
|
||||
Set<String> allowed = Set.of(keys);
|
||||
for (Iterator<String> names = object.fieldNames(); names.hasNext(); ) {
|
||||
String name = names.next();
|
||||
if (!allowed.contains(name)) {
|
||||
throw new AwsException("InvalidRequest", "Model validation failed (" + pointer
|
||||
+ ": extraneous key [" + name + "] is not permitted)", 400);
|
||||
}
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fails when an item of the list repeats another, as the schema's {@code uniqueItems} does. A
|
||||
* list that is not declared, null here, has no repeat.
|
||||
*/
|
||||
private static void requireDistinct(JsonNode items, String pointer) {
|
||||
Set<JsonNode> seen = new HashSet<>();
|
||||
for (int index = 0; items != null && index < items.size(); index++) {
|
||||
if (!seen.add(items.get(index))) {
|
||||
throw new AwsException("InvalidRequest",
|
||||
"Model validation failed (" + pointer + ": array items are not unique)", 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static AwsException typeMismatch(String pointer, String expected, JsonNode value) {
|
||||
return new AwsException("InvalidRequest", "Model validation failed (" + pointer
|
||||
+ ": expected type: " + expected + ", found: " + schemaTypeName(value) + ")", 400);
|
||||
|
||||
+57
@@ -155,6 +155,55 @@ class CloudFormationS3BucketPropertiesIntegrationTest {
|
||||
+ marker + "\" }]" + controls + " } } } }";
|
||||
}
|
||||
|
||||
/** A key the registry schema does not define fails the create, and the stack leaves no bucket. */
|
||||
@Test
|
||||
void anOwnershipRuleWithAKeyTheSchemaDoesNotDefineFailsTheCreate() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "cfn-ownership-extra-" + suffix;
|
||||
String stackId = stack("CreateStack", "cfn-ownership-extra-stack-" + suffix, """
|
||||
{ "Resources": { "Bucket": { "Type": "AWS::S3::Bucket", "Properties": {
|
||||
"BucketName": "%s",
|
||||
"OwnershipControls": { "Rules": [
|
||||
{ "ObjectOwnership": "BucketOwnerEnforced", "Owner": "me" } ] } } } } }
|
||||
""".formatted(bucket));
|
||||
await(stackId, "ROLLBACK_COMPLETE");
|
||||
|
||||
String events = stackEvents(stackId);
|
||||
assertTrue(events.contains(
|
||||
"Model validation failed (#/OwnershipControls/Rules/0: extraneous key [Owner] is not permitted)"),
|
||||
"the create failed on the rule: " + events);
|
||||
given().when().head("/" + bucket).then().statusCode(404);
|
||||
}
|
||||
|
||||
/**
|
||||
* The template is resolved before the schema is checked, so two rules that resolve to the same
|
||||
* mode are a repeated rule. The update rolls back and the bucket keeps its tag and mode.
|
||||
*/
|
||||
@Test
|
||||
void ownershipRulesThatResolveToTheSameModeFailTheUpdate() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String bucket = "cfn-ownership-repeated-" + suffix;
|
||||
String stackName = "cfn-ownership-repeated-stack-" + suffix;
|
||||
String stackId = stack("CreateStack", stackName, ownershipTemplate(bucket, "BucketOwnerEnforced", "before"));
|
||||
await(stackId, "CREATE_COMPLETE");
|
||||
|
||||
stack("UpdateStack", stackName, """
|
||||
{ "Parameters": { "Mode": { "Type": "String", "Default": "ObjectWriter" } },
|
||||
"Resources": { "Bucket": { "Type": "AWS::S3::Bucket", "Properties": {
|
||||
"BucketName": "%s", "Tags": [{ "Key": "marker", "Value": "after" }],
|
||||
"OwnershipControls": { "Rules": [
|
||||
{ "ObjectOwnership": { "Ref": "Mode" } }, { "ObjectOwnership": "ObjectWriter" } ] } } } } }
|
||||
""".formatted(bucket));
|
||||
await(stackId, "UPDATE_ROLLBACK_COMPLETE");
|
||||
|
||||
String events = stackEvents(stackId);
|
||||
assertTrue(events.contains("Model validation failed (#/OwnershipControls/Rules: array items are not unique)"),
|
||||
"the update failed on the repeated rule: " + events);
|
||||
bucketGet(bucket, "ownershipControls")
|
||||
.body(containsString("<ObjectOwnership>BucketOwnerEnforced</ObjectOwnership>"));
|
||||
bucketGet(bucket, "tagging").body(containsString("<Value>before</Value>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theBucketCarriesWhatItsTemplateDeclares() throws InterruptedException {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
@@ -280,6 +329,14 @@ class CloudFormationS3BucketPropertiesIntegrationTest {
|
||||
return given().when().get("/" + bucket + "?" + subresource).then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String stackEvents(String stackId) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "DescribeStackEvents")
|
||||
.formParam("StackName", stackId)
|
||||
.when().post("/").then().statusCode(200).extract().asString();
|
||||
}
|
||||
|
||||
private static String stack(String action, String stackName, String template) {
|
||||
String xml = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
|
||||
+70
@@ -115,6 +115,76 @@ class S3CfnProvisionerTest {
|
||||
verify(s3, never()).putBucketOwnershipControls(anyString(), anyString());
|
||||
}
|
||||
|
||||
/**
|
||||
* The registry schema allows only {@code Rules} on the controls and only {@code ObjectOwnership}
|
||||
* on a rule, no rule listed twice, and an object, a list or a string at each level. An unknown
|
||||
* key is reported ahead of a wrong type beside it, and the schema is checked before S3's own
|
||||
* rules, so a repeated rule is refused for the repetition rather than for the rule count.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', textBlock = """
|
||||
{"Rules": [{"ObjectOwnership": "ObjectWriter"}], "Rule": []} | #/OwnershipControls: extraneous key [Rule] is not permitted
|
||||
{"Rule": [{"ObjectOwnership": "ObjectWriter"}]} | #/OwnershipControls: extraneous key [Rule] is not permitted
|
||||
{"Rules": "ObjectWriter", "Extra": 1} | #/OwnershipControls: extraneous key [Extra] is not permitted
|
||||
{"Rules": [{"ObjectOwnership": "ObjectWriter"}], "ObjectOwnership": "ObjectWriter"} | #/OwnershipControls: extraneous key [ObjectOwnership] is not permitted
|
||||
{"Rules": [{"ObjectOwnership": "ObjectWriter", "Owner": "me"}]} | #/OwnershipControls/Rules/0: extraneous key [Owner] is not permitted
|
||||
{"Rules": [{"Objectownership": "ObjectWriter"}]} | #/OwnershipControls/Rules/0: extraneous key [Objectownership] is not permitted
|
||||
{"Rules": [{"Rules": []}]} | #/OwnershipControls/Rules/0: extraneous key [Rules] is not permitted
|
||||
{"Rules": [{"ObjectOwnership": "ObjectWriter"}, {"ObjectOwnership": "ObjectWriter"}]} | #/OwnershipControls/Rules: array items are not unique
|
||||
{"Rules": [{"ObjectOwnership": "ObjectWriter"}, {"ObjectOwnership": "BucketOwnerPreferred"}, {"ObjectOwnership": "ObjectWriter"}]} | #/OwnershipControls/Rules: array items are not unique
|
||||
"BucketOwnerEnforced" | #/OwnershipControls: expected type: JSONObject, found: String
|
||||
[{"Rules": [{"ObjectOwnership": "ObjectWriter"}]}] | #/OwnershipControls: expected type: JSONObject, found: JSONArray
|
||||
{"Rules": {"ObjectOwnership": "ObjectWriter"}} | #/OwnershipControls/Rules: expected type: JSONArray, found: JSONObject
|
||||
{"Rules": ["ObjectWriter"]} | #/OwnershipControls/Rules/0: expected type: JSONObject, found: String
|
||||
{"Rules": [{"ObjectOwnership": {"Mode": "ObjectWriter"}}]} | #/OwnershipControls/Rules/0/ObjectOwnership: expected type: String, found: JSONObject
|
||||
""")
|
||||
void ownershipControlsTheSchemaRefusesFailBeforeCreatingTheBucket(String controls, String reason) {
|
||||
assertOwnershipControlsFailModelValidation(controls, reason);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every rule is checked on its own before any repeat, so a malformed rule fails for its own
|
||||
* fault, as a single one does, whether it is the repeated rule or comes after a repeat.
|
||||
*/
|
||||
@ParameterizedTest
|
||||
@CsvSource(delimiter = '|', textBlock = """
|
||||
{"Rules": [{}, {}]} | #/OwnershipControls/Rules/0: required key [ObjectOwnership] not found
|
||||
{"Rules": ["ObjectWriter", "ObjectWriter"]} | #/OwnershipControls/Rules/0: expected type: JSONObject, found: String
|
||||
{"Rules": [{"ObjectOwnership": "ObjectWriter"}, {"ObjectOwnership": "ObjectWriter"}, {}]} | #/OwnershipControls/Rules/2: required key [ObjectOwnership] not found
|
||||
""")
|
||||
void aRepeatedRuleIsCheckedOnItsOwnFirst(String controls, String reason) {
|
||||
assertOwnershipControlsFailModelValidation(controls, reason);
|
||||
}
|
||||
|
||||
private void assertOwnershipControlsFailModelValidation(String controls, String reason) {
|
||||
AwsException e = assertThrows(AwsException.class, () -> provisionBucket("""
|
||||
{"BucketName": "my-bucket", "OwnershipControls": %s}
|
||||
""".formatted(controls)));
|
||||
|
||||
assertEquals("InvalidRequest", e.getErrorCode());
|
||||
assertEquals("Model validation failed (" + reason + ")", e.getMessage());
|
||||
verify(s3, never()).createBucket(anyString(), anyString());
|
||||
verify(s3, never()).putBucketOwnershipControls(anyString(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anOwnershipRuleTheSchemaRefusesFailsAnUpdateBeforeTheBucketChanges() {
|
||||
AwsException e = assertThrows(AwsException.class, () -> updateBucket("""
|
||||
{"BucketName": "b", "OwnershipControls": {"Rules": [{"ObjectOwnership": "ObjectWriter"}]}}
|
||||
""", """
|
||||
{"BucketName": "b", "Tags": [{"Key": "k", "Value": "v"}],
|
||||
"OwnershipControls": {"Rules": [{"ObjectOwnership": "BucketOwnerEnforced", "Owner": "me"}]}}
|
||||
"""));
|
||||
|
||||
assertEquals("InvalidRequest", e.getErrorCode());
|
||||
assertEquals("Model validation failed (#/OwnershipControls/Rules/0: extraneous key [Owner] is not permitted)",
|
||||
e.getMessage());
|
||||
verify(s3, never()).deleteBucketCors(anyString());
|
||||
verify(s3, never()).putBucketTagging(anyString(), any());
|
||||
verify(s3, never()).putBucketOwnershipControls(anyString(), anyString());
|
||||
verify(s3, never()).deleteBucketOwnershipControls(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void refIsTheBucketNameAndGetAttExposesTheDocumentedAttributes() {
|
||||
StackResource r = provisionBucket("""
|
||||
|
||||
Reference in new issue
Block a user