mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
feat(iot): domain configurations (#3008)
* feat(iot): add the domain configuration model and service Stores AWS IoT Core domain configurations the way the API reports them: a new configuration is ENABLED and CUSTOMER_MANAGED (ENDPOINT without a domain name), carries one VALID server certificate, the default TLS policy and an ARN with the short id AWS appends. Update changes the status, authorizer, TLS, certificate and protocol settings; delete refuses an ENABLED configuration, as AWS does; list filters by service type and pages with marker and pageSize. Tags work on the ARN. * feat(iot): serve the domain configuration API Adds the REST-JSON routes CreateDomainConfiguration, DescribeDomainConfiguration, UpdateDomainConfiguration, DeleteDomainConfiguration and ListDomainConfigurations under /domainConfigurations, registered with the IoT service so the X-Amzn-Errortype header is set for unsigned callers too. Tags on a configuration ARN go through IotTagHandler; the IoT /untag route now uses the same handler as /tags instead of calling IotService directly. DescribeEndpoint accepts iot:CredentialProvider, the endpoint type that pairs with the CREDENTIAL_PROVIDER service type. * feat(iot): provision AWS::IoT::DomainConfiguration Adds IotDomainConfigurationCfnProvisioner over the domain configuration service. Ref is the configuration name; Fn::GetAtt Arn, DomainType and ServerCertificates resolve to what DescribeDomainConfiguration reports (ServerCertificates as a JSON string, since attributes are strings). Like the CloudFormation handler, a configuration is created ENABLED and a DomainConfigurationStatus of DISABLED is applied with a follow-up update; tags go through TagResource and are reconciled on update; a delete disables the configuration first because the API refuses to delete an ENABLED one. UpdateStack keeps the configuration when the createOnly properties (DomainName, ServiceType, ValidationCertificateArn, ServerCertificateArns) are unchanged and replaces it otherwise, with a fresh generated name when the template names none. Inventory TSV, fixture wiring and the generated resource-type table updated. * docs(iot): describe domain configurations and add the stack integration test IotDomainConfigurationCfnIntegrationTest provisions the type through a stack and asserts Ref and every Fn::GetAtt attribute against DescribeDomainConfiguration, the in-place status update, and that DeleteStack removes the configuration. * test(iot): cover domain configurations in the Java and Go SDK suites Both cases create, describe, list, update and delete a configuration through the real SDK clients and check the AWS error types on the duplicate create, the refused delete of an ENABLED configuration and the describe after deletion. * fix(iot): remove a renamed domain configuration and keep the status when the template omits it A template that changes DomainConfigurationName creates the new configuration and now removes the previous one, as the generated-name replacement already did; before, the old configuration outlived the stack. An update without DomainConfigurationStatus no longer forces ENABLED: the field is omitted and the current status stays, as the AWS handler does. The service rejects a structured JSON value where a string, boolean, list or object is expected instead of turning it into an empty string or silently clearing the authorizer, and validates the whole update before touching the stored record. * fix(iot): let stack rollback remove a domain configuration and make same-name creates atomic A configuration created by a stack is recorded, with the owned marker, before the follow-up status update, so a failure there still lets the create rollback delete it. A replacement that fails after the new configuration exists removes it again, re-enables the previous one if it had been disabled on the way out, and marks the resource restored, as the other provisioners do. CreateDomainConfiguration checks and stores the name in one step, so two overlapping creates of the same name cannot both succeed. A tags value that is not a list is rejected. The Java SDK compatibility case looks for a leftover configuration instead of swallowing every cleanup exception. * fix(iot): point the resource back at the prior domain configuration after a failed replacement After the unwind removes the replacement and re-enables the previous configuration, the resource now carries the previous name and attributes again, without the owned marker, so it describes the configuration that is still there rather than the one just removed. * feat(iot): serve the AWS-managed domain configurations Every AWS account has iot:Data-ATS, iot:Data, iot:CredentialProvider and iot:Jobs without creating them. They now exist in every region on first use: AWS_MANAGED, ENABLED, no server certificate, and the address DescribeEndpoint returns as their domain name. They can be updated and tagged like any other configuration, but not deleted, as on AWS. A client that starts by describing iot:Data-ATS gets an answer instead of a 404. * fix(iot): report a failed replacement cleanup as a rollback failure When the unwind of a failed replacement cannot remove the new domain configuration, the resource now carries the rollback-failure marker with the reason, so the stack ends in UPDATE_ROLLBACK_FAILED instead of reporting a clean rollback while the configuration is still there. The marker moves next to the restored one in CfnRollback so extracted provisioners can set it; the legacy provisioner keeps its alias. * fix(iot): serialise every read-modify-write on a domain configuration Update, delete, tag and untag read a record, change it and write it back. Two overlapping writers lost each other's changes: sixteen tag writers on one configuration left seven keys. All of them now run under the lock the create already used, and a test pins the invariant. A JSON round trip with the mapper setup persistent storage uses pins that the model reloads intact. * fix(iot): keep the prior status the unwind compares against and never delete a same-name replacement The store hands out its live record, so disabling the prior on the way to deleting it changed the very object the unwind later compared against, and a prior whose delete failed half way was left DISABLED while the stack reported a clean rollback. The status seen at the start is now kept and used. The test reproduces the aliasing instead of handing the provisioner a fresh copy per call. A replacement under the same explicit name normally fails on the create; if it goes through because the prior vanished in between, the prior is no longer deleted, which would have removed the configuration just created. * fix(iot): tolerate a domain configuration that vanishes while a stack delete disables it The disable that precedes the delete now treats ResourceNotFoundException as already deleted, the way the delete itself does. The SDK cases also enable an already ENABLED configuration, the call a client makes when it only wants to be sure the configuration is on.
This commit is contained in:
1 parent
f3c251ef20
commit
9220c057b7
21 files changed
+2896
-11
No files matched your search
@@ -39,6 +39,103 @@ func TestIoT(t *testing.T) {
|
||||
assert.NotEmpty(t, aws.ToString(response.EndpointAddress))
|
||||
})
|
||||
|
||||
t.Run("DomainConfigurationLifecycle", func(t *testing.T) {
|
||||
name := "go-iot-domain"
|
||||
certificateArn := "arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111"
|
||||
// A leftover from an earlier run must be disabled before it can be deleted.
|
||||
_, _ = svc.UpdateDomainConfiguration(ctx, &iot.UpdateDomainConfigurationInput{
|
||||
DomainConfigurationName: aws.String(name),
|
||||
DomainConfigurationStatus: iottypes.DomainConfigurationStatusDisabled,
|
||||
})
|
||||
_, _ = svc.DeleteDomainConfiguration(ctx, &iot.DeleteDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
|
||||
_, err := svc.DescribeDomainConfiguration(ctx, &iot.DescribeDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
var notFound *iottypes.ResourceNotFoundException
|
||||
require.ErrorAs(t, err, ¬Found)
|
||||
|
||||
managed, err := svc.DescribeDomainConfiguration(ctx, &iot.DescribeDomainConfigurationInput{DomainConfigurationName: aws.String("iot:Data-ATS")})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, iottypes.DomainTypeAwsManaged, managed.DomainType)
|
||||
assert.Equal(t, iottypes.DomainConfigurationStatusEnabled, managed.DomainConfigurationStatus)
|
||||
assert.NotEmpty(t, aws.ToString(managed.DomainName))
|
||||
|
||||
created, err := svc.CreateDomainConfiguration(ctx, &iot.CreateDomainConfigurationInput{
|
||||
DomainConfigurationName: aws.String(name),
|
||||
DomainName: aws.String("iot.go.example.com"),
|
||||
ServerCertificateArns: []string{certificateArn},
|
||||
ServiceType: iottypes.ServiceTypeData,
|
||||
Tags: []iottypes.Tag{{Key: aws.String("env"), Value: aws.String("go")}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, name, aws.ToString(created.DomainConfigurationName))
|
||||
assert.True(t, strings.HasPrefix(aws.ToString(created.DomainConfigurationArn),
|
||||
"arn:aws:iot:us-east-1:000000000000:domainconfiguration/"+name+"/"))
|
||||
|
||||
_, err = svc.CreateDomainConfiguration(ctx, &iot.CreateDomainConfigurationInput{
|
||||
DomainConfigurationName: aws.String(name),
|
||||
DomainName: aws.String("iot.go.example.com"),
|
||||
ServerCertificateArns: []string{certificateArn},
|
||||
})
|
||||
var alreadyExists *iottypes.ResourceAlreadyExistsException
|
||||
require.ErrorAs(t, err, &alreadyExists)
|
||||
|
||||
described, err := svc.DescribeDomainConfiguration(ctx, &iot.DescribeDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, aws.ToString(created.DomainConfigurationArn), aws.ToString(described.DomainConfigurationArn))
|
||||
assert.Equal(t, "iot.go.example.com", aws.ToString(described.DomainName))
|
||||
assert.Equal(t, iottypes.DomainConfigurationStatusEnabled, described.DomainConfigurationStatus)
|
||||
assert.Equal(t, iottypes.ServiceTypeData, described.ServiceType)
|
||||
assert.Equal(t, iottypes.DomainTypeCustomerManaged, described.DomainType)
|
||||
require.Len(t, described.ServerCertificates, 1)
|
||||
assert.Equal(t, certificateArn, aws.ToString(described.ServerCertificates[0].ServerCertificateArn))
|
||||
assert.Equal(t, iottypes.ServerCertificateStatusValid, described.ServerCertificates[0].ServerCertificateStatus)
|
||||
assert.NotNil(t, described.LastStatusChangeDate)
|
||||
|
||||
listed, err := svc.ListDomainConfigurations(ctx, &iot.ListDomainConfigurationsInput{ServiceType: iottypes.ServiceTypeData})
|
||||
require.NoError(t, err)
|
||||
var names []string
|
||||
for _, summary := range listed.DomainConfigurations {
|
||||
names = append(names, aws.ToString(summary.DomainConfigurationName))
|
||||
}
|
||||
assert.Contains(t, names, name)
|
||||
|
||||
// Enabling an already ENABLED configuration is accepted and changes nothing.
|
||||
enabled, err := svc.UpdateDomainConfiguration(ctx, &iot.UpdateDomainConfigurationInput{
|
||||
DomainConfigurationName: aws.String(name),
|
||||
DomainConfigurationStatus: iottypes.DomainConfigurationStatusEnabled,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, aws.ToString(created.DomainConfigurationArn), aws.ToString(enabled.DomainConfigurationArn))
|
||||
described, err = svc.DescribeDomainConfiguration(ctx, &iot.DescribeDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, iottypes.DomainConfigurationStatusEnabled, described.DomainConfigurationStatus)
|
||||
|
||||
tags, err := svc.ListTagsForResource(ctx, &iot.ListTagsForResourceInput{ResourceArn: created.DomainConfigurationArn})
|
||||
require.NoError(t, err)
|
||||
require.Len(t, tags.Tags, 1)
|
||||
assert.Equal(t, "env", aws.ToString(tags.Tags[0].Key))
|
||||
|
||||
_, err = svc.DeleteDomainConfiguration(ctx, &iot.DeleteDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
var invalid *iottypes.InvalidRequestException
|
||||
require.ErrorAs(t, err, &invalid)
|
||||
|
||||
updated, err := svc.UpdateDomainConfiguration(ctx, &iot.UpdateDomainConfigurationInput{
|
||||
DomainConfigurationName: aws.String(name),
|
||||
DomainConfigurationStatus: iottypes.DomainConfigurationStatusDisabled,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, aws.ToString(created.DomainConfigurationArn), aws.ToString(updated.DomainConfigurationArn))
|
||||
|
||||
described, err = svc.DescribeDomainConfiguration(ctx, &iot.DescribeDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, iottypes.DomainConfigurationStatusDisabled, described.DomainConfigurationStatus)
|
||||
|
||||
_, err = svc.DeleteDomainConfiguration(ctx, &iot.DeleteDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
require.NoError(t, err)
|
||||
_, err = svc.DescribeDomainConfiguration(ctx, &iot.DescribeDomainConfigurationInput{DomainConfigurationName: aws.String(name)})
|
||||
require.ErrorAs(t, err, ¬Found)
|
||||
})
|
||||
|
||||
t.Run("ThingRegistryCrud", func(t *testing.T) {
|
||||
thingName := "go-iot-thing"
|
||||
otherThingName := "go-iot-other-thing"
|
||||
|
||||
@@ -9,25 +9,32 @@ import software.amazon.awssdk.services.iot.IotClient;
|
||||
import software.amazon.awssdk.services.iot.model.AttributePayload;
|
||||
import software.amazon.awssdk.services.iot.model.AttachPolicyRequest;
|
||||
import software.amazon.awssdk.services.iot.model.AttachThingPrincipalRequest;
|
||||
import software.amazon.awssdk.services.iot.model.AuthorizerConfig;
|
||||
import software.amazon.awssdk.services.iot.model.CertificateStatus;
|
||||
import software.amazon.awssdk.services.iot.model.Action;
|
||||
import software.amazon.awssdk.services.iot.model.AddThingToThingGroupRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreateKeysAndCertificateRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreateDomainConfigurationRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreateJobRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreatePolicyRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreateThingGroupRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreateThingRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreateThingTypeRequest;
|
||||
import software.amazon.awssdk.services.iot.model.CreateTopicRuleRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DeleteDomainConfigurationRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DeleteThingGroupRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DeleteTopicRuleRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DeleteThingRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DeleteThingTypeRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DescribeCertificateRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DescribeDomainConfigurationRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DescribeEndpointRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DescribeJobRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DescribeThingRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DescribeThingTypeRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DomainConfigurationStatus;
|
||||
import software.amazon.awssdk.services.iot.model.DomainConfigurationSummary;
|
||||
import software.amazon.awssdk.services.iot.model.DomainType;
|
||||
import software.amazon.awssdk.services.iot.model.DisableTopicRuleRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DeprecateThingTypeRequest;
|
||||
import software.amazon.awssdk.services.iot.model.DetachPolicyRequest;
|
||||
@@ -35,7 +42,9 @@ import software.amazon.awssdk.services.iot.model.DetachThingPrincipalRequest;
|
||||
import software.amazon.awssdk.services.iot.model.EnableTopicRuleRequest;
|
||||
import software.amazon.awssdk.services.iot.model.GetPolicyRequest;
|
||||
import software.amazon.awssdk.services.iot.model.GetTopicRuleRequest;
|
||||
import software.amazon.awssdk.services.iot.model.InvalidRequestException;
|
||||
import software.amazon.awssdk.services.iot.model.ListCertificatesRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ListDomainConfigurationsRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ListJobExecutionsForThingRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ListJobsRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ListPoliciesRequest;
|
||||
@@ -47,6 +56,8 @@ import software.amazon.awssdk.services.iot.model.ListThingPrincipalsRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ListThingTypesRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ListTopicRulesRequest;
|
||||
import software.amazon.awssdk.services.iot.model.RemoveThingFromThingGroupRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ServerCertificateStatus;
|
||||
import software.amazon.awssdk.services.iot.model.ServiceType;
|
||||
import software.amazon.awssdk.services.iot.model.SqsAction;
|
||||
import software.amazon.awssdk.services.iot.model.ResourceAlreadyExistsException;
|
||||
import software.amazon.awssdk.services.iot.model.ResourceNotFoundException;
|
||||
@@ -55,6 +66,7 @@ import software.amazon.awssdk.services.iot.model.TagResourceRequest;
|
||||
import software.amazon.awssdk.services.iot.model.ThingGroupProperties;
|
||||
import software.amazon.awssdk.services.iot.model.ThingTypeProperties;
|
||||
import software.amazon.awssdk.services.iot.model.TopicRulePayload;
|
||||
import software.amazon.awssdk.services.iot.model.UpdateDomainConfigurationRequest;
|
||||
import software.amazon.awssdk.services.iot.model.UntagResourceRequest;
|
||||
import software.amazon.awssdk.services.iot.model.UpdateCertificateRequest;
|
||||
import software.amazon.awssdk.services.iot.model.UpdateThingRequest;
|
||||
@@ -109,6 +121,115 @@ class IotTest {
|
||||
assertThat(response.endpointAddress()).isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainConfigurationLifecycle() {
|
||||
String name = "java-iot-domain";
|
||||
String certificateArn = "arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";
|
||||
boolean leftOver = iot.listDomainConfigurations(ListDomainConfigurationsRequest.builder().build())
|
||||
.domainConfigurations().stream()
|
||||
.anyMatch(summary -> name.equals(summary.domainConfigurationName()));
|
||||
if (leftOver) {
|
||||
iot.updateDomainConfiguration(UpdateDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.domainConfigurationStatus(DomainConfigurationStatus.DISABLED)
|
||||
.build());
|
||||
iot.deleteDomainConfiguration(DeleteDomainConfigurationRequest.builder().domainConfigurationName(name).build());
|
||||
}
|
||||
|
||||
assertThatThrownBy(() -> iot.describeDomainConfiguration(DescribeDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.build()))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
|
||||
var managed = iot.describeDomainConfiguration(DescribeDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName("iot:Data-ATS")
|
||||
.build());
|
||||
assertThat(managed.domainType()).isEqualTo(DomainType.AWS_MANAGED);
|
||||
assertThat(managed.domainConfigurationStatus()).isEqualTo(DomainConfigurationStatus.ENABLED);
|
||||
assertThat(managed.domainName()).isNotBlank();
|
||||
|
||||
var created = iot.createDomainConfiguration(CreateDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.domainName("iot.java.example.com")
|
||||
.serverCertificateArns(certificateArn)
|
||||
.serviceType(ServiceType.DATA)
|
||||
.authorizerConfig(AuthorizerConfig.builder()
|
||||
.defaultAuthorizerName("java-authorizer")
|
||||
.allowAuthorizerOverride(true)
|
||||
.build())
|
||||
.tags(Tag.builder().key("env").value("java").build())
|
||||
.build());
|
||||
assertThat(created.domainConfigurationName()).isEqualTo(name);
|
||||
assertThat(created.domainConfigurationArn())
|
||||
.startsWith("arn:aws:iot:us-east-1:000000000000:domainconfiguration/" + name + "/");
|
||||
|
||||
assertThatThrownBy(() -> iot.createDomainConfiguration(CreateDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.domainName("iot.java.example.com")
|
||||
.serverCertificateArns(certificateArn)
|
||||
.build()))
|
||||
.isInstanceOf(ResourceAlreadyExistsException.class);
|
||||
|
||||
var described = iot.describeDomainConfiguration(DescribeDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.build());
|
||||
assertThat(described.domainConfigurationArn()).isEqualTo(created.domainConfigurationArn());
|
||||
assertThat(described.domainName()).isEqualTo("iot.java.example.com");
|
||||
assertThat(described.domainConfigurationStatus()).isEqualTo(DomainConfigurationStatus.ENABLED);
|
||||
assertThat(described.serviceType()).isEqualTo(ServiceType.DATA);
|
||||
assertThat(described.domainType()).isEqualTo(DomainType.CUSTOMER_MANAGED);
|
||||
assertThat(described.serverCertificates()).hasSize(1);
|
||||
assertThat(described.serverCertificates().get(0).serverCertificateArn()).isEqualTo(certificateArn);
|
||||
assertThat(described.serverCertificates().get(0).serverCertificateStatus()).isEqualTo(ServerCertificateStatus.VALID);
|
||||
assertThat(described.authorizerConfig().defaultAuthorizerName()).isEqualTo("java-authorizer");
|
||||
assertThat(described.authorizerConfig().allowAuthorizerOverride()).isTrue();
|
||||
assertThat(described.lastStatusChangeDate()).isNotNull();
|
||||
assertThat(described.tlsConfig().securityPolicy()).isEqualTo("IoTSecurityPolicy_TLS13_1_2_2022_10");
|
||||
|
||||
var enabled = iot.updateDomainConfiguration(UpdateDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.domainConfigurationStatus(DomainConfigurationStatus.ENABLED)
|
||||
.build());
|
||||
assertThat(enabled.domainConfigurationArn()).isEqualTo(created.domainConfigurationArn());
|
||||
assertThat(iot.describeDomainConfiguration(DescribeDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.build()).domainConfigurationStatus())
|
||||
.isEqualTo(DomainConfigurationStatus.ENABLED);
|
||||
|
||||
var tags = iot.listTagsForResource(ListTagsForResourceRequest.builder()
|
||||
.resourceArn(created.domainConfigurationArn())
|
||||
.build());
|
||||
assertThat(tags.tags()).extracting(Tag::key).contains("env");
|
||||
|
||||
var listed = iot.listDomainConfigurations(ListDomainConfigurationsRequest.builder()
|
||||
.serviceType(ServiceType.DATA)
|
||||
.build());
|
||||
assertThat(listed.domainConfigurations())
|
||||
.extracting(DomainConfigurationSummary::domainConfigurationName)
|
||||
.contains(name);
|
||||
|
||||
assertThatThrownBy(() -> iot.deleteDomainConfiguration(DeleteDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.build()))
|
||||
.isInstanceOf(InvalidRequestException.class);
|
||||
|
||||
var updated = iot.updateDomainConfiguration(UpdateDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.domainConfigurationStatus(DomainConfigurationStatus.DISABLED)
|
||||
.build());
|
||||
assertThat(updated.domainConfigurationArn()).isEqualTo(created.domainConfigurationArn());
|
||||
assertThat(iot.describeDomainConfiguration(DescribeDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.build()).domainConfigurationStatus())
|
||||
.isEqualTo(DomainConfigurationStatus.DISABLED);
|
||||
|
||||
iot.deleteDomainConfiguration(DeleteDomainConfigurationRequest.builder().domainConfigurationName(name).build());
|
||||
assertThatThrownBy(() -> iot.describeDomainConfiguration(DescribeDomainConfigurationRequest.builder()
|
||||
.domainConfigurationName(name)
|
||||
.build()))
|
||||
.isInstanceOf(ResourceNotFoundException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void thingRegistryCrud() {
|
||||
String thingName = "java-iot-thing";
|
||||
|
||||
@@ -86,6 +86,7 @@ cross-resource references.
|
||||
| Pipes | `Pipe` |
|
||||
| Kinesis | `Stream` |
|
||||
| Kinesis Data Firehose | `DeliveryStream` |
|
||||
| IoT Core | `DomainConfiguration` (`ServerCertificates` resolves to a JSON string) |
|
||||
| CloudFront | `Distribution` |
|
||||
| CloudWatch | `Alarm` |
|
||||
| CloudWatch Logs | `LogGroup` |
|
||||
|
||||
+20
-1
@@ -33,7 +33,7 @@ Supported MVP 2 behavior:
|
||||
- Static thing groups: `CreateThingGroup`, `DescribeThingGroup`, `ListThingGroups`, `UpdateThingGroup`, `DeleteThingGroup`, `AddThingToThingGroup`, `RemoveThingFromThingGroup`, `ListThingsInThingGroup`, and `ListThingGroupsForThing`.
|
||||
- Jobs control plane: `CreateJob`, `DescribeJob`, and `ListJobs`, including thing ARN targets and static thing group targets.
|
||||
- Jobs data plane: pending-job listing, `StartNextPendingJobExecution`, `DescribeJobExecution`, and `UpdateJobExecution` with version conflicts and terminal-state checks.
|
||||
- Endpoint discovery accepts `iot:Jobs` in addition to IoT Data endpoint types.
|
||||
- Endpoint discovery accepts `iot:Jobs` and `iot:CredentialProvider` in addition to IoT Data endpoint types.
|
||||
- MQTT clients can use QoS 1 subscribe/publish paths with broker PUBACK and delivery behavior.
|
||||
- IoT Data connection APIs for live MQTT sessions: `GetConnection`, `DeleteConnection`, `ListSubscriptions`, and `SendDirectMessage`.
|
||||
- `DeleteConnection` closes active MQTT client sessions through the embedded broker and optionally purges broker session state for `cleanSession=true`.
|
||||
@@ -48,6 +48,25 @@ Current MVP 2 limitations:
|
||||
- Jobs reserved MQTT topics remain follow-up scope; Jobs Data HTTP APIs are implemented first.
|
||||
- Dynamic thing groups, fleet indexing, job rollouts, cancellations, documents from S3, and advanced job scheduling are not yet modeled.
|
||||
|
||||
## Domain Configurations
|
||||
|
||||
Status: control plane only.
|
||||
|
||||
`CreateDomainConfiguration`, `DescribeDomainConfiguration`, `UpdateDomainConfiguration`, `DeleteDomainConfiguration` and `ListDomainConfigurations` are served on the REST-JSON paths the AWS SDKs use, with the AWS shapes and error codes:
|
||||
|
||||
- A new configuration is `ENABLED` and `CUSTOMER_MANAGED`, its server certificate is reported `VALID`, and its ARN carries the short id AWS appends (`domainconfiguration/<name>/<id>`). A configuration created without a domain name has the `ENDPOINT` domain type.
|
||||
- `UpdateDomainConfiguration` changes the status, the authorizer (or removes it with `removeAuthorizerConfig`), the TLS, server certificate and client certificate settings, the authentication type and the application protocol.
|
||||
- `DeleteDomainConfiguration` refuses an `ENABLED` configuration with `InvalidRequestException`; disable it first, as on AWS.
|
||||
- `ListDomainConfigurations` filters by `serviceType` and pages with `marker` and `pageSize`.
|
||||
- Tags work through `TagResource`, `UntagResource` and `ListTagsForResource` on the configuration ARN.
|
||||
- CloudFormation provisions `AWS::IoT::DomainConfiguration` through the same operations; see the CloudFormation service page for the attribute list.
|
||||
- The four AWS-managed configurations every account has (`iot:Data-ATS`, `iot:Data`, `iot:CredentialProvider`, `iot:Jobs`) exist in every region without being created: `AWS_MANAGED`, `ENABLED`, no server certificate, and the address `DescribeEndpoint` returns as their domain name. They can be updated and tagged but not deleted, as on AWS.
|
||||
|
||||
Current limitations:
|
||||
|
||||
- A custom domain does not change where the broker listens. `DescribeEndpoint` keeps returning Floci's own address, and pointing DNS at the emulator is outside its scope.
|
||||
- Server certificate ARNs are stored as given and reported `VALID`; they are not checked against ACM.
|
||||
|
||||
## MQTT Broker
|
||||
|
||||
Status: complete.
|
||||
|
||||
@@ -13,6 +13,7 @@ import io.github.hectorvent.floci.services.eks.EksController;
|
||||
import io.github.hectorvent.floci.services.fis.FisController;
|
||||
import io.github.hectorvent.floci.services.mwaa.MwaaController;
|
||||
import io.github.hectorvent.floci.services.iot.IotController;
|
||||
import io.github.hectorvent.floci.services.iot.IotDomainConfigurationController;
|
||||
import io.github.hectorvent.floci.services.iot.IotDataController;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcore.BedrockAgentCoreController;
|
||||
import io.github.hectorvent.floci.services.bedrockagentcorecontrol.BedrockAgentCoreControlController;
|
||||
@@ -521,7 +522,7 @@ public class ResolvedServiceCatalog {
|
||||
// DescribeJobExecution, StartNextPendingJobExecution, UpdateJobExecution)
|
||||
// signs under its own name while IotController serves its /things/*/jobs routes
|
||||
Set.of(), Set.of("iot", "execute-api", "iot-jobs-data"), Set.of(),
|
||||
Set.of(IotController.class)),
|
||||
Set.of(IotController.class, IotDomainConfigurationController.class)),
|
||||
descriptor("iotdata", "iotdata", config.services().iotdata().enabled(), true,
|
||||
"iot", config.storage().mode(), 5000L, null, ServiceProtocol.REST_JSON,
|
||||
protocols(ServiceProtocol.REST_JSON),
|
||||
|
||||
+1
-1
@@ -140,7 +140,7 @@ public class CloudFormationResourceProvisioner {
|
||||
private static final String LAMBDA_NAME_MODE_ATTR = "FlociLambdaFunctionNameMode";
|
||||
private static final String LAMBDA_PACKAGE_TYPE_ATTR = "FlociLambdaPackageType";
|
||||
static final String UPDATE_ROLLBACK_RESTORED_ATTR = CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR;
|
||||
static final String UPDATE_ROLLBACK_FAILURE_ATTR = "__FlociUpdateRollbackFailure";
|
||||
static final String UPDATE_ROLLBACK_FAILURE_ATTR = CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR;
|
||||
private static final String INLINE_CLEANUP_POLICY_NAME_ATTR = "__FlociInlineCleanupPolicyName";
|
||||
private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets";
|
||||
private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets";
|
||||
|
||||
+8
@@ -28,6 +28,14 @@ public final class CfnRollback {
|
||||
*/
|
||||
public static final String UPDATE_ROLLBACK_RESTORED_ATTR = "__FlociUpdateRollbackRestored";
|
||||
|
||||
/**
|
||||
* Carries the reason a provisioner's own restoration attempt did not complete after a failed
|
||||
* update. {@code CloudFormationService} copies it onto the committed resource so the rollback
|
||||
* walker reports UPDATE_ROLLBACK_FAILED with that reason instead of claiming the prior entity
|
||||
* is live. Lives here for the same reason as the marker above.
|
||||
*/
|
||||
public static final String UPDATE_ROLLBACK_FAILURE_ATTR = "__FlociUpdateRollbackFailure";
|
||||
|
||||
private CfnRollback() {
|
||||
}
|
||||
|
||||
|
||||
+283
@@ -0,0 +1,283 @@
|
||||
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.IotDomainConfigurationService;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.ServerCertificateSummary;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Provisions {@code AWS::IoT::DomainConfiguration}. The physical id is the configuration name and
|
||||
* {@code Fn::GetAtt} exposes {@code Arn}, {@code DomainType} and {@code ServerCertificates}; the
|
||||
* last is a list of objects on AWS, carried here as a JSON string because attributes are strings.
|
||||
*
|
||||
* <p>Follows the CloudFormation handler: a configuration is created ENABLED and a
|
||||
* {@code DomainConfigurationStatus} of DISABLED is applied with a follow-up update, tags go
|
||||
* through TagResource, and a delete disables first because the API refuses to delete an ENABLED
|
||||
* configuration.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IotDomainConfigurationCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(IotDomainConfigurationCfnProvisioner.class);
|
||||
private static final String NOT_FOUND = "ResourceNotFoundException";
|
||||
private static final int NAME_MAX_LENGTH = 128;
|
||||
/** Template properties that are not part of the create request body. */
|
||||
private static final Set<String> OUTSIDE_THE_REQUEST =
|
||||
Set.of("DomainConfigurationName", "DomainConfigurationStatus", "Tags");
|
||||
/** createOnly in the registry schema: a change to any of these replaces the configuration. */
|
||||
private static final Set<String> CREATE_ONLY =
|
||||
Set.of("domainName", "serviceType", "validationCertificateArn", "serverCertificateArns");
|
||||
|
||||
private final IotDomainConfigurationService domainConfigurationService;
|
||||
|
||||
public IotDomainConfigurationCfnProvisioner(IotDomainConfigurationService domainConfigurationService) {
|
||||
this.domainConfigurationService = domainConfigurationService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of("AWS::IoT::DomainConfiguration");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String explicitName = ctx.resolveOptional(props, "DomainConfigurationName");
|
||||
String name = ctx.stablePhysicalName(explicitName, r.getLogicalId(), NAME_MAX_LENGTH, false);
|
||||
ObjectNode request = requestBody(props, ctx);
|
||||
String status = ctx.resolveOptional(props, "DomainConfigurationStatus");
|
||||
Map<String, String> tags = ctx.resolveTags(props, "Tags");
|
||||
String region = ctx.region();
|
||||
|
||||
// The configuration this resource had before, if any. It is kept when its name and the
|
||||
// createOnly properties are unchanged, and removed once its replacement exists otherwise:
|
||||
// there is no generic replacement flow, so a renamed or replaced configuration must not
|
||||
// outlive the stack that created it.
|
||||
IotDomainConfiguration prior = ctx.isUpdate() ? findExisting(ctx.priorPhysicalId(), region) : null;
|
||||
// The store hands out its live record, and disabling the prior on the way to deleting it
|
||||
// changes that record, so the status a failed replacement has to go back to is kept here.
|
||||
String priorStatus = prior == null ? null : prior.getDomainConfigurationStatus();
|
||||
boolean sameConfiguration = prior != null && name.equals(prior.getDomainConfigurationName());
|
||||
if (sameConfiguration && sameCreateOnlyProperties(prior, request)) {
|
||||
IotDomainConfiguration updated = domainConfigurationService.updateDomainConfiguration(
|
||||
name, updateBody(request, status, prior), region);
|
||||
reconcileTags(updated.getDomainConfigurationArn(), prior.getTags(), tags);
|
||||
record(r, name, updated);
|
||||
return;
|
||||
}
|
||||
if (sameConfiguration && (explicitName == null || explicitName.isBlank())) {
|
||||
// A createOnly property changed under a name CloudFormation generated, so the
|
||||
// replacement gets a fresh generated name, as it does on AWS. Under an explicit
|
||||
// name the create below fails with ResourceAlreadyExistsException, also as on AWS.
|
||||
name = ctx.generatePhysicalName(r.getLogicalId(), NAME_MAX_LENGTH, false);
|
||||
}
|
||||
if (!tags.isEmpty()) {
|
||||
request.set("tags", tagList(tags));
|
||||
}
|
||||
IotDomainConfiguration created = domainConfigurationService.createDomainConfiguration(name, request, region);
|
||||
// Recorded at once and marked as owned by this stack: the create rollback deletes only a
|
||||
// resource that has a physical id and carries that marker, so a failure in the calls
|
||||
// below still leaves nothing behind.
|
||||
record(r, name, created);
|
||||
r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");
|
||||
try {
|
||||
if ("DISABLED".equals(status)) {
|
||||
record(r, name, domainConfigurationService.updateDomainConfiguration(name, statusBody("DISABLED"), region));
|
||||
}
|
||||
// Only a prior under another name is removed. Under the same name the create above
|
||||
// normally fails; if it went through because the prior vanished in between, the
|
||||
// configuration just created is the one to keep.
|
||||
if (prior != null && !name.equals(prior.getDomainConfigurationName())) {
|
||||
delete(r.getResourceType(), prior.getDomainConfigurationName(), region);
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
if (prior != null) {
|
||||
unwindReplacement(r, prior, priorStatus, name, region, failure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
IotDomainConfiguration existing = findExisting(physicalId, region);
|
||||
if (existing == null) {
|
||||
return;
|
||||
}
|
||||
if ("ENABLED".equals(existing.getDomainConfigurationStatus())) {
|
||||
// Already gone is fine here too: the disable only exists to make the delete possible.
|
||||
CfnDeletes.safeDelete("domain configuration", physicalId,
|
||||
() -> domainConfigurationService.updateDomainConfiguration(physicalId, statusBody("DISABLED"), region),
|
||||
NOT_FOUND);
|
||||
}
|
||||
CfnDeletes.safeDelete("domain configuration", physicalId,
|
||||
() -> domainConfigurationService.deleteDomainConfiguration(physicalId, region), NOT_FOUND);
|
||||
}
|
||||
|
||||
private static void record(StackResource r, String name, IotDomainConfiguration configuration) {
|
||||
r.setPhysicalId(name);
|
||||
r.getAttributes().put("Arn", configuration.getDomainConfigurationArn());
|
||||
r.getAttributes().put("DomainType", configuration.getDomainType());
|
||||
r.getAttributes().put("ServerCertificates", serverCertificatesJson(configuration));
|
||||
}
|
||||
|
||||
/**
|
||||
* A replacement failed after its new configuration existed. CloudFormationService restores the
|
||||
* previous StackResource and never learns the new name, so the configuration created here is
|
||||
* removed again, the prior one, disabled on the way to deleting it, is enabled again, and the
|
||||
* resource is pointed back at the prior configuration. The stack must report the original
|
||||
* failure, so a cleanup failure is attached to it and recorded as a rollback failure, which
|
||||
* makes the stack end in UPDATE_ROLLBACK_FAILED rather than claim the prior one is intact.
|
||||
*/
|
||||
private void unwindReplacement(StackResource r, IotDomainConfiguration prior, String priorStatus, String name,
|
||||
String region, RuntimeException failure) {
|
||||
try {
|
||||
delete(r.getResourceType(), name, region);
|
||||
IotDomainConfiguration priorNow = findExisting(prior.getDomainConfigurationName(), region);
|
||||
if (priorNow != null && "ENABLED".equals(priorStatus)
|
||||
&& !"ENABLED".equals(priorNow.getDomainConfigurationStatus())) {
|
||||
domainConfigurationService.updateDomainConfiguration(
|
||||
prior.getDomainConfigurationName(), statusBody("ENABLED"), region);
|
||||
}
|
||||
record(r, prior.getDomainConfigurationName(), prior);
|
||||
r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);
|
||||
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
String reason = "Could not roll back the replacement of domain configuration "
|
||||
+ prior.getDomainConfigurationName() + " by " + name + ": " + cleanupFailure.getMessage();
|
||||
LOG.warn(reason);
|
||||
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR, reason);
|
||||
}
|
||||
}
|
||||
|
||||
private IotDomainConfiguration findExisting(String name, String region) {
|
||||
try {
|
||||
return domainConfigurationService.describeDomainConfiguration(name, region);
|
||||
} catch (AwsException e) {
|
||||
if (!NOT_FOUND.equals(e.getErrorCode())) {
|
||||
throw e;
|
||||
}
|
||||
LOG.debugv("Domain configuration {0} is gone", name);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The template properties as the IoT API spells them: the same names with a lowercase first letter. */
|
||||
private static ObjectNode requestBody(JsonNode props, ProvisionContext ctx) {
|
||||
ObjectNode request = JsonNodeFactory.instance.objectNode();
|
||||
JsonNode resolved = props == null ? null : ctx.engine().resolveNode(props);
|
||||
if (resolved != null && resolved.isObject()) {
|
||||
resolved.fields().forEachRemaining(field -> {
|
||||
if (!OUTSIDE_THE_REQUEST.contains(field.getKey()) && !field.getValue().isNull()) {
|
||||
request.set(decapitalize(field.getKey()), toApiShape(field.getValue()));
|
||||
}
|
||||
});
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
private static boolean sameCreateOnlyProperties(IotDomainConfiguration existing, JsonNode request) {
|
||||
List<String> desiredCertificates = new ArrayList<>();
|
||||
request.path("serverCertificateArns").forEach(arn -> desiredCertificates.add(arn.asText()));
|
||||
List<String> storedCertificates = existing.getServerCertificates().stream()
|
||||
.map(ServerCertificateSummary::serverCertificateArn)
|
||||
.toList();
|
||||
return Objects.equals(existing.getDomainName(), text(request, "domainName"))
|
||||
&& Objects.equals(existing.getServiceType(), request.path("serviceType").asText("DATA"))
|
||||
&& Objects.equals(existing.getValidationCertificateArn(), text(request, "validationCertificateArn"))
|
||||
&& desiredCertificates.equals(storedCertificates);
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-place update: everything the API lets UpdateDomainConfiguration change. A template
|
||||
* without DomainConfigurationStatus leaves the status alone, as the AWS handler does.
|
||||
*/
|
||||
private static ObjectNode updateBody(ObjectNode request, String status, IotDomainConfiguration existing) {
|
||||
ObjectNode body = JsonNodeFactory.instance.objectNode();
|
||||
request.fields().forEachRemaining(field -> {
|
||||
if (!CREATE_ONLY.contains(field.getKey())) {
|
||||
body.set(field.getKey(), field.getValue());
|
||||
}
|
||||
});
|
||||
if (status != null) {
|
||||
body.put("domainConfigurationStatus", status);
|
||||
}
|
||||
if (!request.has("authorizerConfig") && existing.getAuthorizerConfig() != null) {
|
||||
body.put("removeAuthorizerConfig", true);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private static ObjectNode statusBody(String status) {
|
||||
return JsonNodeFactory.instance.objectNode().put("domainConfigurationStatus", status);
|
||||
}
|
||||
|
||||
private static ArrayNode tagList(Map<String, String> tags) {
|
||||
ArrayNode list = JsonNodeFactory.instance.arrayNode();
|
||||
tags.forEach((key, value) -> list.addObject().put("Key", key).put("Value", value));
|
||||
return list;
|
||||
}
|
||||
|
||||
private void reconcileTags(String arn, Map<String, String> current, Map<String, String> desired) {
|
||||
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
|
||||
if (!stale.isEmpty()) {
|
||||
domainConfigurationService.untagResource(arn, stale);
|
||||
}
|
||||
if (!desired.isEmpty()) {
|
||||
domainConfigurationService.tagResource(arn, desired);
|
||||
}
|
||||
}
|
||||
|
||||
private static String serverCertificatesJson(IotDomainConfiguration configuration) {
|
||||
ArrayNode list = JsonNodeFactory.instance.arrayNode();
|
||||
for (ServerCertificateSummary certificate : configuration.getServerCertificates()) {
|
||||
ObjectNode summary = list.addObject();
|
||||
summary.put("ServerCertificateArn", certificate.serverCertificateArn());
|
||||
summary.put("ServerCertificateStatus", certificate.serverCertificateStatus());
|
||||
if (certificate.serverCertificateStatusDetail() != null) {
|
||||
summary.put("ServerCertificateStatusDetail", certificate.serverCertificateStatusDetail());
|
||||
}
|
||||
}
|
||||
return list.toString();
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
return node.hasNonNull(field) ? node.get(field).asText() : null;
|
||||
}
|
||||
}
|
||||
@@ -44,12 +44,15 @@ import java.util.Map;
|
||||
public class IotController {
|
||||
|
||||
private final IotService iotService;
|
||||
private final IotTagHandler iotTagHandler;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public IotController(IotService iotService, RegionResolver regionResolver, ObjectMapper objectMapper) {
|
||||
public IotController(IotService iotService, IotTagHandler iotTagHandler, RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.iotService = iotService;
|
||||
this.iotTagHandler = iotTagHandler;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
@@ -126,10 +129,12 @@ public class IotController {
|
||||
|
||||
@POST
|
||||
@Path("/untag")
|
||||
public Response untagResource(String body) {
|
||||
public Response untagResource(@Context HttpHeaders headers, String body) {
|
||||
try {
|
||||
JsonNode request = objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
|
||||
iotService.untagResource(request.path("resourceArn").asText(null), parseTagKeys(request.path("tagKeys")));
|
||||
// Through the tag handler, like /tags, so every IoT resource kind is reachable here.
|
||||
iotTagHandler.untagResource(regionResolver.resolveRegion(headers),
|
||||
request.path("resourceArn").asText(null), parseTagKeys(request.path("tagKeys")));
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InvalidRequestException", e.getMessage(), 400);
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
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.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.AuthorizerConfig;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.ServerCertificateConfig;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.ServerCertificateSummary;
|
||||
import jakarta.inject.Inject;
|
||||
import jakarta.ws.rs.Consumes;
|
||||
import jakarta.ws.rs.DELETE;
|
||||
import jakarta.ws.rs.GET;
|
||||
import jakarta.ws.rs.POST;
|
||||
import jakarta.ws.rs.PUT;
|
||||
import jakarta.ws.rs.Path;
|
||||
import jakarta.ws.rs.PathParam;
|
||||
import jakarta.ws.rs.Produces;
|
||||
import jakarta.ws.rs.QueryParam;
|
||||
import jakarta.ws.rs.core.Context;
|
||||
import jakarta.ws.rs.core.HttpHeaders;
|
||||
import jakarta.ws.rs.core.MediaType;
|
||||
import jakarta.ws.rs.core.Response;
|
||||
|
||||
/**
|
||||
* REST-JSON routes for AWS IoT domain configurations: CreateDomainConfiguration,
|
||||
* DescribeDomainConfiguration, UpdateDomainConfiguration, DeleteDomainConfiguration and
|
||||
* ListDomainConfigurations, on the paths and shapes the AWS SDKs use.
|
||||
*/
|
||||
@Path("/domainConfigurations")
|
||||
@Produces(MediaType.APPLICATION_JSON)
|
||||
@Consumes(MediaType.APPLICATION_JSON)
|
||||
public class IotDomainConfigurationController {
|
||||
|
||||
private final IotDomainConfigurationService domainConfigurationService;
|
||||
private final RegionResolver regionResolver;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public IotDomainConfigurationController(IotDomainConfigurationService domainConfigurationService,
|
||||
RegionResolver regionResolver,
|
||||
ObjectMapper objectMapper) {
|
||||
this.domainConfigurationService = domainConfigurationService;
|
||||
this.regionResolver = regionResolver;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@POST
|
||||
@Path("/{domainConfigurationName}")
|
||||
public Response createDomainConfiguration(@Context HttpHeaders headers,
|
||||
@PathParam("domainConfigurationName") String domainConfigurationName,
|
||||
String body) {
|
||||
IotDomainConfiguration created = domainConfigurationService.createDomainConfiguration(
|
||||
domainConfigurationName, readJson(body), regionResolver.resolveRegion(headers));
|
||||
return Response.ok(nameAndArn(created)).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
@Path("/{domainConfigurationName}")
|
||||
public Response describeDomainConfiguration(@Context HttpHeaders headers,
|
||||
@PathParam("domainConfigurationName") String domainConfigurationName) {
|
||||
IotDomainConfiguration configuration = domainConfigurationService.describeDomainConfiguration(
|
||||
domainConfigurationName, regionResolver.resolveRegion(headers));
|
||||
return Response.ok(describeResponse(configuration)).build();
|
||||
}
|
||||
|
||||
@PUT
|
||||
@Path("/{domainConfigurationName}")
|
||||
public Response updateDomainConfiguration(@Context HttpHeaders headers,
|
||||
@PathParam("domainConfigurationName") String domainConfigurationName,
|
||||
String body) {
|
||||
IotDomainConfiguration updated = domainConfigurationService.updateDomainConfiguration(
|
||||
domainConfigurationName, readJson(body), regionResolver.resolveRegion(headers));
|
||||
return Response.ok(nameAndArn(updated)).build();
|
||||
}
|
||||
|
||||
@DELETE
|
||||
@Path("/{domainConfigurationName}")
|
||||
@Consumes(MediaType.WILDCARD)
|
||||
public Response deleteDomainConfiguration(@Context HttpHeaders headers,
|
||||
@PathParam("domainConfigurationName") String domainConfigurationName) {
|
||||
domainConfigurationService.deleteDomainConfiguration(domainConfigurationName, regionResolver.resolveRegion(headers));
|
||||
return Response.ok(objectMapper.createObjectNode()).build();
|
||||
}
|
||||
|
||||
@GET
|
||||
public Response listDomainConfigurations(@Context HttpHeaders headers,
|
||||
@QueryParam("marker") String marker,
|
||||
@QueryParam("pageSize") Integer pageSize,
|
||||
@QueryParam("serviceType") String serviceType) {
|
||||
IotService.Page<IotDomainConfiguration> page = domainConfigurationService.listDomainConfigurations(
|
||||
regionResolver.resolveRegion(headers), serviceType, marker, pageSize);
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
ArrayNode summaries = response.putArray("domainConfigurations");
|
||||
for (IotDomainConfiguration configuration : page.items()) {
|
||||
ObjectNode summary = summaries.addObject();
|
||||
summary.put("domainConfigurationName", configuration.getDomainConfigurationName());
|
||||
summary.put("domainConfigurationArn", configuration.getDomainConfigurationArn());
|
||||
summary.put("serviceType", configuration.getServiceType());
|
||||
}
|
||||
if (page.nextToken() != null) {
|
||||
response.put("nextMarker", page.nextToken());
|
||||
}
|
||||
return Response.ok(response).build();
|
||||
}
|
||||
|
||||
private ObjectNode nameAndArn(IotDomainConfiguration configuration) {
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.put("domainConfigurationName", configuration.getDomainConfigurationName());
|
||||
response.put("domainConfigurationArn", configuration.getDomainConfigurationArn());
|
||||
return response;
|
||||
}
|
||||
|
||||
private ObjectNode describeResponse(IotDomainConfiguration configuration) {
|
||||
ObjectNode response = nameAndArn(configuration);
|
||||
putIfPresent(response, "domainName", configuration.getDomainName());
|
||||
ArrayNode certificates = response.putArray("serverCertificates");
|
||||
for (ServerCertificateSummary certificate : configuration.getServerCertificates()) {
|
||||
ObjectNode summary = certificates.addObject();
|
||||
summary.put("serverCertificateArn", certificate.serverCertificateArn());
|
||||
summary.put("serverCertificateStatus", certificate.serverCertificateStatus());
|
||||
putIfPresent(summary, "serverCertificateStatusDetail", certificate.serverCertificateStatusDetail());
|
||||
}
|
||||
AuthorizerConfig authorizerConfig = configuration.getAuthorizerConfig();
|
||||
if (authorizerConfig != null) {
|
||||
ObjectNode authorizer = response.putObject("authorizerConfig");
|
||||
putIfPresent(authorizer, "defaultAuthorizerName", authorizerConfig.defaultAuthorizerName());
|
||||
if (authorizerConfig.allowAuthorizerOverride() != null) {
|
||||
authorizer.put("allowAuthorizerOverride", authorizerConfig.allowAuthorizerOverride());
|
||||
}
|
||||
}
|
||||
// Always present: SDK enums read an omitted status as an empty value, not as ENABLED.
|
||||
response.put("domainConfigurationStatus", configuration.getDomainConfigurationStatus());
|
||||
response.put("serviceType", configuration.getServiceType());
|
||||
response.put("domainType", configuration.getDomainType());
|
||||
if (configuration.getLastStatusChangeDate() != null) {
|
||||
response.put("lastStatusChangeDate", configuration.getLastStatusChangeDate().toEpochMilli() / 1000.0);
|
||||
}
|
||||
if (configuration.getTlsConfig() != null) {
|
||||
putIfPresent(response.putObject("tlsConfig"), "securityPolicy", configuration.getTlsConfig().securityPolicy());
|
||||
}
|
||||
ServerCertificateConfig certificateConfig = configuration.getServerCertificateConfig();
|
||||
if (certificateConfig != null) {
|
||||
ObjectNode node = response.putObject("serverCertificateConfig");
|
||||
if (certificateConfig.enableOCSPCheck() != null) {
|
||||
node.put("enableOCSPCheck", certificateConfig.enableOCSPCheck());
|
||||
}
|
||||
putIfPresent(node, "ocspLambdaArn", certificateConfig.ocspLambdaArn());
|
||||
putIfPresent(node, "ocspAuthorizedResponderArn", certificateConfig.ocspAuthorizedResponderArn());
|
||||
}
|
||||
putIfPresent(response, "authenticationType", configuration.getAuthenticationType());
|
||||
putIfPresent(response, "applicationProtocol", configuration.getApplicationProtocol());
|
||||
if (configuration.getClientCertificateConfig() != null) {
|
||||
putIfPresent(response.putObject("clientCertificateConfig"), "clientCertificateCallbackArn",
|
||||
configuration.getClientCertificateConfig().clientCertificateCallbackArn());
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
private static void putIfPresent(ObjectNode node, String field, String value) {
|
||||
if (value != null) {
|
||||
node.put(field, value);
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode readJson(String body) {
|
||||
try {
|
||||
return objectMapper.readTree(body == null || body.isBlank() ? "{}" : body);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new AwsException("InvalidRequestException", e.getMessage(), 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.AuthorizerConfig;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.ClientCertificateConfig;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.ServerCertificateConfig;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.ServerCertificateSummary;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.TlsConfig;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeMap;
|
||||
import java.util.UUID;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* AWS IoT Core domain configurations: the control-plane records behind a custom domain. A new
|
||||
* configuration is ENABLED and CUSTOMER_MANAGED, exactly as AWS creates it; nothing here changes
|
||||
* where the emulator's broker listens. The four configurations AWS gives every account for its
|
||||
* default endpoints exist here as well, seeded on first use in a region.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IotDomainConfigurationService {
|
||||
|
||||
static final String DEFAULT_SECURITY_POLICY = "IoTSecurityPolicy_TLS13_1_2_2022_10";
|
||||
|
||||
private static final Pattern NAME_PATTERN = Pattern.compile("[\\w.-]{1,128}");
|
||||
private static final Set<String> SERVICE_TYPES = Set.of("DATA", "CREDENTIAL_PROVIDER", "JOBS");
|
||||
private static final Set<String> STATUSES = Set.of("ENABLED", "DISABLED");
|
||||
private static final Set<String> AUTHENTICATION_TYPES =
|
||||
Set.of("CUSTOM_AUTH_X509", "CUSTOM_AUTH", "AWS_X509", "AWS_SIGV4", "DEFAULT");
|
||||
private static final Set<String> APPLICATION_PROTOCOLS = Set.of("SECURE_MQTT", "MQTT_WSS", "HTTPS", "DEFAULT");
|
||||
/** The AWS-managed configurations every account has, with their service types. */
|
||||
private static final Map<String, String> AWS_MANAGED = Map.of(
|
||||
"iot:Data-ATS", "DATA",
|
||||
"iot:Data", "DATA",
|
||||
"iot:CredentialProvider", "CREDENTIAL_PROVIDER",
|
||||
"iot:Jobs", "JOBS");
|
||||
|
||||
private final StorageBackend<String, IotDomainConfiguration> store;
|
||||
private final RegionResolver regionResolver;
|
||||
private final EmulatorConfig config;
|
||||
/**
|
||||
* Guards every read-modify-write on the store: the duplicate check and store of a create, the
|
||||
* seeding of the AWS-managed configurations, and the update, delete and tag paths, which all
|
||||
* read a record, change it and write it back. Without it two overlapping writers lose updates.
|
||||
*/
|
||||
private final Object lock = new Object();
|
||||
|
||||
@Inject
|
||||
public IotDomainConfigurationService(StorageFactory storageFactory, RegionResolver regionResolver,
|
||||
EmulatorConfig config) {
|
||||
this(storageFactory.create("iot", "iot-domain-configurations.json",
|
||||
new TypeReference<Map<String, IotDomainConfiguration>>() {}), regionResolver, config);
|
||||
}
|
||||
|
||||
IotDomainConfigurationService(StorageBackend<String, IotDomainConfiguration> store, RegionResolver regionResolver,
|
||||
EmulatorConfig config) {
|
||||
this.store = store;
|
||||
this.regionResolver = regionResolver;
|
||||
this.config = config;
|
||||
}
|
||||
|
||||
public IotDomainConfiguration createDomainConfiguration(String name, JsonNode request, String region) {
|
||||
if (name == null || !NAME_PATTERN.matcher(name).matches()) {
|
||||
throw invalid("Invalid domain configuration name: " + name);
|
||||
}
|
||||
String key = key(region, name);
|
||||
JsonNode body = request == null ? JsonNodeFactory.instance.objectNode() : request;
|
||||
String domainName = text(body, "domainName");
|
||||
List<String> certificateArns = textList(body, "serverCertificateArns");
|
||||
if (certificateArns.size() > 1) {
|
||||
throw invalid("serverCertificateArns can hold at most one certificate");
|
||||
}
|
||||
if (domainName != null && certificateArns.isEmpty()) {
|
||||
throw invalid("A server certificate is required for a customer-managed domain");
|
||||
}
|
||||
|
||||
IotDomainConfiguration configuration = new IotDomainConfiguration();
|
||||
configuration.setDomainConfigurationName(name);
|
||||
configuration.setDomainConfigurationArn(arn(name, region));
|
||||
configuration.setDomainName(domainName);
|
||||
configuration.setServiceType(enumValue(body, "serviceType", SERVICE_TYPES, "DATA"));
|
||||
configuration.setDomainConfigurationStatus("ENABLED");
|
||||
// A configuration without a domain name describes the account's default endpoint on AWS.
|
||||
configuration.setDomainType(domainName == null ? "ENDPOINT" : "CUSTOMER_MANAGED");
|
||||
configuration.setServerCertificates(certificateArns.stream()
|
||||
.map(arn -> new ServerCertificateSummary(arn, "VALID", null))
|
||||
.toList());
|
||||
configuration.setValidationCertificateArn(text(body, "validationCertificateArn"));
|
||||
configuration.setAuthorizerConfig(parseAuthorizerConfig(body.path("authorizerConfig")));
|
||||
configuration.setTlsConfig(parseTlsConfig(body.path("tlsConfig")));
|
||||
configuration.setServerCertificateConfig(parseServerCertificateConfig(body.path("serverCertificateConfig")));
|
||||
configuration.setAuthenticationType(enumValue(body, "authenticationType", AUTHENTICATION_TYPES, null));
|
||||
configuration.setApplicationProtocol(enumValue(body, "applicationProtocol", APPLICATION_PROTOCOLS, null));
|
||||
configuration.setClientCertificateConfig(parseClientCertificateConfig(body.path("clientCertificateConfig")));
|
||||
configuration.setTags(parseTags(body.path("tags")));
|
||||
configuration.setLastStatusChangeDate(Instant.now());
|
||||
synchronized (lock) {
|
||||
if (store.get(key).isPresent()) {
|
||||
throw new AwsException("ResourceAlreadyExistsException",
|
||||
"Domain configuration already exists: " + name, 409);
|
||||
}
|
||||
store.put(key, configuration);
|
||||
}
|
||||
return configuration;
|
||||
}
|
||||
|
||||
public IotDomainConfiguration describeDomainConfiguration(String name, String region) {
|
||||
seedAwsManaged(region);
|
||||
return store.get(key(region, name)).orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Domain configuration not found: " + name, 404));
|
||||
}
|
||||
|
||||
public IotDomainConfiguration updateDomainConfiguration(String name, JsonNode request, String region) {
|
||||
JsonNode body = request == null ? JsonNodeFactory.instance.objectNode() : request;
|
||||
// Parse and validate everything before touching the stored record, so a bad value changes nothing.
|
||||
String status = enumValue(body, "domainConfigurationStatus", STATUSES, null);
|
||||
String authenticationType = enumValue(body, "authenticationType", AUTHENTICATION_TYPES, null);
|
||||
String applicationProtocol = enumValue(body, "applicationProtocol", APPLICATION_PROTOCOLS, null);
|
||||
AuthorizerConfig authorizerConfig = parseAuthorizerConfig(body.path("authorizerConfig"));
|
||||
boolean removeAuthorizerConfig = body.path("removeAuthorizerConfig").asBoolean(false);
|
||||
TlsConfig tlsConfig = present(body.path("tlsConfig")) ? parseTlsConfig(body.path("tlsConfig")) : null;
|
||||
ServerCertificateConfig serverCertificateConfig = present(body.path("serverCertificateConfig"))
|
||||
? parseServerCertificateConfig(body.path("serverCertificateConfig")) : null;
|
||||
ClientCertificateConfig clientCertificateConfig = parseClientCertificateConfig(body.path("clientCertificateConfig"));
|
||||
|
||||
synchronized (lock) {
|
||||
IotDomainConfiguration configuration = describeDomainConfiguration(name, region);
|
||||
if (authorizerConfig != null) {
|
||||
configuration.setAuthorizerConfig(authorizerConfig);
|
||||
}
|
||||
if (removeAuthorizerConfig) {
|
||||
configuration.setAuthorizerConfig(null);
|
||||
}
|
||||
if (status != null && !status.equals(configuration.getDomainConfigurationStatus())) {
|
||||
configuration.setDomainConfigurationStatus(status);
|
||||
configuration.setLastStatusChangeDate(Instant.now());
|
||||
}
|
||||
if (tlsConfig != null) {
|
||||
configuration.setTlsConfig(tlsConfig);
|
||||
}
|
||||
if (serverCertificateConfig != null) {
|
||||
configuration.setServerCertificateConfig(serverCertificateConfig);
|
||||
}
|
||||
if (authenticationType != null) {
|
||||
configuration.setAuthenticationType(authenticationType);
|
||||
}
|
||||
if (applicationProtocol != null) {
|
||||
configuration.setApplicationProtocol(applicationProtocol);
|
||||
}
|
||||
if (clientCertificateConfig != null) {
|
||||
configuration.setClientCertificateConfig(clientCertificateConfig);
|
||||
}
|
||||
store.put(key(region, name), configuration);
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
|
||||
/** AWS refuses to delete an ENABLED configuration, and never deletes an AWS-managed one. */
|
||||
public void deleteDomainConfiguration(String name, String region) {
|
||||
synchronized (lock) {
|
||||
IotDomainConfiguration configuration = describeDomainConfiguration(name, region);
|
||||
if ("AWS_MANAGED".equals(configuration.getDomainType())) {
|
||||
throw invalid("Domain configuration " + name + " is managed by AWS and cannot be deleted");
|
||||
}
|
||||
if ("ENABLED".equals(configuration.getDomainConfigurationStatus())) {
|
||||
throw invalid("Domain configuration " + name + " must be DISABLED before it can be deleted");
|
||||
}
|
||||
store.delete(key(region, name));
|
||||
}
|
||||
}
|
||||
|
||||
public IotService.Page<IotDomainConfiguration> listDomainConfigurations(String region, String serviceType,
|
||||
String marker, Integer pageSize) {
|
||||
if (serviceType != null && !SERVICE_TYPES.contains(serviceType)) {
|
||||
throw invalid("Unsupported serviceType: " + serviceType);
|
||||
}
|
||||
if (pageSize != null && (pageSize < 1 || pageSize > 250)) {
|
||||
throw invalid("pageSize must be between 1 and 250");
|
||||
}
|
||||
seedAwsManaged(region);
|
||||
String prefix = key(region, "");
|
||||
List<IotDomainConfiguration> items = store.scan(storeKey -> storeKey.startsWith(prefix)).stream()
|
||||
.filter(configuration -> serviceType == null || serviceType.equals(configuration.getServiceType()))
|
||||
.sorted(Comparator.comparing(IotDomainConfiguration::getDomainConfigurationName))
|
||||
.toList();
|
||||
int start = parseMarker(marker, items.size());
|
||||
int end = pageSize == null ? items.size() : Math.min(items.size(), start + pageSize);
|
||||
return new IotService.Page<>(items.subList(start, end), end < items.size() ? Integer.toString(end) : null);
|
||||
}
|
||||
|
||||
public Map<String, String> listTagsForResource(String resourceArn) {
|
||||
return new TreeMap<>(storedByArn(resourceArn).configuration().getTags());
|
||||
}
|
||||
|
||||
public void tagResource(String resourceArn, Map<String, String> tags) {
|
||||
synchronized (lock) {
|
||||
Stored stored = storedByArn(resourceArn);
|
||||
Map<String, String> updated = new TreeMap<>(stored.configuration().getTags());
|
||||
updated.putAll(tags);
|
||||
stored.configuration().setTags(updated);
|
||||
store.put(stored.key(), stored.configuration());
|
||||
}
|
||||
}
|
||||
|
||||
public void untagResource(String resourceArn, List<String> tagKeys) {
|
||||
synchronized (lock) {
|
||||
Stored stored = storedByArn(resourceArn);
|
||||
Map<String, String> updated = new TreeMap<>(stored.configuration().getTags());
|
||||
tagKeys.forEach(updated::remove);
|
||||
stored.configuration().setTags(updated);
|
||||
store.put(stored.key(), stored.configuration());
|
||||
}
|
||||
}
|
||||
|
||||
/** The configuration an ARN names; the random suffix has to match too, as it does on AWS. */
|
||||
private Stored storedByArn(String resourceArn) {
|
||||
AwsArnUtils.Arn arn = parseDomainConfigurationArn(resourceArn);
|
||||
String rest = arn.resource().substring("domainconfiguration/".length());
|
||||
int slash = rest.indexOf('/');
|
||||
String storeKey = key(arn.region(), slash < 0 ? rest : rest.substring(0, slash));
|
||||
return store.get(storeKey)
|
||||
.filter(configuration -> resourceArn.equals(configuration.getDomainConfigurationArn()))
|
||||
.map(configuration -> new Stored(storeKey, configuration))
|
||||
.orElseThrow(() -> new AwsException("ResourceNotFoundException",
|
||||
"Resource not found: " + resourceArn, 404));
|
||||
}
|
||||
|
||||
private static AwsArnUtils.Arn parseDomainConfigurationArn(String resourceArn) {
|
||||
AwsArnUtils.Arn arn;
|
||||
try {
|
||||
arn = AwsArnUtils.parse(resourceArn);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw invalid("Invalid resource ARN: " + resourceArn);
|
||||
}
|
||||
if (!"iot".equals(arn.service()) || arn.region().isBlank()
|
||||
|| !arn.resource().startsWith("domainconfiguration/")) {
|
||||
throw invalid("Invalid resource ARN: " + resourceArn);
|
||||
}
|
||||
return arn;
|
||||
}
|
||||
|
||||
private static int parseMarker(String marker, int size) {
|
||||
if (marker == null || marker.isBlank()) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
return Math.min(size, Math.max(0, Integer.parseInt(marker)));
|
||||
} catch (NumberFormatException e) {
|
||||
throw invalid("Invalid marker: " + marker);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The default-endpoint configurations AWS creates for every account: AWS_MANAGED, ENABLED, no
|
||||
* server certificate, and the address DescribeEndpoint returns as their domain name. They can
|
||||
* be updated and tagged like any other, but not deleted.
|
||||
*/
|
||||
private void seedAwsManaged(String region) {
|
||||
synchronized (lock) {
|
||||
AWS_MANAGED.forEach((name, serviceType) -> {
|
||||
String key = key(region, name);
|
||||
if (store.get(key).isEmpty()) {
|
||||
store.put(key, awsManaged(name, serviceType, region));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private IotDomainConfiguration awsManaged(String name, String serviceType, String region) {
|
||||
IotDomainConfiguration configuration = new IotDomainConfiguration();
|
||||
configuration.setDomainConfigurationName(name);
|
||||
configuration.setDomainConfigurationArn(arn(name, region));
|
||||
configuration.setDomainName(URI.create(config.effectiveBaseUrl()).getAuthority());
|
||||
configuration.setServiceType(serviceType);
|
||||
configuration.setDomainConfigurationStatus("ENABLED");
|
||||
configuration.setDomainType("AWS_MANAGED");
|
||||
configuration.setTlsConfig(new TlsConfig(DEFAULT_SECURITY_POLICY));
|
||||
configuration.setServerCertificateConfig(new ServerCertificateConfig(false, null, null));
|
||||
configuration.setLastStatusChangeDate(Instant.now());
|
||||
return configuration;
|
||||
}
|
||||
|
||||
/** AWS appends a short random id to every domain configuration ARN. */
|
||||
private String arn(String name, String region) {
|
||||
return regionResolver.buildArn("iot", region,
|
||||
"domainconfiguration/" + name + "/" + UUID.randomUUID().toString().replace("-", "").substring(0, 5));
|
||||
}
|
||||
|
||||
private static AuthorizerConfig parseAuthorizerConfig(JsonNode node) {
|
||||
if (!present(node)) {
|
||||
return null;
|
||||
}
|
||||
requireObject(node, "authorizerConfig");
|
||||
return new AuthorizerConfig(text(node, "defaultAuthorizerName"), bool(node, "allowAuthorizerOverride"));
|
||||
}
|
||||
|
||||
private static TlsConfig parseTlsConfig(JsonNode node) {
|
||||
String securityPolicy = null;
|
||||
if (present(node)) {
|
||||
requireObject(node, "tlsConfig");
|
||||
securityPolicy = text(node, "securityPolicy");
|
||||
}
|
||||
return new TlsConfig(securityPolicy == null ? DEFAULT_SECURITY_POLICY : securityPolicy);
|
||||
}
|
||||
|
||||
private static ServerCertificateConfig parseServerCertificateConfig(JsonNode node) {
|
||||
if (!present(node)) {
|
||||
return new ServerCertificateConfig(false, null, null);
|
||||
}
|
||||
requireObject(node, "serverCertificateConfig");
|
||||
Boolean enableOcspCheck = bool(node, "enableOCSPCheck");
|
||||
return new ServerCertificateConfig(enableOcspCheck != null && enableOcspCheck,
|
||||
text(node, "ocspLambdaArn"), text(node, "ocspAuthorizedResponderArn"));
|
||||
}
|
||||
|
||||
private static ClientCertificateConfig parseClientCertificateConfig(JsonNode node) {
|
||||
if (!present(node)) {
|
||||
return null;
|
||||
}
|
||||
requireObject(node, "clientCertificateConfig");
|
||||
return new ClientCertificateConfig(text(node, "clientCertificateCallbackArn"));
|
||||
}
|
||||
|
||||
private static Map<String, String> parseTags(JsonNode node) {
|
||||
Map<String, String> tags = new TreeMap<>();
|
||||
if (!present(node)) {
|
||||
return tags;
|
||||
}
|
||||
if (!node.isArray()) {
|
||||
throw invalid("tags must be a list");
|
||||
}
|
||||
for (JsonNode tag : node) {
|
||||
if (!tag.isObject()) {
|
||||
throw invalid("tags must be a list of Key and Value pairs");
|
||||
}
|
||||
String tagKey = text(tag, "Key");
|
||||
if (tagKey == null || tagKey.isBlank()) {
|
||||
throw invalid("Tag keys must not be blank");
|
||||
}
|
||||
String value = text(tag, "Value");
|
||||
tags.put(tagKey, value == null ? "" : value);
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
private static String enumValue(JsonNode node, String field, Set<String> allowed, String fallback) {
|
||||
String value = text(node, field);
|
||||
if (value == null) {
|
||||
return fallback;
|
||||
}
|
||||
if (!allowed.contains(value)) {
|
||||
throw invalid("Unsupported " + field + ": " + value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static boolean present(JsonNode node) {
|
||||
return node != null && !node.isMissingNode() && !node.isNull();
|
||||
}
|
||||
|
||||
private static void requireObject(JsonNode node, String field) {
|
||||
if (!node.isObject()) {
|
||||
throw invalid(field + " must be an object");
|
||||
}
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
if (node == null || !node.hasNonNull(field)) {
|
||||
return null;
|
||||
}
|
||||
JsonNode value = node.get(field);
|
||||
if (value.isContainerNode()) {
|
||||
throw invalid(field + " must be a string");
|
||||
}
|
||||
return value.asText();
|
||||
}
|
||||
|
||||
/** A boolean, or the strings "true" and "false" a CloudFormation template may carry instead. */
|
||||
private static Boolean bool(JsonNode node, String field) {
|
||||
if (node == null || !node.hasNonNull(field)) {
|
||||
return null;
|
||||
}
|
||||
JsonNode value = node.get(field);
|
||||
if (value.isBoolean()) {
|
||||
return value.booleanValue();
|
||||
}
|
||||
if (value.isTextual() && ("true".equalsIgnoreCase(value.asText()) || "false".equalsIgnoreCase(value.asText()))) {
|
||||
return Boolean.parseBoolean(value.asText());
|
||||
}
|
||||
throw invalid(field + " must be a boolean");
|
||||
}
|
||||
|
||||
private static List<String> textList(JsonNode node, String field) {
|
||||
List<String> values = new ArrayList<>();
|
||||
JsonNode list = node.path(field);
|
||||
if (!present(list)) {
|
||||
return values;
|
||||
}
|
||||
if (!list.isArray()) {
|
||||
throw invalid(field + " must be a list");
|
||||
}
|
||||
for (JsonNode item : list) {
|
||||
if (item.isContainerNode()) {
|
||||
throw invalid(field + " must be a list of strings");
|
||||
}
|
||||
if (!item.isNull() && !item.asText().isBlank()) {
|
||||
values.add(item.asText());
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
private static AwsException invalid(String message) {
|
||||
return new AwsException("InvalidRequestException", message, 400);
|
||||
}
|
||||
|
||||
private static String key(String region, String name) {
|
||||
return "domain-configuration:" + region + ":" + name;
|
||||
}
|
||||
|
||||
private record Stored(String key, IotDomainConfiguration configuration) {
|
||||
}
|
||||
}
|
||||
@@ -159,7 +159,7 @@ public class IotService {
|
||||
|
||||
public String describeEndpoint(String endpointType) {
|
||||
String effectiveType = endpointType == null || endpointType.isBlank() ? DEFAULT_ENDPOINT_TYPE : endpointType;
|
||||
if (!Set.of(DEFAULT_ENDPOINT_TYPE, "iot:Data", "iot:Jobs").contains(effectiveType)) {
|
||||
if (!Set.of(DEFAULT_ENDPOINT_TYPE, "iot:Data", "iot:Jobs", "iot:CredentialProvider").contains(effectiveType)) {
|
||||
throw new AwsException("InvalidRequestException", "Unsupported endpoint type: " + effectiveType, 400);
|
||||
}
|
||||
startMqttIfEnabled();
|
||||
|
||||
@@ -11,10 +11,12 @@ import java.util.Map;
|
||||
public class IotTagHandler implements TagHandler {
|
||||
|
||||
private final IotService iotService;
|
||||
private final IotDomainConfigurationService domainConfigurationService;
|
||||
|
||||
@Inject
|
||||
public IotTagHandler(IotService iotService) {
|
||||
public IotTagHandler(IotService iotService, IotDomainConfigurationService domainConfigurationService) {
|
||||
this.iotService = iotService;
|
||||
this.domainConfigurationService = domainConfigurationService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -29,16 +31,31 @@ public class IotTagHandler implements TagHandler {
|
||||
|
||||
@Override
|
||||
public Map<String, String> listTags(String region, String arn) {
|
||||
return iotService.listTagsForResource(arn);
|
||||
return isDomainConfiguration(arn)
|
||||
? domainConfigurationService.listTagsForResource(arn)
|
||||
: iotService.listTagsForResource(arn);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void tagResource(String region, String arn, Map<String, String> tags) {
|
||||
iotService.tagResource(arn, tags);
|
||||
if (isDomainConfiguration(arn)) {
|
||||
domainConfigurationService.tagResource(arn, tags);
|
||||
} else {
|
||||
iotService.tagResource(arn, tags);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void untagResource(String region, String arn, List<String> tagKeys) {
|
||||
iotService.untagResource(arn, tagKeys);
|
||||
if (isDomainConfiguration(arn)) {
|
||||
domainConfigurationService.untagResource(arn, tagKeys);
|
||||
} else {
|
||||
iotService.untagResource(arn, tagKeys);
|
||||
}
|
||||
}
|
||||
|
||||
/** Domain configurations have their own service; every other IoT resource is tagged through IotService. */
|
||||
private static boolean isDomainConfiguration(String arn) {
|
||||
return arn != null && arn.contains(":domainconfiguration/");
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package io.github.hectorvent.floci.services.iot.model;
|
||||
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/** A domain configuration as AWS IoT Core reports it through DescribeDomainConfiguration. */
|
||||
@RegisterForReflection
|
||||
public class IotDomainConfiguration {
|
||||
private String domainConfigurationName;
|
||||
private String domainConfigurationArn;
|
||||
private String domainName;
|
||||
private String serviceType;
|
||||
private String domainConfigurationStatus;
|
||||
private String domainType;
|
||||
private List<ServerCertificateSummary> serverCertificates = new ArrayList<>();
|
||||
private String validationCertificateArn;
|
||||
private AuthorizerConfig authorizerConfig;
|
||||
private TlsConfig tlsConfig;
|
||||
private ServerCertificateConfig serverCertificateConfig;
|
||||
private String authenticationType;
|
||||
private String applicationProtocol;
|
||||
private ClientCertificateConfig clientCertificateConfig;
|
||||
private Instant lastStatusChangeDate;
|
||||
private Map<String, String> tags = new TreeMap<>();
|
||||
|
||||
public String getDomainConfigurationName() { return domainConfigurationName; }
|
||||
public void setDomainConfigurationName(String domainConfigurationName) { this.domainConfigurationName = domainConfigurationName; }
|
||||
public String getDomainConfigurationArn() { return domainConfigurationArn; }
|
||||
public void setDomainConfigurationArn(String domainConfigurationArn) { this.domainConfigurationArn = domainConfigurationArn; }
|
||||
public String getDomainName() { return domainName; }
|
||||
public void setDomainName(String domainName) { this.domainName = domainName; }
|
||||
public String getServiceType() { return serviceType; }
|
||||
public void setServiceType(String serviceType) { this.serviceType = serviceType; }
|
||||
public String getDomainConfigurationStatus() { return domainConfigurationStatus; }
|
||||
public void setDomainConfigurationStatus(String domainConfigurationStatus) { this.domainConfigurationStatus = domainConfigurationStatus; }
|
||||
public String getDomainType() { return domainType; }
|
||||
public void setDomainType(String domainType) { this.domainType = domainType; }
|
||||
public List<ServerCertificateSummary> getServerCertificates() { return serverCertificates == null ? List.of() : serverCertificates; }
|
||||
public void setServerCertificates(List<ServerCertificateSummary> serverCertificates) {
|
||||
this.serverCertificates = serverCertificates == null ? new ArrayList<>() : new ArrayList<>(serverCertificates);
|
||||
}
|
||||
public String getValidationCertificateArn() { return validationCertificateArn; }
|
||||
public void setValidationCertificateArn(String validationCertificateArn) { this.validationCertificateArn = validationCertificateArn; }
|
||||
public AuthorizerConfig getAuthorizerConfig() { return authorizerConfig; }
|
||||
public void setAuthorizerConfig(AuthorizerConfig authorizerConfig) { this.authorizerConfig = authorizerConfig; }
|
||||
public TlsConfig getTlsConfig() { return tlsConfig; }
|
||||
public void setTlsConfig(TlsConfig tlsConfig) { this.tlsConfig = tlsConfig; }
|
||||
public ServerCertificateConfig getServerCertificateConfig() { return serverCertificateConfig; }
|
||||
public void setServerCertificateConfig(ServerCertificateConfig serverCertificateConfig) { this.serverCertificateConfig = serverCertificateConfig; }
|
||||
public String getAuthenticationType() { return authenticationType; }
|
||||
public void setAuthenticationType(String authenticationType) { this.authenticationType = authenticationType; }
|
||||
public String getApplicationProtocol() { return applicationProtocol; }
|
||||
public void setApplicationProtocol(String applicationProtocol) { this.applicationProtocol = applicationProtocol; }
|
||||
public ClientCertificateConfig getClientCertificateConfig() { return clientCertificateConfig; }
|
||||
public void setClientCertificateConfig(ClientCertificateConfig clientCertificateConfig) { this.clientCertificateConfig = clientCertificateConfig; }
|
||||
public Instant getLastStatusChangeDate() { return lastStatusChangeDate; }
|
||||
public void setLastStatusChangeDate(Instant lastStatusChangeDate) { this.lastStatusChangeDate = lastStatusChangeDate; }
|
||||
public Map<String, String> getTags() { return tags == null ? Map.of() : tags; }
|
||||
public void setTags(Map<String, String> tags) { this.tags = tags == null ? new TreeMap<>() : new TreeMap<>(tags); }
|
||||
|
||||
@RegisterForReflection
|
||||
public record ServerCertificateSummary(String serverCertificateArn, String serverCertificateStatus,
|
||||
String serverCertificateStatusDetail) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record AuthorizerConfig(String defaultAuthorizerName, Boolean allowAuthorizerOverride) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record TlsConfig(String securityPolicy) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record ServerCertificateConfig(Boolean enableOCSPCheck, String ocspLambdaArn, String ocspAuthorizedResponderArn) {
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
public record ClientCertificateConfig(String clientCertificateCallbackArn) {
|
||||
}
|
||||
}
|
||||
+11
@@ -37,6 +37,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.EcrCfnPro
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.EcsCapacityCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.FirehoseCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IamRoleCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.IotDomainConfigurationCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.KinesisCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.KmsCfnProvisioner;
|
||||
import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaAddressingCfnProvisioner;
|
||||
@@ -64,6 +65,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.IotDomainConfigurationService;
|
||||
import io.github.hectorvent.floci.services.kinesis.KinesisService;
|
||||
import io.github.hectorvent.floci.services.kms.KmsService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
|
||||
@@ -145,6 +147,7 @@ final class CfnProvisionerFixture {
|
||||
// Services that back a provisioner without being a constructor argument of the
|
||||
// dispatcher. They exist only so inferredProvisioners() can wire their provisioner.
|
||||
private FlowLogService flowLogService;
|
||||
private IotDomainConfigurationService iotDomainConfigurationService;
|
||||
private LambdaMicrovmsService lambdaMicrovmsService;
|
||||
private AwsConfigService awsConfigService;
|
||||
private OrganizationsService organizationsService;
|
||||
@@ -244,6 +247,9 @@ final class CfnProvisionerFixture {
|
||||
if (flowLogService != null) {
|
||||
discovered.add(new Ec2FlowLogCfnProvisioner(flowLogService));
|
||||
}
|
||||
if (iotDomainConfigurationService != null) {
|
||||
discovered.add(new IotDomainConfigurationCfnProvisioner(iotDomainConfigurationService));
|
||||
}
|
||||
if (lambdaMicrovmsService != null) {
|
||||
discovered.add(new LambdaMicrovmsCfnProvisioner(lambdaMicrovmsService));
|
||||
}
|
||||
@@ -456,6 +462,11 @@ final class CfnProvisionerFixture {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder iotDomainConfiguration(IotDomainConfigurationService v) {
|
||||
this.iotDomainConfigurationService = v;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Builder lambdaMicrovms(LambdaMicrovmsService v) {
|
||||
this.lambdaMicrovmsService = v;
|
||||
return this;
|
||||
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.XmlParser;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Provisions an {@code AWS::IoT::DomainConfiguration} through a CloudFormation stack and asserts
|
||||
* that {@code Ref} and every {@code Fn::GetAtt} attribute carry what {@code DescribeDomainConfiguration}
|
||||
* reports, rather than the literal {@code Domain.Arn} the stub arm would leave behind. Also
|
||||
* covers the in-place status update and that deleting the stack removes the configuration.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IotDomainConfigurationCfnIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request";
|
||||
private static final String STACK = "iot-domain-cfn-it";
|
||||
private static final String NAME = "iot-cfn-it-domain";
|
||||
private static final String CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";
|
||||
|
||||
private static String template(String status) {
|
||||
return """
|
||||
{
|
||||
"Resources": {
|
||||
"Domain": {
|
||||
"Type": "AWS::IoT::DomainConfiguration",
|
||||
"Properties": {
|
||||
"DomainConfigurationName": "%s",
|
||||
"DomainName": "iot.cfn-it.example.com",
|
||||
"ServiceType": "DATA",
|
||||
"ServerCertificateArns": ["%s"],
|
||||
"AuthorizerConfig": {"DefaultAuthorizerName": "cfn-it-authorizer", "AllowAuthorizerOverride": true},
|
||||
"DomainConfigurationStatus": "%s",
|
||||
"Tags": [{"Key": "stack", "Value": "iot-domain-cfn-it"}]
|
||||
}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"DomainRef": {"Value": {"Ref": "Domain"}},
|
||||
"DomainArn": {"Value": {"Fn::GetAtt": ["Domain", "Arn"]}},
|
||||
"DomainType": {"Value": {"Fn::GetAtt": ["Domain", "DomainType"]}},
|
||||
"ServerCertificates": {"Value": {"Fn::GetAtt": ["Domain", "ServerCertificates"]}}
|
||||
}
|
||||
}
|
||||
""".formatted(NAME, CERTIFICATE_ARN, status);
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainConfigurationStackExposesRealAttributesUpdatesInPlaceAndDeletesTheConfiguration() throws Exception {
|
||||
cloudFormation("CreateStack", template("ENABLED"));
|
||||
|
||||
String stacks = describeStacks("CREATE_COMPLETE");
|
||||
String arn = outputValue(stacks, "DomainArn");
|
||||
assertEquals(NAME, outputValue(stacks, "DomainRef"));
|
||||
assertTrue(arn.startsWith("arn:aws:iot:us-east-1:000000000000:domainconfiguration/" + NAME + "/"),
|
||||
"Fn::GetAtt Arn must be the configuration ARN: " + arn);
|
||||
assertEquals("CUSTOMER_MANAGED", outputValue(stacks, "DomainType"));
|
||||
JsonNode certificates = new ObjectMapper().readTree(outputValue(stacks, "ServerCertificates"));
|
||||
assertEquals(CERTIFICATE_ARN, certificates.get(0).path("ServerCertificateArn").asText());
|
||||
assertEquals("VALID", certificates.get(0).path("ServerCertificateStatus").asText());
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationArn", equalTo(arn))
|
||||
.body("domainConfigurationStatus", equalTo("ENABLED"))
|
||||
.body("domainName", equalTo("iot.cfn-it.example.com"))
|
||||
.body("domainType", equalTo("CUSTOMER_MANAGED"))
|
||||
.body("authorizerConfig.defaultAuthorizerName", equalTo("cfn-it-authorizer"))
|
||||
.body("authorizerConfig.allowAuthorizerOverride", equalTo(true));
|
||||
given()
|
||||
.queryParam("resourceArn", arn)
|
||||
.when()
|
||||
.get("/tags")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags.Key", hasItem("stack"));
|
||||
|
||||
cloudFormation("UpdateStack", template("DISABLED"));
|
||||
|
||||
describeStacks("UPDATE_COMPLETE");
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationArn", equalTo(arn))
|
||||
.body("domainConfigurationStatus", equalTo("DISABLED"));
|
||||
|
||||
cloudFormation("DeleteStack", null);
|
||||
awaitStackDeleted();
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
private static void cloudFormation(String action, String templateBody) {
|
||||
RequestSpecification request = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", action)
|
||||
.formParam("StackName", STACK);
|
||||
if (templateBody != null) {
|
||||
request.formParam("TemplateBody", templateBody);
|
||||
}
|
||||
request.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String describeStacks(String expectedStatus) {
|
||||
return given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
|
||||
.extract().asString();
|
||||
}
|
||||
|
||||
/** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
|
||||
private static void awaitStackDeleted() throws InterruptedException {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
String body = given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", CFN_AUTH)
|
||||
.formParam("Action", "DescribeStacks")
|
||||
.formParam("StackName", STACK)
|
||||
.when().post("/").then().extract().asString();
|
||||
if (body.contains("does not exist")) {
|
||||
return;
|
||||
}
|
||||
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
|
||||
fail("stack delete failed: " + body);
|
||||
}
|
||||
Thread.sleep(50);
|
||||
}
|
||||
fail("stack " + STACK + " was not deleted within the timeout");
|
||||
}
|
||||
|
||||
private static String outputValue(String xml, String key) {
|
||||
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
|
||||
}
|
||||
}
|
||||
+554
@@ -0,0 +1,554 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
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.IotDomainConfigurationService;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.AuthorizerConfig;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration.ServerCertificateSummary;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
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.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
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.anyString;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
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.when;
|
||||
|
||||
/**
|
||||
* The IoT domain configuration CFN provisioner in isolation: one mocked service. Every case
|
||||
* asserts the exact physical id and the exact {@code Fn::GetAtt} attribute keys, because an
|
||||
* unmapped type still reports CREATE_COMPLETE through the dispatcher's stub arm.
|
||||
*/
|
||||
class IotDomainConfigurationCfnProvisionerTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String TYPE = "AWS::IoT::DomainConfiguration";
|
||||
private static final String NAME = "iot-domain";
|
||||
private static final String CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";
|
||||
private static final String ARN = "arn:aws:iot:us-east-1:000000000000:domainconfiguration/iot-domain/abcde";
|
||||
private static final String SERVER_CERTIFICATES_JSON =
|
||||
"[{\"ServerCertificateArn\":\"" + CERTIFICATE_ARN + "\",\"ServerCertificateStatus\":\"VALID\"}]";
|
||||
|
||||
private final IotDomainConfigurationService service = mock(IotDomainConfigurationService.class);
|
||||
private final IotDomainConfigurationCfnProvisioner provisioner = new IotDomainConfigurationCfnProvisioner(service);
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private ProvisionContext ctx() {
|
||||
return ctx(null);
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
|
||||
}
|
||||
|
||||
private static StackResource resource() {
|
||||
StackResource r = new StackResource();
|
||||
r.setLogicalId("Domain");
|
||||
r.setResourceType(TYPE);
|
||||
r.setAttributes(new HashMap<>());
|
||||
return r;
|
||||
}
|
||||
|
||||
private ObjectNode customDomainProps(String name) {
|
||||
ObjectNode props = mapper.createObjectNode().put("DomainName", "iot.example.com");
|
||||
if (name != null) {
|
||||
props.put("DomainConfigurationName", name);
|
||||
}
|
||||
props.putArray("ServerCertificateArns").add(CERTIFICATE_ARN);
|
||||
return props;
|
||||
}
|
||||
|
||||
private static IotDomainConfiguration stored(String name, String arn, String domainName, String status) {
|
||||
IotDomainConfiguration configuration = new IotDomainConfiguration();
|
||||
configuration.setDomainConfigurationName(name);
|
||||
configuration.setDomainConfigurationArn(arn);
|
||||
configuration.setDomainName(domainName);
|
||||
configuration.setServiceType("DATA");
|
||||
configuration.setDomainConfigurationStatus(status);
|
||||
configuration.setDomainType(domainName == null ? "ENDPOINT" : "CUSTOMER_MANAGED");
|
||||
configuration.setServerCertificates(domainName == null
|
||||
? List.of()
|
||||
: List.of(new ServerCertificateSummary(CERTIFICATE_ARN, "VALID", null)));
|
||||
return configuration;
|
||||
}
|
||||
|
||||
private JsonNode capturedCreateBody(String name) {
|
||||
ArgumentCaptor<JsonNode> captor = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).createDomainConfiguration(eq(name), captor.capture(), eq(REGION));
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
private JsonNode capturedUpdateBody(String name) {
|
||||
ArgumentCaptor<JsonNode> captor = ArgumentCaptor.forClass(JsonNode.class);
|
||||
verify(service).updateDomainConfiguration(eq(name), captor.capture(), eq(REGION));
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void createSetsTheNameAsPhysicalIdAndTheThreeSchemaAttributes() {
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(NAME), ctx());
|
||||
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
assertEquals(Map.of("Arn", ARN, "DomainType", "CUSTOMER_MANAGED", "ServerCertificates", SERVER_CERTIFICATES_JSON),
|
||||
r.getAttributes());
|
||||
verify(service, never()).updateDomainConfiguration(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPassesTemplatePropertiesToTheServiceInApiShape() {
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
ObjectNode props = customDomainProps(NAME)
|
||||
.put("ServiceType", "JOBS")
|
||||
.put("ValidationCertificateArn", CERTIFICATE_ARN)
|
||||
.put("AuthenticationType", "CUSTOM_AUTH")
|
||||
.put("ApplicationProtocol", "MQTT_WSS");
|
||||
props.putObject("AuthorizerConfig").put("DefaultAuthorizerName", "my-authorizer").put("AllowAuthorizerOverride", true);
|
||||
props.putObject("TlsConfig").put("SecurityPolicy", "IoTSecurityPolicy_TLS12_1_2_2022_10");
|
||||
props.putObject("ServerCertificateConfig").put("EnableOCSPCheck", true)
|
||||
.put("OcspLambdaArn", "arn:aws:lambda:us-east-1:000000000000:function:ocsp");
|
||||
props.putObject("ClientCertificateConfig")
|
||||
.put("ClientCertificateCallbackArn", "arn:aws:lambda:us-east-1:000000000000:function:callback");
|
||||
props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");
|
||||
|
||||
provisioner.provision(resource(), props, ctx());
|
||||
|
||||
JsonNode body = capturedCreateBody(NAME);
|
||||
assertEquals("iot.example.com", body.path("domainName").asText());
|
||||
assertEquals("JOBS", body.path("serviceType").asText());
|
||||
assertEquals(CERTIFICATE_ARN, body.path("serverCertificateArns").get(0).asText());
|
||||
assertEquals(CERTIFICATE_ARN, body.path("validationCertificateArn").asText());
|
||||
assertEquals("my-authorizer", body.path("authorizerConfig").path("defaultAuthorizerName").asText());
|
||||
assertTrue(body.path("authorizerConfig").path("allowAuthorizerOverride").isBoolean());
|
||||
assertTrue(body.path("authorizerConfig").path("allowAuthorizerOverride").asBoolean());
|
||||
assertEquals("IoTSecurityPolicy_TLS12_1_2_2022_10", body.path("tlsConfig").path("securityPolicy").asText());
|
||||
assertTrue(body.path("serverCertificateConfig").path("enableOCSPCheck").asBoolean());
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:ocsp",
|
||||
body.path("serverCertificateConfig").path("ocspLambdaArn").asText());
|
||||
assertEquals("CUSTOM_AUTH", body.path("authenticationType").asText());
|
||||
assertEquals("MQTT_WSS", body.path("applicationProtocol").asText());
|
||||
assertEquals("arn:aws:lambda:us-east-1:000000000000:function:callback",
|
||||
body.path("clientCertificateConfig").path("clientCertificateCallbackArn").asText());
|
||||
assertEquals("env", body.path("tags").get(0).path("Key").asText());
|
||||
assertEquals("test", body.path("tags").get(0).path("Value").asText());
|
||||
assertFalse(body.has("domainConfigurationName"));
|
||||
assertFalse(body.has("domainConfigurationStatus"));
|
||||
assertFalse(body.has("Tags"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void endpointConfigurationWithoutADomainNameReportsItsTypeAndAnEmptyCertificateList() {
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, null, "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode().put("DomainConfigurationName", NAME), ctx());
|
||||
|
||||
assertEquals(Map.of("Arn", ARN, "DomainType", "ENDPOINT", "ServerCertificates", "[]"), r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledStatusIsAppliedWithAFollowUpUpdateLikeTheCloudFormationHandler() {
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.updateDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "DISABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(NAME).put("DomainConfigurationStatus", "DISABLED"), ctx());
|
||||
|
||||
InOrder order = inOrder(service);
|
||||
order.verify(service).createDomainConfiguration(eq(NAME), any(), eq(REGION));
|
||||
order.verify(service).updateDomainConfiguration(eq(NAME), any(), eq(REGION));
|
||||
JsonNode update = capturedUpdateBody(NAME);
|
||||
assertEquals("DISABLED", update.path("domainConfigurationStatus").asText());
|
||||
assertEquals(1, update.size());
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
assertEquals(ARN, r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledStatusNeedsNoFollowUpUpdate() {
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
|
||||
provisioner.provision(resource(), customDomainProps(NAME).put("DomainConfigurationStatus", "ENABLED"), ctx());
|
||||
|
||||
verify(service, never()).updateDomainConfiguration(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nameIsGeneratedWhenTheTemplateGivesNone() {
|
||||
when(service.createDomainConfiguration(anyString(), any(), eq(REGION)))
|
||||
.thenAnswer(inv -> stored(inv.getArgument(0), ARN, "iot.example.com", "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(null), ctx());
|
||||
|
||||
assertTrue(r.getPhysicalId().matches("my-stack-Domain-[0-9a-f]{12}"), r.getPhysicalId());
|
||||
verify(service).createDomainConfiguration(eq(r.getPhysicalId()), any(), eq(REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithUnchangedCreateOnlyPropertiesUpdatesInPlaceAndReconcilesTags() {
|
||||
IotDomainConfiguration existing = stored(NAME, ARN, "iot.example.com", "ENABLED");
|
||||
existing.setAuthorizerConfig(new AuthorizerConfig("old-authorizer", true));
|
||||
existing.setTags(Map.of("stale", "x", "env", "old"));
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(existing);
|
||||
when(service.updateDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "DISABLED"));
|
||||
ObjectNode props = customDomainProps(NAME).put("DomainConfigurationStatus", "DISABLED");
|
||||
props.putObject("TlsConfig").put("SecurityPolicy", "IoTSecurityPolicy_TLS12_1_2_2022_10");
|
||||
props.putArray("Tags").addObject().put("Key", "env").put("Value", "test");
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, props, ctx(NAME));
|
||||
|
||||
verify(service, never()).createDomainConfiguration(any(), any(), any());
|
||||
verify(service, never()).deleteDomainConfiguration(any(), any());
|
||||
JsonNode update = capturedUpdateBody(NAME);
|
||||
assertEquals("DISABLED", update.path("domainConfigurationStatus").asText());
|
||||
assertEquals("IoTSecurityPolicy_TLS12_1_2_2022_10", update.path("tlsConfig").path("securityPolicy").asText());
|
||||
assertTrue(update.path("removeAuthorizerConfig").asBoolean(),
|
||||
"the template dropped AuthorizerConfig, so the update must remove it");
|
||||
assertFalse(update.has("authorizerConfig"));
|
||||
assertFalse(update.has("domainName"));
|
||||
assertFalse(update.has("serverCertificateArns"));
|
||||
verify(service).untagResource(ARN, List.of("stale"));
|
||||
verify(service).tagResource(ARN, Map.of("env", "test"));
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
assertEquals(Map.of("Arn", ARN, "DomainType", "CUSTOMER_MANAGED", "ServerCertificates", SERVER_CERTIFICATES_JSON),
|
||||
r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateKeepingTheAuthorizerSendsItWithoutTheRemoveFlag() {
|
||||
IotDomainConfiguration existing = stored(NAME, ARN, "iot.example.com", "ENABLED");
|
||||
existing.setAuthorizerConfig(new AuthorizerConfig("old-authorizer", true));
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(existing);
|
||||
when(service.updateDomainConfiguration(eq(NAME), any(), eq(REGION))).thenReturn(existing);
|
||||
ObjectNode props = customDomainProps(NAME);
|
||||
props.putObject("AuthorizerConfig").put("DefaultAuthorizerName", "new-authorizer");
|
||||
|
||||
provisioner.provision(resource(), props, ctx(NAME));
|
||||
|
||||
JsonNode update = capturedUpdateBody(NAME);
|
||||
assertEquals("new-authorizer", update.path("authorizerConfig").path("defaultAuthorizerName").asText());
|
||||
assertFalse(update.has("removeAuthorizerConfig"));
|
||||
// No DomainConfigurationStatus in the template leaves the status alone, as the AWS handler does.
|
||||
assertFalse(update.has("domainConfigurationStatus"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithoutANameKeepsTheGeneratedNameAndUpdatesInPlace() {
|
||||
String generated = "my-stack-Domain-aaaaaaaaaaaa";
|
||||
when(service.describeDomainConfiguration(generated, REGION))
|
||||
.thenReturn(stored(generated, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.updateDomainConfiguration(eq(generated), any(), eq(REGION)))
|
||||
.thenReturn(stored(generated, ARN, "iot.example.com", "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(null), ctx(generated));
|
||||
|
||||
verify(service, never()).createDomainConfiguration(any(), any(), any());
|
||||
verify(service, never()).deleteDomainConfiguration(any(), any());
|
||||
verify(service).updateDomainConfiguration(eq(generated), any(), eq(REGION));
|
||||
assertEquals(generated, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRenamingTheConfigurationCreatesTheNewOneAndRemovesTheOld() {
|
||||
// DomainConfigurationName is createOnly: a new name is a replacement, and the previous
|
||||
// configuration must not outlive the stack that created it.
|
||||
String oldArn = "arn:aws:iot:us-east-1:000000000000:domainconfiguration/old-name/aaaaa";
|
||||
when(service.describeDomainConfiguration("old-name", REGION))
|
||||
.thenReturn(stored("old-name", oldArn, "iot.example.com", "ENABLED"));
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(NAME), ctx("old-name"));
|
||||
|
||||
InOrder order = inOrder(service);
|
||||
order.verify(service).createDomainConfiguration(eq(NAME), any(), eq(REGION));
|
||||
order.verify(service).updateDomainConfiguration(eq("old-name"),
|
||||
argThat(body -> "DISABLED".equals(body.path("domainConfigurationStatus").asText())), eq(REGION));
|
||||
order.verify(service).deleteDomainConfiguration("old-name", REGION);
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
assertEquals(ARN, r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateChangingACreateOnlyPropertyUnderAnExplicitNameFailsOnTheCreateAsOnAws() {
|
||||
// DomainName is createOnly. CloudFormation creates the replacement before deleting the
|
||||
// original, and the explicit name is already taken, so the update fails like it does on AWS.
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "old.example.com", "ENABLED"));
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 409));
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(resource(), customDomainProps(NAME), ctx(NAME)));
|
||||
|
||||
assertEquals("ResourceAlreadyExistsException", failure.getErrorCode());
|
||||
verify(service, never()).updateDomainConfiguration(any(), any(), any());
|
||||
verify(service, never()).deleteDomainConfiguration(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateChangingACreateOnlyPropertyUnderAGeneratedNameReplacesTheConfiguration() {
|
||||
String priorName = "my-stack-Domain-aaaaaaaaaaaa";
|
||||
String priorArn = "arn:aws:iot:us-east-1:000000000000:domainconfiguration/" + priorName + "/aaaaa";
|
||||
when(service.describeDomainConfiguration(priorName, REGION)).thenReturn(stored(priorName, priorArn, "old.example.com", "ENABLED"));
|
||||
when(service.createDomainConfiguration(anyString(), any(), eq(REGION)))
|
||||
.thenAnswer(inv -> stored(inv.getArgument(0), ARN, "iot.example.com", "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(null), ctx(priorName));
|
||||
|
||||
assertNotEquals(priorName, r.getPhysicalId());
|
||||
assertTrue(r.getPhysicalId().matches("my-stack-Domain-[0-9a-f]{12}"), r.getPhysicalId());
|
||||
verify(service).createDomainConfiguration(eq(r.getPhysicalId()), any(), eq(REGION));
|
||||
InOrder order = inOrder(service);
|
||||
order.verify(service).updateDomainConfiguration(eq(priorName),
|
||||
argThat(body -> "DISABLED".equals(body.path("domainConfigurationStatus").asText())), eq(REGION));
|
||||
order.verify(service).deleteDomainConfiguration(priorName, REGION);
|
||||
assertEquals(ARN, r.getAttributes().get("Arn"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWhoseFollowUpDisableFailsLeavesAnOwnedResourceForTheRollback() {
|
||||
// The create rollback deletes only resources that have a physical id and carry the owned
|
||||
// marker, so both must be in place before the follow-up status update can fail.
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.updateDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("InternalFailureException", "boom", 500));
|
||||
StackResource r = resource();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
r, customDomainProps(NAME).put("DomainConfigurationStatus", "DISABLED"), ctx()));
|
||||
|
||||
assertEquals("InternalFailureException", failure.getErrorCode());
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
assertEquals(ARN, r.getAttributes().get("Arn"));
|
||||
assertEquals("true", r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementWhoseFollowUpDisableFailsRemovesTheNewConfigurationAndKeepsThePrior() {
|
||||
// CloudFormationService restores the previous StackResource on a failed update and never
|
||||
// learns the new name, so the configuration created here must not be left behind.
|
||||
String oldArn = "arn:aws:iot:us-east-1:000000000000:domainconfiguration/old-name/aaaaa";
|
||||
when(service.describeDomainConfiguration("old-name", REGION))
|
||||
.thenReturn(stored("old-name", oldArn, "iot.example.com", "ENABLED"));
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.updateDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("InternalFailureException", "boom", 500))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "DISABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
r, customDomainProps(NAME).put("DomainConfigurationStatus", "DISABLED"), ctx("old-name")));
|
||||
|
||||
assertEquals("InternalFailureException", failure.getErrorCode());
|
||||
verify(service).deleteDomainConfiguration(NAME, REGION);
|
||||
verify(service, never()).deleteDomainConfiguration("old-name", REGION);
|
||||
verify(service, never()).updateDomainConfiguration(eq("old-name"), any(), eq(REGION));
|
||||
assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
|
||||
// The resource describes the configuration that is still there, not the removed one.
|
||||
assertEquals("old-name", r.getPhysicalId());
|
||||
assertEquals(oldArn, r.getAttributes().get("Arn"));
|
||||
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementWhosePriorCannotBeDeletedRemovesTheNewConfigurationAndReEnablesThePrior() {
|
||||
String oldArn = "arn:aws:iot:us-east-1:000000000000:domainconfiguration/old-name/aaaaa";
|
||||
// The store hands out its live object, so the disable that precedes the delete changes the
|
||||
// very instance the provisioner captured as the prior. The status it saw at the start is
|
||||
// what the unwind must go back to.
|
||||
IotDomainConfiguration old = stored("old-name", oldArn, "iot.example.com", "ENABLED");
|
||||
when(service.describeDomainConfiguration("old-name", REGION)).thenReturn(old);
|
||||
when(service.updateDomainConfiguration(eq("old-name"), any(), eq(REGION))).thenAnswer(inv -> {
|
||||
JsonNode body = inv.getArgument(1);
|
||||
old.setDomainConfigurationStatus(body.path("domainConfigurationStatus").asText());
|
||||
return old;
|
||||
});
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
doThrow(new AwsException("InternalFailureException", "boom", 500))
|
||||
.when(service).deleteDomainConfiguration("old-name", REGION);
|
||||
StackResource r = resource();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class,
|
||||
() -> provisioner.provision(r, customDomainProps(NAME), ctx("old-name")));
|
||||
|
||||
assertEquals("InternalFailureException", failure.getErrorCode());
|
||||
InOrder order = inOrder(service);
|
||||
order.verify(service).updateDomainConfiguration(eq(NAME),
|
||||
argThat(body -> "DISABLED".equals(body.path("domainConfigurationStatus").asText())), eq(REGION));
|
||||
order.verify(service).deleteDomainConfiguration(NAME, REGION);
|
||||
order.verify(service).updateDomainConfiguration(eq("old-name"),
|
||||
argThat(body -> "ENABLED".equals(body.path("domainConfigurationStatus").asText())), eq(REGION));
|
||||
assertEquals("ENABLED", old.getDomainConfigurationStatus());
|
||||
assertEquals("true", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
|
||||
assertEquals("old-name", r.getPhysicalId());
|
||||
assertEquals(oldArn, r.getAttributes().get("Arn"));
|
||||
assertNull(r.getAttributes().get(CfnRollback.ROLLBACK_OWNED_ATTR));
|
||||
}
|
||||
|
||||
@Test
|
||||
void replacementWhoseCleanupAlsoFailsReportsTheRollbackFailureInsteadOfClaimingARestore() {
|
||||
// If the new configuration cannot be removed, the engine must not report a clean rollback:
|
||||
// the failure marker makes it end in UPDATE_ROLLBACK_FAILED with the reason.
|
||||
String oldArn = "arn:aws:iot:us-east-1:000000000000:domainconfiguration/old-name/aaaaa";
|
||||
when(service.describeDomainConfiguration("old-name", REGION))
|
||||
.thenReturn(stored("old-name", oldArn, "iot.example.com", "ENABLED"));
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
// A fresh exception per call, as a real service raises: the follow-up disable fails, and so
|
||||
// does the disable the cleanup attempts.
|
||||
when(service.updateDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenAnswer(inv -> {
|
||||
throw new AwsException("InternalFailureException", "boom", 500);
|
||||
});
|
||||
StackResource r = resource();
|
||||
|
||||
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(
|
||||
r, customDomainProps(NAME).put("DomainConfigurationStatus", "DISABLED"), ctx("old-name")));
|
||||
|
||||
assertEquals("InternalFailureException", failure.getErrorCode());
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
String reason = r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR);
|
||||
assertNotNull(reason);
|
||||
assertTrue(reason.contains(NAME), reason);
|
||||
assertNull(r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
|
||||
verify(service, never()).deleteDomainConfiguration(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void explicitNameReplacementWhoseCreateUnexpectedlySucceedsKeepsTheNewConfiguration() {
|
||||
// Under an explicit name the create normally fails with ResourceAlreadyExistsException. If
|
||||
// the prior vanished in between and the create went through, the configuration just
|
||||
// created must not be removed as if it were the prior.
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "old.example.com", "ENABLED"));
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(NAME), ctx(NAME));
|
||||
|
||||
verify(service, never()).deleteDomainConfiguration(any(), any());
|
||||
verify(service, never()).updateDomainConfiguration(any(), any(), any());
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
assertEquals(Map.of("Arn", ARN, "DomainType", "CUSTOMER_MANAGED", "ServerCertificates", SERVER_CERTIFICATES_JSON),
|
||||
r.getAttributes());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWhosePriorConfigurationIsGoneCreatesAFreshOne() {
|
||||
when(service.describeDomainConfiguration(NAME, REGION))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 404));
|
||||
when(service.createDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
StackResource r = resource();
|
||||
|
||||
provisioner.provision(r, customDomainProps(NAME), ctx(NAME));
|
||||
|
||||
verify(service, never()).deleteDomainConfiguration(any(), any());
|
||||
verify(service, never()).updateDomainConfiguration(any(), any(), any());
|
||||
assertEquals(NAME, r.getPhysicalId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDisablesAnEnabledConfigurationBeforeDeletingIt() {
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
|
||||
provisioner.delete(TYPE, NAME, REGION);
|
||||
|
||||
InOrder order = inOrder(service);
|
||||
order.verify(service).updateDomainConfiguration(eq(NAME),
|
||||
argThat(body -> "DISABLED".equals(body.path("domainConfigurationStatus").asText())), eq(REGION));
|
||||
order.verify(service).deleteDomainConfiguration(NAME, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteOfADisabledConfigurationSkipsTheStatusUpdate() {
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "iot.example.com", "DISABLED"));
|
||||
|
||||
provisioner.delete(TYPE, NAME, REGION);
|
||||
|
||||
verify(service, never()).updateDomainConfiguration(any(), any(), any());
|
||||
verify(service).deleteDomainConfiguration(NAME, REGION);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAnAlreadyDeletedConfiguration() {
|
||||
when(service.describeDomainConfiguration(NAME, REGION))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 404));
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, NAME, REGION));
|
||||
|
||||
verify(service, never()).deleteDomainConfiguration(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteToleratesAConfigurationThatVanishesWhileBeingDisabled() {
|
||||
// Seen ENABLED, then gone by the time the disable runs: already deleted is the outcome the
|
||||
// stack wants, on the disable as much as on the delete itself.
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "iot.example.com", "ENABLED"));
|
||||
when(service.updateDomainConfiguration(eq(NAME), any(), eq(REGION)))
|
||||
.thenThrow(new AwsException("ResourceNotFoundException", "gone", 404));
|
||||
doThrow(new AwsException("ResourceNotFoundException", "gone", 404))
|
||||
.when(service).deleteDomainConfiguration(NAME, REGION);
|
||||
|
||||
assertDoesNotThrow(() -> provisioner.delete(TYPE, NAME, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePropagatesAFailureThatIsNotAlreadyGone() {
|
||||
when(service.describeDomainConfiguration(NAME, REGION)).thenReturn(stored(NAME, ARN, "iot.example.com", "DISABLED"));
|
||||
doThrow(new AwsException("InvalidRequestException", "refused", 400))
|
||||
.when(service).deleteDomainConfiguration(NAME, REGION);
|
||||
|
||||
assertThrows(AwsException.class, () -> provisioner.delete(TYPE, NAME, REGION));
|
||||
}
|
||||
}
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.notNullValue;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
|
||||
/**
|
||||
* Drives the domain configuration routes the way the AWS SDKs do (REST-JSON under
|
||||
* {@code /domainConfigurations}) and checks the wire shapes and error codes AWS IoT returns.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class IotDomainConfigurationIntegrationTest {
|
||||
|
||||
private static final String NAME = "it-domain";
|
||||
private static final String CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";
|
||||
|
||||
private static String createBody(String domainName, String serviceType) {
|
||||
return """
|
||||
{
|
||||
"domainName": "%s",
|
||||
"serverCertificateArns": ["%s"],
|
||||
"serviceType": "%s"
|
||||
}
|
||||
""".formatted(domainName, CERTIFICATE_ARN, serviceType);
|
||||
}
|
||||
|
||||
@Test
|
||||
void domainConfigurationLifecycleMatchesAws() {
|
||||
String arn = given()
|
||||
.contentType("application/json")
|
||||
.body("""
|
||||
{
|
||||
"domainName": "iot.it.example.com",
|
||||
"serverCertificateArns": ["%s"],
|
||||
"authorizerConfig": {"defaultAuthorizerName": "it-authorizer", "allowAuthorizerOverride": true},
|
||||
"tags": [{"Key": "env", "Value": "it"}]
|
||||
}
|
||||
""".formatted(CERTIFICATE_ARN))
|
||||
.when()
|
||||
.post("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationName", equalTo(NAME))
|
||||
.body("domainConfigurationArn",
|
||||
startsWith("arn:aws:iot:us-east-1:000000000000:domainconfiguration/" + NAME + "/"))
|
||||
.extract().path("domainConfigurationArn");
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body(createBody("iot.it.example.com", "DATA"))
|
||||
.when()
|
||||
.post("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(409)
|
||||
.body("__type", equalTo("ResourceAlreadyExistsException"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationName", equalTo(NAME))
|
||||
.body("domainConfigurationArn", equalTo(arn))
|
||||
.body("domainName", equalTo("iot.it.example.com"))
|
||||
.body("domainConfigurationStatus", equalTo("ENABLED"))
|
||||
.body("serviceType", equalTo("DATA"))
|
||||
.body("domainType", equalTo("CUSTOMER_MANAGED"))
|
||||
.body("serverCertificates[0].serverCertificateArn", equalTo(CERTIFICATE_ARN))
|
||||
.body("serverCertificates[0].serverCertificateStatus", equalTo("VALID"))
|
||||
.body("authorizerConfig.defaultAuthorizerName", equalTo("it-authorizer"))
|
||||
.body("authorizerConfig.allowAuthorizerOverride", equalTo(true))
|
||||
.body("tlsConfig.securityPolicy", equalTo("IoTSecurityPolicy_TLS13_1_2_2022_10"))
|
||||
.body("serverCertificateConfig.enableOCSPCheck", equalTo(false))
|
||||
.body("lastStatusChangeDate", notNullValue());
|
||||
|
||||
given()
|
||||
.queryParam("resourceArn", arn)
|
||||
.when()
|
||||
.get("/tags")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags.Key", hasItem("env"))
|
||||
.body("tags.Value", hasItem("it"));
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"resourceArn\": \"" + arn + "\", \"tags\": [{\"Key\": \"owner\", \"Value\": \"iot\"}]}")
|
||||
.when()
|
||||
.post("/tags")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"resourceArn\": \"" + arn + "\", \"tagKeys\": [\"env\"]}")
|
||||
.when()
|
||||
.post("/untag")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.queryParam("resourceArn", arn)
|
||||
.when()
|
||||
.get("/tags")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("tags.Key", hasItem("owner"))
|
||||
.body("tags.Key", not(hasItem("env")));
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body(createBody("jobs.it.example.com", "JOBS"))
|
||||
.when()
|
||||
.post("/domainConfigurations/" + NAME + "-jobs")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.queryParam("serviceType", "JOBS")
|
||||
.when()
|
||||
.get("/domainConfigurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurations.domainConfigurationName", hasItem(NAME + "-jobs"))
|
||||
.body("domainConfigurations.domainConfigurationName", not(hasItem(NAME)))
|
||||
.body("domainConfigurations[0].serviceType", equalTo("JOBS"))
|
||||
.body("domainConfigurations[0].domainConfigurationArn", notNullValue());
|
||||
|
||||
String marker = given()
|
||||
.queryParam("pageSize", 1)
|
||||
.when()
|
||||
.get("/domainConfigurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurations.size()", equalTo(1))
|
||||
.body("nextMarker", notNullValue())
|
||||
.extract().path("nextMarker");
|
||||
|
||||
given()
|
||||
.queryParam("pageSize", 1)
|
||||
.queryParam("marker", marker)
|
||||
.when()
|
||||
.get("/domainConfigurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurations.size()", equalTo(1));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.delete("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"domainConfigurationStatus\": \"DISABLED\", \"removeAuthorizerConfig\": true}")
|
||||
.when()
|
||||
.put("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationName", equalTo(NAME))
|
||||
.body("domainConfigurationArn", equalTo(arn));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationStatus", equalTo("DISABLED"))
|
||||
.body("authorizerConfig", equalTo(null));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.delete("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/" + NAME)
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.header("x-amzn-ErrorType", equalTo("ResourceNotFoundException"))
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"domainConfigurationStatus\": \"DISABLED\"}")
|
||||
.when()
|
||||
.put("/domainConfigurations/" + NAME + "-jobs")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
given()
|
||||
.when()
|
||||
.delete("/domainConfigurations/" + NAME + "-jobs")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void awsManagedConfigurationsExistWithoutBeingCreated() {
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/iot:Data-ATS")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationName", equalTo("iot:Data-ATS"))
|
||||
.body("domainConfigurationArn",
|
||||
startsWith("arn:aws:iot:us-east-1:000000000000:domainconfiguration/iot:Data-ATS/"))
|
||||
.body("domainName", equalTo("localhost:4566"))
|
||||
.body("domainType", equalTo("AWS_MANAGED"))
|
||||
.body("serviceType", equalTo("DATA"))
|
||||
.body("domainConfigurationStatus", equalTo("ENABLED"))
|
||||
.body("serverCertificates.size()", equalTo(0))
|
||||
.body("tlsConfig.securityPolicy", equalTo("IoTSecurityPolicy_TLS13_1_2_2022_10"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurations.domainConfigurationName",
|
||||
hasItems("iot:Data-ATS", "iot:Data", "iot:CredentialProvider", "iot:Jobs"));
|
||||
|
||||
given()
|
||||
.queryParam("serviceType", "CREDENTIAL_PROVIDER")
|
||||
.when()
|
||||
.get("/domainConfigurations")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurations.domainConfigurationName", hasItem("iot:CredentialProvider"))
|
||||
.body("domainConfigurations.domainConfigurationName", not(hasItem("iot:Jobs")));
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"domainConfigurationStatus\": \"DISABLED\"}")
|
||||
.when()
|
||||
.put("/domainConfigurations/iot:Data")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationName", equalTo("iot:Data"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/iot:Data")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("domainConfigurationStatus", equalTo("DISABLED"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.delete("/domainConfigurations/iot:Data")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"domainConfigurationStatus\": \"ENABLED\"}")
|
||||
.when()
|
||||
.put("/domainConfigurations/iot:Data")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownDomainConfigurationIsNotFoundOnEveryRoute() {
|
||||
given()
|
||||
.when()
|
||||
.get("/domainConfigurations/absent")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body("{\"domainConfigurationStatus\": \"ENABLED\"}")
|
||||
.when()
|
||||
.put("/domainConfigurations/absent")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
|
||||
given()
|
||||
.when()
|
||||
.delete("/domainConfigurations/absent")
|
||||
.then()
|
||||
.statusCode(404)
|
||||
.body("__type", equalTo("ResourceNotFoundException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsAReservedNameAndListRejectsABadPageSize() {
|
||||
given()
|
||||
.contentType("application/json")
|
||||
.body(createBody("data.it.example.com", "DATA"))
|
||||
.when()
|
||||
.post("/domainConfigurations/iot:Data-ATS")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
|
||||
given()
|
||||
.queryParam("pageSize", 0)
|
||||
.when()
|
||||
.get("/domainConfigurations")
|
||||
.then()
|
||||
.statusCode(400)
|
||||
.body("__type", equalTo("InvalidRequestException"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeEndpointAcceptsTheCredentialProviderEndpointType() {
|
||||
given()
|
||||
.queryParam("endpointType", "iot:CredentialProvider")
|
||||
.when()
|
||||
.get("/endpoint")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("endpointAddress", equalTo("localhost:4566"));
|
||||
}
|
||||
}
|
||||
+567
@@ -0,0 +1,567 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotDomainConfiguration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class IotDomainConfigurationServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/11111111-1111-1111-1111-111111111111";
|
||||
private static final String OTHER_CERTIFICATE_ARN =
|
||||
"arn:aws:acm:us-east-1:000000000000:certificate/22222222-2222-2222-2222-222222222222";
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final IotDomainConfigurationService service = new IotDomainConfigurationService(
|
||||
new InMemoryStorage<>(), new RegionResolver(REGION, "000000000000"), endpointConfig());
|
||||
|
||||
private static EmulatorConfig endpointConfig() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
when(config.effectiveBaseUrl()).thenReturn("http://localhost:4566");
|
||||
return config;
|
||||
}
|
||||
|
||||
private ObjectNode customDomainRequest() {
|
||||
ObjectNode request = mapper.createObjectNode().put("domainName", "iot.example.com");
|
||||
request.putArray("serverCertificateArns").add(CERTIFICATE_ARN);
|
||||
return request;
|
||||
}
|
||||
|
||||
private static AwsException assertAwsError(String code, int status, Runnable call) {
|
||||
AwsException failure = assertThrows(AwsException.class, call::run);
|
||||
assertEquals(code, failure.getErrorCode());
|
||||
assertEquals(status, failure.getHttpStatus());
|
||||
return failure;
|
||||
}
|
||||
|
||||
@Test
|
||||
void createReturnsAnEnabledCustomerManagedConfiguration() {
|
||||
IotDomainConfiguration created = service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION);
|
||||
|
||||
assertEquals("iot-domain", created.getDomainConfigurationName());
|
||||
assertTrue(created.getDomainConfigurationArn().matches(
|
||||
"arn:aws:iot:us-east-1:000000000000:domainconfiguration/iot-domain/[a-z0-9]{5}"),
|
||||
"AWS appends a short id to the ARN: " + created.getDomainConfigurationArn());
|
||||
assertEquals("iot.example.com", created.getDomainName());
|
||||
assertEquals("DATA", created.getServiceType());
|
||||
assertEquals("ENABLED", created.getDomainConfigurationStatus());
|
||||
assertEquals("CUSTOMER_MANAGED", created.getDomainType());
|
||||
assertEquals(List.of(new IotDomainConfiguration.ServerCertificateSummary(CERTIFICATE_ARN, "VALID", null)),
|
||||
created.getServerCertificates());
|
||||
assertEquals(new IotDomainConfiguration.TlsConfig("IoTSecurityPolicy_TLS13_1_2_2022_10"), created.getTlsConfig());
|
||||
assertEquals(new IotDomainConfiguration.ServerCertificateConfig(false, null, null), created.getServerCertificateConfig());
|
||||
assertNotNull(created.getLastStatusChangeDate());
|
||||
assertNull(created.getAuthorizerConfig());
|
||||
assertNull(created.getAuthenticationType());
|
||||
assertNull(created.getApplicationProtocol());
|
||||
assertNull(created.getClientCertificateConfig());
|
||||
assertTrue(created.getTags().isEmpty());
|
||||
assertEquals(created.getDomainConfigurationArn(),
|
||||
service.describeDomainConfiguration("iot-domain", REGION).getDomainConfigurationArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStoresEveryRequestField() {
|
||||
ObjectNode request = customDomainRequest()
|
||||
.put("serviceType", "JOBS")
|
||||
.put("validationCertificateArn", OTHER_CERTIFICATE_ARN)
|
||||
.put("authenticationType", "CUSTOM_AUTH")
|
||||
.put("applicationProtocol", "MQTT_WSS");
|
||||
request.putObject("authorizerConfig").put("defaultAuthorizerName", "my-authorizer").put("allowAuthorizerOverride", true);
|
||||
request.putObject("tlsConfig").put("securityPolicy", "IoTSecurityPolicy_TLS12_1_2_2022_10");
|
||||
request.putObject("serverCertificateConfig").put("enableOCSPCheck", true)
|
||||
.put("ocspLambdaArn", "arn:aws:lambda:us-east-1:000000000000:function:ocsp")
|
||||
.put("ocspAuthorizedResponderArn", OTHER_CERTIFICATE_ARN);
|
||||
request.putObject("clientCertificateConfig")
|
||||
.put("clientCertificateCallbackArn", "arn:aws:lambda:us-east-1:000000000000:function:callback");
|
||||
request.putArray("tags").addObject().put("Key", "env").put("Value", "test");
|
||||
|
||||
IotDomainConfiguration created = service.createDomainConfiguration("iot-domain", request, REGION);
|
||||
|
||||
assertEquals("JOBS", created.getServiceType());
|
||||
assertEquals(OTHER_CERTIFICATE_ARN, created.getValidationCertificateArn());
|
||||
assertEquals(new IotDomainConfiguration.AuthorizerConfig("my-authorizer", true), created.getAuthorizerConfig());
|
||||
assertEquals(new IotDomainConfiguration.TlsConfig("IoTSecurityPolicy_TLS12_1_2_2022_10"), created.getTlsConfig());
|
||||
assertEquals(new IotDomainConfiguration.ServerCertificateConfig(true,
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:ocsp", OTHER_CERTIFICATE_ARN),
|
||||
created.getServerCertificateConfig());
|
||||
assertEquals("CUSTOM_AUTH", created.getAuthenticationType());
|
||||
assertEquals("MQTT_WSS", created.getApplicationProtocol());
|
||||
assertEquals(new IotDomainConfiguration.ClientCertificateConfig(
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:callback"), created.getClientCertificateConfig());
|
||||
assertEquals(Map.of("env", "test"), created.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWithoutADomainNameIsAnEndpointConfiguration() {
|
||||
IotDomainConfiguration created = service.createDomainConfiguration("default-endpoint", mapper.createObjectNode(), REGION);
|
||||
|
||||
assertEquals("ENDPOINT", created.getDomainType());
|
||||
assertNull(created.getDomainName());
|
||||
assertTrue(created.getServerCertificates().isEmpty());
|
||||
assertEquals("ENABLED", created.getDomainConfigurationStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createTreatsAJsonNullAsAbsent() {
|
||||
ObjectNode request = customDomainRequest();
|
||||
request.putNull("authorizerConfig");
|
||||
request.putNull("validationCertificateArn");
|
||||
request.putNull("authenticationType");
|
||||
request.putNull("tags");
|
||||
|
||||
IotDomainConfiguration created = service.createDomainConfiguration("iot-domain", request, REGION);
|
||||
|
||||
assertNull(created.getAuthorizerConfig());
|
||||
assertNull(created.getValidationCertificateArn());
|
||||
assertNull(created.getAuthenticationType());
|
||||
assertTrue(created.getTags().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStoresATagWithoutAValueAsEmpty() {
|
||||
ObjectNode request = customDomainRequest();
|
||||
request.putArray("tags").addObject().put("Key", "env");
|
||||
|
||||
assertEquals(Map.of("env", ""), service.createDomainConfiguration("iot-domain", request, REGION).getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsAStructuredValueWhereAStringIsExpected() {
|
||||
ObjectNode request = customDomainRequest();
|
||||
request.putObject("domainName");
|
||||
|
||||
assertAwsError("InvalidRequestException", 400,
|
||||
() -> service.createDomainConfiguration("iot-domain", request, REGION));
|
||||
assertAwsError("ResourceNotFoundException", 404, () -> service.describeDomainConfiguration("iot-domain", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRejectsAnAuthorizerConfigThatIsNotAnObjectAndKeepsTheStoredOne() {
|
||||
ObjectNode create = customDomainRequest();
|
||||
create.putObject("authorizerConfig").put("defaultAuthorizerName", "first");
|
||||
service.createDomainConfiguration("iot-domain", create, REGION);
|
||||
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.updateDomainConfiguration("iot-domain",
|
||||
mapper.createObjectNode().put("authorizerConfig", "not-an-object"), REGION));
|
||||
assertEquals(new IotDomainConfiguration.AuthorizerConfig("first", null),
|
||||
service.describeDomainConfiguration("iot-domain", REGION).getAuthorizerConfig());
|
||||
}
|
||||
|
||||
@Test
|
||||
void awsManagedConfigurationsExistInEveryRegionWithoutBeingCreated() {
|
||||
IotDomainConfiguration dataAts = service.describeDomainConfiguration("iot:Data-ATS", REGION);
|
||||
|
||||
assertTrue(dataAts.getDomainConfigurationArn().matches(
|
||||
"arn:aws:iot:us-east-1:000000000000:domainconfiguration/iot:Data-ATS/[a-z0-9]{5}"),
|
||||
dataAts.getDomainConfigurationArn());
|
||||
assertEquals("localhost:4566", dataAts.getDomainName());
|
||||
assertEquals("DATA", dataAts.getServiceType());
|
||||
assertEquals("AWS_MANAGED", dataAts.getDomainType());
|
||||
assertEquals("ENABLED", dataAts.getDomainConfigurationStatus());
|
||||
assertTrue(dataAts.getServerCertificates().isEmpty());
|
||||
assertEquals(new IotDomainConfiguration.TlsConfig("IoTSecurityPolicy_TLS13_1_2_2022_10"), dataAts.getTlsConfig());
|
||||
assertEquals(new IotDomainConfiguration.ServerCertificateConfig(false, null, null), dataAts.getServerCertificateConfig());
|
||||
assertNotNull(dataAts.getLastStatusChangeDate());
|
||||
assertEquals(dataAts.getDomainConfigurationArn(),
|
||||
service.describeDomainConfiguration("iot:Data-ATS", REGION).getDomainConfigurationArn(),
|
||||
"seeded once, so the ARN is stable");
|
||||
|
||||
assertEquals("DATA", service.describeDomainConfiguration("iot:Data", REGION).getServiceType());
|
||||
assertEquals("CREDENTIAL_PROVIDER",
|
||||
service.describeDomainConfiguration("iot:CredentialProvider", REGION).getServiceType());
|
||||
assertEquals("JOBS", service.describeDomainConfiguration("iot:Jobs", REGION).getServiceType());
|
||||
assertTrue(service.describeDomainConfiguration("iot:Jobs", "eu-west-1").getDomainConfigurationArn()
|
||||
.startsWith("arn:aws:iot:eu-west-1:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void awsManagedConfigurationsCanBeUpdatedAndTaggedButNotDeleted() {
|
||||
IotDomainConfiguration legacy = service.updateDomainConfiguration("iot:Data",
|
||||
mapper.createObjectNode().put("domainConfigurationStatus", "DISABLED"), REGION);
|
||||
assertEquals("DISABLED", legacy.getDomainConfigurationStatus());
|
||||
assertEquals("DISABLED", service.describeDomainConfiguration("iot:Data", REGION).getDomainConfigurationStatus());
|
||||
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.deleteDomainConfiguration("iot:Data", REGION));
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.deleteDomainConfiguration("iot:Data-ATS", REGION));
|
||||
assertEquals("AWS_MANAGED", service.describeDomainConfiguration("iot:Data", REGION).getDomainType());
|
||||
|
||||
String jobsArn = service.describeDomainConfiguration("iot:Jobs", REGION).getDomainConfigurationArn();
|
||||
service.tagResource(jobsArn, Map.of("team", "devices"));
|
||||
assertEquals(Map.of("team", "devices"), service.listTagsForResource(jobsArn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configurationSurvivesTheJsonRoundTripPersistentStorageUses() throws Exception {
|
||||
ObjectNode request = customDomainRequest()
|
||||
.put("serviceType", "JOBS")
|
||||
.put("validationCertificateArn", OTHER_CERTIFICATE_ARN)
|
||||
.put("authenticationType", "CUSTOM_AUTH")
|
||||
.put("applicationProtocol", "MQTT_WSS");
|
||||
request.putObject("authorizerConfig").put("defaultAuthorizerName", "my-authorizer").put("allowAuthorizerOverride", true);
|
||||
request.putObject("serverCertificateConfig").put("enableOCSPCheck", true)
|
||||
.put("ocspLambdaArn", "arn:aws:lambda:us-east-1:000000000000:function:ocsp");
|
||||
request.putObject("clientCertificateConfig").put("clientCertificateCallbackArn", "arn:aws:lambda:us-east-1:000000000000:function:cb");
|
||||
request.putArray("tags").addObject().put("Key", "env").put("Value", "test");
|
||||
IotDomainConfiguration created = service.createDomainConfiguration("iot-domain", request, REGION);
|
||||
|
||||
// The same mapper setup PersistentStorage uses: defaults plus java.time, so an unmapped
|
||||
// property or an unreadable record would fail the reload of a persisted store.
|
||||
ObjectMapper persistence = new ObjectMapper().registerModule(new JavaTimeModule());
|
||||
String json = persistence.writeValueAsString(created);
|
||||
IotDomainConfiguration reloaded = persistence.readValue(json, IotDomainConfiguration.class);
|
||||
|
||||
assertEquals(json, persistence.writeValueAsString(reloaded));
|
||||
assertEquals(created.getDomainConfigurationArn(), reloaded.getDomainConfigurationArn());
|
||||
assertEquals(created.getServerCertificates(), reloaded.getServerCertificates());
|
||||
assertEquals(created.getAuthorizerConfig(), reloaded.getAuthorizerConfig());
|
||||
assertEquals(created.getTlsConfig(), reloaded.getTlsConfig());
|
||||
assertEquals(created.getServerCertificateConfig(), reloaded.getServerCertificateConfig());
|
||||
assertEquals(created.getClientCertificateConfig(), reloaded.getClientCertificateConfig());
|
||||
assertEquals(created.getLastStatusChangeDate(), reloaded.getLastStatusChangeDate());
|
||||
assertEquals(created.getTags(), reloaded.getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentTagWritesOnOneConfigurationKeepEveryKey() throws Exception {
|
||||
String arn = service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION).getDomainConfigurationArn();
|
||||
int writers = 16;
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
ExecutorService pool = Executors.newFixedThreadPool(writers);
|
||||
try {
|
||||
List<Future<?>> writes = new ArrayList<>();
|
||||
for (int i = 0; i < writers; i++) {
|
||||
String tagKey = "key" + i;
|
||||
writes.add(pool.submit(() -> {
|
||||
start.await();
|
||||
service.tagResource(arn, Map.of(tagKey, "v"));
|
||||
return null;
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
for (Future<?> write : writes) {
|
||||
write.get();
|
||||
}
|
||||
assertEquals(writers, service.listTagsForResource(arn).size(), "a concurrent tag write must not drop another writer's key");
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsADuplicateName() {
|
||||
service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION);
|
||||
|
||||
assertAwsError("ResourceAlreadyExistsException", 409,
|
||||
() -> service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void concurrentCreatesOfTheSameNameLetExactlyOneThrough() throws Exception {
|
||||
int callers = 16;
|
||||
CountDownLatch start = new CountDownLatch(1);
|
||||
AtomicInteger conflicts = new AtomicInteger();
|
||||
List<Future<String>> results = new ArrayList<>();
|
||||
ExecutorService pool = Executors.newFixedThreadPool(callers);
|
||||
try {
|
||||
for (int i = 0; i < callers; i++) {
|
||||
results.add(pool.submit(() -> {
|
||||
start.await();
|
||||
try {
|
||||
return service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION)
|
||||
.getDomainConfigurationArn();
|
||||
} catch (AwsException e) {
|
||||
assertEquals("ResourceAlreadyExistsException", e.getErrorCode());
|
||||
conflicts.incrementAndGet();
|
||||
return null;
|
||||
}
|
||||
}));
|
||||
}
|
||||
start.countDown();
|
||||
List<String> arns = new ArrayList<>();
|
||||
for (Future<String> result : results) {
|
||||
String arn = result.get();
|
||||
if (arn != null) {
|
||||
arns.add(arn);
|
||||
}
|
||||
}
|
||||
assertEquals(1, arns.size(), "exactly one create may succeed");
|
||||
assertEquals(callers - 1, conflicts.get());
|
||||
assertEquals(arns.get(0), service.describeDomainConfiguration("iot-domain", REGION).getDomainConfigurationArn());
|
||||
} finally {
|
||||
pool.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsTagsThatAreNotAList() {
|
||||
ObjectNode request = customDomainRequest();
|
||||
request.putObject("tags").put("env", "test");
|
||||
|
||||
assertAwsError("InvalidRequestException", 400,
|
||||
() -> service.createDomainConfiguration("iot-domain", request, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsNamesOutsideTheAwsPattern() {
|
||||
for (String name : List.of("", "has space", "iot:Data-ATS", "x".repeat(129))) {
|
||||
assertAwsError("InvalidRequestException", 400,
|
||||
() -> service.createDomainConfiguration(name, customDomainRequest(), REGION));
|
||||
}
|
||||
assertAwsError("InvalidRequestException", 400,
|
||||
() -> service.createDomainConfiguration(null, customDomainRequest(), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsMoreThanOneServerCertificate() {
|
||||
ObjectNode request = customDomainRequest();
|
||||
request.withArray("serverCertificateArns").add(OTHER_CERTIFICATE_ARN);
|
||||
|
||||
assertAwsError("InvalidRequestException", 400,
|
||||
() -> service.createDomainConfiguration("iot-domain", request, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsACustomDomainWithoutAServerCertificate() {
|
||||
ObjectNode request = mapper.createObjectNode().put("domainName", "iot.example.com");
|
||||
|
||||
assertAwsError("InvalidRequestException", 400,
|
||||
() -> service.createDomainConfiguration("iot-domain", request, REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRejectsValuesOutsideTheAwsEnums() {
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.createDomainConfiguration(
|
||||
"a", customDomainRequest().put("serviceType", "MQTT"), REGION));
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.createDomainConfiguration(
|
||||
"b", customDomainRequest().put("authenticationType", "NONE"), REGION));
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.createDomainConfiguration(
|
||||
"c", customDomainRequest().put("applicationProtocol", "AMQP"), REGION));
|
||||
assertAwsError("ResourceNotFoundException", 404, () -> service.describeDomainConfiguration("a", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void describeUnknownConfigurationIsNotFound() {
|
||||
assertAwsError("ResourceNotFoundException", 404,
|
||||
() -> service.describeDomainConfiguration("missing", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configurationsAreScopedToTheirRegion() {
|
||||
service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION);
|
||||
|
||||
assertAwsError("ResourceNotFoundException", 404,
|
||||
() -> service.describeDomainConfiguration("iot-domain", "eu-west-1"));
|
||||
IotDomainConfiguration other = service.createDomainConfiguration("iot-domain", customDomainRequest(), "eu-west-1");
|
||||
assertTrue(other.getDomainConfigurationArn().startsWith("arn:aws:iot:eu-west-1:"));
|
||||
assertFalse(other.getDomainConfigurationArn().equals(
|
||||
service.describeDomainConfiguration("iot-domain", REGION).getDomainConfigurationArn()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateFlipsTheStatusAndRecordsWhenItChanged() throws InterruptedException {
|
||||
Instant createdAt = service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION)
|
||||
.getLastStatusChangeDate();
|
||||
Thread.sleep(10);
|
||||
|
||||
IotDomainConfiguration updated = service.updateDomainConfiguration("iot-domain",
|
||||
mapper.createObjectNode().put("domainConfigurationStatus", "DISABLED"), REGION);
|
||||
|
||||
assertEquals("DISABLED", updated.getDomainConfigurationStatus());
|
||||
assertTrue(updated.getLastStatusChangeDate().isAfter(createdAt));
|
||||
assertEquals("DISABLED", service.describeDomainConfiguration("iot-domain", REGION).getDomainConfigurationStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateWithTheSameStatusKeepsLastStatusChangeDate() throws InterruptedException {
|
||||
Instant createdAt = service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION)
|
||||
.getLastStatusChangeDate();
|
||||
Thread.sleep(10);
|
||||
|
||||
IotDomainConfiguration updated = service.updateDomainConfiguration("iot-domain",
|
||||
mapper.createObjectNode().put("domainConfigurationStatus", "ENABLED"), REGION);
|
||||
|
||||
assertEquals(createdAt, updated.getLastStatusChangeDate());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRejectsAnUnknownStatus() {
|
||||
service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION);
|
||||
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.updateDomainConfiguration("iot-domain",
|
||||
mapper.createObjectNode().put("domainConfigurationStatus", "PAUSED"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateReplacesTheAuthorizerAndRemoveAuthorizerConfigClearsIt() {
|
||||
ObjectNode create = customDomainRequest();
|
||||
create.putObject("authorizerConfig").put("defaultAuthorizerName", "first");
|
||||
service.createDomainConfiguration("iot-domain", create, REGION);
|
||||
|
||||
ObjectNode replace = mapper.createObjectNode();
|
||||
replace.putObject("authorizerConfig").put("defaultAuthorizerName", "second").put("allowAuthorizerOverride", false);
|
||||
assertEquals(new IotDomainConfiguration.AuthorizerConfig("second", false),
|
||||
service.updateDomainConfiguration("iot-domain", replace, REGION).getAuthorizerConfig());
|
||||
|
||||
ObjectNode remove = mapper.createObjectNode().put("removeAuthorizerConfig", true);
|
||||
assertNull(service.updateDomainConfiguration("iot-domain", remove, REGION).getAuthorizerConfig());
|
||||
assertNull(service.describeDomainConfiguration("iot-domain", REGION).getAuthorizerConfig());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateAppliesTlsCertificateAndProtocolSettingsAndLeavesTheRestAlone() {
|
||||
IotDomainConfiguration created = service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION);
|
||||
ObjectNode request = mapper.createObjectNode()
|
||||
.put("authenticationType", "AWS_SIGV4")
|
||||
.put("applicationProtocol", "HTTPS");
|
||||
request.putObject("tlsConfig").put("securityPolicy", "IoTSecurityPolicy_TLS12_1_2_2022_10");
|
||||
request.putObject("serverCertificateConfig").put("enableOCSPCheck", true);
|
||||
request.putObject("clientCertificateConfig")
|
||||
.put("clientCertificateCallbackArn", "arn:aws:lambda:us-east-1:000000000000:function:callback");
|
||||
|
||||
IotDomainConfiguration updated = service.updateDomainConfiguration("iot-domain", request, REGION);
|
||||
|
||||
assertEquals(new IotDomainConfiguration.TlsConfig("IoTSecurityPolicy_TLS12_1_2_2022_10"), updated.getTlsConfig());
|
||||
assertEquals(new IotDomainConfiguration.ServerCertificateConfig(true, null, null), updated.getServerCertificateConfig());
|
||||
assertEquals("AWS_SIGV4", updated.getAuthenticationType());
|
||||
assertEquals("HTTPS", updated.getApplicationProtocol());
|
||||
assertEquals(new IotDomainConfiguration.ClientCertificateConfig(
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:callback"), updated.getClientCertificateConfig());
|
||||
assertEquals(created.getDomainConfigurationArn(), updated.getDomainConfigurationArn());
|
||||
assertEquals("iot.example.com", updated.getDomainName());
|
||||
assertEquals("DATA", updated.getServiceType());
|
||||
assertEquals("ENABLED", updated.getDomainConfigurationStatus());
|
||||
assertEquals(created.getServerCertificates(), updated.getServerCertificates());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateUnknownConfigurationIsNotFound() {
|
||||
assertAwsError("ResourceNotFoundException", 404, () -> service.updateDomainConfiguration("missing",
|
||||
mapper.createObjectNode().put("domainConfigurationStatus", "DISABLED"), REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRefusesAnEnabledConfiguration() {
|
||||
service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION);
|
||||
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.deleteDomainConfiguration("iot-domain", REGION));
|
||||
assertEquals("ENABLED", service.describeDomainConfiguration("iot-domain", REGION).getDomainConfigurationStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteRemovesADisabledConfiguration() {
|
||||
service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION);
|
||||
service.updateDomainConfiguration("iot-domain",
|
||||
mapper.createObjectNode().put("domainConfigurationStatus", "DISABLED"), REGION);
|
||||
|
||||
service.deleteDomainConfiguration("iot-domain", REGION);
|
||||
|
||||
assertAwsError("ResourceNotFoundException", 404, () -> service.describeDomainConfiguration("iot-domain", REGION));
|
||||
assertAwsError("ResourceNotFoundException", 404, () -> service.deleteDomainConfiguration("iot-domain", REGION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturnsConfigurationsSortedByNameAndFiltersByServiceType() {
|
||||
service.createDomainConfiguration("zulu", customDomainRequest(), REGION);
|
||||
service.createDomainConfiguration("alpha", customDomainRequest().put("serviceType", "JOBS"), REGION);
|
||||
service.createDomainConfiguration("mike", customDomainRequest(), "eu-west-1");
|
||||
|
||||
IotService.Page<IotDomainConfiguration> all = service.listDomainConfigurations(REGION, null, null, null);
|
||||
assertEquals(List.of("alpha", "iot:CredentialProvider", "iot:Data", "iot:Data-ATS", "iot:Jobs", "zulu"),
|
||||
all.items().stream().map(IotDomainConfiguration::getDomainConfigurationName).toList());
|
||||
assertNull(all.nextToken());
|
||||
|
||||
IotService.Page<IotDomainConfiguration> jobs = service.listDomainConfigurations(REGION, "JOBS", null, null);
|
||||
assertEquals(List.of("alpha", "iot:Jobs"),
|
||||
jobs.items().stream().map(IotDomainConfiguration::getDomainConfigurationName).toList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listPagesWithMarkerAndPageSize() {
|
||||
for (String name : List.of("a", "b", "c")) {
|
||||
service.createDomainConfiguration(name, customDomainRequest(), REGION);
|
||||
}
|
||||
|
||||
IotService.Page<IotDomainConfiguration> first = service.listDomainConfigurations(REGION, null, null, 3);
|
||||
assertEquals(List.of("a", "b", "c"),
|
||||
first.items().stream().map(IotDomainConfiguration::getDomainConfigurationName).toList());
|
||||
assertNotNull(first.nextToken());
|
||||
|
||||
IotService.Page<IotDomainConfiguration> second =
|
||||
service.listDomainConfigurations(REGION, null, first.nextToken(), 3);
|
||||
assertEquals(List.of("iot:CredentialProvider", "iot:Data", "iot:Data-ATS"),
|
||||
second.items().stream().map(IotDomainConfiguration::getDomainConfigurationName).toList());
|
||||
assertNotNull(second.nextToken());
|
||||
|
||||
IotService.Page<IotDomainConfiguration> third =
|
||||
service.listDomainConfigurations(REGION, null, second.nextToken(), 3);
|
||||
assertEquals(List.of("iot:Jobs"),
|
||||
third.items().stream().map(IotDomainConfiguration::getDomainConfigurationName).toList());
|
||||
assertNull(third.nextToken());
|
||||
}
|
||||
|
||||
@Test
|
||||
void listRejectsInvalidPagingAndFilterValues() {
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.listDomainConfigurations(REGION, null, null, 0));
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.listDomainConfigurations(REGION, null, null, 251));
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.listDomainConfigurations(REGION, null, "not-a-marker", null));
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.listDomainConfigurations(REGION, "MQTT", null, null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsCanBeListedAddedAndRemovedByArn() {
|
||||
ObjectNode request = customDomainRequest();
|
||||
request.putArray("tags").addObject().put("Key", "env").put("Value", "test");
|
||||
String arn = service.createDomainConfiguration("iot-domain", request, REGION).getDomainConfigurationArn();
|
||||
|
||||
assertEquals(Map.of("env", "test"), service.listTagsForResource(arn));
|
||||
|
||||
service.tagResource(arn, Map.of("owner", "iot", "env", "prod"));
|
||||
assertEquals(Map.of("env", "prod", "owner", "iot"), service.listTagsForResource(arn));
|
||||
|
||||
service.untagResource(arn, List.of("env", "absent"));
|
||||
assertEquals(Map.of("owner", "iot"), service.listTagsForResource(arn));
|
||||
assertEquals(Map.of("owner", "iot"), service.describeDomainConfiguration("iot-domain", REGION).getTags());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagOperationsRejectArnsThatDoNotNameAStoredConfiguration() {
|
||||
String arn = service.createDomainConfiguration("iot-domain", customDomainRequest(), REGION).getDomainConfigurationArn();
|
||||
|
||||
assertAwsError("InvalidRequestException", 400,
|
||||
() -> service.listTagsForResource("arn:aws:iot:us-east-1:000000000000:thing/some-thing"));
|
||||
assertAwsError("InvalidRequestException", 400, () -> service.listTagsForResource("not-an-arn"));
|
||||
assertAwsError("ResourceNotFoundException", 404,
|
||||
() -> service.listTagsForResource("arn:aws:iot:us-east-1:000000000000:domainconfiguration/missing/abcde"));
|
||||
assertAwsError("ResourceNotFoundException", 404,
|
||||
() -> service.tagResource(arn.replaceAll("/[a-z0-9]{5}$", "/zzzzz"), Map.of("k", "v")));
|
||||
assertAwsError("ResourceNotFoundException", 404,
|
||||
() -> service.untagResource("arn:aws:iot:eu-west-1:000000000000:domainconfiguration/iot-domain/abcde", List.of("k")));
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,7 @@ AWS::IAM::ManagedPolicy LEGACY_SWITCH
|
||||
AWS::IAM::Policy LEGACY_SWITCH
|
||||
AWS::IAM::Role IamRoleCfnProvisioner
|
||||
AWS::IAM::User LEGACY_SWITCH
|
||||
AWS::IoT::DomainConfiguration IotDomainConfigurationCfnProvisioner
|
||||
AWS::KMS::Alias KmsCfnProvisioner
|
||||
AWS::KMS::Key KmsCfnProvisioner
|
||||
AWS::Kinesis::Stream KinesisCfnProvisioner
|
||||
|
||||
|
@@ -41,6 +41,7 @@ order:
|
||||
- AWS::Pipes
|
||||
- AWS::Kinesis
|
||||
- AWS::KinesisFirehose
|
||||
- AWS::IoT
|
||||
- AWS::CloudFront
|
||||
- AWS::CloudWatch
|
||||
- AWS::Logs
|
||||
@@ -115,6 +116,7 @@ service_labels:
|
||||
AWS::ElasticLoadBalancingV2: Elastic Load Balancing v2
|
||||
AWS::Events: EventBridge
|
||||
AWS::IAM: IAM
|
||||
AWS::IoT: IoT Core
|
||||
AWS::KMS: KMS
|
||||
AWS::Kinesis: Kinesis
|
||||
AWS::KinesisFirehose: Kinesis Data Firehose
|
||||
@@ -145,6 +147,7 @@ notes:
|
||||
AWS::RDS::DBInstance: starts a real container
|
||||
AWS::RDS::DBCluster: starts a real container
|
||||
AWS::CDK::Metadata: accepted; no-op
|
||||
AWS::IoT::DomainConfiguration: '`ServerCertificates` resolves to a JSON string'
|
||||
Custom::DynamoDBReplica: applied natively against DynamoDB, not via a provider Lambda
|
||||
|
||||
# Trailing prose appended to a row after its type list, for behaviour that belongs to the service
|
||||
|
||||
Reference in new issue
Block a user