feat(cloudformation): provision AWS::IoT::Authorizer (#4830)

* test(cloudformation): cover AWS::IoT::Authorizer against AWS

* feat(cloudformation): provision AWS::IoT::Authorizer

CloudFormation stubbed AWS::IoT::Authorizer with a fake ARN and created
nothing. IotAuthorizerCfnProvisioner now creates a real authorizer
through IotAuthorizerService.

Ref is the authorizer name and Fn::GetAtt Arn the ARN. A missing
AuthorizerFunctionArn fails with the registry's model validation error
before any call. Status, EnableCachingForHttp, AuthorizerFunctionArn and
the token settings update in place, sending only the declared
properties, tags are reconciled, and a failed stack update restores
them from a snapshot. Changing AuthorizerName or SigningDisabled
replaces the authorizer and deletes the old one once the update
commits; a replacement that keeps an explicit name is refused. Delete
deactivates the authorizer first and tolerates one already gone.

Closes #4822

* chore(cloudformation): move the IoT authorizer snapshot constant

It sat at the same insertion point as other pull requests' snapshot constants, so they could not be merged together.

* fix(cloudformation): treat only an empty intrinsic result as AWS::NoValue for IoT authorizers

* fix(cloudformation): undo an IoT authorizer update whose tag reconcile fails

* fix(cloudformation): report a SigningDisabled change on an IoT authorizer as a replacement

* fix(cloudformation): create an IoT authorizer over a dispatcher stub and refuse declaring its generated name

* fix(cloudformation): refuse an IoT authorizer boolean that is neither true nor false

* fix(cloudformation): never delete a dispatcher stub's id in replacement cleanup

* fix(cloudformation): tell a stub from a migrated resource and roll back a stub migration that kept its id

* fix(cloudformation): name an unnamed IoT authorizer <LogicalId>_<12 chars> as CloudFormation does
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-10-05 14:37:54 -04:00
1 parent 4fb52e0b07
commit 4be8309e8d
16 files changed
+1995 -13

No files matched your search

@@ -18,6 +18,7 @@ class CfnCreateOnlyPropertiesTest {
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "QueueName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "FifoQueue"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "BucketName"));
assertTrue(CfnCreateOnlyProperties.isCreateOnly("AWS::IoT::Authorizer", "SigningDisabled"));
}
@Test
@@ -25,6 +26,7 @@ class CfnCreateOnlyPropertiesTest {
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::SQS::Queue", "VisibilityTimeout"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::Redshift::Cluster", "NumberOfNodes"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::S3::Bucket", "VersioningConfiguration"));
assertFalse(CfnCreateOnlyProperties.isCreateOnly("AWS::IoT::Authorizer", "Status"));
}
@Test
@@ -77,6 +77,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaCfn
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamPolicyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamUserCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotAuthorizerCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotDomainConfigurationCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.KinesisCfnProvisioner;
@@ -122,6 +123,7 @@ import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.iam.IamService;
import io.github.hectorvent.floci.services.iot.IotAuthorizerService;
import io.github.hectorvent.floci.services.iot.IotDomainConfigurationService;
import io.github.hectorvent.floci.services.iot.IotService;
import io.github.hectorvent.floci.services.kinesis.KinesisService;
@@ -212,6 +214,7 @@ final class CfnProvisionerFixture {
private FlowLogService flowLogService;
private CloudWatchDashboardsService cloudWatchDashboardsService;
private CloudWatchLogsMetricFilterService logsMetricFilterService;
private IotAuthorizerService iotAuthorizerService;
private IotDomainConfigurationService iotDomainConfigurationService;
private IotService iotService;
private LambdaMicrovmsService lambdaMicrovmsService;
@@ -373,6 +376,9 @@ final class CfnProvisionerFixture {
if (flowLogService != null) {
discovered.add(new Ec2FlowLogCfnProvisioner(flowLogService));
}
if (iotAuthorizerService != null) {
discovered.add(new IotAuthorizerCfnProvisioner(iotAuthorizerService));
}
if (iotDomainConfigurationService != null) {
discovered.add(new IotDomainConfigurationCfnProvisioner(iotDomainConfigurationService));
}
@@ -652,6 +658,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder iotAuthorizer(IotAuthorizerService v) {
this.iotAuthorizerService = v;
return this;
}
public Builder iotDomainConfiguration(IotDomainConfigurationService v) {
this.iotDomainConfigurationService = v;
return this;
@@ -0,0 +1,297 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.security.KeyPairGenerator;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Provisions an {@code AWS::IoT::Authorizer} through a CloudFormation stack and reads it back
* through the IoT API. {@code Ref} is the authorizer name and {@code Fn::GetAtt Arn} its ARN; status,
* caching, function and tags update in place and a property removed from the template keeps its
* value; a {@code SigningDisabled} change replaces the authorizer, and is refused for an explicitly
* named one; and the stack delete removes it, even while ACTIVE or after it was deleted out of band.
*/
@QuarkusTest
class CloudFormationIotAuthorizerIntegrationTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20261001/us-east-1/cloudformation/aws4_request";
private static final String FUNCTION = "arn:aws:lambda:us-east-1:000000000000:function:cfn-auth";
private static final String OTHER_FUNCTION = "arn:aws:lambda:us-east-1:000000000000:function:cfn-auth-2";
private static final String ARN_PREFIX = "arn:aws:iot:us-east-1:000000000000:authorizer/";
private final List<String> stacks = new ArrayList<>();
@AfterEach
void cleanUp() {
for (String stack : List.copyOf(stacks)) {
deleteStack(stack);
}
}
@Test
void createExposesRefAndArnAndReadsBackThroughDescribeAuthorizer() throws Exception {
String name = "cfn-auth-" + suffix();
Map<String, Object> properties = properties(name);
properties.put("Status", "ACTIVE");
properties.put("Tags", List.of(Map.of("Key", "team", "Value", "a")));
String body = awaitStatus(createStack(template(properties)), "CREATE_COMPLETE");
assertEquals(name, output(body, "AuthRef"), "Ref is the authorizer name");
assertEquals(ARN_PREFIX + name, output(body, "AuthArn"), "GetAtt Arn is the authorizer ARN");
JsonPath authorizer = describe(name);
assertEquals(ARN_PREFIX + name, authorizer.getString("authorizerArn"));
assertEquals(FUNCTION, authorizer.getString("authorizerFunctionArn"));
assertEquals("ACTIVE", authorizer.getString("status"));
assertTrue(authorizer.getBoolean("signingDisabled"));
assertFalse(authorizer.getBoolean("enableCachingForHttp"));
assertEquals(Map.of("team", "a"), tags(name));
}
@Test
void inPlaceUpdatesKeepTheAuthorizerAndRemovedPropertiesKeepTheirValues() throws Exception {
String name = "cfn-auth-" + suffix();
Map<String, Object> properties = properties(name);
properties.put("Status", "ACTIVE");
properties.put("Tags", List.of(Map.of("Key", "team", "Value", "a"), Map.of("Key", "stage", "Value", "x")));
String stack = createStack(template(properties));
awaitStatus(stack, "CREATE_COMPLETE");
properties.put("Status", "INACTIVE");
properties.put("EnableCachingForHttp", true);
properties.put("Tags", List.of(Map.of("Key", "team", "Value", "b"), Map.of("Key", "env", "Value", "dev")));
updateStack(stack, template(properties));
String body = awaitStatus(stack, "UPDATE_COMPLETE");
assertEquals(name, output(body, "AuthRef"));
assertEquals(ARN_PREFIX + name, output(body, "AuthArn"));
JsonPath updated = describe(name);
assertEquals("INACTIVE", updated.getString("status"));
assertTrue(updated.getBoolean("enableCachingForHttp"));
assertEquals(Map.of("team", "b", "env", "dev"), tags(name));
properties.remove("Status");
properties.remove("EnableCachingForHttp");
properties.put("AuthorizerFunctionArn", OTHER_FUNCTION);
updateStack(stack, template(properties));
awaitStatus(stack, "UPDATE_COMPLETE");
JsonPath kept = describe(name);
assertEquals(OTHER_FUNCTION, kept.getString("authorizerFunctionArn"));
assertEquals("INACTIVE", kept.getString("status"), "a removed Status keeps its value");
assertTrue(kept.getBoolean("enableCachingForHttp"), "a removed EnableCachingForHttp keeps its value");
}
@Test
void turningSigningOnReplacesAGeneratedAuthorizer() throws Exception {
Map<String, Object> properties = properties(null);
String stack = createStack(template(properties));
String original = output(awaitStatus(stack, "CREATE_COMPLETE"), "AuthRef");
assertTrue(original.matches("Auth_[A-Za-z0-9]{12}"), original);
assertEquals("INACTIVE", describe(original).getString("status"), "no Status creates it INACTIVE");
String key = rsaPublicKey();
properties.put("SigningDisabled", false);
properties.put("TokenKeyName", "tok");
properties.put("TokenSigningPublicKeys", Map.of("k1", key));
updateStack(stack, template(properties));
String body = awaitStatus(stack, "UPDATE_COMPLETE");
String replacement = output(body, "AuthRef");
assertNotEquals(original, replacement);
assertEquals(ARN_PREFIX + replacement, output(body, "AuthArn"));
JsonPath authorizer = describe(replacement);
assertFalse(authorizer.getBoolean("signingDisabled"));
assertEquals("tok", authorizer.getString("tokenKeyName"));
assertEquals(key, authorizer.getString("tokenSigningPublicKeys.k1"));
assertGone(original);
}
@Test
void replacingAnExplicitlyNamedAuthorizerIsRefused() throws Exception {
String name = "cfn-auth-" + suffix();
Map<String, Object> properties = properties(name);
properties.put("Status", "ACTIVE");
String stack = createStack(template(properties));
awaitStatus(stack, "CREATE_COMPLETE");
properties.put("SigningDisabled", false);
properties.put("TokenKeyName", "tok");
properties.put("TokenSigningPublicKeys", Map.of("k1", rsaPublicKey()));
updateStack(stack, template(properties));
awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE");
assertResourceEvent(stack, "UPDATE_FAILED", "CloudFormation cannot update a stack when a custom-named "
+ "resource requires replacing. Rename " + name + " and update the stack again.");
JsonPath authorizer = describe(name);
assertTrue(authorizer.getBoolean("signingDisabled"));
assertEquals("ACTIVE", authorizer.getString("status"));
}
@Test
void missingFunctionArnFailsTheCreate() throws Exception {
String name = "cfn-auth-" + suffix();
Map<String, Object> properties = properties(name);
properties.remove("AuthorizerFunctionArn");
String stack = createStack(template(properties));
awaitStatus(stack, "ROLLBACK_COMPLETE");
assertResourceEvent(stack, "CREATE_FAILED",
"Model validation failed (#: required key [AuthorizerFunctionArn] not found)");
assertGone(name);
}
@Test
void deleteStackRemovesAnActiveAuthorizer() throws Exception {
String name = "cfn-auth-" + suffix();
Map<String, Object> properties = properties(name);
properties.put("Status", "ACTIVE");
String stack = createStack(template(properties));
awaitStatus(stack, "CREATE_COMPLETE");
assertEquals("ACTIVE", describe(name).getString("status"));
deleteStack(stack);
assertGone(name);
}
@Test
void deleteStackToleratesAnAuthorizerDeletedOutOfBand() throws Exception {
String name = "cfn-auth-" + suffix();
Map<String, Object> properties = properties(name);
properties.put("Status", "ACTIVE");
String stack = createStack(template(properties));
awaitStatus(stack, "CREATE_COMPLETE");
given().contentType("application/json").body("{\"status\": \"INACTIVE\"}")
.when().put("/authorizer/" + name).then().statusCode(200);
given().when().delete("/authorizer/" + name).then().statusCode(200);
deleteStack(stack);
assertGone(name);
}
private static String suffix() {
return Long.toString(System.nanoTime(), 36);
}
private static String rsaPublicKey() throws Exception {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
byte[] der = generator.generateKeyPair().getPublic().getEncoded();
return "-----BEGIN PUBLIC KEY-----\n"
+ Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(der)
+ "\n-----END PUBLIC KEY-----";
}
private String createStack(String template) {
String stack = "cfn-auth-" + suffix();
cfn(stack, "CreateStack", template).then().statusCode(200);
stacks.add(stack);
return stack;
}
private static void updateStack(String stack, String template) {
cfn(stack, "UpdateStack", template).then().statusCode(200);
}
/** Waits for the stack to be gone, which a DELETE_FAILED stack never is. */
private void deleteStack(String stack) {
cfn(stack, "DeleteStack", null).then().statusCode(200);
await().atMost(Duration.ofSeconds(15)).untilAsserted(() -> {
Response response = cfn(stack, "DescribeStacks", null);
assertEquals(400, response.statusCode(), response.asString());
assertTrue(response.asString().contains("does not exist"), response.asString());
});
stacks.remove(stack);
}
private static String awaitStatus(String stack, String status) {
return await().atMost(Duration.ofSeconds(15)).until(
() -> cfn(stack, "DescribeStacks", null).then().statusCode(200).extract().asString(),
body -> status.equals(XmlParser.extractFirst(body, "StackStatus", null)));
}
private static void assertResourceEvent(String stack, String status, String reason) {
List<Map<String, String>> events = XmlParser.extractGroups(cfn(stack, "DescribeStackEvents", null)
.then().statusCode(200).extract().asString(), "member");
assertTrue(events.stream().anyMatch(event -> "Auth".equals(event.get("LogicalResourceId"))
&& status.equals(event.get("ResourceStatus"))
&& reason.equals(event.get("ResourceStatusReason"))),
"no " + status + " event with reason " + reason + " in " + events);
}
private static String output(String body, String key) {
String value = XmlParser.extractPairs(body, "Outputs", "OutputKey", "OutputValue").get(key);
assertFalse(value == null || value.isBlank(), body);
return value;
}
private static Response cfn(String stack, String action, String template) {
RequestSpecification request = given().contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH).formParam("Action", action).formParam("StackName", stack);
if (template != null) {
request.formParam("TemplateBody", template);
}
return request.post("/");
}
private static JsonPath describe(String name) {
return given().when().get("/authorizer/" + name).then().statusCode(200)
.extract().jsonPath().setRootPath("authorizerDescription");
}
private static Map<String, String> tags(String name) {
List<Map<String, String>> tags = given().queryParam("resourceArn", ARN_PREFIX + name)
.when().get("/tags").then().statusCode(200).extract().jsonPath().getList("tags");
Map<String, String> byKey = new LinkedHashMap<>();
tags.forEach(tag -> byKey.put(tag.get("Key"), tag.get("Value")));
return byKey;
}
private static void assertGone(String name) {
given().when().get("/authorizer/" + name).then().statusCode(404);
}
private static Map<String, Object> properties(String name) {
Map<String, Object> properties = new LinkedHashMap<>();
if (name != null) {
properties.put("AuthorizerName", name);
}
properties.put("AuthorizerFunctionArn", FUNCTION);
properties.put("SigningDisabled", true);
return properties;
}
private static String template(Map<String, Object> properties) throws Exception {
Map<String, Object> outputs = new LinkedHashMap<>();
outputs.put("AuthRef", Map.of("Value", Map.of("Ref", "Auth")));
outputs.put("AuthArn", Map.of("Value", Map.of("Fn::GetAtt", List.of("Auth", "Arn"))));
return MAPPER.writeValueAsString(Map.of(
"Resources", Map.of("Auth", Map.of("Type", "AWS::IoT::Authorizer", "Properties", properties)),
"Outputs", outputs));
}
}
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
@@ -11,6 +12,7 @@ import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@@ -72,6 +74,58 @@ class CfnResourceDispatcherTest {
assertEquals("CREATE_COMPLETE", resource.getStatus());
}
@Test
void aProvisionerThatMigratesAStubWithoutWritingAnArnDropsTheStubArn() {
when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) ->
resource.setPhysicalId("dash-real"))));
StackResource resource = dispatcher.provision("Dash", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack", "Dash-1a2b3c4d", Map.of("Arn", "arn:aws:stub:::Dash"));
assertFalse(resource.getAttributes().containsKey("Arn"),
"the real resource must not read as a stub on its next update");
assertEquals("dash-real", resource.getPhysicalId());
assertEquals("CREATE_COMPLETE", resource.getStatus());
}
@Test
void aProvisionerThatMigratesAStubAndWritesOtherAttributesStillDropsTheStubArn() {
when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) ->
resource.getAttributes().put("FlociThingNameMode", "generated"))));
StackResource resource = dispatcher.provision("Dash", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack", "Dash-1a2b3c4d", Map.of("Arn", "arn:aws:stub:::Dash"));
assertEquals(Map.of("FlociThingNameMode", "generated"), resource.getAttributes());
}
@Test
void aProvisionerThatMigratesAStubKeepsTheArnItWrites() {
when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> {
resource.setPhysicalId("dash-real");
resource.getAttributes().put("Arn", "arn:aws:test:us-east-1:000000000000:thing/dash-real");
})));
StackResource resource = dispatcher.provision("Dash", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack", "Dash-1a2b3c4d", Map.of("Arn", "arn:aws:stub:::Dash"));
assertEquals("arn:aws:test:us-east-1:000000000000:thing/dash-real", resource.getAttributes().get("Arn"));
assertEquals("CREATE_COMPLETE", resource.getStatus());
}
@Test
void aProvisionerThatThrowsLeavesTheResourceCreateFailed() {
when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> {
throw new AwsException("ValidationError", "Thing requires Name", 400);
})));
StackResource resource = dispatcher.provision("Thing", TYPE, mapper.createObjectNode(), null,
"us-east-1", "000000000000", "my-stack");
assertEquals("CREATE_FAILED", resource.getStatus());
assertEquals("Thing requires Name", resource.getStatusReason());
}
@Test
void deleteHandsTheOwnerTheWholeResource() {
CfnResourceProvisioner owner = mock(CfnResourceProvisioner.class);
@@ -296,6 +296,57 @@ class CloudWatchDashboardCfnProvisionerTest {
assertEquals("generated", r.getAttributes().get("FlociDashboardNameMode"));
}
/**
* A stub migrated without a name keeps the stub's id as the dashboard's name, and the
* dispatcher drops the stub Arn, so renaming it later deletes the real dashboard it displaced.
*/
@Test
void aDashboardMigratedFromAStubIsOwedItsDeleteWhenALaterUpdateRenamesIt() {
CfnResourceDispatcher dispatcher = new CfnResourceDispatcher(MAPPER,
new CloudFormationResourceRegistry(List.of(provisioner)), null, null);
StackResource migrated = dispatcher.provision("Dashboard", TYPE, props("""
{"DashboardBody": "{}"}
"""), engine, REGION, ACCOUNT_ID, STACK, "Dashboard-1a2b3c4d",
Map.of("Arn", "arn:aws:stub:::Dashboard"));
assertEquals("CREATE_COMPLETE", migrated.getStatus(), migrated.getStatusReason());
assertEquals("Dashboard-1a2b3c4d", migrated.getPhysicalId());
dispatcher.clearUpdate(migrated);
StackResource renamed = dispatcher.provision("Dashboard", TYPE, props("""
{"DashboardName": "DashTwo", "DashboardBody": "{}"}
"""), engine, REGION, ACCOUNT_ID, STACK, migrated.getPhysicalId(), migrated.getAttributes());
assertEquals("CREATE_COMPLETE", renamed.getStatus(), renamed.getStatusReason());
assertEquals("DashTwo", renamed.getPhysicalId());
assertEquals("Dashboard-1a2b3c4d", dispatcher.updateCleanupPhysicalId(renamed),
"the migrated dashboard is real, so the rename owes its delete");
}
/**
* An unnamed stub migration creates the dashboard under the stub's id, so a failed stack update
* deletes it and puts the stub back.
*/
@Test
void rollingBackAnUnnamedStubMigrationDeletesTheDashboardItCreatedAndRestoresTheStub() {
CfnResourceDispatcher dispatcher = new CfnResourceDispatcher(MAPPER,
new CloudFormationResourceRegistry(List.of(provisioner)), null, null);
when(dashboards.getDashboard("Dashboard-1a2b3c4d", REGION))
.thenThrow(new AwsException("ResourceNotFound", "Dashboard does not exist: Dashboard-1a2b3c4d", 404));
StackResource migrated = dispatcher.provision("Dashboard", TYPE, props("""
{"DashboardBody": "{}"}
"""), engine, REGION, ACCOUNT_ID, STACK, "Dashboard-1a2b3c4d",
Map.of("Arn", "arn:aws:stub:::Dashboard"));
assertEquals("CREATE_COMPLETE", migrated.getStatus(), migrated.getStatusReason());
assertEquals("Dashboard-1a2b3c4d", migrated.getPhysicalId());
assertTrue(dispatcher.rollbackUpdate(migrated));
verify(dashboards).deleteDashboards(List.of("Dashboard-1a2b3c4d"), REGION);
assertEquals("Dashboard-1a2b3c4d", migrated.getPhysicalId());
assertEquals("arn:aws:stub:::Dashboard", migrated.getAttributes().get("Arn"));
assertFalse(migrated.getAttributes().containsKey("FlociDashboardNameMode"));
}
@Test
void moreTagsThanTheSchemaAllowsAreRejected() {
StringBuilder tags = new StringBuilder();
@@ -0,0 +1,690 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.iot.IotAuthorizerService;
import io.github.hectorvent.floci.services.iot.model.IotAuthorizer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
/**
* {@code AWS::IoT::Authorizer}: the name is the physical id and {@code Ref}, {@code Arn} the
* authorizer ARN, an in-place update sends only the properties the template declares, a changed
* name or {@code SigningDisabled} replaces the authorizer, and a delete deactivates it first.
*/
class IotAuthorizerCfnProvisionerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String REGION = "us-east-1";
private static final String ACCOUNT = "000000000000";
private static final String STACK = "my-stack";
private static final String TYPE = "AWS::IoT::Authorizer";
private static final String FUNCTION = "arn:aws:lambda:us-east-1:000000000000:function:auth";
private static final String OTHER_FUNCTION = "arn:aws:lambda:us-east-1:000000000000:function:auth-2";
private static final String KEY = "-----BEGIN PUBLIC KEY-----\nMIIB\n-----END PUBLIC KEY-----";
private final IotAuthorizerService service = mock(IotAuthorizerService.class);
private final CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
private final IotAuthorizerCfnProvisioner provisioner = new IotAuthorizerCfnProvisioner(service);
/** What the mocked service holds, so describe and the tag calls see what earlier calls stored. */
private final Map<String, IotAuthorizer> authorizers = new HashMap<>();
@BeforeEach
void setUp() {
// Like the real engine, AWS::NoValue resolves to an empty string.
when(engine.resolve(any())).thenAnswer(i -> {
JsonNode node = resolveNode(i.getArgument(0));
if (node == null || node.isMissingNode() || node.isNull()) {
return null;
}
return node.asText();
});
when(engine.resolveNode(any())).thenAnswer(i -> resolveNode(i.getArgument(0)));
when(service.createAuthorizer(anyString(), any(), eq(REGION))).thenAnswer(i -> {
String name = i.getArgument(0);
JsonNode body = i.getArgument(1);
IotAuthorizer authorizer = new IotAuthorizer();
authorizer.setAuthorizerName(name);
authorizer.setAuthorizerArn(arn(name));
authorizer.setAuthorizerFunctionArn(body.path("authorizerFunctionArn").asText());
authorizer.setStatus(body.path("status").asText("INACTIVE"));
authorizer.setSigningDisabled(body.path("signingDisabled").asBoolean(false));
authorizer.setEnableCachingForHttp(body.path("enableCachingForHttp").asBoolean(false));
authorizer.setTokenKeyName(body.path("tokenKeyName").asText(null));
if (body.path("tokenSigningPublicKeys").isObject()) {
authorizer.setTokenSigningPublicKeys(MAPPER.convertValue(body.get("tokenSigningPublicKeys"),
new TypeReference<Map<String, String>>() {}));
}
Map<String, String> tags = new TreeMap<>();
body.path("tags").forEach(tag -> tags.put(tag.path("Key").asText(), tag.path("Value").asText()));
authorizer.setTags(tags);
authorizers.put(name, authorizer);
return authorizer;
});
when(service.describeAuthorizer(anyString(), eq(REGION))).thenAnswer(i -> stored(i.getArgument(0)));
when(service.updateAuthorizer(anyString(), any(), eq(REGION))).thenAnswer(i -> {
IotAuthorizer authorizer = stored(i.getArgument(0));
JsonNode body = i.getArgument(1);
if (body.has("status")) {
authorizer.setStatus(body.get("status").asText());
}
if (body.has("enableCachingForHttp")) {
authorizer.setEnableCachingForHttp(body.get("enableCachingForHttp").asBoolean());
}
if (body.has("authorizerFunctionArn")) {
authorizer.setAuthorizerFunctionArn(body.get("authorizerFunctionArn").asText());
}
return authorizer;
});
doAnswer(i -> {
stored(nameOf(i.getArgument(0))).getTags().putAll(i.getArgument(1));
return null;
}).when(service).tagResource(anyString(), anyMap());
doAnswer(i -> {
stored(nameOf(i.getArgument(0))).getTags().keySet().removeAll(i.<List<String>>getArgument(1));
return null;
}).when(service).untagResource(anyString(), anyList());
}
@Test
void servesOnlyTheAuthorizerType() {
assertEquals(Set.of(TYPE), provisioner.resourceTypes());
}
@Test
void createWithAnExplicitNameSendsTheDeclaredPropertiesAndSetsRefAndArn() {
StackResource resource = create(props("auth")
.put("SigningDisabled", true)
.put("Status", "ACTIVE")
.put("EnableCachingForHttp", true)
.set("Tags", tags("team", "a")));
verify(service).createAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "status": "ACTIVE", "signingDisabled": true,
"enableCachingForHttp": true, "tags": [{"Key": "team", "Value": "a"}]}
""".formatted(FUNCTION)), REGION);
assertEquals("auth", resource.getPhysicalId());
assertEquals(arn("auth"), resource.getAttributes().get("Arn"));
verify(service, never()).tagResource(anyString(), anyMap());
}
@Test
void createWithSigningSendsTheTokenKeyNameAndKeys() {
create(props("auth").put("TokenKeyName", "tok").set("TokenSigningPublicKeys", keys()));
verify(service).createAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "tokenKeyName": "tok", "tokenSigningPublicKeys": {"k1": "%s"}}
""".formatted(FUNCTION, KEY.replace("\n", "\\n"))), REGION);
}
@Test
void aSigningKeyResolvedToNoValueIsNotSent() {
ObjectNode keys = keys();
keys.putObject("k2").putArray("Fn::If").add("HasSecondKey").add(KEY).add(noValue());
create(props("auth").put("TokenKeyName", "tok").set("TokenSigningPublicKeys", keys));
verify(service).createAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "tokenKeyName": "tok", "tokenSigningPublicKeys": {"k1": "%s"}}
""".formatted(FUNCTION, KEY.replace("\n", "\\n"))), REGION);
}
@Test
void aLiteralEmptySigningKeyStillReachesTheService() {
create(props("auth").put("TokenKeyName", "tok").set("TokenSigningPublicKeys", keys().put("k2", "")));
verify(service).createAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "tokenKeyName": "tok", "tokenSigningPublicKeys": {"k1": "%s", "k2": ""}}
""".formatted(FUNCTION, KEY.replace("\n", "\\n"))), REGION);
}
@Test
void omittedNameIsGeneratedWithinTheIotNameRule() {
StackResource resource = resource();
provisioner.provision(resource, props(null).put("SigningDisabled", true),
new ProvisionContext(engine, REGION, ACCOUNT, "stack".repeat(30)));
String name = resource.getPhysicalId();
assertTrue(name.matches("Auth_[A-Za-z0-9]{12}"), name);
verify(service).createAuthorizer(name, json("""
{"authorizerFunctionArn": "%s", "signingDisabled": true}
""".formatted(FUNCTION)), REGION);
assertEquals(arn(name), resource.getAttributes().get("Arn"));
}
@Test
void aLongLogicalIdIsCutSoTheGeneratedNameFitsTheIotLimit() {
StackResource resource = resource();
String logicalId = "Auth".repeat(50);
resource.setLogicalId(logicalId);
provisioner.provision(resource, props(null).put("SigningDisabled", true),
new ProvisionContext(engine, REGION, ACCOUNT, STACK));
String name = resource.getPhysicalId();
assertTrue(name.length() <= 128, name);
assertTrue(name.matches("[A-Za-z0-9]+_[A-Za-z0-9]{12}"), name);
assertTrue(logicalId.startsWith(name.substring(0, name.length() - 13)), name);
}
@Test
void aWhitespaceNameFromAnIntrinsicIsKeptInsteadOfGenerated() {
ObjectNode properties = props(null);
properties.putObject("AuthorizerName").putArray("Fn::If").add("HasCustomName").add("auth").add(" ");
StackResource resource = create(properties);
assertEquals(" ", resource.getPhysicalId());
verify(service).createAuthorizer(" ", json("""
{"authorizerFunctionArn": "%s"}
""".formatted(FUNCTION)), REGION);
}
@Test
void missingFunctionArnIsRefusedBeforeAnyCall() {
ObjectNode properties = MAPPER.createObjectNode().put("AuthorizerName", "auth").put("SigningDisabled", true);
AwsException error = assertThrows(AwsException.class, () -> create(properties));
assertEquals("Model validation failed (#: required key [AuthorizerFunctionArn] not found)",
error.getMessage());
verifyNoInteractions(service);
}
@Test
void inPlaceUpdateSendsOnlyTheDeclaredProperties() {
StackResource resource = create(props("auth").put("SigningDisabled", true)
.put("Status", "ACTIVE").put("EnableCachingForHttp", true));
clearInvocations(service);
update(resource, props("auth").put("SigningDisabled", true).put("Status", "INACTIVE"));
verify(service).updateAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "status": "INACTIVE"}
""".formatted(FUNCTION)), REGION);
verify(service, never()).createAuthorizer(anyString(), any(), anyString());
assertEquals("auth", resource.getPhysicalId());
assertEquals(arn("auth"), resource.getAttributes().get("Arn"));
assertFalse(provisioner.hasReplacementUpdate(resource));
}
@Test
void propertiesRemovedFromTheTemplateAreNotSent() {
StackResource resource = create(props("auth").put("SigningDisabled", true)
.put("Status", "ACTIVE").put("EnableCachingForHttp", true));
clearInvocations(service);
ObjectNode properties = props("auth").put("SigningDisabled", true);
properties.set("Status", noValue());
update(resource, properties);
verify(service).updateAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s"}
""".formatted(FUNCTION)), REGION);
}
@Test
void aWhitespaceCachingFlagFromAnIntrinsicIsRefusedRatherThanReadAsFalse() {
StackResource resource = create(props("auth").put("SigningDisabled", true).put("EnableCachingForHttp", true));
clearInvocations(service);
ObjectNode properties = props("auth").put("SigningDisabled", true);
properties.putObject("EnableCachingForHttp").putArray("Fn::If").add("Cache").add(true).add(" ");
AwsException error = assertThrows(AwsException.class, () -> update(resource, properties));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("AWS::IoT::Authorizer EnableCachingForHttp must be true or false, got ", error.getMessage());
verify(service, never()).updateAuthorizer(anyString(), any(), anyString());
assertTrue(authorizers.get("auth").isEnableCachingForHttp());
}
@Test
void inPlaceUpdateResendsTheDeclaredTokenProperties() {
StackResource resource = create(props("auth").put("TokenKeyName", "tok").set("TokenSigningPublicKeys", keys()));
clearInvocations(service);
update(resource, props("auth").put("TokenKeyName", "tok").put("Status", "ACTIVE")
.set("TokenSigningPublicKeys", keys()));
verify(service).updateAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "status": "ACTIVE", "tokenKeyName": "tok",
"tokenSigningPublicKeys": {"k1": "%s"}}
""".formatted(FUNCTION, KEY.replace("\n", "\\n"))), REGION);
}
@Test
void inPlaceUpdateReconcilesTheTags() {
ArrayNode created = tags("team", "a");
created.addObject().put("Key", "stage").put("Value", "x");
StackResource resource = create(props("auth").put("SigningDisabled", true).set("Tags", created));
clearInvocations(service);
ArrayNode desired = tags("team", "b");
desired.addObject().put("Key", "env").put("Value", "dev");
update(resource, props("auth").put("SigningDisabled", true).set("Tags", desired));
verify(service).untagResource(arn("auth"), List.of("stage"));
verify(service).tagResource(arn("auth"), Map.of("team", "b", "env", "dev"));
assertEquals(Map.of("team", "b", "env", "dev"), authorizers.get("auth").getTags());
}
@Test
void rollbackUpdateRestoresTheSnapshot() {
StackResource resource = create(props("auth").put("SigningDisabled", true)
.put("Status", "ACTIVE").set("Tags", tags("team", "a")));
update(resource, props("auth").put("SigningDisabled", true).put("Status", "INACTIVE")
.put("EnableCachingForHttp", true).put("AuthorizerFunctionArn", OTHER_FUNCTION)
.set("Tags", tags("env", "dev")));
assertTrue(resource.getAttributes().containsKey(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR));
clearInvocations(service);
assertTrue(provisioner.rollbackUpdate(resource));
verify(service).updateAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "status": "ACTIVE", "enableCachingForHttp": false}
""".formatted(FUNCTION)), REGION);
IotAuthorizer restored = authorizers.get("auth");
assertEquals("ACTIVE", restored.getStatus());
assertFalse(restored.isEnableCachingForHttp());
assertEquals(FUNCTION, restored.getAuthorizerFunctionArn());
assertEquals(Map.of("team", "a"), restored.getTags());
assertFalse(resource.getAttributes().containsKey(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR));
}
@Test
void rollbackUpdateWithoutASnapshotChangesNothing() {
StackResource resource = create(props("auth").put("SigningDisabled", true));
clearInvocations(service);
assertTrue(provisioner.rollbackUpdate(resource));
verifyNoInteractions(service);
}
@Test
void clearUpdateDropsTheSnapshot() {
StackResource resource = create(props("auth").put("SigningDisabled", true));
update(resource, props("auth").put("SigningDisabled", true).put("Status", "ACTIVE"));
provisioner.clearUpdate(resource);
assertFalse(resource.getAttributes().containsKey(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR));
}
/**
* The stack puts back the resource it held before the attempt, which never carried the
* snapshot, so an update that failed on its tags restores the authorizer itself.
*/
@Test
void anInPlaceUpdateThatFailedOnItsTagsRestoresTheAuthorizer() {
StackResource resource = create(props("auth").put("SigningDisabled", true).put("Status", "ACTIVE"));
AwsException failure = new AwsException("InternalFailureException", "tags down", 500);
doThrow(failure).when(service).tagResource(anyString(), anyMap());
AwsException thrown = assertThrows(AwsException.class, () -> update(resource, props("auth")
.put("SigningDisabled", true).put("Status", "INACTIVE").set("Tags", tags("team", "a"))));
assertSame(failure, thrown);
verify(service).updateAuthorizer("auth", json("""
{"authorizerFunctionArn": "%s", "status": "ACTIVE", "enableCachingForHttp": false}
""".formatted(FUNCTION)), REGION);
assertEquals("ACTIVE", authorizers.get("auth").getStatus());
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
assertFalse(resource.getAttributes().containsKey(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR));
assertFalse(resource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
}
/**
* A restore that fails too is recorded as a rollback failure and keeps the snapshot, so the
* stack ends in UPDATE_ROLLBACK_FAILED while still reporting the update's own failure.
*/
@Test
void anUnwindThatCannotRestoreIsReportedAsARollbackFailure() {
StackResource resource = create(props("auth").put("SigningDisabled", true).put("Status", "ACTIVE"));
AwsException failure = new AwsException("InternalFailureException", "tags down", 500);
doThrow(failure).when(service).tagResource(anyString(), anyMap());
AwsException restoreFailure = new AwsException("InternalFailureException", "still down", 500);
doThrow(restoreFailure).when(service).updateAuthorizer(eq("auth"), eq(json("""
{"authorizerFunctionArn": "%s", "status": "ACTIVE", "enableCachingForHttp": false}
""".formatted(FUNCTION))), eq(REGION));
AwsException thrown = assertThrows(AwsException.class, () -> update(resource, props("auth")
.put("SigningDisabled", true).put("Status", "INACTIVE").set("Tags", tags("team", "a"))));
assertSame(failure, thrown);
assertEquals(List.of(restoreFailure), List.of(thrown.getSuppressed()));
assertEquals("Could not roll back the update of authorizer auth: still down",
resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));
assertTrue(resource.getAttributes().containsKey(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR));
assertFalse(resource.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
}
@Test
void renamingTheAuthorizerReplacesItAndDeletesTheOldOneOnCommit() {
StackResource resource = create(props("auth").put("SigningDisabled", true).put("Status", "ACTIVE"));
clearInvocations(service);
update(resource, props("auth-2").put("SigningDisabled", true));
assertEquals("auth-2", resource.getPhysicalId());
assertEquals(arn("auth-2"), resource.getAttributes().get("Arn"));
verify(service).createAuthorizer("auth-2", json("""
{"authorizerFunctionArn": "%s", "signingDisabled": true}
""".formatted(FUNCTION)), REGION);
verify(service, never()).updateAuthorizer(anyString(), any(), anyString());
verify(service, never()).deleteAuthorizer(anyString(), anyString());
assertTrue(provisioner.hasReplacementUpdate(resource));
assertEquals("auth", provisioner.updateCleanupPhysicalId(resource));
commit(resource);
InOrder order = inOrder(service);
order.verify(service).updateAuthorizer("auth", json("{\"status\": \"INACTIVE\"}"), REGION);
order.verify(service).deleteAuthorizer("auth", REGION);
verify(service, never()).deleteAuthorizer("auth-2", REGION);
}
@Test
void changingSigningDisabledReplacesAGeneratedAuthorizer() {
StackResource resource = create(props(null).put("SigningDisabled", true).put("Status", "ACTIVE"));
String original = resource.getPhysicalId();
clearInvocations(service);
update(resource, props(null).put("SigningDisabled", false).put("TokenKeyName", "tok")
.set("TokenSigningPublicKeys", keys()));
String replacement = resource.getPhysicalId();
assertNotEquals(original, replacement);
assertTrue(replacement.matches("Auth_[A-Za-z0-9]{12}"), replacement);
verify(service).createAuthorizer(replacement, json("""
{"authorizerFunctionArn": "%s", "signingDisabled": false, "tokenKeyName": "tok",
"tokenSigningPublicKeys": {"k1": "%s"}}
""".formatted(FUNCTION, KEY.replace("\n", "\\n"))), REGION);
assertEquals(original, provisioner.updateCleanupPhysicalId(resource));
commit(resource);
verify(service).deleteAuthorizer(original, REGION);
}
@Test
void anUnchangedGeneratedNameIsKept() {
StackResource resource = create(props(null).put("SigningDisabled", true));
String generated = resource.getPhysicalId();
clearInvocations(service);
update(resource, props(null).put("SigningDisabled", true).put("Status", "ACTIVE"));
assertEquals(generated, resource.getPhysicalId());
verify(service, never()).createAuthorizer(anyString(), any(), anyString());
assertFalse(provisioner.hasReplacementUpdate(resource));
}
@Test
void droppingTheExplicitNameReplacesTheAuthorizer() {
StackResource resource = create(props("auth").put("SigningDisabled", true));
clearInvocations(service);
update(resource, props(null).put("SigningDisabled", true));
String generated = resource.getPhysicalId();
assertTrue(generated.matches("Auth_[A-Za-z0-9]{12}"), generated);
verify(service).createAuthorizer(eq(generated), any(), eq(REGION));
assertEquals("auth", provisioner.updateCleanupPhysicalId(resource));
}
@Test
void replacingAnExplicitlyNamedAuthorizerIsRefusedBeforeAnyChange() {
StackResource resource = create(props("auth").put("SigningDisabled", true));
clearInvocations(service);
AwsException error = assertThrows(AwsException.class, () -> update(resource,
props("auth").put("SigningDisabled", false).put("TokenKeyName", "tok")
.set("TokenSigningPublicKeys", keys())));
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename auth and update the stack again.", error.getMessage());
verify(service, never()).createAuthorizer(anyString(), any(), anyString());
verify(service, never()).updateAuthorizer(anyString(), any(), anyString());
verify(service, never()).deleteAuthorizer(anyString(), anyString());
assertEquals("auth", resource.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(resource));
}
/** Adding the generated name explicitly replaces the authorizer under the same name, which is refused. */
@Test
void declaringTheGeneratedNameExplicitlyIsRefusedBeforeAnyChange() {
StackResource resource = create(props(null).put("SigningDisabled", true));
String generated = resource.getPhysicalId();
clearInvocations(service);
AwsException error = assertThrows(AwsException.class,
() -> update(resource, props(generated).put("SigningDisabled", true)));
assertEquals("ValidationError", error.getErrorCode());
assertEquals("CloudFormation cannot update a stack when a custom-named resource requires replacing. "
+ "Rename " + generated + " and update the stack again.", error.getMessage());
verify(service, never()).createAuthorizer(anyString(), any(), anyString());
verify(service, never()).updateAuthorizer(anyString(), any(), anyString());
}
/** A stack from before this provisioner holds the dispatcher's stub, which names no authorizer. */
@Test
void updatingADispatcherStubCreatesTheAuthorizerUnderAGeneratedName() {
StackResource resource = resource();
resource.setPhysicalId("Auth-1a2b3c4d");
resource.getAttributes().put("Arn", "arn:aws:stub:::Auth");
update(resource, props(null).put("SigningDisabled", true));
String generated = resource.getPhysicalId();
assertTrue(generated.matches("Auth_[A-Za-z0-9]{12}"), generated);
verify(service).createAuthorizer(eq(generated), any(), eq(REGION));
verify(service, never()).describeAuthorizer(anyString(), anyString());
verify(service, never()).updateAuthorizer(anyString(), any(), anyString());
assertEquals(arn(generated), resource.getAttributes().get("Arn"));
assertNull(provisioner.updateCleanupPhysicalId(resource), "a stub created nothing, so no delete is owed for its id");
}
@Test
void updatingADispatcherStubWithAnExplicitNameCreatesThatAuthorizer() {
StackResource resource = resource();
resource.setPhysicalId("Auth-1a2b3c4d");
resource.getAttributes().put("Arn", "arn:aws:stub:::Auth");
update(resource, props("auth").put("SigningDisabled", true));
assertEquals("auth", resource.getPhysicalId());
verify(service).createAuthorizer(eq("auth"), any(), eq(REGION));
verify(service, never()).describeAuthorizer(anyString(), anyString());
}
@Test
void aFailedStackUpdateDeletesTheReplacementAndRestoresThePriorAuthorizer() {
StackResource resource = create(props("auth").put("SigningDisabled", true));
update(resource, props("auth-2").put("SigningDisabled", true));
clearInvocations(service);
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals("auth", resource.getPhysicalId());
assertEquals(arn("auth"), resource.getAttributes().get("Arn"));
verify(service).deleteAuthorizer("auth-2", REGION);
verify(service, never()).deleteAuthorizer("auth", REGION);
}
/** A stub migrated under the stub's own id created that authorizer, so a failed stack update deletes it. */
@Test
void aFailedStackUpdateDeletesTheAuthorizerAStubMigrationCreatedUnderTheStubId() {
StackResource resource = resource();
resource.setPhysicalId("Auth-1a2b3c4d");
resource.getAttributes().put("Arn", "arn:aws:stub:::Auth");
update(resource, props("Auth-1a2b3c4d").put("SigningDisabled", true));
verify(service).createAuthorizer(eq("Auth-1a2b3c4d"), any(), eq(REGION));
clearInvocations(service);
assertTrue(provisioner.rollbackUpdate(resource));
InOrder order = inOrder(service);
order.verify(service).updateAuthorizer("Auth-1a2b3c4d", json("{\"status\": \"INACTIVE\"}"), REGION);
order.verify(service).deleteAuthorizer("Auth-1a2b3c4d", REGION);
assertEquals("Auth-1a2b3c4d", resource.getPhysicalId());
assertEquals(Map.of("Arn", "arn:aws:stub:::Auth"), resource.getAttributes());
}
@Test
void deleteDeactivatesThenDeletes() {
authorizers.put("auth", new IotAuthorizer());
provisioner.delete(TYPE, "auth", REGION);
InOrder order = inOrder(service);
order.verify(service).updateAuthorizer("auth", json("{\"status\": \"INACTIVE\"}"), REGION);
order.verify(service).deleteAuthorizer("auth", REGION);
}
@Test
void deleteToleratesAnAuthorizerThatIsAlreadyGone() {
doThrow(new AwsException("ResourceNotFoundException", "Authorizer auth not found", 404))
.when(service).updateAuthorizer(eq("auth"), any(), eq(REGION));
assertDoesNotThrow(() -> provisioner.delete(TYPE, "auth", REGION));
}
@Test
void deletePropagatesOtherFailures() {
authorizers.put("auth", new IotAuthorizer());
AwsException conflict = new AwsException("DeleteConflictException",
"Cannot delete default authorizer auth. Change default and retry delete.", 409);
doThrow(conflict).when(service).deleteAuthorizer("auth", REGION);
assertSame(conflict, assertThrows(AwsException.class, () -> provisioner.delete(TYPE, "auth", REGION)));
}
private StackResource create(ObjectNode properties) {
StackResource resource = resource();
provisioner.provision(resource, properties, new ProvisionContext(engine, REGION, ACCOUNT, STACK));
return resource;
}
private void update(StackResource resource, ObjectNode properties) {
provisioner.provision(resource, properties,
new ProvisionContext(engine, REGION, ACCOUNT, STACK, resource.getPhysicalId()));
}
private void commit(StackResource resource) {
assertTrue(provisioner.completeUpdate(resource).complete());
provisioner.clearUpdate(resource);
}
private IotAuthorizer stored(String name) {
IotAuthorizer authorizer = authorizers.get(name);
if (authorizer == null) {
throw new AwsException("ResourceNotFoundException", "Authorizer " + name + " not found", 404);
}
return authorizer;
}
private static StackResource resource() {
StackResource resource = new StackResource();
resource.setLogicalId("Auth");
resource.setResourceType(TYPE);
resource.setAttributes(new HashMap<>());
return resource;
}
private static ObjectNode props(String name) {
ObjectNode properties = MAPPER.createObjectNode();
if (name != null) {
properties.put("AuthorizerName", name);
}
return properties.put("AuthorizerFunctionArn", FUNCTION);
}
private static ArrayNode tags(String key, String value) {
ArrayNode tags = MAPPER.createArrayNode();
tags.addObject().put("Key", key).put("Value", value);
return tags;
}
private static ObjectNode keys() {
return MAPPER.createObjectNode().put("k1", KEY);
}
private static JsonNode json(String text) {
try {
return MAPPER.readTree(text);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
private static JsonNode noValue() {
return MAPPER.createObjectNode().put("Ref", "AWS::NoValue");
}
/** Like the real engine: AWS::NoValue becomes "", an object is walked; conditions here are all false. */
private static JsonNode resolveNode(JsonNode node) {
if (node == null || !node.isObject()) {
return node;
}
if (isNoValue(node)) {
return TextNode.valueOf("");
}
if (node.has("Fn::If")) {
return resolveNode(node.get("Fn::If").get(2));
}
ObjectNode resolved = MAPPER.createObjectNode();
node.properties().forEach(field -> resolved.set(field.getKey(), resolveNode(field.getValue())));
return resolved;
}
private static boolean isNoValue(JsonNode node) {
return node.isObject() && "AWS::NoValue".equals(node.path("Ref").asText());
}
private static String nameOf(String arn) {
return arn.substring(arn.indexOf("authorizer/") + "authorizer/".length());
}
private static String arn(String name) {
return "arn:aws:iot:us-east-1:000000000000:authorizer/" + name;
}
}
@@ -6,10 +6,12 @@ import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** The cleanup record's orphan handling in isolation: what a provisioner records and what the engine's merge carries. */
@@ -49,6 +51,121 @@ class ReplacementCleanupTest {
assertEquals("subnet-replacement", ReplacementCleanup.cleanupPhysicalId(r), "Retain keeps what a committed replacement displaced, not a failed update's leftovers");
}
@Test
void aDispatcherStubIsNeverOwedADelete() {
StackResource r = resource("subnet-replacement");
List<String> deleted = new ArrayList<>();
ReplacementCleanup.record(r, stubUpdate(), Map.of("Arn", "arn:aws:stub:::Subnet"));
String announced = ReplacementCleanup.cleanupPhysicalId(r);
ReplacementCleanup.complete(r, (type, id, region) -> deleted.add(id));
assertEquals(List.of(), deleted, "a stub created nothing, so its id may name an entity the stack never owned");
assertNull(announced);
}
@Test
void aStubCarryingOnlyInternalAttributesBesideItsArnIsStillNeverOwedADelete() {
StackResource r = resource("subnet-replacement");
ReplacementCleanup.record(r, stubUpdate(), Map.of("Arn", "arn:aws:stub:::Subnet",
CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true"));
assertNull(ReplacementCleanup.cleanupPhysicalId(r));
assertFalse(ReplacementCleanup.hasReplacement(r));
}
/**
* An older Floci migrated a stub without dropping the stub's Arn, so a real resource can still
* carry it beside its own attributes. It names a real entity, so a rename owes its delete.
*/
@Test
void aRealResourceThatStillCarriesAStubArnIsOwedItsDelete() {
StackResource r = resource("DashTwo");
List<String> deleted = new ArrayList<>();
ReplacementCleanup.record(r, new ProvisionContext(null, "us-east-1", "000000000000", "stack", "Dashboard-1a2b3c4d"),
Map.of("Arn", "arn:aws:stub:::Dashboard", "FlociDashboardNameMode", "generated"));
assertEquals("Dashboard-1a2b3c4d", ReplacementCleanup.cleanupPhysicalId(r));
ReplacementCleanup.complete(r, (type, id, region) -> deleted.add(id));
assertEquals(List.of("Dashboard-1a2b3c4d"), deleted);
}
/**
* A group attachment keeps its state in internal attributes only, so one an older Floci migrated
* from a stub carries nothing else beside the stub Arn. Its id is not a stub's, so a replacement
* owes its delete.
*/
@Test
void aMigratedResourceWithOnlyInternalAttributesBesideAStubArnIsOwedItsDelete() {
StackResource r = resource("pool|group|other-user");
r.setLogicalId("Membership");
r.setResourceType("AWS::Cognito::UserPoolUserToGroupAttachment");
ReplacementCleanup.record(r, new ProvisionContext(null, "us-east-1", "000000000000", "stack", "pool|group|user"),
Map.of("Arn", CfnResourceDispatcher.STUB_ARN_PREFIX + "Membership",
"__FlociCognitoMemberships", "{\"pool|group|user\":[\"pool\",\"group\",\"user\"]}"));
assertTrue(ReplacementCleanup.hasReplacement(r));
assertEquals("pool|group|user", ReplacementCleanup.cleanupPhysicalId(r));
}
@Test
void rollingBackAStubMigrationRestoresTheStubAndDeletesTheReplacement() {
StackResource r = resource("subnet-replacement");
List<String> deleted = new ArrayList<>();
ReplacementCleanup.record(r, stubUpdate(), Map.of("Arn", "arn:aws:stub:::Subnet"));
assertTrue(ReplacementCleanup.rollback(r, (type, id, region) -> deleted.add(id)));
assertEquals("Subnet-1a2b3c4d", r.getPhysicalId());
assertEquals("arn:aws:stub:::Subnet", r.getAttributes().get("Arn"));
assertEquals(List.of("subnet-replacement"), deleted);
assertFalse(ReplacementCleanup.hasReplacement(r));
}
private static ProvisionContext stubUpdate() {
return new ProvisionContext(null, "us-east-1", "000000000000", "stack", "Subnet-1a2b3c4d");
}
/** A stub migrated under the stub's own id created that entity, so a rollback deletes it and puts the stub back. */
@Test
void rollingBackAStubMigrationThatKeptTheStubIdDeletesWhatItCreated() {
StackResource r = resource("Subnet-1a2b3c4d");
r.getAttributes().put("VpcId", "vpc-1a2b3c4d");
List<String> deleted = new ArrayList<>();
ReplacementCleanup.record(r, stubUpdate(), Map.of("Arn", "arn:aws:stub:::Subnet"));
assertNull(ReplacementCleanup.cleanupPhysicalId(r), "the commit path must never delete what the migration created");
assertTrue(ReplacementCleanup.rollback(r, (type, id, region) -> deleted.add(id)));
assertEquals("Subnet-1a2b3c4d", r.getPhysicalId());
assertEquals(Map.of("Arn", "arn:aws:stub:::Subnet"), r.getAttributes());
assertEquals(List.of("Subnet-1a2b3c4d"), deleted);
assertFalse(ReplacementCleanup.hasReplacement(r));
}
/** The restored stub has no live entity, so the entity its rollback could not delete is owed under the stub's own id. */
@Test
void aSameIdStubRollbackWhoseDeleteFailedIsRetriedByTheNextCleanup() {
StackResource r = resource("Subnet-1a2b3c4d");
r.getAttributes().put("VpcId", "vpc-1a2b3c4d");
List<String> deleted = new ArrayList<>();
ReplacementCleanup.record(r, stubUpdate(), Map.of("Arn", "arn:aws:stub:::Subnet"));
assertThrows(IllegalStateException.class, () -> ReplacementCleanup.rollback(r, (type, id, region) -> {
throw new IllegalStateException("DependencyViolation");
}));
assertEquals("Subnet-1a2b3c4d", ReplacementCleanup.cleanupPhysicalId(r));
UpdateCleanupResult result = ReplacementCleanup.complete(r, (type, id, region) -> deleted.add(id));
assertEquals(List.of("Subnet-1a2b3c4d"), deleted);
assertTrue(result.complete());
assertFalse(ReplacementCleanup.hasReplacement(r));
}
@Test
void mergingCarriesUnknownOrphansWithTheirAttemptsAndSkipsKnownOrOwnIds() {
// The attempt's own id is left out of the record on purpose (complete/cleanupPhysicalId skip