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

@@ -0,0 +1,387 @@
package com.floci.test;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.PartitionMetadata;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
import software.amazon.awssdk.services.cloudformation.model.Output;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.cloudformation.model.StackResource;
import software.amazon.awssdk.services.iot.IotClient;
import software.amazon.awssdk.services.iot.model.AuthorizerDescription;
import software.amazon.awssdk.services.iot.model.AuthorizerStatus;
import software.amazon.awssdk.services.iot.model.ResourceNotFoundException;
import software.amazon.awssdk.services.iot.model.Tag;
import software.amazon.awssdk.services.sts.StsClient;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyPairGenerator;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.BooleanSupplier;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@DisplayName("CloudFormation AWS::IoT::Authorizer")
class CloudFormationIotAuthorizerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final long TIMEOUT_NANOS = 300_000_000_000L;
private static CloudFormationClient cfn;
private static IotClient iot;
private static String partition;
private static String region;
private static String account;
private static String rsaKey;
private String prefix;
private String stackName;
private String stackId;
private final Set<String> authorizers = new LinkedHashSet<>();
@BeforeAll
static void clients() throws GeneralSecurityException {
cfn = TestFixtures.cloudFormationClient();
iot = TestFixtures.iotClient();
Region clientRegion = iot.serviceClientConfiguration().region();
region = clientRegion.id();
partition = PartitionMetadata.of(clientRegion).id();
try (StsClient sts = TestFixtures.stsClient()) {
account = sts.getCallerIdentity().account();
}
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048);
byte[] der = generator.generateKeyPair().getPublic().getEncoded();
rsaKey = "-----BEGIN PUBLIC KEY-----\n"
+ Base64.getMimeEncoder(64, "\n".getBytes(StandardCharsets.US_ASCII)).encodeToString(der)
+ "\n-----END PUBLIC KEY-----";
}
@BeforeEach
void setup() {
prefix = "compat-cfn-auth-" + UUID.randomUUID().toString().substring(0, 8);
stackName = prefix;
}
@AfterEach
void cleanup() throws InterruptedException {
collectStackAuthorizers();
try {
deleteStack();
} finally {
for (String name : authorizers) {
removeAuthorizer(name);
}
authorizers.clear();
deleteStack();
}
}
@AfterAll
static void closeClients() {
cfn.close();
iot.close();
}
@Test
@DisplayName("Create a named ACTIVE authorizer, read it back, then delete the stack while it is ACTIVE")
void createsNamedActiveAuthorizerAndDeletesItWithTheStackWhileActive() throws InterruptedException {
String name = prefix + "-auth";
String function = functionArn("fn");
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("AuthorizerName", name);
properties.put("AuthorizerFunctionArn", function);
properties.put("SigningDisabled", true);
properties.put("Status", "ACTIVE");
properties.put("Tags", List.of(Map.of("Key", "team", "Value", "a")));
authorizers.add(name);
createStack(template(properties));
assertThat(output("AuthRef")).as("Ref is the authorizer name").isEqualTo(name);
assertThat(output("AuthArn")).as("GetAtt Arn is the authorizer ARN").isEqualTo(authorizerArn(name));
AuthorizerDescription description = describe(name);
assertThat(description.authorizerArn()).isEqualTo(authorizerArn(name));
assertThat(description.status()).isEqualTo(AuthorizerStatus.ACTIVE);
assertThat(description.signingDisabled()).isTrue();
assertThat(description.enableCachingForHttp()).isFalse();
assertThat(description.authorizerFunctionArn()).isEqualTo(function);
assertThat(tags(name)).containsOnly(Map.entry("team", "a"));
deleteStack();
assertNotFound(name);
}
@Test
@DisplayName("Status, caching, tags and function ARN update the named authorizer in place")
void inPlaceUpdatesKeepTheNamedAuthorizer() throws InterruptedException {
String name = prefix + "-auth";
String firstFunction = functionArn("fn1");
String secondFunction = functionArn("fn2");
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("AuthorizerName", name);
properties.put("AuthorizerFunctionArn", firstFunction);
properties.put("SigningDisabled", true);
properties.put("Status", "ACTIVE");
properties.put("Tags", List.of(Map.of("Key", "team", "Value", "a"), Map.of("Key", "stage", "Value", "x")));
authorizers.add(name);
createStack(template(properties));
String arn = output("AuthArn");
assertThat(describe(name).status()).isEqualTo(AuthorizerStatus.ACTIVE);
properties.put("Status", "INACTIVE");
updateStack(template(properties));
assertIdentity(name, arn);
AuthorizerDescription inactive = describe(name);
assertThat(inactive.status()).isEqualTo(AuthorizerStatus.INACTIVE);
assertThat(inactive.enableCachingForHttp()).isFalse();
assertThat(tags(name)).containsOnly(Map.entry("team", "a"), Map.entry("stage", "x"));
properties.put("EnableCachingForHttp", true);
properties.put("Tags", List.of(Map.of("Key", "team", "Value", "b"), Map.of("Key", "env", "Value", "dev")));
updateStack(template(properties));
assertIdentity(name, arn);
AuthorizerDescription caching = describe(name);
assertThat(caching.enableCachingForHttp()).isTrue();
assertThat(caching.status()).isEqualTo(AuthorizerStatus.INACTIVE);
assertThat(tags(name)).as("a tag removed from the template is untagged")
.containsOnly(Map.entry("team", "b"), Map.entry("env", "dev"));
properties.remove("Status");
properties.remove("EnableCachingForHttp");
updateStack(template(properties));
assertIdentity(name, arn);
AuthorizerDescription unspecified = describe(name);
assertThat(unspecified.status()).as("removing Status from the template keeps the last value")
.isEqualTo(AuthorizerStatus.INACTIVE);
assertThat(unspecified.enableCachingForHttp())
.as("removing EnableCachingForHttp from the template keeps the last value")
.isTrue();
properties.put("AuthorizerFunctionArn", secondFunction);
updateStack(template(properties));
assertIdentity(name, arn);
AuthorizerDescription moved = describe(name);
assertThat(moved.authorizerFunctionArn()).isEqualTo(secondFunction);
assertThat(moved.status()).isEqualTo(AuthorizerStatus.INACTIVE);
assertThat(moved.enableCachingForHttp()).isTrue();
assertThat(moved.signingDisabled()).isTrue();
}
@Test
@DisplayName("Turning signing on replaces a generated authorizer and deletes the old one")
void changingSigningDisabledReplacesAGeneratedAuthorizer() throws InterruptedException {
String function = functionArn("fn");
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("AuthorizerFunctionArn", function);
properties.put("SigningDisabled", true);
createStack(template(properties));
String original = output("AuthRef");
authorizers.add(original);
assertGeneratedName(original);
assertThat(output("AuthArn")).isEqualTo(authorizerArn(original));
AuthorizerDescription before = describe(original);
assertThat(before.signingDisabled()).isTrue();
assertThat(before.status()).as("no Status in the template creates an INACTIVE authorizer")
.isEqualTo(AuthorizerStatus.INACTIVE);
properties.put("SigningDisabled", false);
properties.put("TokenKeyName", "tok");
properties.put("TokenSigningPublicKeys", Map.of("k1", rsaKey));
updateStack(template(properties));
String replacement = output("AuthRef");
authorizers.add(replacement);
assertGeneratedName(replacement);
assertThat(replacement).as("SigningDisabled is create-only, so the authorizer is replaced")
.isNotEqualTo(original);
assertThat(output("AuthArn")).isEqualTo(authorizerArn(replacement));
assertNotFound(original);
AuthorizerDescription after = describe(replacement);
assertThat(after.signingDisabled()).isFalse();
assertThat(after.tokenKeyName()).isEqualTo("tok");
assertThat(after.tokenSigningPublicKeys()).containsExactly(Map.entry("k1", rsaKey));
assertThat(after.authorizerFunctionArn()).isEqualTo(function);
}
@Test
@DisplayName("Deleting the stack succeeds after the authorizer was deleted out of band")
void deletingTheStackAfterAnOutOfBandDeleteCompletes() throws InterruptedException {
String name = prefix + "-auth";
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("AuthorizerName", name);
properties.put("AuthorizerFunctionArn", functionArn("fn"));
properties.put("SigningDisabled", true);
properties.put("Status", "ACTIVE");
authorizers.add(name);
createStack(template(properties));
assertThat(describe(name).status()).isEqualTo(AuthorizerStatus.ACTIVE);
iot.updateAuthorizer(r -> r.authorizerName(name).status(AuthorizerStatus.INACTIVE));
iot.deleteAuthorizer(r -> r.authorizerName(name));
assertNotFound(name);
deleteStack();
assertNotFound(name);
}
private static String template(Map<String, Object> properties) {
Map<String, Object> template = Map.of(
"Resources", Map.of("Auth", Map.of("Type", "AWS::IoT::Authorizer", "Properties", properties)),
"Outputs", Map.of(
"AuthRef", Map.of("Value", Map.of("Ref", "Auth")),
"AuthArn", Map.of("Value", Map.of("Fn::GetAtt", List.of("Auth", "Arn")))));
try {
return MAPPER.writeValueAsString(template);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Unable to render the template", e);
}
}
private String functionArn(String suffix) {
return "arn:" + partition + ":lambda:" + region + ":" + account + ":function:" + prefix + "-" + suffix;
}
private String authorizerArn(String name) {
return "arn:" + partition + ":iot:" + region + ":" + account + ":authorizer/" + name;
}
private AuthorizerDescription describe(String name) {
return iot.describeAuthorizer(r -> r.authorizerName(name)).authorizerDescription();
}
private Map<String, String> tags(String name) {
return iot.listTagsForResource(r -> r.resourceArn(authorizerArn(name))).tags().stream()
.collect(Collectors.toMap(Tag::key, Tag::value, (a, b) -> b, LinkedHashMap::new));
}
private void assertNotFound(String name) {
assertThatThrownBy(() -> iot.describeAuthorizer(r -> r.authorizerName(name)))
.isInstanceOfSatisfying(ResourceNotFoundException.class, e -> {
assertThat(e.statusCode()).isEqualTo(404);
assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("Authorizer " + name + " not found");
});
}
private void assertIdentity(String name, String arn) {
assertThat(output("AuthRef")).as("the update keeps the authorizer name").isEqualTo(name);
assertThat(output("AuthArn")).isEqualTo(arn);
}
private static void assertGeneratedName(String name) {
assertThat(name).as("CloudFormation names an unnamed authorizer <LogicalId>_<12 alphanumerics>")
.matches("Auth_[A-Za-z0-9]{12}");
}
private void createStack(String template) throws InterruptedException {
stackId = cfn.createStack(r -> r.stackName(stackName).templateBody(template)).stackId();
awaitStatus("CREATE_COMPLETE");
}
private void updateStack(String template) throws InterruptedException {
cfn.updateStack(r -> r.stackName(stackName).templateBody(template));
awaitStatus("UPDATE_COMPLETE");
}
private String output(String key) {
return cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).outputs().stream()
.filter(o -> key.equals(o.outputKey())).map(Output::outputValue)
.findFirst().orElseThrow();
}
private void collectStackAuthorizers() {
if (stackId == null) {
return;
}
try {
cfn.describeStackResources(r -> r.stackName(stackId)).stackResources().stream()
.filter(resource -> "AWS::IoT::Authorizer".equals(resource.resourceType()))
.map(StackResource::physicalResourceId)
.filter(id -> id != null && !id.isEmpty())
.forEach(authorizers::add);
} catch (CloudFormationException e) {
if (!e.getMessage().contains("does not exist")) {
throw e;
}
}
}
private void removeAuthorizer(String name) {
try {
if (describe(name).status() == AuthorizerStatus.ACTIVE) {
iot.updateAuthorizer(r -> r.authorizerName(name).status(AuthorizerStatus.INACTIVE));
}
iot.deleteAuthorizer(r -> r.authorizerName(name));
} catch (ResourceNotFoundException expected) {
// The stack deletion, a replacement or the test itself already removed it.
}
}
private void awaitStatus(String expected) throws InterruptedException {
await(() -> {
Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);
String status = stack.stackStatusAsString();
if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {
throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());
}
return expected.equals(status);
}, expected);
}
private void deleteStack() throws InterruptedException {
if (stackId == null) {
return;
}
cfn.deleteStack(r -> r.stackName(stackId));
await(() -> {
try {
List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackId)).stacks();
if (stacks.isEmpty()) {
return true;
}
Stack stack = stacks.get(0);
if ("DELETE_FAILED".equals(stack.stackStatusAsString())) {
throw new AssertionError(stackName + " deletion failed: " + stack.stackStatusReason());
}
return "DELETE_COMPLETE".equals(stack.stackStatusAsString());
} catch (CloudFormationException e) {
if ("ValidationError".equals(e.awsErrorDetails().errorCode())
&& e.getMessage().contains("does not exist")) {
return true;
}
throw e;
}
}, "stack deletion");
stackId = null;
}
private void await(BooleanSupplier condition, String expected) throws InterruptedException {
long pollMillis = TestFixtures.isRealAws() ? 2_000 : 100;
long deadline = System.nanoTime() + TIMEOUT_NANOS;
while (System.nanoTime() < deadline) {
if (condition.getAsBoolean()) {
return;
}
Thread.sleep(pollMillis);
}
throw new AssertionError(stackName + " timed out waiting for " + expected);
}
}
+1 -1
View File
@@ -161,7 +161,7 @@ cross-resource references.
| Pipes | `Pipe` |
| Kinesis | `Stream` |
| Kinesis Data Firehose | `DeliveryStream` |
| IoT Core | `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` |
| IoT Core | `Authorizer`, `DomainConfiguration` (`ServerCertificates` resolves to a JSON string), `Policy` (deleted after detaching it from its principals; on AWS the delete fails with `DeleteConflictException` while the policy is attached), `Thing`, `TopicRule` |
| CloudFront | `CachePolicy`, `Distribution`, `OriginAccessControl`, `OriginRequestPolicy`, `ResponseHeadersPolicy` |
| CloudWatch | `Alarm`, `Dashboard` |
| CloudWatch Logs | `LogGroup`, `LogStream`, `MetricFilter` |
+1 -1
View File
@@ -80,11 +80,11 @@ Status: control plane only.
- `ListAuthorizers` returns the newest authorizer first (`isAscendingOrder=true` reverses it), filters by `status` and pages with `marker` and `pageSize` (1 to 250).
- Setting the authorizer that already is the default fails with `ResourceAlreadyExistsException`; setting another one replaces it.
- Tags work through `TagResource`, `UntagResource` and `ListTagsForResource` on the authorizer ARN.
- CloudFormation provisions `AWS::IoT::Authorizer`: `Ref` is the name and `Fn::GetAtt Arn` the ARN.
Current limitations:
- Authorizers are not evaluated: no connection or HTTP publish invokes the function, and `TestInvokeAuthorizer` is not served (see [MQTT over WebSocket](#mqtt-over-websocket)).
- CloudFormation `AWS::IoT::Authorizer` is not provisioned.
## MQTT Broker
@@ -16,6 +16,7 @@ import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.function.Consumer;
import java.util.regex.Pattern;
/**
* Routes each CloudFormation resource to the per-service provisioner that owns its type, through
@@ -32,6 +33,9 @@ public class CfnResourceDispatcher {
private static final Logger LOG = Logger.getLogger(CfnResourceDispatcher.class);
/** The prefix of a stub's {@code Arn} attribute: the mark of a resource nothing was created for. */
static final String STUB_ARN_PREFIX = "arn:aws:stub:::"; // partition-literal: stub marker for an unowned type, asserted by tests
private final ObjectMapper objectMapper;
private final CloudFormationResourceRegistry registry;
private final CfnDynamicReferences dynamicReferences;
@@ -86,6 +90,12 @@ public class CfnResourceDispatcher {
if (owner != null) {
owner.provision(resource, properties,
new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress));
// A provisioner that migrated a stub without writing its own Arn would leave the
// stub's, and the real resource would read as a stub on its next update.
String arn = resource.getAttributes().get("Arn");
if (arn != null && arn.startsWith(STUB_ARN_PREFIX)) {
resource.getAttributes().remove("Arn");
}
} else if (!stubUnsupportedResourceTypesAllowed()) {
// Before the physical id below is assigned, so the Cloud Control path sees a
// resource with none and reports this message rather than a success. On the stack
@@ -106,7 +116,7 @@ public class CfnResourceDispatcher {
resource.setStatusReason(unsupportedResourceTypeMessage(resourceType)
+ " It was stubbed and nothing was created for it.");
resource.setPhysicalId(logicalId + "-" + UUID.randomUUID().toString().substring(0, 8));
resource.getAttributes().put("Arn", "arn:aws:stub:::" + logicalId); // partition-literal: stub marker for an unowned type, asserted by tests
resource.getAttributes().put("Arn", STUB_ARN_PREFIX + logicalId);
}
resource.setStatus("CREATE_COMPLETE");
} catch (Exception e) {
@@ -117,6 +127,29 @@ public class CfnResourceDispatcher {
return resource;
}
/**
* Whether this resource is a dispatcher stub, which names nothing that exists: a stub {@code Arn},
* the stub's own {@code <LogicalId>-<8 hex>} id and internal {@code __Floci} attributes only.
* A real resource an older Floci migrated without dropping the stub's {@code Arn} fails the id
* or attribute check, so it does not read as one.
*/
static boolean isStub(String physicalId, Map<String, String> attributes) {
String arn = attributes.get("Arn");
if (arn == null || !arn.startsWith(STUB_ARN_PREFIX)) {
return false;
}
String logicalId = arn.substring(STUB_ARN_PREFIX.length());
if (physicalId == null || !physicalId.matches(Pattern.quote(logicalId) + "-[0-9a-f]{8}")) {
return false;
}
for (String key : attributes.keySet()) {
if (!"Arn".equals(key) && !key.startsWith("__Floci")) {
return false;
}
}
return true;
}
/**
* Whether a resource type with no provisioner may be stubbed. The dispatchers hand-built in
* unit tests carry no config; absent configuration means the documented default, which here is
@@ -102,6 +102,14 @@ public final class CfnRollback {
*/
public static final String REST_API_UPDATE_SNAPSHOT_ATTR = "__FlociRestApiUpdateSnapshot";
/**
* Holds the function ARN, status, caching flag, token settings and tags an IoT authorizer
* carried before an in-place update changed them, so a failed stack update can put them back.
* Written by {@code IotAuthorizerCfnProvisioner} before its update call and spent by its
* {@code rollbackUpdate}.
*/
public static final String AUTHORIZER_UPDATE_SNAPSHOT_ATTR = "__FlociAuthorizerUpdateSnapshot";
/**
* Holds the customer id, description, enabled flag and tags an API key carried before an
* in-place update changed them, or the key an update created because the one the stack held
@@ -0,0 +1,316 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
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 io.github.hectorvent.floci.core.common.AwsException;
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 jakarta.enterprise.context.ApplicationScoped;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
/**
* Provisions {@code AWS::IoT::Authorizer}. Things, policies and topic rules belong to
* {@link IotCfnProvisioner}; this class takes only the authorizer service so the test fixture can
* wire it from that service.
*
* <p>The authorizer name is the physical id and {@code Ref}, generated when the template gives none
* and kept across updates; {@code Fn::GetAtt Arn} is the authorizer ARN. The name and
* {@code SigningDisabled} are create-only. An update that keeps both changes the authorizer in
* place through UpdateAuthorizer, sending only the properties the template declares, so a property
* dropped from the template keeps its stored value, reconciles the tags, and keeps what it replaces
* on the resource so a failed stack update can put it back. An in-place update whose tag reconcile
* fails puts the authorizer back itself before reporting the failure, because the resource the
* stack restores never carried that snapshot. An update that changes either, or drops
* an explicit name, creates the new authorizer and leaves the displaced one to the
* {@link ReplacementCleanup} record; a replacement that would keep an explicit name is refused, as
* CloudFormation refuses it for any custom-named resource. Declaring the generated name as an
* explicit name is refused the same way, because adding the create-only name is a replacement that
* would keep it. A stack created before this provisioner existed holds the dispatcher's stub, which
* names no authorizer, so its first update creates the authorizer as a first deploy would. A delete
* deactivates the authorizer first, because the API refuses to delete an ACTIVE one.
*/
@ApplicationScoped
public class IotAuthorizerCfnProvisioner implements CfnResourceProvisioner {
private static final String TYPE = "AWS::IoT::Authorizer";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final int NAME_MAX_LENGTH = 128;
/**
* Records whether the name came from the template or was generated, so a later update can tell
* an explicit name being dropped, which replaces the authorizer on AWS, from an unnamed
* authorizer keeping the name it was given. Read back off the stored attributes.
*/
private static final String NAME_MODE_ATTR = "FlociAuthorizerNameMode";
private static final String NAME_MODE_EXPLICIT = "explicit";
private static final String NAME_MODE_GENERATED = "generated";
private final IotAuthorizerService authorizerService;
public IotAuthorizerCfnProvisioner(IotAuthorizerService authorizerService) {
this.authorizerService = authorizerService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(TYPE);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
// A snapshot describes the update in flight; one an earlier update left behind is stale.
r.getAttributes().remove(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
Map<String, String> attributesBefore = Map.copyOf(r.getAttributes());
String functionArn = resolvePresent(props, "AuthorizerFunctionArn", ctx);
if (functionArn == null) {
// The registry schema's required key, checked before the handler makes any call.
throw new AwsException("InvalidRequest",
"Model validation failed (#: required key [AuthorizerFunctionArn] not found)", 400);
}
String explicitName = resolvePresent(props, "AuthorizerName", ctx);
boolean hasExplicitName = explicitName != null;
String signingDisabled = resolveBoolean(props, "SigningDisabled", ctx);
ObjectNode declared = MAPPER.createObjectNode().put("authorizerFunctionArn", functionArn);
putIfPresent(declared, "status", resolvePresent(props, "Status", ctx));
putIfPresent(declared, "tokenKeyName", resolvePresent(props, "TokenKeyName", ctx));
String caching = resolveBoolean(props, "EnableCachingForHttp", ctx);
if (caching != null) {
declared.put("enableCachingForHttp", Boolean.parseBoolean(caching));
}
JsonNode keys = props == null ? null : ctx.engine().resolveNode(props.get("TokenSigningPublicKeys"));
if (keys != null && keys.isObject()) {
ObjectNode present = declared.putObject("tokenSigningPublicKeys");
// ponytail: an intrinsic resolving to "" counts as AWS::NoValue and is dropped,
// so an empty PEM chosen by Fn::If is not refused; a literal "" still is.
for (Map.Entry<String, JsonNode> key : keys.properties()) {
boolean literal = props.path("TokenSigningPublicKeys").path(key.getKey()).isTextual();
if (literal || !"".equals(key.getValue().textValue())) {
present.set(key.getKey(), key.getValue());
}
}
}
Map<String, String> tags = ctx.resolveTags(props, "Tags");
// A stack from before this type had a provisioner holds the dispatcher's stub here, which
// names no authorizer and never recorded a name mode, so the authorizer is created as on a first deploy.
boolean updatesAuthorizer = ctx.isUpdate() && attributesBefore.containsKey(NAME_MODE_ATTR);
IotAuthorizer prior = updatesAuthorizer
? authorizerService.describeAuthorizer(ctx.priorPhysicalId(), ctx.region())
: null;
// ponytail: compared with the stored flag, so an absent SigningDisabled reads as its API default false.
boolean signingChanged = prior != null && prior.isSigningDisabled() != Boolean.parseBoolean(signingDisabled);
boolean nameWasGenerated = NAME_MODE_GENERATED.equals(attributesBefore.get(NAME_MODE_ATTR));
if ((signingChanged || nameWasGenerated) && hasExplicitName && explicitName.equals(ctx.priorPhysicalId())) {
throw new AwsException("ValidationError",
"CloudFormation cannot update a stack when a custom-named resource requires "
+ "replacing. Rename " + explicitName + " and update the stack again.", 400);
}
String name = physicalName(r, ctx, explicitName, updatesAuthorizer, signingChanged);
IotAuthorizer authorizer;
if (updatesAuthorizer && ctx.reusesPriorEntity(name)) {
snapshotBeforeUpdate(r, prior, ctx.region());
authorizer = authorizerService.updateAuthorizer(name, declared, ctx.region());
try {
reconcileTags(prior, tags);
} catch (RuntimeException failure) {
unwind(r, name, failure);
throw failure;
}
} else {
if (signingDisabled != null) {
declared.put("signingDisabled", Boolean.parseBoolean(signingDisabled));
}
if (!tags.isEmpty()) {
ArrayNode tagList = declared.putArray("tags");
tags.forEach((key, value) -> tagList.addObject().put("Key", key).put("Value", value));
}
authorizer = authorizerService.createAuthorizer(name, declared, ctx.region());
}
r.setPhysicalId(name);
r.getAttributes().put("Arn", authorizer.getAuthorizerArn());
r.getAttributes().put(NAME_MODE_ATTR, hasExplicitName ? NAME_MODE_EXPLICIT : NAME_MODE_GENERATED);
ReplacementCleanup.record(r, ctx, attributesBefore);
}
/**
* An in-place update that changed the authorizer and then failed on its tags undoes itself.
* CloudFormationService puts the resource the stack held before the attempt back in its place,
* and that object never carried the snapshot taken here, so it marks the resource restored and
* the rollback walker skips {@link #rollbackUpdate}: without this the stack reports a completed
* rollback while the changed authorizer is still live. The stack must report the original
* failure, so an unwind that cannot restore is attached to it and recorded as a rollback
* failure, which ends the stack in UPDATE_ROLLBACK_FAILED. The unwind repeats the tag calls the
* update just made, so it can come back carrying the very exception that interrupted the
* update; a throwable cannot be suppressed under itself.
*/
private void unwind(StackResource r, String name, RuntimeException failure) {
try {
rollbackUpdate(r);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
} catch (RuntimeException unwindFailure) {
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,
"Could not roll back the update of authorizer " + name + ": " + unwindFailure.getMessage());
if (unwindFailure != failure) {
failure.addSuppressed(unwindFailure);
}
}
}
/**
* The resolved property, or null when it is absent or an intrinsic resolved to AWS::NoValue,
* which the engine yields as an empty string. A literal string, and an intrinsic result that is
* only whitespace, is kept as written.
*/
private static String resolvePresent(JsonNode props, String name, ProvisionContext ctx) {
String value = ctx.resolveOptional(props, name);
boolean literal = props != null && props.path(name).isTextual();
return literal || (value != null && !value.isEmpty()) ? value : null;
}
/** A present boolean property, refused unless it is true or false rather than read as false. */
private static String resolveBoolean(JsonNode props, String name, ProvisionContext ctx) {
String value = resolvePresent(props, name, ctx);
if (value != null && !"true".equalsIgnoreCase(value) && !"false".equalsIgnoreCase(value)) {
throw new AwsException("ValidationError", TYPE + " " + name + " must be true or false, got " + value, 400);
}
return value;
}
private static void putIfPresent(ObjectNode body, String field, String value) {
if (value != null) {
body.put(field, value);
}
}
/**
* The template's name when it gives one; otherwise the generated name the authorizer already
* has, unless the previous name was explicit or signing changed, since either replaces the
* authorizer on AWS, or the prior resource names no authorizer; and a fresh generated name
* otherwise. Logical ids only hold characters the IoT name rule allows, and the generator
* truncates to its limit.
*/
private static String physicalName(StackResource r, ProvisionContext ctx, String explicitName,
boolean updatesAuthorizer, boolean signingChanged) {
if (explicitName != null) {
return explicitName;
}
boolean explicitNameRemoved = ctx.isUpdate()
&& NAME_MODE_EXPLICIT.equals(r.getAttributes().get(NAME_MODE_ATTR));
if (updatesAuthorizer && !explicitNameRemoved && !signingChanged) {
return ctx.priorPhysicalId();
}
return generatedName(r.getLogicalId());
}
/** CloudFormation names an unnamed authorizer {@code <LogicalId>_<12 chars>}, with no stack prefix. */
private static String generatedName(String logicalId) {
String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12);
int prefixMax = NAME_MAX_LENGTH - 1 - suffix.length();
String prefix = logicalId.length() > prefixMax ? logicalId.substring(0, prefixMax) : logicalId;
return prefix + "_" + suffix;
}
private void reconcileTags(IotAuthorizer authorizer, Map<String, String> desired) {
List<String> stale = ProvisionContext.staleTagKeys(authorizer.getTags(), desired);
if (!stale.isEmpty()) {
authorizerService.untagResource(authorizer.getAuthorizerArn(), stale);
}
if (!desired.isEmpty()) {
authorizerService.tagResource(authorizer.getAuthorizerArn(), desired);
}
}
/**
* Keeps what an in-place update can change, as the UpdateAuthorizer body that puts it back,
* with the tags beside it, so {@link #rollbackUpdate} can restore them.
*/
private static void snapshotBeforeUpdate(StackResource r, IotAuthorizer current, String region) {
ObjectNode snapshot = MAPPER.createObjectNode();
snapshot.put("region", region);
snapshot.put("name", current.getAuthorizerName());
ObjectNode restore = snapshot.putObject("body")
.put("authorizerFunctionArn", current.getAuthorizerFunctionArn())
.put("status", current.getStatus())
.put("enableCachingForHttp", current.isEnableCachingForHttp());
putIfPresent(restore, "tokenKeyName", current.getTokenKeyName());
// ponytail: UpdateAuthorizer merges keys by name, so a key the update added survives a rollback.
if (current.getTokenSigningPublicKeys() != null) {
restore.set("tokenSigningPublicKeys", MAPPER.valueToTree(current.getTokenSigningPublicKeys()));
}
snapshot.set("tags", MAPPER.valueToTree(current.getTags()));
r.getAttributes().put(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
}
/** Deactivates, then deletes, as the AWS handler does; an authorizer already gone counts as deleted. */
@Override
public void delete(String resourceType, String physicalId, String region) {
CfnDeletes.safeDelete("IoT authorizer", physicalId, () -> {
authorizerService.updateAuthorizer(physicalId,
MAPPER.createObjectNode().put("status", "INACTIVE"), region);
authorizerService.deleteAuthorizer(physicalId, region);
}, "ResourceNotFoundException");
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.clear(resource);
}
/**
* A replacement is undone through the cleanup record and an in-place update from the snapshot
* taken before it. With neither on the resource the provision failed before it changed
* anything, so there is nothing to undo.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
if (ReplacementCleanup.rollback(resource, this::delete)) {
return true;
}
// The snapshot is spent only once the restore succeeded: a restore that throws leaves it in
// place for the next attempt instead of reporting a rollback that never happened.
String raw = resource.getAttributes().get(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
if (raw == null) {
return true;
}
JsonNode snapshot;
try {
snapshot = MAPPER.readTree(raw);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the authorizer update snapshot for "
+ resource.getLogicalId(), e);
}
String region = snapshot.path("region").asText();
IotAuthorizer restored = authorizerService.updateAuthorizer(snapshot.path("name").asText(),
snapshot.path("body"), region);
Map<String, String> tags = new LinkedHashMap<>();
snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText()));
reconcileTags(restored, tags);
resource.getAttributes().remove(CfnRollback.AUTHORIZER_UPDATE_SNAPSHOT_ATTR);
return true;
}
}
@@ -52,7 +52,9 @@ public final class ReplacementCleanup {
* physical id. Call after the new entity exists, with the attributes the resource carried
* before {@code provision} overwrote them: they are what {@link #rollback} puts back. A
* provision that replaced nothing drops the rollback fields but keeps any entity an earlier
* failed rollback left owed a delete.
* failed rollback left owed a delete. A dispatcher stub's id is never listed, because a stub
* created nothing, but a stub migration that kept the stub's id still keeps the rollback fields,
* because the entity under that id is the one this update created.
*/
static void record(StackResource r, ProvisionContext ctx, Map<String, String> attributesBeforeProvision) {
ObjectNode cleanup = readOrEmpty(r);
@@ -60,7 +62,8 @@ public final class ReplacementCleanup {
cleanup.remove("priorAttributes");
cleanup.put("region", ctx.region());
String prior = ctx.priorPhysicalId();
if (ctx.isUpdate() && !prior.equals(r.getPhysicalId())) {
boolean priorIsStub = CfnResourceDispatcher.isStub(prior, attributesBeforeProvision);
if (ctx.isUpdate() && (!prior.equals(r.getPhysicalId()) || priorIsStub)) {
cleanup.put("priorPhysicalId", prior);
ObjectNode priorAttributes = cleanup.putObject("priorAttributes");
attributesBeforeProvision.forEach((key, value) -> {
@@ -68,7 +71,9 @@ public final class ReplacementCleanup {
priorAttributes.put(key, value);
}
});
addDisplaced(cleanup, prior, r.getResourceType(), ctx.region(), true);
if (!priorIsStub) {
addDisplaced(cleanup, prior, r.getResourceType(), ctx.region(), true);
}
}
write(r, cleanup);
}
@@ -76,7 +81,8 @@ public final class ReplacementCleanup {
/**
* Undoes this update's replacement when a later resource failed the stack update: the resource
* names the prior entity again, with the attributes it had, and the replacement is deleted. The
* prior entity was displaced, never changed, so nothing is written to it.
* prior entity was displaced, never changed, so nothing is written to it. A stub migration that
* kept the stub's id still has its entity deleted, because the restored stub created nothing.
*
* <p>The prior leaves the delete list before the replacement's delete is attempted: it is
* standing again, and a resource still owing its delete would put it on the next cleanup's list.
@@ -105,7 +111,7 @@ public final class ReplacementCleanup {
cleanup.remove("priorAttributes");
removeDisplaced(cleanup, prior);
write(r, cleanup);
if (prior.equals(replacement)) {
if (prior.equals(replacement) && !CfnResourceDispatcher.isStub(prior, r.getAttributes())) {
return true;
}
try {
@@ -150,14 +156,14 @@ public final class ReplacementCleanup {
if (cleanup == null) {
return null;
}
JsonNode next = nextOwed(cleanup.path("displaced"), r.getPhysicalId(), "Retain".equals(r.getUpdateReplacePolicy()));
JsonNode next = nextOwed(cleanup.path("displaced"), liveEntityId(r), "Retain".equals(r.getUpdateReplacePolicy()));
return next == null ? null : next.path("physicalId").asText(null);
}
/**
* The owed entry with the fewest attempts, ties by list order: the one the engine's retries are
* still for. Skips the resource's own entity and, under Retain, the entities a committed
* replacement displaced.
* still for. Skips the resource's live entity, which a stub has none of, and, under Retain, the
* entities a committed replacement displaced.
*/
private static JsonNode nextOwed(JsonNode displaced, String currentPhysicalId, boolean retain) {
JsonNode next = null;
@@ -218,12 +224,13 @@ public final class ReplacementCleanup {
return UpdateCleanupResult.notApplicable();
}
boolean retain = "Retain".equals(r.getUpdateReplacePolicy());
String liveEntityId = liveEntityId(r);
ArrayNode displaced = cleanup.withArray("displaced");
ArrayNode remaining = MAPPER.createArrayNode();
for (JsonNode node : displaced) {
ObjectNode entry = (ObjectNode) node;
String physicalId = entry.path("physicalId").asText(null);
if (physicalId == null || physicalId.equals(r.getPhysicalId())
if (physicalId == null || physicalId.equals(liveEntityId)
|| (retain && entry.path("retainable").asBoolean(false))) {
continue;
}
@@ -248,11 +255,15 @@ public final class ReplacementCleanup {
}
// The result names the entity with the fewest attempts, the one the engine's retries are
// still for and the one cleanupPhysicalId announced, so both events point at the same thing.
JsonNode next = nextOwed(remaining, r.getPhysicalId(), retain);
JsonNode next = nextOwed(remaining, liveEntityId, retain);
return new UpdateCleanupResult(true, false, next.path("physicalId").asText(null),
next.path("cleanupAttempts").asInt(0), next.path("cleanupFailureReason").asText(null));
}
private static String liveEntityId(StackResource r) {
return CfnResourceDispatcher.isStub(r.getPhysicalId(), r.getAttributes()) ? null : r.getPhysicalId();
}
private static String firstDisplaced(ArrayNode displaced) {
return displaced.isEmpty() ? null : displaced.get(0).path("physicalId").asText(null);
}
@@ -455,6 +455,10 @@
"AWS::IAM::User": [
"UserName"
],
"AWS::IoT::Authorizer": [
"SigningDisabled",
"AuthorizerName"
],
"AWS::IoT::DomainConfiguration": [
"DomainConfigurationName",
"DomainName",
@@ -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
@@ -98,6 +98,7 @@ AWS::IAM::ManagedPolicy IamManagedPolicyCfnProvisioner
AWS::IAM::Policy IamPolicyCfnProvisioner
AWS::IAM::Role IamRoleCfnProvisioner
AWS::IAM::User IamUserCfnProvisioner
AWS::IoT::Authorizer IotAuthorizerCfnProvisioner
AWS::IoT::DomainConfiguration IotDomainConfigurationCfnProvisioner
AWS::IoT::Policy IotCfnProvisioner
AWS::IoT::Thing IotCfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
98 AWS::IAM::Policy IamPolicyCfnProvisioner
99 AWS::IAM::Role IamRoleCfnProvisioner
100 AWS::IAM::User IamUserCfnProvisioner
101 AWS::IoT::Authorizer IotAuthorizerCfnProvisioner
102 AWS::IoT::DomainConfiguration IotDomainConfigurationCfnProvisioner
103 AWS::IoT::Policy IotCfnProvisioner
104 AWS::IoT::Thing IotCfnProvisioner