fix(organizations): apply PutResourcePolicy tags only on creation (#8174)

PutResourcePolicy replaced the tag set of an existing resource policy
whenever the request carried Tags. The model says tags apply only to
the initial creation of the resource policy and that the call throws
otherwise. It now applies Tags only when it creates the policy and
answers InvalidInputException for Tags on an existing one, before it
changes anything. The model names no error for this case;
InvalidInputException is the one it lists for invalid request values.
An empty Tags list has no tags to apply and is accepted.

The CloudFormation provisioner relied on the old replace to converge
the Tags of AWS::Organizations::ResourcePolicy on update. An update now
leaves Tags out of PutResourcePolicy and converges them through
TagResource and UntagResource by the rp- ID, as the provisioner does
for OUs, accounts and policies and as AWS's own handler does.

Co-authored-by: Priamo Germosen <6233424+pgermosen@users.noreply.github.com>
This commit is contained in:
soreavis
2026-11-12 22:18:32 -04:00
committed by GitHub
co-authored by Priamo Germosen
parent 405a3cad12
commit b2fa3e0cfb
7 changed files with 141 additions and 38 deletions
+3 -1
View File
@@ -388,7 +388,9 @@ returns the management account id, while `Fn::GetAtt Org.Id` returns the organiz
- `Policy` — `TargetIds` is reconciled on update: targets the template adds are attached and ones
it drops are detached. Deleting the resource detaches its remaining targets first, since
`DeletePolicy` refuses while a policy is still attached.
- `ResourcePolicy` — backed by `PutResourcePolicy`, which is already create-or-update.
- `ResourcePolicy` — backed by `PutResourcePolicy`, which is create-or-update but applies `Tags`
only when it creates the policy, so an update converges `Tags` through `TagResource` and
`UntagResource` on the policy's `rp-` id.
`Fn::GetAtt OrganizationalUnit.Path` and `Fn::GetAtt Account.Paths` return the organization path —
`o-<org>/r-<root>/[ou-<ou>/…]<id>/`. An account has one parent and therefore one path, so the
@@ -260,9 +260,17 @@ public class OrganizationsCfnProvisioner implements CfnResourceProvisioner {
// ──────────────────────────── Resource policy ────────────────────────────
private void provisionResourcePolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
// PutResourcePolicy is already create-or-update, so the same call serves both paths.
OrganizationsService.ResourcePolicyView policy = organizationsService.putResourcePolicy(
ctx.accountId(), resolveContent(props, ctx), resolveTags(props, ctx));
String content = resolveContent(props, ctx);
Map<String, String> tags = resolveTags(props, ctx);
OrganizationsService.ResourcePolicyView policy;
if (ctx.isUpdate()) {
// PutResourcePolicy applies Tags only when it creates the policy.
policy = organizationsService.putResourcePolicy(ctx.accountId(), content, null);
replaceTags(ctx.accountId(), policy.id(), tags);
} else {
policy = organizationsService.putResourcePolicy(ctx.accountId(), content, tags);
}
r.setPhysicalId(policy.id());
r.getAttributes().put("Id", policy.id());
@@ -1249,15 +1249,16 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
organization.setResourcePolicyId(policyId);
organization.setResourcePolicyArn(
arn(organization.getMasterAccountId(), "resourcepolicy/" + organization.getId() + "/" + policyId));
if (tags != null) {
organization.getResourcePolicyTags().putAll(tags);
}
} else if (tags != null && !tags.isEmpty()) {
// The model says Tags apply only when this call creates the policy and that it throws
// otherwise, without naming the error. An empty list has no tags to apply.
throw invalidInput("Tags apply only to the initial creation of the resource policy."
+ " Use TagResource and UntagResource to change its tags.");
}
organization.setResourcePolicyContent(content);
if (tags != null) {
// Put replaces rather than merges: a caller that supplies Tags is stating the full set,
// so a key it no longer lists is dropped. CloudFormation relies on this to converge
// Tags on an update. Omitting Tags entirely (null) leaves the existing ones untouched.
organization.getResourcePolicyTags().clear();
organization.getResourcePolicyTags().putAll(tags);
}
organizations.putForAccount(organization.getMasterAccountId(), organization.getId(), organization);
return resourcePolicyView(organization);
}
@@ -23,6 +23,7 @@ import static org.awaitility.Awaitility.await;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesRegex;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
@@ -96,7 +97,8 @@ class OrganizationsCfnIntegrationTest {
"Action": "organizations:Describe*",
"Resource": "*"
} ]
}
},
"Tags": [ { "Key": "team", "Value": "security" } ]
}
}
},
@@ -340,6 +342,24 @@ class OrganizationsCfnIntegrationTest {
@Test
@Order(8)
void updateStackConvergesTheResourcePolicyTags() {
String updated = TEMPLATE.replace("\"Key\": \"team\", \"Value\": \"security\"",
"\"Key\": \"owner\", \"Value\": \"platform\"");
cloudFormation("UpdateStack", "StackName", STACK_NAME, "TemplateBody", updated)
.then().statusCode(200);
awaitStackStatus("UPDATE_COMPLETE");
organizations("ListTagsForResource",
"{\"ResourceId\":\"" + output(describeStacks(), "ResourcePolicyId") + "\"}")
.then().statusCode(200)
.body("Tags", hasSize(1))
.body("Tags[0].Key", equalTo("owner"))
.body("Tags[0].Value", equalTo("platform"));
}
@Test
@Order(9)
void deleteStackTearsTheOrganizationDown() {
cloudFormation("DeleteStack", "StackName", STACK_NAME).then().statusCode(200);
@@ -352,7 +372,7 @@ class OrganizationsCfnIntegrationTest {
}
@Test
@Order(9)
@Order(10)
void theManagementAccountIsFreeToStartOver() {
// The teardown must leave no organization behind for this account, otherwise a second
// stack — or a re-run of this test class — would hit AlreadyInOrganizationException.
@@ -29,6 +29,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -57,6 +58,10 @@ class OrganizationsCfnProvisionerTest {
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
return ctx(null);
}
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
@@ -70,7 +75,7 @@ class OrganizationsCfnProvisionerTest {
JsonNode node = inv.getArgument(0);
return node.isTextual() ? node.asText() : node.toString();
});
return new ProvisionContext(engine, "us-east-1", ACCOUNT, "my-stack");
return new ProvisionContext(engine, "us-east-1", ACCOUNT, "my-stack", priorPhysicalId);
}
private StackResource resource(String type, String logicalId) {
@@ -442,12 +447,16 @@ class OrganizationsCfnProvisionerTest {
// ──────────────────────────── Resource policy ────────────────────────────
@Test
void resourcePolicySetsPhysicalIdAndGetAttAttributes() {
private void stubPutResourcePolicy() {
when(organizations.putResourcePolicy(eq(ACCOUNT), anyString(), any()))
.thenReturn(new OrganizationsService.ResourcePolicyView("rp-abcd1234",
"arn:aws:organizations::" + ACCOUNT + ":resourcepolicy/" + ORG_ID + "/rp-abcd1234",
"{}", Map.of()));
}
@Test
void resourcePolicySetsPhysicalIdAndGetAttAttributes() {
stubPutResourcePolicy();
StackResource r = resource("AWS::Organizations::ResourcePolicy", "Rp");
ObjectNode props = mapper.createObjectNode();
@@ -462,24 +471,59 @@ class OrganizationsCfnProvisionerTest {
}
@Test
void resourcePolicyUpdatePassesTheFullTagSetSoDroppedKeysAreRemoved() {
when(organizations.putResourcePolicy(eq(ACCOUNT), anyString(), any()))
.thenReturn(new OrganizationsService.ResourcePolicyView("rp-abcd1234",
"arn:aws:organizations::" + ACCOUNT + ":resourcepolicy/" + ORG_ID + "/rp-abcd1234",
"{}", Map.of()));
void resourcePolicyCreatePassesItsTagsToPut() {
stubPutResourcePolicy();
StackResource r = resource("AWS::Organizations::ResourcePolicy", "Rp");
ObjectNode props = mapper.createObjectNode();
props.putObject("Content").put("Version", "2012-10-17");
props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");
provisioner.provision(r, props, ctx());
verify(organizations).putResourcePolicy(eq(ACCOUNT), anyString(), eq(Map.of("env", "test")));
verify(organizations, never()).tagResource(anyString(), anyString(), any());
verify(organizations, never()).untagResource(anyString(), anyString(), any());
}
@Test
void resourcePolicyUpdateConvergesTagsThroughTagAndUntagResource() {
stubPutResourcePolicy();
when(organizations.listTagsForResource(ACCOUNT, "rp-abcd1234"))
.thenReturn(Map.of("env", "test", "owner", "platform"));
StackResource r = resource("AWS::Organizations::ResourcePolicy", "Rp");
r.setPhysicalId("rp-abcd1234");
ObjectNode props = mapper.createObjectNode();
props.putObject("Content").put("Version", "2012-10-17");
// The previous revision also carried "owner"; this one drops it.
props.putArray("Tags").addObject().put("Key", "env").put("Value", "prod");
// env changes, owner is dropped and team is added.
props.putArray("Tags")
.add(mapper.createObjectNode().put("Key", "env").put("Value", "prod"))
.add(mapper.createObjectNode().put("Key", "team").put("Value", "red"));
provisioner.provision(r, props, ctx());
provisioner.provision(r, props, ctx("rp-abcd1234"));
// putResourcePolicy replaces the tag map, so handing it exactly the template's set is what
// removes the dropped key. The other three types reach the same end via replaceTags.
verify(organizations).putResourcePolicy(eq(ACCOUNT), anyString(), eq(Map.of("env", "prod")));
// PutResourcePolicy applies Tags only when it creates the policy, so an update leaves them out.
verify(organizations).putResourcePolicy(eq(ACCOUNT), anyString(), isNull());
verify(organizations).untagResource(ACCOUNT, "rp-abcd1234", List.of("owner"));
verify(organizations).tagResource(ACCOUNT, "rp-abcd1234", Map.of("env", "prod", "team", "red"));
}
@Test
void resourcePolicyUpdateWithUnchangedTagsRemovesNone() {
stubPutResourcePolicy();
when(organizations.listTagsForResource(ACCOUNT, "rp-abcd1234")).thenReturn(Map.of("env", "test"));
StackResource r = resource("AWS::Organizations::ResourcePolicy", "Rp");
r.setPhysicalId("rp-abcd1234");
ObjectNode props = mapper.createObjectNode();
props.putObject("Content").put("Version", "2012-10-17");
props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");
provisioner.provision(r, props, ctx("rp-abcd1234"));
verify(organizations).putResourcePolicy(eq(ACCOUNT), anyString(), isNull());
verify(organizations, never()).untagResource(anyString(), anyString(), any());
}
// ──────────────────────────── Delete ────────────────────────────
@@ -869,6 +869,14 @@ class OrganizationsIntegrationTest {
.then()
.statusCode(200);
organizations("PutResourcePolicy",
"{\"Content\":" + quote(content) + ",\"Tags\":[{\"Key\":\"env\",\"Value\":\"prod\"}]}")
.when()
.post("/")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidInputException"));
organizations("ListTagsForResource", "{\"ResourceId\":\"" + resourcePolicyId + "\"}")
.when()
.post("/")
@@ -408,22 +408,42 @@ class OrganizationsServiceTest {
}
@Test
void putResourcePolicyReplacesTagsRatherThanMergingThem() {
void putResourcePolicyWithoutTagsCreatesAnUntaggedPolicy() {
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String policyId = service.putResourcePolicy(MANAGEMENT_ACCOUNT, "{\"Version\":\"2012-10-17\"}", null).id();
assertTrue(service.listTagsForResource(MANAGEMENT_ACCOUNT, policyId).isEmpty());
}
@Test
void putResourcePolicyRefusesTagsForAnExistingPolicyAndChangesNothing() {
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String content = "{\"Version\":\"2012-10-17\"}";
service.putResourcePolicy(MANAGEMENT_ACCOUNT, content, Map.of("env", "test"));
service.putResourcePolicy(MANAGEMENT_ACCOUNT, content, Map.of("env", "test", "owner", "platform"));
assertEquals(Map.of("env", "test", "owner", "platform"),
service.describeResourcePolicy(MANAGEMENT_ACCOUNT).tags());
AwsException error = assertThrows(AwsException.class, () -> service.putResourcePolicy(
MANAGEMENT_ACCOUNT, "{\"Statement\":[]}", Map.of("env", "prod")));
assertEquals("InvalidInputException", error.getErrorCode());
// Put drops a key the new set leaves out; CloudFormation relies on that to converge on update.
service.putResourcePolicy(MANAGEMENT_ACCOUNT, content, Map.of("env", "prod"));
assertEquals(Map.of("env", "prod"), service.describeResourcePolicy(MANAGEMENT_ACCOUNT).tags());
OrganizationsService.ResourcePolicyView policy = service.describeResourcePolicy(MANAGEMENT_ACCOUNT);
assertEquals(content, policy.content());
assertEquals(Map.of("env", "test"), policy.tags());
}
// Omitting Tags entirely is "don't touch", matching how the provisioner treats an absent
// Tags property on every other Organizations type.
service.putResourcePolicy(MANAGEMENT_ACCOUNT, content, null);
assertEquals(Map.of("env", "prod"), service.describeResourcePolicy(MANAGEMENT_ACCOUNT).tags());
@Test
void putResourcePolicyWithoutTagsUpdatesAnExistingPolicyAndKeepsItsTags() {
service.createOrganization(MANAGEMENT_ACCOUNT, "ALL");
String policyId = service.putResourcePolicy(MANAGEMENT_ACCOUNT, "{\"Version\":\"2012-10-17\"}",
Map.of("env", "test")).id();
String updated = "{\"Statement\":[]}";
OrganizationsService.ResourcePolicyView policy = service.putResourcePolicy(MANAGEMENT_ACCOUNT, updated, null);
assertEquals(policyId, policy.id());
assertEquals(updated, policy.content());
assertEquals(Map.of("env", "test"), policy.tags());
// An empty Tags list has no tags to apply, so it is not refused either.
assertEquals(Map.of("env", "test"), service.putResourcePolicy(MANAGEMENT_ACCOUNT, updated, Map.of()).tags());
}
@Test