feat(iot): provision AWS::IoT::Thing, Policy and TopicRule (#3014)

* feat(iot): provision AWS::IoT::Thing, Policy and TopicRule

CloudFormation now creates, updates and deletes things, policies and
topic rules through the existing IoT operations. Ref returns the name;
Fn::GetAtt returns the thing ARN and id, the policy ARN and id (the
name, as on AWS) and the rule ARN. Attribute payloads are replaced in
place, a changed policy document becomes a new default version, a rule
is replaced in place, and a rename replaces the entity. The topic rule
payload is handed to the service in the API's own shape. A policy is
detached from its principals before it is deleted.

* test(iot): keep policy variables verbatim in a stack-created policy

* fix(iot): cap a policy at five versions and prune the oldest on a stack update

CreatePolicyVersion refuses a sixth version with VersionsLimitExceededException (HTTP 409), as AWS does, and every policy version write runs under one lock so racing creates cannot slip past the check. A stack update with a changed document now does what the AWS CloudFormation handler does when the service refuses: it deletes the oldest version, after moving the default to the newest when the oldest is the default, and creates the new version again. Before this change the versions of a policy updated by a stack piled up without limit.

* fix(iot): keep pruning when another version fills the slot before the retry

The prune and the retry are separate calls, so another client could create a version between them and the single retry failed the stack update. The provisioner now prunes and tries again, up to as many times as a policy has versions, before it gives up.

* fix(iot): delete the oldest policy version in one step under the version lock

A stack update pruning a full policy selected the oldest version, moved the default and deleted it in separate service calls, so a direct client could delete or promote that version in between and the stale delete failed the update. The selection, the default move and the delete are now one step in IotService under the version lock; the provisioner only asks for it and retries.

* fix(iot): make room for a policy version in one step and lock the policy delete

A policy persisted before the cap can hold more than five versions, and the one-version prune then needed one failed stack update per four surplus versions. The service now deletes the oldest versions until one more fits, in one step under the lock, and the provisioner asks for that. DeletePolicy takes the same lock: a version created in the middle of a delete used to put the policy back after the delete had returned. The limit error now carries the message AWS sends, and the tolerated limit error is logged at debug level.

* docs(cloudformation): regenerate the resource-type table after the rebase onto main
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-09-06 11:06:47 -04:00
1 parent 8468dd1ef3
commit dec348d382
12 files changed
+1789 -39

No files matched your search

@@ -0,0 +1,295 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
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.IotService;
import io.github.hectorvent.floci.services.iot.model.IotPolicy;
import io.github.hectorvent.floci.services.iot.model.IotTopicRule;
import io.github.hectorvent.floci.services.iot.model.Thing;
import jakarta.enterprise.context.ApplicationScoped;
import org.jboss.logging.Logger;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Provisions the IoT Core registry and rules engine types: {@code AWS::IoT::Thing},
* {@code AWS::IoT::Policy} and {@code AWS::IoT::TopicRule}. The physical id is the resource name,
* as it is on AWS, so a rename is a replacement: the new entity is created first and the prior
* one removed afterwards, since there is no generic replacement flow.
*/
@ApplicationScoped
public class IotCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(IotCfnProvisioner.class);
private static final String NOT_FOUND = "ResourceNotFoundException";
private static final int NAME_MAX_LENGTH = 128;
private final IotService iotService;
public IotCfnProvisioner(IotService iotService) {
this.iotService = iotService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::IoT::Thing", "AWS::IoT::Policy", "AWS::IoT::TopicRule");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
switch (r.getResourceType()) {
case "AWS::IoT::Thing" -> provisionThing(r, props, ctx);
case "AWS::IoT::Policy" -> provisionPolicy(r, props, ctx);
case "AWS::IoT::TopicRule" -> provisionTopicRule(r, props, ctx);
default -> throw new IllegalStateException("IotCfnProvisioner cannot handle " + r.getResourceType());
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
switch (resourceType) {
case "AWS::IoT::Thing" -> CfnDeletes.safeDelete("thing", physicalId,
() -> iotService.deleteThing(physicalId, region), NOT_FOUND);
case "AWS::IoT::Policy" -> CfnDeletes.safeDelete("policy", physicalId,
() -> detachAndDeletePolicy(physicalId, region), NOT_FOUND);
case "AWS::IoT::TopicRule" -> CfnDeletes.safeDelete("topic rule", physicalId,
() -> iotService.deleteTopicRule(physicalId, region), NOT_FOUND);
default -> throw new IllegalStateException("IotCfnProvisioner cannot handle " + resourceType);
}
}
/**
* {@code AttributePayload.Attributes} is the whole desired attribute set: an update replaces the
* stored attributes rather than merging into them, as the CloudFormation handler does.
*/
private void provisionThing(StackResource r, JsonNode props, ProvisionContext ctx) {
String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "ThingName"),
r.getLogicalId(), NAME_MAX_LENGTH, false);
Map<String, String> attributes = thingAttributes(props, ctx);
String region = ctx.region();
boolean sameThing = ctx.reusesPriorEntity(name);
Thing thing = sameThing
? iotService.updateThing(name, attributes, null, region)
: iotService.createThing(name, attributes, region);
r.setPhysicalId(name);
r.getAttributes().put("Arn", thing.getThingArn());
r.getAttributes().put("Id", thing.getThingId());
if (!sameThing) {
deletePrior(r, ctx);
}
}
/**
* A changed document becomes a new default version, as the CloudFormation handler does; the
* document is compared as the string the policy stores, which is what this provisioner wrote
* on the previous execution. {@code Id} is the policy name, as on AWS.
*/
private void provisionPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "PolicyName"),
r.getLogicalId(), NAME_MAX_LENGTH, false);
String document = props == null ? null : ctx.engine().resolveJsonAttribute(props.path("PolicyDocument"));
if (document == null || document.isBlank()) {
throw new IllegalArgumentException("AWS::IoT::Policy requires PolicyDocument");
}
Map<String, String> tags = ctx.resolveTags(props, "Tags");
String region = ctx.region();
if (ctx.reusesPriorEntity(name)) {
IotPolicy policy = iotService.getPolicy(name, region);
if (!document.equals(policy.getPolicyDocument())) {
createDefaultVersion(name, document, region);
}
reconcileTags(policy.getPolicyArn(), tags);
recordPolicy(r, name, policy.getPolicyArn());
return;
}
IotPolicy policy = iotService.createPolicy(name, document, region);
recordPolicy(r, name, policy.getPolicyArn());
finishCreate(r, ctx, () -> applyTags(policy.getPolicyArn(), tags));
deletePrior(r, ctx);
}
/**
* A policy holds at most five versions. When the service refuses a sixth, this does what the
* AWS handler does: the oldest version goes, in one step on the service's side, and the new one
* is created again. Unlike that handler it tries more than once, because a version created by
* another client between the delete and the retry would otherwise fail the stack update; it
* gives up after as many attempts as a policy has versions.
*/
private void createDefaultVersion(String name, String document, String region) {
for (int attempt = 1; ; attempt++) {
try {
iotService.createPolicyVersion(name, document, true, region);
return;
} catch (AwsException e) {
if (!"VersionsLimitExceededException".equals(e.getErrorCode())
|| attempt >= IotService.MAX_POLICY_VERSIONS) {
throw e;
}
LOG.debugv("Policy {0} is at its version limit, deleting the oldest version before the new default: {1}",
name, e.getMessage());
}
iotService.makeRoomForPolicyVersion(name, region);
}
}
/**
* The template payload is handed to the service in the IoT API's own shape: the same members
* with a lowercase first letter, all the way down into the actions. A generated name keeps only
* the characters a rule name allows, since AWS rejects the hyphens
* {@link ProvisionContext#generatePhysicalName} emits.
*/
private void provisionTopicRule(StackResource r, JsonNode props, ProvisionContext ctx) {
String name = ctx.resolveOptional(props, "RuleName");
if (name == null || name.isBlank()) {
name = ctx.stablePhysicalName(null, r.getLogicalId(), NAME_MAX_LENGTH, false)
.replaceAll("[^A-Za-z0-9_]", "");
}
if (props == null || !props.hasNonNull("TopicRulePayload")) {
throw new IllegalArgumentException("AWS::IoT::TopicRule requires TopicRulePayload");
}
JsonNode payload = toApiShape(ctx.engine().resolveNode(props.get("TopicRulePayload")));
Map<String, String> tags = ctx.resolveTags(props, "Tags");
String region = ctx.region();
if (ctx.reusesPriorEntity(name)) {
IotTopicRule rule = iotService.replaceTopicRule(name, payload, region);
reconcileTags(rule.getRuleArn(), tags);
recordTopicRule(r, name, rule.getRuleArn());
return;
}
IotTopicRule rule = iotService.createTopicRule(name, payload, region);
recordTopicRule(r, name, rule.getRuleArn());
finishCreate(r, ctx, () -> applyTags(rule.getRuleArn(), tags));
deletePrior(r, ctx);
}
/**
* The service refuses to delete a policy that is still attached to a principal, and on AWS the
* stack would fail with a DeleteConflictException. Here the stack that created the policy also
* takes its attachments with it, so a local teardown never gets stuck on a device that was
* connected while the stack existed.
*/
private void detachAndDeletePolicy(String policyName, String region) {
for (String target : iotService.listTargetsForPolicy(policyName, region)) {
iotService.detachPolicy(policyName, target, region);
}
iotService.deletePolicy(policyName, region);
}
private static void recordPolicy(StackResource r, String name, String arn) {
r.setPhysicalId(name);
r.getAttributes().put("Arn", arn);
r.getAttributes().put("Id", name);
}
private static void recordTopicRule(StackResource r, String name, String arn) {
r.setPhysicalId(name);
r.getAttributes().put("Arn", arn);
}
private static Map<String, String> thingAttributes(JsonNode props, ProvisionContext ctx) {
Map<String, String> attributes = new LinkedHashMap<>();
if (props == null || !props.has("AttributePayload")) {
return attributes;
}
JsonNode resolved = ctx.engine().resolveNode(props.get("AttributePayload"));
JsonNode values = resolved == null ? null : resolved.path("Attributes");
if (values != null && values.isObject()) {
values.fields().forEachRemaining(field ->
attributes.put(field.getKey(), ctx.engine().resolve(field.getValue())));
}
return attributes;
}
/** Recursively renames the members of a resolved node to the API's camelCase, dropping nulls. */
private static JsonNode toApiShape(JsonNode node) {
if (node.isObject()) {
ObjectNode out = JsonNodeFactory.instance.objectNode();
node.fields().forEachRemaining(field -> {
if (!field.getValue().isNull()) {
out.set(decapitalize(field.getKey()), toApiShape(field.getValue()));
}
});
return out;
}
if (node.isArray()) {
ArrayNode out = JsonNodeFactory.instance.arrayNode();
node.forEach(item -> out.add(toApiShape(item)));
return out;
}
return node;
}
private static String decapitalize(String key) {
return key.isEmpty() ? key : Character.toLowerCase(key.charAt(0)) + key.substring(1);
}
/**
* Runs the calls that follow a create with the resource marked as owned by this stack, so a
* failure among them still lets the create rollback delete the entity that now exists. When the
* create was a replacement, the entity is removed here instead: CloudFormationService restores
* the prior StackResource and never learns the new name, so nothing else would.
*/
private void finishCreate(StackResource r, ProvisionContext ctx, Runnable finish) {
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
try {
finish.run();
} catch (RuntimeException failure) {
if (ctx.isUpdate()) {
unwindReplacement(r, ctx.region(), failure);
}
throw failure;
}
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
}
private void unwindReplacement(StackResource r, String region, RuntimeException failure) {
try {
delete(r.getResourceType(), r.getPhysicalId(), region);
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
} catch (RuntimeException cleanupFailure) {
failure.addSuppressed(cleanupFailure);
String reason = "Could not remove " + r.getPhysicalId() + ", the replacement created for "
+ r.getLogicalId() + " by a failed update: " + cleanupFailure.getMessage();
LOG.warn(reason);
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason);
}
}
/**
* Removes the entity a replacement supersedes. As in CloudFormation's update cleanup, a failure
* does not fail the update: the stack already points at the new entity, so the prior one is
* left behind with a warning in the log.
*/
private void deletePrior(StackResource r, ProvisionContext ctx) {
if (!ctx.isUpdate()) {
return;
}
try {
delete(r.getResourceType(), ctx.priorPhysicalId(), ctx.region());
} catch (AwsException e) {
LOG.warnv("Could not delete {0} {1} replaced by {2}: {3}",
r.getResourceType(), ctx.priorPhysicalId(), r.getPhysicalId(), e.getMessage());
}
}
private void applyTags(String arn, Map<String, String> tags) {
if (!tags.isEmpty()) {
iotService.tagResource(arn, tags);
}
}
private void reconcileTags(String arn, Map<String, String> desired) {
List<String> stale = ProvisionContext.staleTagKeys(iotService.listTagsForResource(arn), desired);
if (!stale.isEmpty()) {
iotService.untagResource(arn, stale);
}
applyTags(arn, desired);
}
}
@@ -70,6 +70,10 @@ public class IotService {
private static final Pattern THING_NAME_PATTERN = Pattern.compile("[a-zA-Z0-9:_-]{1,128}");
/** The {@code FirehoseSeparator} shape of the IoT API model. */
private static final Pattern FIREHOSE_SEPARATOR = Pattern.compile("([\\n\\t])|(\\r\\n)|(,)");
public static final int MAX_POLICY_VERSIONS = 5;
/** One lock for every policy version write and the policy delete, so a cap check, an append and a delete cannot interleave. */
private final Object policyWriteLock = new Object();
private final StorageBackend<String, Thing> thingStore;
private final StorageBackend<String, IotCertificate> certificateStore;
@@ -433,34 +437,42 @@ public class IotService {
}
public void deletePolicy(String policyName, String region) {
getPolicy(policyName, region);
if (!policyAttachmentStore.get(policyAttachmentKey(region, policyName)).orElse(Set.of()).isEmpty()) {
throw new AwsException("InvalidRequestException", "Cannot delete attached policy", 400);
synchronized (policyWriteLock) {
getPolicy(policyName, region);
if (!policyAttachmentStore.get(policyAttachmentKey(region, policyName)).orElse(Set.of()).isEmpty()) {
throw new AwsException("InvalidRequestException", "Cannot delete attached policy", 400);
}
policyStore.delete(policyKey(region, policyName));
policyAttachmentStore.delete(policyAttachmentKey(region, policyName));
}
policyStore.delete(policyKey(region, policyName));
policyAttachmentStore.delete(policyAttachmentKey(region, policyName));
}
public IotPolicy.PolicyVersion createPolicyVersion(String policyName, String policyDocument, boolean setAsDefault, String region) {
IotPolicy policy = getPolicy(policyName, region);
int next = policy.getVersions().stream()
.map(IotPolicy.PolicyVersion::getVersionId)
.mapToInt(Integer::parseInt)
.max()
.orElse(0) + 1;
IotPolicy.PolicyVersion version = new IotPolicy.PolicyVersion();
version.setVersionId(Integer.toString(next));
version.setDocument(policyDocument);
version.setCreateDate(Instant.now());
List<IotPolicy.PolicyVersion> versions = new java.util.ArrayList<>(policy.getVersions());
versions.add(version);
policy.setVersions(versions);
if (setAsDefault) {
policy.setDefaultVersionId(version.getVersionId());
policy.setPolicyDocument(policyDocument);
synchronized (policyWriteLock) {
IotPolicy policy = getPolicy(policyName, region);
if (policy.getVersions().size() >= MAX_POLICY_VERSIONS) {
throw new AwsException("VersionsLimitExceededException", "The policy " + policyName
+ " already has the maximum number of versions (" + MAX_POLICY_VERSIONS + ")", 409);
}
int next = policy.getVersions().stream()
.map(IotPolicy.PolicyVersion::getVersionId)
.mapToInt(Integer::parseInt)
.max()
.orElse(0) + 1;
IotPolicy.PolicyVersion version = new IotPolicy.PolicyVersion();
version.setVersionId(Integer.toString(next));
version.setDocument(policyDocument);
version.setCreateDate(Instant.now());
List<IotPolicy.PolicyVersion> versions = new ArrayList<>(policy.getVersions());
versions.add(version);
policy.setVersions(versions);
if (setAsDefault) {
policy.setDefaultVersionId(version.getVersionId());
policy.setPolicyDocument(policyDocument);
}
policyStore.put(policyKey(region, policyName), policy);
return version;
}
policyStore.put(policyKey(region, policyName), policy);
return version;
}
public IotPolicy.PolicyVersion getPolicyVersion(String policyName, String versionId, String region) {
@@ -478,26 +490,55 @@ public class IotService {
}
public void setDefaultPolicyVersion(String policyName, String versionId, String region) {
IotPolicy policy = getPolicy(policyName, region);
IotPolicy.PolicyVersion version = getPolicyVersion(policyName, versionId, region);
policy.setDefaultVersionId(versionId);
policy.setPolicyDocument(version.getDocument());
policyStore.put(policyKey(region, policyName), policy);
synchronized (policyWriteLock) {
IotPolicy policy = getPolicy(policyName, region);
IotPolicy.PolicyVersion version = getPolicyVersion(policyName, versionId, region);
policy.setDefaultVersionId(versionId);
policy.setPolicyDocument(version.getDocument());
policyStore.put(policyKey(region, policyName), policy);
}
}
public void deletePolicyVersion(String policyName, String versionId, String region) {
IotPolicy policy = getPolicy(policyName, region);
if (versionId.equals(policy.getDefaultVersionId())) {
throw new AwsException("InvalidRequestException", "Cannot delete default policy version", 400);
synchronized (policyWriteLock) {
IotPolicy policy = getPolicy(policyName, region);
if (versionId.equals(policy.getDefaultVersionId())) {
throw new AwsException("InvalidRequestException", "Cannot delete default policy version", 400);
}
List<IotPolicy.PolicyVersion> versions = policy.getVersions().stream()
.filter(version -> !versionId.equals(version.getVersionId()))
.toList();
if (versions.size() == policy.getVersions().size()) {
throw new AwsException("ResourceNotFoundException", "Policy version not found: " + versionId, 404);
}
policy.setVersions(versions);
policyStore.put(policyKey(region, policyName), policy);
}
List<IotPolicy.PolicyVersion> versions = policy.getVersions().stream()
.filter(version -> !versionId.equals(version.getVersionId()))
.toList();
if (versions.size() == policy.getVersions().size()) {
throw new AwsException("ResourceNotFoundException", "Policy version not found: " + versionId, 404);
}
/**
* Deletes the oldest versions until one more fits under the cap, which is what the AWS
* CloudFormation handler means to do once the service refuses a sixth (it sorts version ids as
* text, so past nine it picks another one). A policy persisted before the cap can hold more
* than five, so this deletes as many as it takes. A default version cannot be deleted, so when
* the oldest is the default the newest becomes the default first. One step under the policy
* write lock, so nothing else can move the selection in between.
*/
public void makeRoomForPolicyVersion(String policyName, String region) {
synchronized (policyWriteLock) {
IotPolicy policy = getPolicy(policyName, region);
while (policy.getVersions().size() >= MAX_POLICY_VERSIONS) {
List<IotPolicy.PolicyVersion> versions = policy.getVersions().stream()
.sorted(Comparator.comparingInt(version -> Integer.parseInt(version.getVersionId())))
.toList();
String oldest = versions.get(0).getVersionId();
if (oldest.equals(policy.getDefaultVersionId())) {
setDefaultPolicyVersion(policyName, versions.get(versions.size() - 1).getVersionId(), region);
}
deletePolicyVersion(policyName, oldest, region);
policy = getPolicy(policyName, region);
}
}
policy.setVersions(versions);
policyStore.put(policyKey(region, policyName), policy);
}
public void attachPolicy(String policyName, String target, String region) {